{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Script to illustrate using Sage to analyze data concerning the decomposition of H2O2.\n",
    "\n",
    "#Times at which data was taken (seconds)\n",
    "times = [0, 120, 300, 600, 1200, 1800, 2400, 3000, 3600]; #Times in seconds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#H2O2 concentration, moles per liter at each time above\n",
    "data = [1.00, 0.91, 0.78, 0.59, 0.37, 0.22, 0.13, 0.08, 0.05];"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Logarithmic transformation of data\n",
    "log_of_data = [log(data[i]) for i in range(len(data))]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Plot the log data versus time. Call the plot \"plot1\".\n",
    "pdata = list(zip(times,log_of_data))\n",
    "plt1 = scatter_plot(pdata)\n",
    "show(plt1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Fit a line y = -k*t to this data.\n",
    "var('k, t') #Declare k,t as symbolic variables\n",
    "model(t) = -k*t #Specify the model to be fit, with \"t\" as the independent variable\n",
    "sol = find_fit(pdata,model,parameters=[k]) #Fit the model by adjusting k\n",
    "f(t) = model(k=sol[0].rhs()) #Define the best fit function of the form in \"model\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Now plot best-fit model overlayed on data\n",
    "plt2=plot(f(t),t,[0,3600],color='red')\n",
    "pp = plt1+plt2\n",
    "pp.axes_labels(['time (seconds)','log(concentration)'])\n",
    "show(pp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "SageMath 9.2",
   "language": "sage",
   "name": "sagemath"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}