{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\nFit Using Bounds\n================\n\nA major advantage of using lmfit is that one can specify boundaries on fitting\nparameters, even if the underlying algorithm in SciPy does not support this.\nFor more information on how this is implemented, please refer to:\nhttps://lmfit.github.io/lmfit-py/bounds.html\n\nThe example below shows how to set boundaries using the ``min`` and ``max``\nattributes to fitting parameters.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nfrom numpy import exp, linspace, pi, random, sign, sin\n\nfrom lmfit import Parameters, minimize\nfrom lmfit.printfuncs import report_fit\n\np_true = Parameters()\np_true.add('amp', value=14.0)\np_true.add('period', value=5.4321)\np_true.add('shift', value=0.12345)\np_true.add('decay', value=0.01000)\n\n\ndef residual(pars, x, data=None):\n argu = (x * pars['decay'])**2\n shift = pars['shift']\n if abs(shift) > pi/2:\n shift = shift - sign(shift)*pi\n model = pars['amp'] * sin(shift + x/pars['period']) * exp(-argu)\n if data is None:\n return model\n return model - data\n\n\nrandom.seed(0)\nx = linspace(0, 250, 1500)\nnoise = random.normal(scale=2.80, size=x.size)\ndata = residual(p_true, x) + noise\n\nfit_params = Parameters()\nfit_params.add('amp', value=13.0, max=20, min=0.0)\nfit_params.add('period', value=2, max=10)\nfit_params.add('shift', value=0.0, max=pi/2., min=-pi/2.)\nfit_params.add('decay', value=0.02, max=0.10, min=0.00)\n\nout = minimize(residual, fit_params, args=(x,), kws={'data': data})\nfit = residual(out.params, x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This gives the following fitting results:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "report_fit(out, show_correl=True, modelpars=p_true)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and shows the plot below:\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.plot(x, data, 'ro')\nplt.plot(x, fit, 'b')\nplt.show()" ] } ], "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.6" } }, "nbformat": 4, "nbformat_minor": 0 }