File: example_expression_model.py

package info (click to toggle)
lmfit-py 1.3.3-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,332 kB
  • sloc: python: 13,071; makefile: 130; sh: 30
file content (36 lines) | stat: -rw-r--r-- 1,273 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
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

"""
import matplotlib.pyplot as plt
import numpy as np

from lmfit.models import ExpressionModel

###############################################################################
# Generate synthetic data for the user-supplied model:
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)
np.random.seed(2021)
y = y + np.random.normal(size=x.size, scale=0.01)

###############################################################################
# Define the ``ExpressionModel`` and perform the fit:
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:
print(result.fit_report())

###############################################################################
plt.plot(x, y, 'o')
plt.plot(x, result.init_fit, '--', label='initial fit')
plt.plot(x, result.best_fit, '-', label='best fit')
plt.legend()