#Script to illustrate using Sage to analyze data concerning the decomposition of H2O2.

#Times at which data was taken (seconds)
times = [0, 120, 300, 600, 1200, 1800, 2400, 3000, 3600]; #Times in seconds

#H2O2 concentration, moles per liter at each time above
data = [1.00, 0.91, 0.78, 0.59, 0.37, 0.22, 0.13, 0.08, 0.05];

#Logarithmic transformation of data
log_of_data = [log(data[i]) for i in range(len(data))]

#Plot the log data versus time. Call the plot "plot1".
pdata = list(zip(times,log_of_data))
plt1 = scatter_plot(pdata)
show(plt1)

#Fit a line y = -k*t to this data.
var('k, t') #Declare k,t as symbolic variables
model(t) = -k*t #Specify the model to be fit, with "t" as the independent variable
sol = find_fit(pdata,model,parameters=[k]) #Fit the model by adjusting k
f(t) = model(k=sol[0].rhs()) #Define the best fit function of the form in "model"

#Now plot best-fit model overlayed on data
plt2=plot(f(t),t,[0,3600],color='red')
pp = plt1+plt2
pp.axes_labels(['time (seconds)','log(concentration)'])
show(pp)