0
# Model Interface
1
2
The Model class provides a high-level interface for curve fitting, transforming user-defined functions into fitting models with automatic parameter creation, initial value guessing, and comprehensive result analysis. Models can be combined using arithmetic operators to create composite models for complex data.
3
4
## Capabilities
5
6
### Model Class
7
8
High-level curve fitting interface that wraps user functions with parameter management and fitting capabilities.
9
10
```python { .api }
11
class Model:
12
"""Create fitting models from user-supplied functions"""
13
14
def __init__(self, func, independent_vars=None, param_names=None,
15
nan_policy='raise', prefix='', name='', **kws):
16
"""
17
Create a Model from a user function.
18
19
Args:
20
func: Function to convert to model (should return numpy array)
21
independent_vars (list): Names of independent variables (default: ['x'])
22
param_names (list): Names of parameters (auto-detected if None)
23
nan_policy (str): Policy for NaN values ('raise', 'propagate', 'omit')
24
prefix (str): Prefix for parameter names to avoid conflicts
25
name (str): Name for the model
26
**kws: Additional keyword arguments
27
"""
28
29
def fit(self, data, params=None, weights=None, method='leastsq',
30
iter_cb=None, scale_covar=True, verbose=False, fit_kws=None, **kws):
31
"""
32
Fit the model to data.
33
34
Args:
35
data (array-like): Data to fit
36
params (Parameters): Parameters for fit (uses make_params() if None)
37
weights (array-like): Weights for data points
38
method (str): Optimization method
39
iter_cb: Iteration callback function
40
scale_covar (bool): Scale covariance matrix
41
verbose (bool): Print fit progress
42
fit_kws (dict): Additional arguments for minimizer
43
**kws: Values for independent variables
44
45
Returns:
46
ModelResult: Comprehensive fit results
47
"""
48
49
def guess(self, data, **kws):
50
"""
51
Guess initial parameter values from data.
52
53
Args:
54
data (array-like): Data to analyze for parameter guessing
55
**kws: Values for independent variables and other options
56
57
Returns:
58
Parameters: Parameters with guessed initial values
59
"""
60
61
def make_params(self, verbose=False, **kws):
62
"""
63
Create Parameters for the model.
64
65
Args:
66
verbose (bool): Print parameter creation info
67
**kws: Initial values for parameters
68
69
Returns:
70
Parameters: Parameters object for the model
71
"""
72
73
def eval(self, params=None, **kws):
74
"""
75
Evaluate the model function.
76
77
Args:
78
params (Parameters): Parameter values to use
79
**kws: Values for independent variables
80
81
Returns:
82
array: Model values
83
"""
84
85
def set_param_hint(self, name, **kws):
86
"""
87
Set parameter hints for automatic parameter creation.
88
89
Args:
90
name (str): Parameter name
91
**kws: Parameter attributes (value, min, max, vary, expr, etc.)
92
"""
93
94
def print_param_hints(self, columns=['name', 'value', 'min', 'max', 'vary', 'expr']):
95
"""
96
Print table of parameter hints.
97
98
Args:
99
columns (list): Columns to display in table
100
"""
101
```
102
103
### CompositeModel Class
104
105
Composite models created by combining Model instances with arithmetic operators.
106
107
```python { .api }
108
class CompositeModel(Model):
109
"""Model created by combining other models with operators"""
110
111
def __init__(self, left, right, op, **kws):
112
"""
113
Create composite model (usually created automatically via operators).
114
115
Args:
116
left (Model): Left operand model
117
right (Model): Right operand model
118
op (function): Operator function (+, -, *, /)
119
**kws: Additional keyword arguments
120
"""
121
122
# Inherits all Model methods with combined functionality
123
```
124
125
### ModelResult Class
126
127
Comprehensive results from Model.fit() with enhanced analysis capabilities.
128
129
```python { .api }
130
class ModelResult(MinimizerResult):
131
"""Results from Model.fit() with enhanced model-specific features"""
132
133
def eval_components(self, params=None, **kws):
134
"""
135
Evaluate individual components of composite models.
136
137
Args:
138
params (Parameters): Parameter values (uses best-fit if None)
139
**kws: Values for independent variables
140
141
Returns:
142
dict: Component names mapped to their evaluated values
143
"""
144
145
def plot(self, datafmt='o', fitfmt='-', initfmt='--', xlabel=None,
146
ylabel=None, yerr=None, numpoints=None, fig=None,
147
data_kws=None, fit_kws=None, init_kws=None,
148
ax_res_kws=None, ax_fit_kws=None, fig_kws=None,
149
show_init=False, parse_complex='abs'):
150
"""
151
Plot data, initial fit, and best fit with residuals.
152
153
Args:
154
datafmt (str): Format for data points
155
fitfmt (str): Format for fit line
156
initfmt (str): Format for initial fit line
157
xlabel (str): X-axis label
158
ylabel (str): Y-axis label
159
yerr (array): Error bars for data
160
numpoints (int): Number of points for fit line
161
fig: Matplotlib figure to use
162
data_kws (dict): Keyword arguments for data plot
163
fit_kws (dict): Keyword arguments for fit plot
164
init_kws (dict): Keyword arguments for initial fit plot
165
ax_res_kws (dict): Keyword arguments for residuals axis
166
ax_fit_kws (dict): Keyword arguments for fit axis
167
fig_kws (dict): Keyword arguments for figure
168
show_init (bool): Show initial parameter fit
169
parse_complex (str): How to handle complex values
170
171
Returns:
172
Figure with data, fit, and residuals
173
"""
174
175
def plot_fit(self, ax=None, datafmt='o', fitfmt='-', initfmt='--',
176
xlabel=None, ylabel=None, yerr=None, numpoints=None,
177
data_kws=None, fit_kws=None, init_kws=None, ax_kws=None,
178
show_init=False, parse_complex='abs'):
179
"""
180
Plot data and fit without residuals.
181
182
Args:
183
ax: Matplotlib axis to plot on
184
Other args: Same as plot() method
185
"""
186
187
def plot_residuals(self, ax=None, datafmt='o', yerr=None,
188
data_kws=None, fit_kws=None, ax_kws=None,
189
parse_complex='abs'):
190
"""
191
Plot fit residuals.
192
193
Args:
194
ax: Matplotlib axis to plot on
195
datafmt (str): Format for residual points
196
yerr (array): Error bars for residuals
197
data_kws (dict): Keyword arguments for data plot
198
fit_kws (dict): Keyword arguments for fit plot
199
ax_kws (dict): Keyword arguments for axis
200
parse_complex (str): How to handle complex residuals
201
"""
202
```
203
204
### Model Persistence Functions
205
206
```python { .api }
207
def save_modelresult(modelresult, fname):
208
"""
209
Save ModelResult to file.
210
211
Args:
212
modelresult (ModelResult): Results to save
213
fname (str): Filename for saving
214
"""
215
216
def load_modelresult(fname, **kws):
217
"""
218
Load ModelResult from file.
219
220
Args:
221
fname (str): Filename to load from
222
**kws: Additional keyword arguments
223
224
Returns:
225
ModelResult: Loaded results
226
"""
227
```
228
229
## Usage Examples
230
231
### Creating a Simple Model
232
233
```python
234
import numpy as np
235
from lmfit import Model
236
237
def exponential_decay(x, amplitude, decay, offset):
238
"""Exponential decay function"""
239
return amplitude * np.exp(-decay * x) + offset
240
241
# Create model from function
242
model = Model(exponential_decay)
243
244
# Generate sample data
245
x = np.linspace(0, 10, 101)
246
data = 5.0 * np.exp(-0.8 * x) + 2.0 + np.random.normal(size=101, scale=0.1)
247
248
# Fit the model
249
result = model.fit(data, x=x, amplitude=10, decay=1, offset=1)
250
251
print(result.fit_report())
252
```
253
254
### Parameter Hints and Guessing
255
256
```python
257
# Set parameter hints for better automatic behavior
258
model.set_param_hint('amplitude', min=0, value=5)
259
model.set_param_hint('decay', min=0, value=1)
260
model.set_param_hint('offset', value=0)
261
262
# Create parameters with hints
263
params = model.make_params()
264
265
# Or let the model guess initial values
266
guess_params = model.guess(data, x=x)
267
268
# Fit with guessed parameters
269
result = model.fit(data, guess_params, x=x)
270
```
271
272
### Composite Models
273
274
```python
275
from lmfit.models import GaussianModel, LinearModel
276
277
# Create individual models
278
gaussian = GaussianModel(prefix='g_')
279
linear = LinearModel(prefix='l_')
280
281
# Combine models with operators
282
composite = gaussian + linear
283
284
# The composite model has parameters from both components:
285
# g_amplitude, g_center, g_sigma, l_slope, l_intercept
286
params = composite.make_params()
287
288
# Set initial values
289
params['g_amplitude'].set(value=10, min=0)
290
params['g_center'].set(value=5)
291
params['g_sigma'].set(value=1, min=0.01)
292
params['l_slope'].set(value=0)
293
params['l_intercept'].set(value=0)
294
295
# Fit composite model
296
result = composite.fit(data, params, x=x)
297
```
298
299
### Advanced Model Usage
300
301
```python
302
def multi_peak(x, **params):
303
"""Multi-peak function with variable number of peaks"""
304
y = params.get('background', 0)
305
i = 1
306
while f'amp{i}' in params:
307
amp = params[f'amp{i}']
308
cen = params[f'cen{i}']
309
wid = params[f'wid{i}']
310
y += amp * np.exp(-(x - cen)**2 / (2 * wid**2))
311
i += 1
312
return y
313
314
# Create model with custom independent variables
315
model = Model(multi_peak, independent_vars=['x'])
316
317
# Set parameter hints for multiple peaks
318
for i in range(1, 4): # 3 peaks
319
model.set_param_hint(f'amp{i}', value=1, min=0)
320
model.set_param_hint(f'cen{i}', value=i*3)
321
model.set_param_hint(f'wid{i}', value=1, min=0.1)
322
323
model.set_param_hint('background', value=0)
324
325
# Create and fit
326
params = model.make_params()
327
result = model.fit(data, params, x=x)
328
```
329
330
### Evaluating Models and Components
331
332
```python
333
# Evaluate model at best-fit parameters
334
best_fit = result.best_fit
335
336
# Evaluate at custom parameters
337
custom_params = result.params.copy()
338
custom_params['amplitude'].value = 8.0
339
custom_fit = model.eval(custom_params, x=x)
340
341
# For composite models, evaluate individual components
342
if hasattr(result, 'eval_components'):
343
components = result.eval_components(x=x)
344
gaussian_component = components['g_']
345
linear_component = components['l_']
346
```
347
348
### Model Plotting
349
350
```python
351
# Plot data and fit with residuals
352
result.plot()
353
354
# Plot just the fit
355
result.plot_fit(show_init=True) # Include initial parameters
356
357
# Plot just residuals
358
result.plot_residuals()
359
360
# Customize plots
361
result.plot(datafmt='ko', fitfmt='r-', xlabel='Time (s)',
362
ylabel='Signal', data_kws={'markersize': 4})
363
```