{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From: https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#global-optimization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from scipy.optimize import least_squares\n",
    "\n",
    "def model(x, u):\n",
    "    return x[0]*(u*u + x[1] * u) / (u*u + x[2]*u + x[3])\n",
    "\n",
    "def fun(x, u, y):\n",
    "    return model(x, u) - y\n",
    "\n",
    "def jac(x, u, y):\n",
    "    J = np.empty((u.size, x.size))\n",
    "    den = u*u + x[2]*u + x[3]\n",
    "    num = u*u + x[1]*u\n",
    "    J[:, 0] = num/den\n",
    "    J[:, 1] =  x[0]*u/den\n",
    "    J[:, 2] = -x[0]*num*u/(den*den)\n",
    "    J[:, 3] = -x[0]*num  /(den*den)\n",
    "    \n",
    "    return J"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "u  = np.array([4.0, 2.0, 1.0, 5.0e-1, 2.5e-1, 1.67e-1, 1.25e-1, 1.0e-1,\n",
    "               8.33e-2, 7.14e-2, 6.25e-2])\n",
    "y  = np.array([1.957e-1, 1.947e-1, 1.735e-1, 1.6e-1, 8.44e-2, 6.27e-2,\n",
    "               4.56e-2, 3.42e-2, 3.23e-2, 2.35e-2, 2.46e-2])\n",
    "x0 = np.array([2.5, 3.9, 4.15, 3.9])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = least_squares(fun, x0, jac=jac, bounds=(0, 100), args=(u, y), verbose=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result.x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def plot_model(u_test, y_test):\n",
    "    plt.plot(u, y, 'o', markersize=4, label='data')\n",
    "    plt.plot(u_test, y_test, label='fitted model')\n",
    "    plt.xlabel(\"u\")\n",
    "    plt.ylabel(\"y\")\n",
    "    plt.legend(loc='lower right')\n",
    "    \n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "u_test = np.linspace(0, 5)\n",
    "y_test = model(result.x, u_test)\n",
    "\n",
    "plot_model(u_test, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "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
}
