0
# Results and Reporting
1
2
LMFIT provides comprehensive reporting functions for displaying fit results, parameter values, uncertainties, correlations, and confidence intervals in both human-readable text and HTML formats suitable for notebooks and web applications.
3
4
## Capabilities
5
6
### Text Reporting Functions
7
8
Functions for generating detailed text reports of fit results and confidence intervals.
9
10
```python { .api }
11
def fit_report(inpars, modelpars=None, show_correl=True, min_correl=0.1, sort_pars=False):
12
"""
13
Generate detailed text report of fit results.
14
15
Args:
16
inpars (Parameters or MinimizerResult): Parameters or result from fit
17
modelpars (Parameters): Model parameters (for comparison with fit params)
18
show_correl (bool): Include parameter correlation matrix
19
min_correl (float): Minimum correlation coefficient to display
20
sort_pars (bool): Sort parameters alphabetically
21
22
Returns:
23
str: Formatted text report with fit statistics and parameter values
24
"""
25
26
def ci_report(ci, with_offset=True, ndigits=5):
27
"""
28
Generate confidence interval report.
29
30
Args:
31
ci (dict): Confidence intervals from conf_interval()
32
with_offset (bool): Show parameter offsets from best-fit values
33
ndigits (int): Number of digits for numerical display
34
35
Returns:
36
str: Formatted confidence interval report
37
"""
38
39
def report_fit(params, **kws):
40
"""
41
Alias for fit_report() for backwards compatibility.
42
43
Args:
44
params: Parameters or MinimizerResult
45
**kws: Additional arguments passed to fit_report()
46
47
Returns:
48
str: Formatted fit report
49
"""
50
51
def report_ci(ci):
52
"""
53
Alias for ci_report() for backwards compatibility.
54
55
Args:
56
ci (dict): Confidence intervals
57
58
Returns:
59
str: Formatted confidence interval report
60
"""
61
```
62
63
### HTML Reporting Functions
64
65
Functions for generating HTML tables suitable for Jupyter notebooks and web display.
66
67
```python { .api }
68
def fitreport_html_table(result, show_correl=True, min_correl=0.1):
69
"""
70
Generate HTML table for fit results.
71
72
Args:
73
result (MinimizerResult): Results from minimization
74
show_correl (bool): Include correlation matrix
75
min_correl (float): Minimum correlation to display
76
77
Returns:
78
str: HTML table string
79
"""
80
81
def params_html_table(params):
82
"""
83
Generate HTML table for Parameters display.
84
85
Args:
86
params (Parameters): Parameters object
87
88
Returns:
89
str: HTML table string for parameters
90
"""
91
```
92
93
### Utility Functions
94
95
Helper functions for formatting and display customization.
96
97
```python { .api }
98
def gformat(val, length=11):
99
"""
100
Format numerical values for display.
101
102
Args:
103
val (float): Value to format
104
length (int): Total field width
105
106
Returns:
107
str: Formatted value string
108
"""
109
110
def getfloat_attr(obj, attr, length=11):
111
"""
112
Extract and format floating point attributes from objects.
113
114
Args:
115
obj: Object containing the attribute
116
attr (str): Attribute name
117
length (int): Field width for formatting
118
119
Returns:
120
str: Formatted attribute value
121
"""
122
123
def correl_table(params, min_correl=0.1):
124
"""
125
Generate correlation matrix table.
126
127
Args:
128
params (Parameters): Parameters with correlation data
129
min_correl (float): Minimum correlation coefficient to display
130
131
Returns:
132
str: Formatted correlation table
133
"""
134
135
def alphanumeric_sort(s):
136
"""
137
Sort strings alphanumerically (natural sorting).
138
139
Args:
140
s (str): String to generate sort key for
141
142
Returns:
143
list: Sort key for natural ordering
144
"""
145
```
146
147
## Usage Examples
148
149
### Basic Fit Reporting
150
151
```python
152
import numpy as np
153
from lmfit import minimize, Parameters, fit_report
154
155
def exponential_residual(params, x, data):
156
"""Exponential decay model"""
157
a = params['amplitude']
158
t = params['decay_time']
159
c = params['offset']
160
model = a * np.exp(-x / t) + c
161
return model - data
162
163
# Generate sample data
164
x = np.linspace(0, 10, 101)
165
data = 5.0 * np.exp(-x / 2.0) + 1.0 + np.random.normal(size=101, scale=0.1)
166
167
# Set up and perform fit
168
params = Parameters()
169
params.add('amplitude', value=10, min=0)
170
params.add('decay_time', value=1, min=0.1)
171
params.add('offset', value=1)
172
173
result = minimize(exponential_residual, params, args=(x, data))
174
175
# Generate comprehensive fit report
176
report = fit_report(result)
177
print(report)
178
```
179
180
### Customizing Reports
181
182
```python
183
# Generate report without correlation matrix
184
report_no_correl = fit_report(result, show_correl=False)
185
print("Report without correlations:")
186
print(report_no_correl)
187
188
# Show only strong correlations
189
report_strong_correl = fit_report(result, min_correl=0.5)
190
print("\nReport with strong correlations only:")
191
print(report_strong_correl)
192
193
# Sort parameters alphabetically
194
report_sorted = fit_report(result, sort_pars=True)
195
print("\nReport with sorted parameters:")
196
print(report_sorted)
197
```
198
199
### Confidence Interval Reporting
200
201
```python
202
from lmfit import conf_interval, ci_report
203
204
# Calculate confidence intervals
205
ci = conf_interval(result.minimizer, result)
206
207
# Generate confidence interval report
208
ci_rep = ci_report(ci)
209
print("Confidence Intervals:")
210
print(ci_rep)
211
212
# Report without parameter offsets
213
ci_rep_no_offset = ci_report(ci, with_offset=False)
214
print("\nConfidence intervals (absolute values):")
215
print(ci_rep_no_offset)
216
217
# Custom precision
218
ci_rep_precise = ci_report(ci, ndigits=8)
219
print("\nHigh precision confidence intervals:")
220
print(ci_rep_precise)
221
```
222
223
### Model Results Reporting
224
225
```python
226
from lmfit.models import ExponentialModel
227
228
# Using Model interface
229
exp_model = ExponentialModel()
230
params = exp_model.guess(data, x=x)
231
model_result = exp_model.fit(data, params, x=x)
232
233
# Model results include additional information
234
print("Model Fit Report:")
235
print(model_result.fit_report())
236
237
# Compare initial and final parameters
238
print("\nComparison with initial parameters:")
239
print(fit_report(model_result.params, model_result.init_params))
240
```
241
242
### HTML Reporting for Notebooks
243
244
```python
245
# Generate HTML table for Jupyter notebook display
246
from IPython.display import HTML, display
247
248
html_table = fitreport_html_table(result)
249
display(HTML(html_table))
250
251
# HTML table for parameters only
252
params_table = params_html_table(result.params)
253
display(HTML(params_table))
254
```
255
256
### Custom Report Formatting
257
258
```python
259
def custom_report(result):
260
"""Create custom fit report with additional information"""
261
report_lines = []
262
263
# Basic fit statistics
264
report_lines.append("="*50)
265
report_lines.append("CUSTOM FIT REPORT")
266
report_lines.append("="*50)
267
report_lines.append(f"Method: {result.method}")
268
report_lines.append(f"Function evaluations: {result.nfev}")
269
report_lines.append(f"Data points: {result.ndata}")
270
report_lines.append(f"Variables: {result.nvarys}")
271
report_lines.append(f"Chi-squared: {result.chisqr:.6f}")
272
report_lines.append(f"Reduced chi-squared: {result.redchi:.6f}")
273
report_lines.append(f"AIC: {result.aic:.6f}")
274
report_lines.append(f"BIC: {result.bic:.6f}")
275
report_lines.append("")
276
277
# Parameter values with custom formatting
278
report_lines.append("PARAMETERS:")
279
report_lines.append("-"*50)
280
for name, param in result.params.items():
281
if param.vary:
282
stderr_str = f"±{param.stderr:.4f}" if param.stderr else "±N/A"
283
report_lines.append(f"{name:12s}: {param.value:.6f} {stderr_str}")
284
else:
285
report_lines.append(f"{name:12s}: {param.value:.6f} (fixed)")
286
287
return "\n".join(report_lines)
288
289
# Use custom report
290
print(custom_report(result))
291
```
292
293
### Saving Reports to Files
294
295
```python
296
# Save text report to file
297
with open('fit_results.txt', 'w') as f:
298
f.write(fit_report(result))
299
if 'ci' in locals():
300
f.write('\n\nConfidence Intervals:\n')
301
f.write(ci_report(ci))
302
303
# Save HTML report for web display
304
html_content = f"""
305
<!DOCTYPE html>
306
<html>
307
<head>
308
<title>Fit Results</title>
309
<style>
310
body {{ font-family: Arial, sans-serif; margin: 20px; }}
311
table {{ border-collapse: collapse; margin: 20px 0; }}
312
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
313
th {{ background-color: #f2f2f2; }}
314
</style>
315
</head>
316
<body>
317
<h1>Fit Results</h1>
318
{fitreport_html_table(result)}
319
</body>
320
</html>
321
"""
322
323
with open('fit_results.html', 'w') as f:
324
f.write(html_content)
325
```
326
327
### Batch Reporting for Multiple Fits
328
329
```python
330
def compare_multiple_fits(results_dict):
331
"""Compare multiple fit results in a single report"""
332
333
print("COMPARISON OF MULTIPLE FITS")
334
print("="*60)
335
336
# Header
337
header = f"{'Model':<15} {'Chi-sq':<12} {'Red Chi-sq':<12} {'AIC':<12} {'BIC':<12}"
338
print(header)
339
print("-"*60)
340
341
# Results for each fit
342
for name, result in results_dict.items():
343
line = f"{name:<15} {result.chisqr:<12.4f} {result.redchi:<12.4f} {result.aic:<12.2f} {result.bic:<12.2f}"
344
print(line)
345
346
print("\nDETAILED REPORTS:")
347
print("="*60)
348
349
# Individual detailed reports
350
for name, result in results_dict.items():
351
print(f"\n{name.upper()} FIT:")
352
print("-"*30)
353
print(fit_report(result, show_correl=False))
354
355
# Example usage with multiple models
356
from lmfit.models import LinearModel, QuadraticModel
357
358
linear_model = LinearModel()
359
quad_model = QuadraticModel()
360
361
linear_result = linear_model.fit(data, x=x)
362
quad_result = quad_model.fit(data, x=x)
363
364
results = {
365
'Linear': linear_result,
366
'Quadratic': quad_result,
367
'Exponential': model_result
368
}
369
370
compare_multiple_fits(results)
371
```
372
373
### Parameter Summary Tables
374
375
```python
376
def parameter_summary_table(results_list, model_names):
377
"""Create parameter comparison table across multiple fits"""
378
379
# Collect all parameter names
380
all_params = set()
381
for result in results_list:
382
all_params.update(result.params.keys())
383
384
# Create header
385
header = f"{'Parameter':<15}"
386
for name in model_names:
387
header += f"{name:<15}"
388
print(header)
389
print("-" * (15 + 15 * len(model_names)))
390
391
# Parameter rows
392
for param_name in sorted(all_params):
393
row = f"{param_name:<15}"
394
for result in results_list:
395
if param_name in result.params:
396
param = result.params[param_name]
397
if param.stderr:
398
value_str = f"{param.value:.3f}±{param.stderr:.3f}"
399
else:
400
value_str = f"{param.value:.3f}"
401
row += f"{value_str:<15}"
402
else:
403
row += f"{'N/A':<15}"
404
print(row)
405
406
# Usage
407
parameter_summary_table([linear_result, quad_result, model_result],
408
['Linear', 'Quadratic', 'Exponential'])
409
```