{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Worksheet to support Exercise 3.4.11, modeling a cooling potato with an ODE u'(t) = -k*(u(t)-A)^r.\n",
    "\n",
    "#The data, in time/temperature pairs:\n",
    "data = [[0, 204], [2, 193], [4, 184], [8, 169], [10, 162], [13, 156], [17, 149], [20, 143], [24, 138], [30, 130]]\n",
    "N = len(data);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#A plot:\n",
    "plt1 = scatter_plot(data);\n",
    "show(plt1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#We seek to fit a function\n",
    "A = 72; u0 = 204;\n",
    "var('t k r');\n",
    "u(t,k,r) = A + ((u0-A)^(1-r) + k*(r-1)*t)^(1/(1-r));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#A least-squares fuction:\n",
    "SS = function('SS')(k,r);\n",
    "SS(k,r) = add((u(data[i][0],k,r)-data[i][1])^2 for i in range(N));"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Now minimize SS(k,r) with respect to k,r. A plot of log(SS) might help\n",
    "plot3d(log(SS(k,r)),(k,0,0.0004),(r,2,2.5),aspect_ratio=[1000,1,1],adaptive=True)"
   ]
  },
  {
   "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
}