{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\nUsing an ExpressionModel\n========================\n\nExpressionModels allow a model to be built from a user-supplied expression.\nSee: https://lmfit.github.io/lmfit-py/builtin_models.html#user-defined-models\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom lmfit.models import ExpressionModel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Generate synthetic data for the user-supplied model:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "x = np.linspace(-10, 10, 201)\namp, cen, wid = 3.4, 1.8, 0.5\n\ny = amp * np.exp(-(x-cen)**2 / (2*wid**2)) / (np.sqrt(2*np.pi)*wid)\ny = y + np.random.normal(size=x.size, scale=0.01)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the ExpressionModel and perform the fit:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "gmod = ExpressionModel(\"amp * exp(-(x-cen)**2 /(2*wid**2))/(sqrt(2*pi)*wid)\")\nresult = gmod.fit(y, x=x, amp=5, cen=5, wid=1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "this results in the following output:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(result.fit_report())\n\nplt.plot(x, y, 'bo')\nplt.plot(x, result.init_fit, 'k--', label='initial fit')\nplt.plot(x, result.best_fit, 'r-', label='best fit')\nplt.legend(loc='best')\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 }