summaryrefslogtreecommitdiff
path: root/examples/example_fit_multi_datasets.py
diff options
context:
space:
mode:
Diffstat (limited to 'examples/example_fit_multi_datasets.py')
-rw-r--r--examples/example_fit_multi_datasets.py25
1 files changed, 10 insertions, 15 deletions
diff --git a/examples/example_fit_multi_datasets.py b/examples/example_fit_multi_datasets.py
index 2920f0d..587b9da 100644
--- a/examples/example_fit_multi_datasets.py
+++ b/examples/example_fit_multi_datasets.py
@@ -5,9 +5,9 @@ Fit Multiple Data Sets
Fitting multiple (simulated) Gaussian data sets simultaneously.
All minimizers require the residual array to be one-dimensional. Therefore, in
-the ``objective`` we need to ```flatten``` the array before returning it.
+the ``objective`` function we need to ``flatten`` the array before returning it.
-TODO: this should be using the Model interface / built-in models!
+TODO: this could/should be using the Model interface / built-in models!
"""
import matplotlib.pyplot as plt
@@ -23,9 +23,9 @@ def gauss(x, amp, cen, sigma):
def gauss_dataset(params, i, x):
"""Calculate Gaussian lineshape from parameters for data set."""
- amp = params['amp_%i' % (i+1)]
- cen = params['cen_%i' % (i+1)]
- sig = params['sig_%i' % (i+1)]
+ amp = params[f'amp_{i+1}']
+ cen = params[f'cen_{i+1}']
+ sig = params[f'sig_{i+1}']
return gauss(x, amp, cen, sig)
@@ -44,7 +44,7 @@ def objective(params, x, data):
###############################################################################
# Create five simulated Gaussian data sets
-
+np.random.seed(2021)
x = np.linspace(-1, 2, 151)
data = []
for _ in np.arange(5):
@@ -58,31 +58,26 @@ data = np.array(data)
###############################################################################
# Create five sets of fitting parameters, one per data set
-
fit_params = Parameters()
for iy, y in enumerate(data):
- fit_params.add('amp_%i' % (iy+1), value=0.5, min=0.0, max=200)
- fit_params.add('cen_%i' % (iy+1), value=0.4, min=-2.0, max=2.0)
- fit_params.add('sig_%i' % (iy+1), value=0.3, min=0.01, max=3.0)
+ fit_params.add(f'amp_{iy+1}', value=0.5, min=0.0, max=200)
+ fit_params.add(f'cen_{iy+1}', value=0.4, min=-2.0, max=2.0)
+ fit_params.add(f'sig_{iy+1}', value=0.3, min=0.01, max=3.0)
###############################################################################
# Constrain the values of sigma to be the same for all peaks by assigning
# sig_2, ..., sig_5 to be equal to sig_1.
-
for iy in (2, 3, 4, 5):
- fit_params['sig_%i' % iy].expr = 'sig_1'
+ fit_params[f'sig_{iy}'].expr = 'sig_1'
###############################################################################
# Run the global fit and show the fitting result
-
out = minimize(objective, fit_params, args=(x, data))
report_fit(out.params)
###############################################################################
# Plot the data sets and fits
-
plt.figure()
for i in range(5):
y_fit = gauss_dataset(out.params, i, x)
plt.plot(x, data[i, :], 'o', x, y_fit, '-')
-plt.show()