fitting¶
Fitting functions using lmfit
See: https://lmfit.github.io/lmfit-py/builtin_models.html
Use of peakfit: from fitting import peakfit fit = peakfit(xdata, ydata) # returns lmfit object print(fit) fit.plot()
FitResults
¶
FitResults Class Wrapper for lmfit results object with additional functions specific to i16_peakfit
res = model.fit(ydata, x=xdata) # lmfit ouput fitres = FitResults(res)
--- Parameters --- fitres.res # lmfit output
data from fit:¶
fitres.npeaks # number of peak models used, fitres.chisqr # Chi^2 of fit, fitres.xdata # x-data used for fit, fitres.ydata # y-data used for fit, fitres.yfit # y-fit values, fitres.weights # res.weights, fitres.yerror # 1 / res.weights if res.weights is not None else 0 * res.data,
data from components, e.g.¶
fitres.p1_amplitude # Peak 1 area, fitres.p1_fwhm # Peak 1 full-width and half-maximum fitres.p1_center # Peak 1 peak position fitres.p1_height # Peak 1 fitted height,
data for total fit:¶
fitres.amplitude # Total summed area, fitres.center # average centre of peaks, fitres.height # average height of peaks, fitres.fwhm # average FWHM of peaks, fitres.background # fitted background,
errors on all parameters, e.g.¶
fitres.stderr_amplitude # error on 'amplitude
--- Functions --- print(fitres) # prints formatted str with results ouputdict = fitres.results() # creates ouput dict xdata, yfit = fitres.fit(ntimes=10) # interpolated fit results fig = fitres.plot(axes, xlabel, ylabel, title) # create plot
Source code in mmg_toolbox/utils/fitting.py
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | |
ScanFitManager
¶
ScanFitManager Holds several functions for automatically fitting scan data
fit = ScanFitManager(scan) fit.peak_ratio(yaxis) # calculates peak power fit.find_peaks(xaxis, yaxis) # automated peak finding routine fit.fit(xaxis, yaxis) # estimate & fit data against a peak profile model using lmfit fit.multi_peak_fit(xaxis, yaxis) # find peaks & fit multiprofile model using lmfit fit.model_fit(xaxis, yaxis, model, pars) # fit supplied model against data fit.fit_results() # return lmfit.ModelResult for last fit fit.fit_values() # return dict of fit values for last fit fit.fit_report() # return str of fit report fit.plot() # plot last lmfit results * xaxis, yaxis are str names of arrays in the scan namespace
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scan
|
NexusScan
|
babelscan.Scan |
required |
Source code in mmg_toolbox/utils/fitting.py
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 | |
__call__(*args, **kwargs)
¶
find_peaks(xaxis='axes', yaxis='signal', min_peak_power=None, peak_distance_idx=6)
¶
Find peak shaps in linear-spaced 1d arrays with poisson like numerical values
E.G. centres, index, power = self.find_peaks(xaxis, yaxis, min_peak_power=None, peak_distance_idx=10)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
array(m) of estimated power of each peak |
Source code in mmg_toolbox/utils/fitting.py
fit(xaxis='axes', yaxis='signal', model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit x,y data to a peak model using lmfit
E.G.: res = self.fit('axes', 'signal', model='Gauss') print(res) res.plot() val1 = res.p1_amplitude val2 = res.p2_amplitude
Peak Models: Choice of peak model: 'Gaussian', 'Lorentzian', 'Voight', 'PseudoVoight' Background Models: Choice of background model: 'flat', 'slope', 'exponential'
Peak Parameters (%d=number of peak): 'amplitude', 'center', 'sigma', pvoight only: 'fraction' output only: 'fwhm', 'height' Background parameters: 'bkg_slope', 'bkg_intercept', or for exponential: 'bkg_amplitude', 'bkg_decay' output only: 'background' Uncertainties (errors): 'stderr_PARAMETER', e.g. 'stderr_amplitude'
Provide initial guess: res = self.fit(x, y, model='Voight', initial_parameters={'p1_center':1.23})
Fix parameter: res = self.fit(x, y, model='gauss', fix_parameters={'p1_sigma': fwhm/2.3548200})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
model
|
str
|
str, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
method
|
str
|
str method name, from lmfit fitting methods |
'leastsq'
|
print_result
|
bool
|
if True, prints the fit results using fit.fit_report() |
False
|
plot_result
|
bool
|
if True, plots the results using fit.plot() |
False
|
Returns:
| Type | Description |
|---|---|
FitResults
|
FitResult object |
Source code in mmg_toolbox/utils/fitting.py
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 | |
fit_parameter(parameter_name='amplitude')
¶
Returns parameter, error from the last run fit
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter_name
|
str
|
str, name from last fit e.g. 'amplitude', 'center', 'fwhm', 'background' |
'amplitude'
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
value, error |
Source code in mmg_toolbox/utils/fitting.py
fit_report()
¶
fit_result()
¶
gen_lmfit_script(xaxis='axes', yaxis='signal', npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None)
¶
Generate script string of fit process, using only lmfit
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
Returns:
| Type | Description |
|---|---|
|
str |
Source code in mmg_toolbox/utils/fitting.py
gen_model(xaxis='axes', yaxis='signal', npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None)
¶
Generate lmfit model and parameters
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Model, Parameters]
|
model, pars |
Source code in mmg_toolbox/utils/fitting.py
gen_model_script(xaxis='axes', yaxis='signal', npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None, only_lmfit=False)
¶
Generate script string of fit process
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
only_lmfit
|
bool
|
if True, only include imports for lmfit |
False
|
Returns:
| Type | Description |
|---|---|
str
|
str |
Source code in mmg_toolbox/utils/fitting.py
modelfit(xaxis='axis', yaxis='signal', model=None, pars=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit data from scan against lmfit model
Example: from lmfit.models import GaussianModel, LinearModel mod = GaussainModel(prefix='p1_') + LinearModel(prefix='bkg_') pars = mod.make_params() pars['p1_center'].set(value=np.mean(x), min=x.min(), max=x.max()) res = scan.fit.modelfit('axis', 'signal', mod, pars) print(res.fit_report()) res.plot() area = res.params['p1_amplitude'].value err = res.params['p1_amplitude'].stderr
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axis'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
model
|
Model | None
|
lmfit.Model - object defining combination of models |
None
|
pars
|
Parameters | None
|
lmfit.Parameters - object defining model parameters |
None
|
method
|
str
|
str name of fitting method to use |
'leastsq'
|
print_result
|
bool
|
bool, if True, print results.fit_report() |
False
|
plot_result
|
bool
|
bool, if True, generate results.plot() |
False
|
Returns:
| Type | Description |
|---|---|
ModelResult
|
lmfit fit results |
Source code in mmg_toolbox/utils/fitting.py
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 | |
multi_peak_fit(xaxis='axes', yaxis='signal', npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit x,y data to a peak model using lmfit
E.G.: res = self.multi_peak_fit('axes', 'signal', npeaks=2, model='Gauss') print(res) res.plot() val1 = res.p1_amplitude val2 = res.p2_amplitude
Peak centers: Will attempt a fit using 'npeaks' peaks, with centers defined by defalult by the find_peaks function if 'npeaks' is None, the number of peaks will be found by find_peaks() if 'npeaks' is greater than the number of peaks found by find_peaks, initial peak centers are evenly distrubuted along xdata.
Peak Models: Choice of peak model: 'Gaussian', 'Lorentzian', 'Voight','PseudoVoight' Background Models: Choice of background model: 'flat', 'slope', 'exponential'
Peak Parameters (%d=number of peak): 'p%d_amplitude', 'p%d_center', 'p%d_sigma', pvoight only: 'p%d_fraction' output only: 'p%d_fwhm', 'p%d_height' Background parameters: 'bkg_slope', 'bkg_intercept', or for exponential: 'bkg_amplitude', 'bkg_decay' Total parameters (always available, output only - sum/averages of all peaks): 'amplitude', 'center', 'sigma', 'fwhm', 'height', 'background' Uncertainties (errors): 'stderr_PARAMETER', e.g. 'stderr_amplitude'
Provide initial guess: res = self.multi_peak_fit(x, y, model='Voight', initial_parameters={'p1_center':1.23})
Fix parameter: res = self.multi_peak_fit(x, y, model='gauss', fix_parameters={'p1_sigma': fwhm/2.3548200})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xaxis
|
str
|
str name or address of array to plot on x axis |
'axes'
|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
int | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
method
|
str
|
str method name, from lmfit fitting methods |
'leastsq'
|
print_result
|
bool
|
if True, prints the fit results using fit.fit_report() |
False
|
plot_result
|
bool
|
if True, plots the results using fit.plot() |
False
|
Returns:
| Type | Description |
|---|---|
FitResults
|
FitResults object |
Source code in mmg_toolbox/utils/fitting.py
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 | |
peak_ratio(yaxis='signal')
¶
Return the ratio signal / error for given dataset From Blessing, J. Appl. Cryst. (1997). 30, 421-426 Equ: (1) + (6) peak_ratio = (sum((y-bkg)/dy2)/sum(1/dy2)) / sqrt(i/sum(1/dy^2))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
yaxis
|
str
|
str name or address of array to plot on y axis |
'signal'
|
Returns:
| Type | Description |
|---|---|
float
|
float ratio signal / err |
Source code in mmg_toolbox/utils/fitting.py
find_local_maxima(y, yerror=None)
¶
Find local maxima in 1d arrays, returns index of local maximums, plus estimation of the peak power for each maxima and a classification of whether the maxima is greater than the standard deviation of the error.
E.G. index, power, isgood = find_local_maxima(ydata) maxima = ydata[index[isgood]] maxima_power = power[isgood]
Peak Power: peak power for each maxima is calculated using the peak_ratio algorithm for each maxima and adjacent points Good Peaks: Maxima are returned Good if: power > (max(y) - min(y)) / std(yerror)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
array(n) of data |
required |
yerror
|
ndarray | None
|
array(n) of errors on data, or None to use default error function (sqrt(abs(y)+1)) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
bool array(m) where True elements have power > power of the array |
Source code in mmg_toolbox/utils/fitting.py
find_peaks(y, yerror=None, min_peak_power=None, peak_distance_idx=6)
¶
Find peak shaps in linear-spaced 1d arrays with poisson like numerical values
E.G. index, power = find_peaks(ydata, yerror, min_peak_power=None, peak_distance_idx=10) peak_centres = xdata[index] # ordered by peak strength
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
array(n) of data |
required |
yerror
|
ndarray | None
|
array(n) of errors on data, or None to use default error function (sqrt(abs(y)+1)) |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
array(m) of estimated power of each peak |
Source code in mmg_toolbox/utils/fitting.py
find_peaks_str(x, y, yerror=None, min_peak_power=None, peak_distance_idx=6)
¶
Find peak shaps in linear-spaced 1d arrays with poisson like numerical values
E.G. index, power = find_peaks(ydata, yerror, min_peak_power=None, peak_distance_idx=10) peak_centres = xdata[index] # ordered by peak strength
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
array(n) of data |
required |
y
|
ndarray
|
array(n) of data |
required |
yerror
|
ndarray | None
|
array(n) of errors on data, or None to use default error function (sqrt(abs(y)+1)) |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
Returns:
| Type | Description |
|---|---|
str
|
array(m) of estimated power of each peak |
Source code in mmg_toolbox/utils/fitting.py
gauss(x, y=None, height=1, cen=0, fwhm=0.5, bkg=0, cen_y=None)
¶
Define Gaussian distribution in 1 or 2 dimensions
y[1xn] = gauss(x[1xn], height=10, cen=0, fwhm=1, bkg=0)
- OR -
Z[nxm] = gauss(x[1xn], y[1xm], height=100, cen=4, fwhm=5, bkg=30)
From http://fityk.nieto.pl/model.html
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
[1xn] array of values, defines size of gaussian in dimension 1 |
required |
y
|
ndarray | None
|
None* or [1xm] array of values, defines size of gaussian in dimension 2 |
None
|
height
|
float
|
peak height |
1
|
cen
|
float
|
peak centre |
0
|
fwhm
|
float
|
peak full width at half-max |
0.5
|
bkg
|
float
|
background |
0
|
cen_y
|
float | None
|
peak centre in y-axis (None to use cen) |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
[nxm array] 2D Gaussian distribution |
Source code in mmg_toolbox/utils/fitting.py
gen_weights(yerrors=None)
¶
Generate weights for fitting routines
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
yerrors
|
array(n) or None |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
array(n) or None |
Source code in mmg_toolbox/utils/fitting.py
generate_model(xvals, yvals, yerrors=None, npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None)
¶
Generate lmfit profile models See: https://lmfit.github.io/lmfit-py/builtin_models.html#example-3-fitting-multiple-peaks-and-using-prefixes E.G.: mod, pars = generate_model(x, y, npeaks=1, model='Gauss', backgroud='slope')
Peak Search: The number of peaks and initial peak centers will be estimated using the find_peaks function. If npeaks is given, the largest npeaks will be used initially. 'min_peak_power' and 'peak_distance_idx' can be input to tailor the peak search results. If the peak search returns < npeaks, fitting parameters will initially choose npeaks equally distributed points
Peak Models: Choice of peak model: 'Gaussian', 'Lorentzian', 'Voight',' PseudoVoight' Background Models: Choice of background model: 'slope', 'exponential'
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvals
|
ndarray
|
array(n) position data |
required |
yvals
|
ndarray
|
array(n) intensity data |
required |
yerrors
|
ndarray | None
|
None or array(n) - error data to pass to fitting function as weights: 1/errors^2 |
None
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str or lmfit.Model, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Model, Parameters]
|
model, parameters |
Source code in mmg_toolbox/utils/fitting.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 | |
generate_model_script(xvals, yvals, yerrors=None, npeaks=None, min_peak_power=None, peak_distance_idx=6, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None, only_lmfit=False)
¶
Generate script to create lmfit profile models E.G.: string = generate_mode_stringl(x, y, npeaks=1, model='Gauss', backgroud='slope')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvals
|
ndarray
|
array(n) position data |
required |
yvals
|
ndarray
|
array(n) intensity data |
required |
yerrors
|
ndarray
|
None or array(n) - error data to pass to fitting function as weights: 1/errors^2 |
None
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int
|
int, group adjacent maxima if closer in index than this |
6
|
model
|
str
|
str or lmfit.Model, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
only_lmfit
|
bool
|
if True, only include lmfit imports |
False
|
Returns:
| Type | Description |
|---|---|
str
|
str |
Source code in mmg_toolbox/utils/fitting.py
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 | |
group_adjacent(values, close=10)
¶
Average adjacent values in array, return grouped array and indexes to return groups to original array
E.G. grp, idx = group_adjacent([1,2,3,10,12,31], close=3) grp -> [2, 11, 31] idx -> [[0,1,2], [3,4], [5]]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ndarray
|
array of values to be grouped |
required |
close
|
float
|
float |
10
|
Returns:
| Type | Description |
|---|---|
|
[n] list of lists, each item relates to an averaged group, with indexes from values |
Source code in mmg_toolbox/utils/fitting.py
local_maxima_1d(y)
¶
Find local maxima in 1d array Returns points with central point higher than neighboring points.
Copied from scipy.signal._peak_finding_utils https://github.com/scipy/scipy/blob/v1.7.1/scipy/signal/_peak_finding_utils.pyx
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
list or array |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
array of peak indexes |
Source code in mmg_toolbox/utils/fitting.py
modelfit(xvals, yvals, yerrors=None, model=None | Model, initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit x,y data to a model from lmfit E.G.: res = modelfit(x, y, model='Gauss') print(res.fit_report()) res.plot() val = res.params['amplitude'].value err = res.params['amplitude'].stderr
Model: from lmfit import models model1 = model.GaussianModel() model2 = model.LinearModel() model = model1 + model2 res = model.fit(y, x=x)
Provide initial guess: res = modelfit(x, y, model=VoightModel(), initial_parameters={'center':1.23})
Fix parameter: res = modelfit(x, y, model=VoightModel(), fix_parameters={'sigma': fwhm/2.3548200})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvals
|
ndarray
|
array(n) position data |
required |
yvals
|
ndarray
|
array(n) intensity data |
required |
yerrors
|
ndarray | None
|
None or array(n) - error data to pass to fitting function as weights: 1/errors^2 |
None
|
model
|
lmfit.Model |
None | Model
|
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
method
|
str
|
str method name, from lmfit fitting methods |
'leastsq'
|
print_result
|
bool
|
if True, prints the fit results using fit.fit_report() |
False
|
plot_result
|
bool
|
if True, plots the results using fit.plot() |
False
|
Returns:
| Type | Description |
|---|---|
ModelResult
|
lmfit.model.ModelResult < fit results object |
Source code in mmg_toolbox/utils/fitting.py
multipeakfit(xvals, yvals, yerrors=None, npeaks=None, min_peak_power=None, peak_distance_idx=10, model='Gaussian', background='slope', initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit x,y data to a model with multiple peaks using lmfit See: https://lmfit.github.io/lmfit-py/builtin_models.html#example-3-fitting-multiple-peaks-and-using-prefixes
E.G.: res = multipeakfit(x, y, npeaks=None, model='Gauss', plot_result=True) val = res.params['p1_amplitude'].value err = res.params['p1_amplitude'].stderr
Peak Search: The number of peaks and initial peak centers will be estimated using the find_peaks function. If npeaks is given, the largest npeaks will be used initially. 'min_peak_power' and 'peak_distance_idx' can be input to tailor the peak search results. If the peak search returns < npeaks, fitting parameters will initially choose npeaks equally distributed points
Peak Models: Choice of peak model: 'Gaussian', 'Lorentzian', 'Voight',' PseudoVoight' Background Models: Choice of background model: 'slope', 'exponential'
Peak Parameters (%d=number of peak): Parameters in '.._parameters' dicts and in output results. Each peak (upto npeaks) has a set number of parameters: 'p%d_amplitude', 'p%d_center', 'p%d_dsigma', pvoight only: 'p%d_fraction' output only: 'p%d_fwhm', 'p%d_height' Background parameters: 'bkg_slope', 'bkg_intercept', or for exponential: 'bkg_amplitude', 'bkg_decay'
Provide initial guess: res = multipeakfit(x, y, model='Voight', initial_parameters={'p1_center':1.23})
Fix parameter: res = multipeakfit(x, y, model='gauss', fix_parameters={'p1_sigma': fwhm/2.3548200})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvals
|
ndarray
|
array(n) position data |
required |
yvals
|
ndarray
|
array(n) intensity data |
required |
yerrors
|
ndarray | None
|
None or array(n) - error data to pass to fitting function as weights: 1/errors^2 |
None
|
npeaks
|
int | None
|
None or int number of peaks to fit. None will guess the number of peaks |
None
|
min_peak_power
|
float | None
|
float, only return peaks with power greater than this. If None compare against std(y) |
None
|
peak_distance_idx
|
int | None
|
int, group adjacent maxima if closer in index than this |
10
|
model
|
str
|
str or lmfit.Model, specify the peak model 'Gaussian','Lorentzian','Voight' |
'Gaussian'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
method
|
str
|
str method name, from lmfit fitting methods |
'leastsq'
|
print_result
|
bool
|
if True, prints the fit results using fit.fit_report() |
False
|
plot_result
|
bool
|
if True, plots the results using fit.plot() |
False
|
Returns:
| Type | Description |
|---|---|
FitResults
|
FitResults object |
Source code in mmg_toolbox/utils/fitting.py
peak2dfit(xdata, ydata, image_data, initial_parameters=None, fix_parameters=None, print_result=False, plot_result=False)
¶
Fit Gaussian Peak in 2D *** requires lmfit > 1.0.3 *** Not yet finished!
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xdata
|
ndarray
|
|
required |
ydata
|
ndarray
|
|
required |
image_data
|
ndarray
|
|
required |
initial_parameters
|
dict | None
|
|
None
|
fix_parameters
|
dict | None
|
|
None
|
print_result
|
bool
|
|
False
|
plot_result
|
bool
|
|
False
|
Returns:
| Type | Description |
|---|---|
|
|
Source code in mmg_toolbox/utils/fitting.py
peak_ratio(y, yerror=None)
¶
Return the ratio signal / error for given dataset From Blessing, J. Appl. Cryst. (1997). 30, 421-426 Equ: (1) + (6) peak_ratio = (sum((y-bkg)/dy2)/sum(1/dy2)) / sqrt(i/sum(1/dy^2))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
ndarray
|
array of y data |
required |
yerror
|
ndarray | None
|
array of errors on data, or None to calcualte np.sqrt(y+0.001) |
None
|
Returns:
| Type | Description |
|---|---|
float
|
float ratio signal / err |
Source code in mmg_toolbox/utils/fitting.py
peak_results(res)
¶
Generate dict of fit results, including summed totals totals = peak_results(res) totals = { 'lmfit': lmfit_result (res), 'npeaks': number of peak models used, 'chisqr': Chi^2 of fit, 'xdata': x-data used for fit, 'ydata': y-data used for fit, 'yfit': y-fit values, 'weights': res.weights, 'yerror': 1 / res.weights if res.weights is not None else 0 * res.data, # plus data from components, e.g. 'p1_amplitude': Peak 1 area, 'p1_fwhm': Peak 1 full-width and half-maximum 'p1_center': Peak 1 peak position 'p1_height': Peak 1 fitted height, # plus data for total fit: 'amplitude': Total summed area, 'center': average centre of peaks, 'height': average height of peaks, 'fwhm': average FWHM of peaks, 'background': fitted background, # plut the errors on all parameters, e.g. 'stderr_amplitude': error on 'amplitude', }
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
ModelResult
|
lmfit fit result - ModelResult |
required |
Returns:
| Type | Description |
|---|---|
dict
|
{totals: (value, error)} |
Source code in mmg_toolbox/utils/fitting.py
peak_results_fit(res, ntimes=10, x_data=None)
¶
Generate xfit, yfit data, interpolated to give smoother variation
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
ModelResult
|
lmfit_result |
required |
ntimes
|
int
|
int, number of points * old number of points |
10
|
x_data
|
ndarray | None
|
x data to interpolate or None to use data from fit |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
xfit, yfit |
Source code in mmg_toolbox/utils/fitting.py
peak_results_plot(res, axes=None, xlabel=None, ylabel=None, title=None)
¶
Plot peak results
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
ModelResult
|
lmfit result |
required |
axes
|
None or matplotlib axes |
None
|
|
xlabel
|
str
|
None or str |
None
|
ylabel
|
str
|
None or str |
None
|
title
|
str
|
None or str |
None
|
Returns:
| Type | Description |
|---|---|
|
matplotlib figure or axes |
Source code in mmg_toolbox/utils/fitting.py
peak_results_str(res)
¶
Generate output str from lmfit results, including totals
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
|
ModelResult
|
lmfit_result |
required |
Returns:
| Type | Description |
|---|---|
str
|
str |
Source code in mmg_toolbox/utils/fitting.py
peakfit(xvals, yvals, yerrors=None, model='Voight', background='slope', initial_parameters=None, fix_parameters=None, method='leastsq', print_result=False, plot_result=False)
¶
Fit x,y data to a peak model using lmfit
E.G.: res = peakfit(x, y, model='Gauss') print(res) res.plot() val = res.params['amplitude'].value err = res.params['amplitude'].stderr
Peak Models: Choice of peak model: 'Gaussian', 'Lorentzian', 'Voight',' PseudoVoight' Background Models: Choice of background model: 'slope', 'exponential'
Peak Parameters: 'amplitude', 'center', 'sigma', pvoight only: 'fraction' output only: 'fwhm', 'height' Background parameters: 'bkg_slope', 'bkg_intercept', or for exponential: 'bkg_amplitude', 'bkg_decay'
Provide initial guess: res = peakfit(x, y, model='Voight', initial_parameters={'center': 1.23})
Fix parameter: res = peakfit(x, y, model='gauss', fix_parameters={'sigma': fwhm/2.3548200})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvals
|
ndarray
|
array(n) position data |
required |
yvals
|
ndarray
|
array(n) intensity data |
required |
yerrors
|
ndarray | None
|
None or array(n) - error data to pass to fitting function as weights: 1/errors^2 |
None
|
model
|
str
|
str, specify the peak model: 'Gaussian','Lorentzian','Voight' |
'Voight'
|
background
|
str
|
str, specify the background model: 'slope', 'exponential' |
'slope'
|
initial_parameters
|
dict | None
|
None or dict of initial values for parameters |
None
|
fix_parameters
|
dict | None
|
None or dict of parameters to fix at positions |
None
|
method
|
str
|
str method name, from lmfit fitting methods |
'leastsq'
|
print_result
|
bool
|
if True, prints the fit results using fit.fit_report() |
False
|
plot_result
|
bool
|
if True, plots the results using fit.plot() |
False
|
Returns:
| Type | Description |
|---|---|
FitResults
|
fit result object |
Source code in mmg_toolbox/utils/fitting.py
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |