def onSaveFitResult(self, event=None): deffile = self.datagroup.filename.replace('.', '_') + 'peak.modl' sfile = FileSave(self, 'Save Fit Model', default_file=deffile, wildcard=ModelWcards) if sfile is not None: result = self.get_fitresult() save_modelresult(result, sfile)
def test_saveload_modelresult_expression_model(): """Test for ModelResult.loads()/dumps() for ExpressionModel. * make sure that the loaded ModelResult has `init_params` and `init_fit`. """ savefile = 'expr_modres.txt' 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) y = y + np.random.normal(size=x.size, scale=0.01) 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) save_modelresult(result, savefile) time.sleep(0.25) result2 = load_modelresult(savefile) assert result2 is not None assert result2.init_fit is not None assert_allclose((result2.init_fit - result.init_fit).sum() + 1.00, 1.00, rtol=1.0e-2) os.unlink(savefile)
def test_save_load_modelresult(dill): """Save/load ModelResult with/without dill.""" if dill: pytest.importorskip("dill") else: lmfit.jsonutils.HAS_DILL = False # create model, perform fit, save ModelResult and perform some tests model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists text = '' with open(SAVE_MODELRESULT, 'r') as fh: text = fh.read() assert_between(len(text), 8000, 25000) # load the saved ModelResult from file and compare results result_saved = load_modelresult(SAVE_MODELRESULT) check_fit_results(result_saved) clear_savefile(SAVE_MODEL)
def test_save_load_modelresult(dill): """Save/load ModelResult with/without dill.""" if dill: pytest.importorskip("dill") else: lmfit.jsonutils.HAS_DILL = False # create model, perform fit, save ModelResult and perform some tests model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists text = '' with open(SAVE_MODELRESULT, 'r') as fh: text = fh.read() assert_between(len(text), 8000, 25000) # load the saved ModelResult from file and compare results result_saved = load_modelresult(SAVE_MODELRESULT) check_fit_results(result_saved) clear_savefile(SAVE_MODEL)
def onSaveFitResult(self, event=None): deffile = self.datagroup.filename.replace('.', '_') + 'peak.modl' sfile = FileSave(self, 'Save Fit Model', default_file=deffile, wildcard=ModelWcards) if sfile is not None: result = self.get_fitresult() save_modelresult(result, sfile)
def test_saveload_usersyms(): """Test save/load of modelresult with non-trivial user symbols, this example uses a VoigtModel, wheree `wofz()` is used in a constraint expression""" x = np.linspace(0, 20, 501) y = gaussian(x, 1.1, 8.5, 2) + lorentzian(x, 1.7, 8.5, 1.5) np.random.seed(20) y = y + np.random.normal(size=len(x), scale=0.025) model = VoigtModel() pars = model.guess(y, x=x) result = model.fit(y, pars, x=x) savefile = 'tmpvoigt_modelresult.sav' save_modelresult(result, savefile) assert_param_between(result.params['sigma'], 0.7, 2.1) assert_param_between(result.params['center'], 8.4, 8.6) assert_param_between(result.params['height'], 0.2, 1.0) time.sleep(0.25) result2 = load_modelresult(savefile) assert_param_between(result2.params['sigma'], 0.7, 2.1) assert_param_between(result2.params['center'], 8.4, 8.6) assert_param_between(result2.params['height'], 0.2, 1.0)
def FitSpectrumInit(self, label): """ Fit the spectrum with the fit params of another spectrum (given by label) as initial values. Useful when you fit big number of similar spectra. """ borders = np.genfromtxt(label + '/spectrumborders_' + label + '.txt', unpack=True) np.savetxt(self.label + '/spectrumborders_' + self.label + '.txt', borders) self.y = self.y[(self.x > borders[0]) & (self.x < borders[-1])] self.x = self.x[(self.x > borders[0]) & (self.x < borders[-1])] FitData = np.load(label + '/fitparams_' + label + '.npz') baseline = FitData['c'] / self.maxyvalue ctr = FitData['x0'] sigma = FitData['sigma'] gamma = FitData['gamma'] ramanmodel = ConstantModel() ramanmodel.set_param_hint('c', value=baseline[0], min=0) for i in range(len(sigma)): prefix = 'p' + str(i + 1) tempvoigt = Model(func=voigt, prefix=prefix) tempvoigt.set_param_hint(prefix + 'x0', value=ctr[i], min=0) tempvoigt.set_param_hint(prefix + 'sigma', value=sigma[i], min=0) tempvoigt.set_param_hint(prefix + 'gamma', value=gamma[i], min=0) tempvoigt.set_param_hint(prefix + 'height', expr='wofz(((0) + 1j*' + prefix + 'gamma) / ' + prefix + 'sigma / sqrt(2)).real') tempvoigt.set_param_hint(prefix + 'fwhm', expr='0.5346 * 2 *' + prefix + 'gamma + sqrt(0.2166 * (2*' + prefix + 'gamma)**2 + (2 * ' + prefix + 'sigma * sqrt(2 * log(2) ) )**2 )') ramanmodel += tempvoigt pars = ramanmodel.make_params() fitresult = ramanmodel.fit(self.y, pars, x=self.x, scale_covar=True) plt.clf() comps = fitresult.eval_components() xplot = np.linspace(self.x[0], self.x[-1], 1000) plt.plot(self.x, self.y * self.maxyvalue, 'r-') plt.plot(self.x, fitresult.best_fit * self.maxyvalue) for i in range(0, len(sigma)): plt.plot( self.x, comps['p' + str(i + 1)] * self.maxyvalue + comps['constant'] * self.maxyvalue, 'k-') plt.savefig(self.label + '/rawplot_' + self.label + '.pdf') save_modelresult(fitresult, self.label + '/modelresult_' + self.label + '.sav') plt.clf()
def FitSpectrum(self): """ Fit Spectrum with initial values provided by SelectBaseline() and SelectPeaks() """ polyparams = self.Fitbaseline(self) base = polyparams[0].n ramanmodel = ConstantModel() ramanmodel.set_param_hint('c', value=base, min=0) globwidth = 1 xpeak, ypeak = np.genfromtxt(self.peakfile, unpack=True) if type(xpeak) == np.float64: xpeak = [xpeak] ypeak = [ypeak] for i in range(0, len(xpeak)): prefix = 'p' + str(i + 1) tempvoigt = Model(func=voigt, prefix=prefix) tempvoigt.set_param_hint(prefix + 'x0', value=xpeak[i], min=0) tempvoigt.set_param_hint(prefix + 'sigma', value=globwidth, min=0) tempvoigt.set_param_hint(prefix + 'gamma', value=globwidth, min=0) tempvoigt.set_param_hint(prefix + 'height', value=ypeak[i], expr='wofz(((0) + 1j*' + prefix + 'gamma) / ' + prefix + 'sigma / sqrt(2)).real') tempvoigt.set_param_hint(prefix + 'fwhm', expr='0.5346 * 2 *' + prefix + 'gamma + sqrt(0.2166 * (2*' + prefix + 'gamma)**2 + (2 * ' + prefix + 'sigma * sqrt(2 * log(2) ) )**2 )') ramanmodel += tempvoigt pars = ramanmodel.make_params() fitresult = ramanmodel.fit(self.y, pars, x=self.x, scale_covar=True) print(fitresult.fit_report(min_correl=0.5)) comps = fitresult.eval_components() xplot = np.linspace(self.x[0], self.x[-1], 1000) plt.plot(self.x, self.y * self.maxyvalue, 'rx') plt.plot(self.x, fitresult.best_fit * self.maxyvalue) for i in range(0, len(xpeak)): plt.plot( self.x, comps['p' + str(i + 1)] * self.maxyvalue + comps['constant'] * self.maxyvalue, 'k-') plt.show() plt.savefig(self.label + '/rawplot_' + self.label + '.pdf') save_modelresult(fitresult, self.label + '/modelresult_' + self.label + '.sav')
def autosave_modelresult(self, result, fname=None): """autosave model result to user larch folder""" confdir = os.path.join(site_config.usr_larchdir, 'xas_viewer') if not os.path.exists(confdir): try: os.makedirs(confdir) except OSError: print("Warning: cannot create XAS_Viewer user folder") return if not HAS_MODELSAVE: print("Warning: cannot save model results: upgrade lmfit") return if fname is None: fname = 'autosave.fitmodel' save_modelresult(result, os.path.join(confdir, fname))
def autosave_modelresult(self, result, fname=None): """autosave model result to user larch folder""" confdir = os.path.join(site_config.usr_larchdir, 'xas_viewer') if not os.path.exists(confdir): try: os.makedirs(confdir) except OSError: print("Warning: cannot create XAS_Viewer user folder") return if not HAS_MODELSAVE: print("Warning: cannot save model results: upgrade lmfit") return if fname is None: fname = 'autosave.fitmodel' save_modelresult(result, os.path.join(confdir, fname))
def do_save_modelresult(with_dill=True): x, y = XDAT, YDAT if DILL_AVAILABLE and with_dill: lmfit.jsonutils.HAS_DILL = True else: lmfit.jsonutils.HAS_DILL = False model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert(file_exists) text = '' with open(SAVE_MODELRESULT, 'r') as fh: text = fh.read() assert_between(len(text), 8000, 25000)
def test_savelod_modelresult_items(): clear_savefile(SAVE_MODELRESULT) x, y = XDAT, YDAT model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) time.sleep(0.25) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert(file_exists) time.sleep(0.25) loaded = load_modelresult(SAVE_MODELRESULT) assert(len(result.data) == len(loaded.data)) assert(abs(max(result.data) - max(loaded.data)) < 0.001) for pname in result.params.keys(): assert( abs(result.init_params[pname].value - loaded.init_params[pname].value) < 0.001)
def test_saveload_modelresult_attributes(): """Test for restoring all attributes of the ModelResult.""" model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) time.sleep(0.25) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists time.sleep(0.25) loaded = load_modelresult(SAVE_MODELRESULT) assert len(result.data) == len(loaded.data) assert_allclose(result.data, loaded.data) for pname in result.params.keys(): assert_allclose(result.init_params[pname].value, loaded.init_params[pname].value) clear_savefile(SAVE_MODELRESULT)
def test_saveload_modelresult_attributes(): """Test for restoring all attributes of the ModelResult.""" model, params = create_model_params(x, y) result = model.fit(y, params, x=x) save_modelresult(result, SAVE_MODELRESULT) time.sleep(0.25) file_exists = wait_for_file(SAVE_MODELRESULT, timeout=10) assert file_exists time.sleep(0.25) loaded = load_modelresult(SAVE_MODELRESULT) assert len(result.data) == len(loaded.data) assert_allclose(result.data, loaded.data) for pname in result.params.keys(): assert_allclose(result.init_params[pname].value, loaded.init_params[pname].value) clear_savefile(SAVE_MODELRESULT)
#!/usr/bin/env python # <examples/doc_model_savemodelresult.py> import matplotlib.pyplot as plt import numpy as np from lmfit.model import save_modelresult from lmfit.models import GaussianModel data = np.loadtxt('model1d_gauss.dat') x = data[:, 0] y = data[:, 1] gmodel = GaussianModel() result = gmodel.fit(y, x=x, amplitude=5, center=5, sigma=1) save_modelresult(result, 'gauss_modelresult.sav') print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_savemodelresult.py>
with open(str(OUTPATH) + "_fit-report.txt", "w") as f: f.write(result.fit_report()) with open(str(OUTPATH) + "_fit-params.txt", "w") as f, redirect_stdout(f): print(to_dataframe(result.params)) if args.conf_interval is not None: print("Calculating confidence intervals (this takes a while)...", end="") ci_kwargs = dict(verbose=args.verbose) if args.conf_interval: ci_kwargs.update(dict(sigmas=args.conf_interval)) result.conf_interval(**ci_kwargs) print("...done.") print(result.ci_report(ndigits=10)) save_modelresult(result, str(OUTPATH) + "_model-result.json") if args.emcee: print("Calculating posteriors with emcee...") mcmc_result = model.fit( data=np.array([ic_p, ic_n]).flatten() if config.getboolean("BOTH_BRANCHES") else ic_p, weights=1 / uncertainty, bfield=bfield, params=result.params, # nan_policy="omit", method="emcee", fit_kws=dict(steps=1000, nwalkers=100, burn=200, thin=10,
def gFit(self, cfg_par): key = 'general' workDir = cfg_par[key]['workdir'] #open line lineList lineInfo = tP.openLineList(cfg_par) diffusion = 1e-5 #open table for bins wave, xAxis, yAxis, pxSize, noiseBin, vorBinInfo = tP.openTablesPPXF( cfg_par, workDir + cfg_par[key]['outVorTableName'], workDir + cfg_par[key]['tableSpecName']) #open datacube f = fits.open(cfg_par[key]['cubeDir'] + cfg_par[key]['dataCubeName']) hh = f[0].header dd = f[0].data #define x-axis array lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) Ydim = dd.shape[1] Xdim = dd.shape[2] binID, binArr, fitResArr, lineArr = tP.makeInputArrays( cfg_par, lineInfo, Xdim, Ydim) counter = 0 #for j in range(205,208): # for i in range(250,252): for j in range(0, dd.shape[1]): for i in range(0, dd.shape[2]): y = dd[idxMin:idxMax, j, i] waveCut = wave[idxMin:idxMax] #check if spectrum is not empty if np.sum(y) > 0: gMod, gPars = self.lineModDef(cfg_par, waveCut, y, lineInfo) # identify voronoi bin xVal = xAxis[i] yVal = yAxis[j] index = np.where( (vorBinInfo['X'] < (xVal + pxSize / 2. + diffusion)) & ((xVal - pxSize / 2. - diffusion) < vorBinInfo['X']) & (vorBinInfo['Y'] < (yVal + pxSize / 2. + diffusion)) & ((yVal - pxSize / 2. - diffusion) < vorBinInfo['Y'])) if np.sum(index) > 0: binArr = tP.updateBinArray(cfg_par, binArr, vorBinInfo, index, i, j, counter) binIDName = binArr['BIN_ID'][counter] else: #fitResArr = np.delete(fitResArr,counter,0) #lineArr = np.delete(lineArr,counter,0) counter += 1 continue #check if it is first time in bin if binIDName not in binID[:, :] and np.sum(index) > 0: binID[j, i] = binIDName noiseVec = noiseBin[binIDName][:] # FIT result = gMod.fit(y, gPars, x=waveCut) save_modelresult( result, cfg_par['general']['modNameDir'] + str(binIDName) + '_' + cfg_par['gFit']['modName'] + '.sav') fitResArr = tP.updateFitArray(cfg_par, fitResArr, result, binIDName, counter) lineArr = tP.updateLineArray(cfg_par, lineArr, result, lineInfo, binIDName, counter) #plot Fit if cfg_par['gPlot']['enable'] == True: #self.plotSpecFit(waveCut, y,result,noiseVec[idxMin:idxMax],i,j,lineInfo,vorBinInfo[index]) sP.plotLineZoom(cfg_par, waveCut, y, result, noiseVec[idxMin:idxMax], i, j, lineInfo, vorBinInfo[index]) counter += 1 match_indices = np.where(binArr['BIN_ID'] == 0.0)[0] binArr = np.delete(binArr, match_indices, 0) match_indices = np.where(fitResArr['BIN_ID'] == 0.0)[0] fitResArr = np.delete(fitResArr, match_indices, 0) match_indices = np.where(lineArr['BIN_ID'] == 0)[0] lineArr = np.delete(lineArr, match_indices, 0) #print 'end_for' tP.saveOutputTable(cfg_par, binArr, fitResArr, lineArr) print('''\t+---------+\n\t gFit done\n\t+---------+''') return 0
def gFitMp(cfg_par, lineInfo, vorBinInfo, wave, dd, noiseBin, counter, ii, ubins, binArr, fitResArr, lineArr): ''' Fits the spectrum of a single Voronoi bin a model of 1 or multiple gaussians Parameters: cfg_par - configuration file lineInfo - array with columns of lineList.txt file vorBinInfo - array of table of voronoi binned datacube wave - x-axis of spectrum in log(lambda) units dd - datacube noiseBin - voronoi binned noise cube counter - step of multiprocess loop ubins - array of BINID binArr - array where to store information about bins fitResArr - array where to store information about fit results lineArr - array where to store best fit parameters of the multi-gaussian model Returns: binArr fitResArr lineArr ''' match_bin = np.where(ubins[ii] == vorBinInfo['BIN_ID'])[0] index = match_bin[0] j = int(vorBinInfo['PixY'][index]) i = int(vorBinInfo['PixX'][index]) lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) Ydim = int(dd.shape[1]) Xdim = int(dd.shape[2]) y = dd[idxMin:idxMax, j, i] waveCut = wave[idxMin:idxMax] all_zeros = not np.all(y) if not np.isnan(y).all() and all_zeros != True: gMod, gPars = lineModDefMp(cfg_par, waveCut, y, lineInfo) if np.sum(index) > 0: binArr = tP.updateBinArray(cfg_par, binArr, vorBinInfo, index, i, j, counter) binIDName = vorBinInfo['BIN_ID'][index] else: fitResArr = np.delete(fitResArr, counter, 0) lineArr = np.delete(lineArr, counter, 0) counter += 1 return counter, binArr, fitResArr, lineArr #print(noiseBin.shape,binIDName) noiseMinRed = cfg_par['general']['redshift'] * cfg_par['gFit'][ 'noiseMin'] + cfg_par['gFit']['noiseMin'] noiseMaxRed = cfg_par['general']['redshift'] * cfg_par['gFit'][ 'noiseMin'] + cfg_par['gFit']['noiseMin'] indexNoiseMinRed = int( np.where( abs(np.exp(waveCut) - noiseMinRed) == abs(np.exp(waveCut) - noiseMinRed).min())[0]) indexNoiseMaxRed = int( np.where( abs(np.exp(waveCut) - noiseMaxRed) == abs(np.exp(waveCut) - noiseMaxRed).min())[0]) noiseVec = np.nanstd(dd[indexNoiseMinRed:indexNoiseMaxRed, j, i]) noiseVec = np.zeros(len(wave)) + noiseVec # FIT result = gMod.fit(y, gPars, x=waveCut) save_modelresult( result, cfg_par['general']['modNameDir'] + str(binIDName) + '_' + cfg_par['gFit']['modName'] + '.sav') fitResArr = tP.updateFitArray(cfg_par, fitResArr, result, binIDName, counter) lineArr = tP.updateLineArray(cfg_par, waveCut, lineArr, result, noiseVec[idxMin], lineInfo, binIDName, counter) #plot Fit if cfg_par['gPlot']['enable'] == True: sP.plotLineZoom(cfg_par, waveCut, y, result, noiseVec[idxMin:idxMax], i, j, lineInfo, vorBinInfo[index]) counter += 1 return counter, binArr, fitResArr, lineArr
def plotSingleBin(self, cfg_par, binID, doFit=False): key = 'general' workDir = cfg_par[key]['workdir'] cubeDir = cfg_par[key]['cubeDir'] #open datacube f = fits.open(cfg_par[key]['dataCubeName']) dd = f[0].data f.close() #open datacube if cfg_par['gFit']['method'] != 'pixel': f = fits.open(cfg_par[key]['outVorNoise']) nn = f[0].data f.close() lineInfo = tP.openLineList(cfg_par) #open table for bins wave, xAxis, yAxis, pxSize, noiseBin, vorBinInfo, dataSpec = tP.openVorLineOutput( cfg_par, cfg_par['general']['outVorLineTableName'], cfg_par['general']['outVorSpectra']) hdul = fits.open(cfg_par['general']['outVorLineTableName']) tabGen = hdul[1].data lambdaMin = np.log(cfg_par['gFit']['lambdaMin']) lambdaMax = np.log(cfg_par['gFit']['lambdaMax']) idxMin = int( np.where(abs(wave - lambdaMin) == abs(wave - lambdaMin).min())[0]) idxMax = int( np.where(abs(wave - lambdaMax) == abs(wave - lambdaMax).min())[0]) idxTable = int(np.where(tabGen['BIN_ID'] == int(binID))[0][0]) y = dd[idxMin:idxMax, int(tabGen['PixY'][idxTable]), int(tabGen['PixX'][idxTable])] all_zeros = not np.any(y) waveCut = wave[idxMin:idxMax] if doFit == False and os.path.exists(cfg_par[key]['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav'): result = load_modelresult(cfg_par[key]['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav') elif doFit == True: print('''\t+---------+\n\t ...fitting...\n\t+---------+''') gMod, gPars = self.lineModDef(cfg_par, waveCut, y, lineInfo) all_zeros = not np.any(y) if all_zeros != True: result = gMod.fit(y, gPars, x=waveCut) vals = result.params.valuesdict() save_modelresult( result, cfg_par['general']['modNameDir'] + str(binID) + '_' + cfg_par['gFit']['modName'] + '.sav') else: print('''\t+---------+\n\t spectrum is empty\n\t+---------+''') print('''\t+---------+\n\t EXIT with ERROR\n\t+---------+''') sys.exit(0) cfg_par['gPlot']['loadModel'] = True if cfg_par['gFit']['method'] != 'pixel': noiseVec = nn[idxMin:idxMax, int(tabGen['PixY'][idxTable]), int(tabGen['PixX'][idxTable])] else: noiseVec = np.zeros(len(waveCut)) #noiseVec[idxMin:idxMax] -= np.nanmedian(noiseVec[idxMin:idxMax]) #print(np.nanmean(noiseVec[idxMin:idxMax]),noiseVec[idxMin:idxMax]) #print(np.nanmean(y),y) #plot Fit #self.plotSpecFit(waveCut, y,result,noiseVec[idxMin:idxMax],i,j,tab,vorBinInfo[index]) print('''\t+---------+\n\t ...plotting...\n\t+---------+''') sP.plotLineZoom(cfg_par, waveCut, y, result, noiseVec, int(tabGen['PixX'][idxTable]), int(tabGen['PixY'][idxTable]), lineInfo, tabGen[:][idxTable]) print('''\t+---------+\n\t bin Plotted\n\t+---------+''') return 0
def save_fit_result(self, fitresult, outfile): """saves a customized ModelResult""" save_modelresult(fitresult, outfile)
pars['cen2'].set(value=1.5, vary=True, min=1.5, max=2.0) pars['wid2'].set(2.75, min=fwhm(0.8), max=fwhm(0.2)) pars['ampA3'].set(value=-1) pars['ampB3'].set(value=5, vary=True) pars['cen3'].set(value=peak3[1], vary=False) pars['wid3'].set(1, min=0, max=10) pars['ampA4'].set(value=2) pars['ampB4'].set(value=0, vary=True, min=-8, max=4) pars['cen4'].set(value=3.5, vary=True, min=2.8, max=5) pars['wid4'].set(3, min=fwhm(2), max=fwhm(0.5)) print(pars) # init_fit = ab_term_model_total.eval(pars, x=x) fitting_result = ab_term_model_total.fit(y, pars, x=x) save_modelresult(fitting_result, material + '_' + peak_count + 'peak_params' + '.sav') print(fitting_result.fit_report(min_correl=0.5)) wid_list = [] cen_list = [] param_list = [] # print('-------------------------------') # print('Parameter Value Stderr') for name, param in fitting_result.params.items(): # print('{:7s} {:11.5f} {:11.5f}'.format(name, param.value, param.stderr)) if 'cen' in name: cen_list.append(param.value) elif 'wid' in name: wid_list.append(getSigma(getFWHM(param.value)))
# <examples/doc_model_savemodelresult.py> import matplotlib.pyplot as plt import numpy as np from lmfit.model import save_modelresult from lmfit.models import GaussianModel data = np.loadtxt('model1d_gauss.dat') x = data[:, 0] y = data[:, 1] gmodel = GaussianModel() result = gmodel.fit(y, x=x, amplitude=5, center=5, sigma=1) save_modelresult(result, 'gauss_modelresult.sav') print(result.fit_report()) plt.plot(x, y, 'bo') plt.plot(x, result.init_fit, 'k--') plt.plot(x, result.best_fit, 'r-') plt.show() # <end examples/doc_model_savemodelresult.py>
dat = np.loadtxt('NIST_Gauss2.dat') x = dat[:, 1] y = dat[:, 0] exp_mod = ExponentialModel(prefix='exp_') pars = exp_mod.guess(y, x=x) gauss1 = GaussianModel(prefix='g1_') pars.update(gauss1.make_params()) pars['g1_center'].set(value=105, min=75, max=125) pars['g1_sigma'].set(value=15, min=3) pars['g1_amplitude'].set(value=2000, min=10) gauss2 = GaussianModel(prefix='g2_') pars.update(gauss2.make_params()) pars['g2_center'].set(value=155, min=125, max=175) pars['g2_sigma'].set(value=15, min=3) pars['g2_amplitude'].set(value=2000, min=10) mod = gauss1 + gauss2 + exp_mod init = mod.eval(pars, x=x) result = mod.fit(y, pars, x=x) save_modelresult(result, 'nistgauss_modelresult.sav') print(result.fit_report()) # <end examples/doc_model_savemodelresult2.py>