.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_example_expression_model.py: Using an ExpressionModel ======================== ExpressionModels allow a model to be built from a user-supplied expression. See: https://lmfit.github.io/lmfit-py/builtin_models.html#user-defined-models .. code-block:: default import matplotlib.pyplot as plt import numpy as np from lmfit.models import ExpressionModel Generate synthetic data for the user-supplied model: .. code-block:: default x = np.linspace(-10, 10, 201) amp, cen, wid = 3.4, 1.8, 0.5 y = amp * np.exp(-(x-cen)**2 / (2*wid**2)) / (np.sqrt(2*np.pi)*wid) y = y + np.random.normal(size=x.size, scale=0.01) Define the ExpressionModel and perform the fit: .. code-block:: default gmod = ExpressionModel("amp * exp(-(x-cen)**2 /(2*wid**2))/(sqrt(2*pi)*wid)") result = gmod.fit(y, x=x, amp=5, cen=5, wid=1) this results in the following output: .. code-block:: default print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--', label='initial fit') plt.plot(x, result.best_fit, 'r-', label='best fit') plt.legend(loc='best') plt.show() .. image:: /examples/images/sphx_glr_example_expression_model_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [[Model]] Model(_eval) [[Fit Statistics]] # fitting method = leastsq # function evals = 52 # data points = 201 # variables = 3 chi-square = 0.02184805 reduced chi-square = 1.1034e-04 Akaike info crit = -1828.51661 Bayesian info crit = -1818.60669 [[Variables]] amp: 3.40725701 +/- 0.00541581 (0.16%) (init = 5) cen: 1.80147428 +/- 9.1751e-04 (0.05%) (init = 5) wid: 0.49989801 +/- 9.1751e-04 (0.18%) (init = 1) [[Correlations]] (unreported correlations are < 0.100) C(amp, wid) = 0.577 /Users/Newville/Codes/lmfit-py/examples/example_expression_model.py:35: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. plt.show() .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.089 seconds) .. _sphx_glr_download_examples_example_expression_model.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: example_expression_model.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: example_expression_model.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_