def Fit(self): """Run the fitting code.""" self.Discard().Normalise().offset_correct() chi2= self.p0.shape[0]>1 method=getattr(self,self.method) if not chi2: # Single fit mode, consider whether to plot and save etc fit=method(self.model,p0=self.p0,result=True,header="Fit",output="report") if self.show_plot: self.plot_results() if self.save_fit: self.save(False) if self.report: print(fit.fit_report()) return fit else: #chi^2 mapping mode d=Data(self) fit = d.lmfit(self.model, p0=self.p0, result=True, header="Fit", output="data") if self.show_plot: fit.plot(multiple="panels",capsize=3) fit.yscale = "log" # Adjust y scale for chi^2 fit.tight_layout() if self.save_fit: fit.filename=None fit.save(False)
def Fit(self): """Run the fitting code.""" self.Discard().Normalise().offset_correct() chi2 = self.p0.shape[0] > 1 method = getattr(self, self.method) if not chi2: # Single fit mode, consider whether to plot and save etc fit = method( self.model, p0=self.p0, result=True, header="Fit", output="report", ) if self.show_plot: self.plot_results() if self.save_fit: self.save(False) if self.report: print(fit.fit_report()) return fit d = Data(self) fit = d.lmfit( self.model, p0=self.p0, result=True, header="Fit", output="data" ) if self.show_plot: fit.plot(multiple="panels", capsize=3) fit.yscale = "log" # Adjust y scale for chi^2 fit.tight_layout() if self.save_fit: fit.filename = None fit.save(False)
class AnalysisMixins_test(unittest.TestCase): """Path to sample Data File""" datadir = path.join(pth, "sample-data") def setUp(self): x_data = np.linspace(-10, 10, 101) y_data = 0.01 * x_data**2 + 0.3 * x_data - 2 y_data *= np.random.normal(size=101, loc=1.0, scale=0.01) x_data += np.random.normal(size=101, scale=0.02) self.data = Data(x_data, y_data, column_headers=["X", "Y"]) self.data.setas = "xy" def test_cuve_fit(self): for output, fmt in zip(["fit", "row", "full", "dict", "data"], [tuple, np.ndarray, tuple, dict, Data]): res = self.data.curve_fit(fit, p0=[0.02, 0.2, 2], output=output) self.assertTrue( isinstance(res, fmt), "Failed to get expected output from curve_fit for {} (got {})". format(output, type(res))) def test_lmfit(self): for output, fmt in zip(["fit", "row", "full", "dict", "data"], [tuple, np.ndarray, tuple, dict, Data]): res = self.data.lmfit(fit, p0=[0.02, 0.2, 2], output=output) self.assertTrue( isinstance(res, fmt), "Failed to get expected output from lmfit for {} (got {})". format(output, type(res))) def test_odr(self): for output, fmt in zip(["fit", "row", "full", "dict", "data"], [tuple, np.ndarray, tuple, dict, Data]): res = self.data.odr(fit, p0=[0.02, 0.2, 2], output=output) self.assertTrue( isinstance(res, fmt), "Failed to get expected output from idr for {} (got {})". format(output, type(res))) def test_differential_evolution(self): for output, fmt in zip(["fit", "row", "full", "dict", "data"], [tuple, np.ndarray, tuple, dict, Data]): res = self.data.differential_evolution(fit, p0=[0.02, 0.2, 2], output=output) self.assertTrue( isinstance(res, fmt), "Failed to get expected output from differential_evolution for {} (got {})" .format(output, type(res)))
from numpy import linspace, ones_like from numpy.random import normal from copy import deepcopy T = linspace(4.2, 300, 101) params = [265, 65, 1.0, 5] params2 = deepcopy(params) G = SF.blochGrueneisen(T, *params) + normal(size=len(T), scale=5E-5) dG = ones_like(T) * 5E-5 d = Data(T, G, dG, setas="xye", column_headers=["Temperature (K)", "Resistivity", "dR"]) d.curve_fit(SF.blochGrueneisen, p0=params, result=True, header="curve_fit") d.setas = "xy" d.lmfit(SF.BlochGrueneisen, p0=params2, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(SF.blochGrueneisen, x=20, y=65.05, fontdict={"size": "x-small"}) d.annotate_fit(SF.BlochGrueneisen, x=100, y=65, fontdict={"size": "x-small"}, prefix="BlochGrueneisen") d.title = "Bloch-Grueneisen Fit" d.tight_layout()
sensitivity=50 critical_edge=0.8 fringe_offset=1 d=Data(filename,setas="xy") #Load the low angle scan #Now get the section of the data file that has the peak positions # This is really doing the hard work # We differentiate the data using a Savitsky-Golay filter with a 5 point window fitting quartics. # This has proved most succesful for me looking at some MdV data. # We then threshold for zero crossing of the derivative # And check the second derivative to see whether we like the peak as signficant. This is the significance parameter # and seems to be largely empirical # Finally we interpolate back to the complete data set to make sure we get the angle as well as the counts. d.lmfit(ExponentialModel,result=True,replace=False,header="Envelope") d.subtract("Counts","Envelope",replace=False,header="peaks") d.setas="xy" sys.exit() t=Data(d.interpolate(d.peaks(significance=sensitivity,width=8,poly=4))) t.column_headers=copy(d.column_headers) d%='peaks' t%='peaks' d.setas="xy" d.labels[d.find_col('Angle')]=r"Reflection Angle $\theta$" t.del_rows(0, lambda x,y: x<critical_edge) t.setas="xy" t.template.fig_width=7.0 t.template.fig_height=5.0 t.plot(fmt='go', plotter=pyplot.semilogy)
d.setas = "xy" d.curve_fit(SF.quadratic, result=True, header="Curve-fit") d.setas = "x...y" d.plot(fmt="b-", label="curve-fit") d.annotate_fit( SF.quadratic, prefix="quadratic", x=0.2, y=0.65, fontdict={"size": "x-small", "color": "blue"}, ) d.setas = "xy" fit = SF.Quadratic() p0 = fit.guess(y, x=x) d.lmfit(SF.Quadratic, p0=p0, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-", label="lmfit") d.annotate_fit( SF.Quadratic, prefix="Quadratic", x=0.65, y=0.65, fontdict={"size": "x-small", "color": "green"}, ) d.title = "Qudratic Fitting" plt.legend(loc=4)
sensitivity = 50 critical_edge = 0.8 fringe_offset = 1 d = Data(filename, setas="xy") # Load the low angle scan # Now get the section of the data file that has the peak positions # This is really doing the hard work # We differentiate the data using a Savitsky-Golay filter with a 5 point window fitting quartics. # This has proved most succesful for me looking at some MdV data. # We then threshold for zero crossing of the derivative # And check the second derivative to see whether we like the peak as signficant. This is the significance parameter # and seems to be largely empirical # Finally we interpolate back to the complete data set to make sure we get the angle as well as the counts. d.lmfit(ExponentialModel, result=True, replace=False, header="Envelope") d.subtract("Counts", "Envelope", replace=False, header="peaks") d.setas = "xy" sys.exit() t = Data(d.interpolate(d.peaks(significance=sensitivity, width=8, poly=4))) t.column_headers = copy(d.column_headers) d %= "peaks" t %= "peaks" d.setas = "xy" d.labels[d.find_col("Angle")] = r"Reflection Angle $\theta$" t.del_rows(0, lambda x, y: x < critical_edge) t.setas = "xy" t.template.fig_width = 7.0 t.template.fig_height = 5.0 t.plot(fmt="go", plotter=pyplot.semilogy)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Fit Ic(B) to Airy function. """ from Stoner import Data, __home__ from Stoner.Fit import Ic_B_Airy import os os.chdir(os.path.join(__home__, "..", "doc", "samples", "Fitting")) data = Data("data/Ic_B.txt", setas={"x": "Magnet Output", "y": "Ic"}) data.lmfit(Ic_B_Airy, result=True, header="Fit") data.setas = {"x": "Magnet Output", "y": ["Ic", "Fit"]} data.plot(fmt=["r+", "b-"]) data.annotate_fit(Ic_B_Airy, mode="eng", x=0.6, y=0.5, fontsize="small") data.title = "Critical current vs Field for $4\mu m$ junction" data.xlabel = r"Magnetic Field $\mu_0H (\mathrm{T})$" data.ylabel = r"Critical Current $I_c (A)$"
R = vftEquation(T, *params) * normal(size=len(T), scale=noise, loc=1.0) dR = vftEquation(T, *params) * noise d = Data(T, R, dR, setas="xy.", column_headers=["T", "Rate"]) # Plot the data points. d.plot(fmt="r.", label="Data Points") # Turn on the sigma column (error bars look messy on plot due to logscale) d.setas[2] = "e" # Curve_fit on its own d.curve_fit(vftEquation, p0=params, result=True, header="curve_fit") # lmfit uses some guesses p0 = params d.lmfit(VFTEquation, p0=p0, result=True, header="lmfit") # Plot these results too d.setas = "x..yy" d.plot(fmt=["b-", "g-"]) # Annotate the graph d.annotate_fit( vftEquation, x=0.25, y=0.35, fontdict={"size": "x-small", "color": "blue"}, mode="eng", ) d.annotate_fit( VFTEquation, x=0.5,
result.e = result.e / mu_0 resfldr += result # Stash the results # Merge the two field signs into a single file, taking care of the error columns too result = resfldr[0].clone for c in [0, 2, 4, 6, 8, 9, 10]: result.data[:, c] = (resfldr[1][:, c] + resfldr[0][:, c]) / 2.0 for c in [1, 3, 5, 7]: result.data[:, c] = gmean((resfldr[0][:, c], resfldr[1][:, c]), axis=0) # Doing the Kittel fit with an orthogonal distance regression as we have x errors not y errors p0 = [2, 200e3, 10e3] # Some sensible guesses result.lmfit(Inverse_Kittel, p0=p0, result=True, header="Kittel Fit", output="report") result.setas[-1] = "y" result.template.yformatter = TexEngFormatter result.template.xformatter = TexEngFormatter result.labels = None result.figure(figsize=(6, 8)) result.subplot(211) result.plot(fmt=["r.", "b-"]) result.annotate_fit(Inverse_Kittel, x=7e9, y=1e5, fontdict={"size": 8}) result.ylabel = "$H_{res} \\mathrm{(Am^{-1})}$" result.title = "Inverse Kittel Fit" # Get alpha
@simple_model.guesser def guess_vals(y, x=None): """Should guess parameter values really!""" m = (y.max() - y.min()) / (x[y.argmax()] - x[y.argmin()]) c = x.mean() * m - y.mean() # return one value per parameter return [m, c] # Add a function to sry vonstraints on parameters (optional) @simple_model.hinter def hint_parameters(): """Five some hints about the parameter.""" return {"m": {"max": 10.0, "min": 0.0}, "c": {"max": 5.0, "min": -5.0}} # Create some x,y data x = linspace(0, 10, 101) y = 4.5 * x - 2.3 + normal(scale=0.4, size=len(x)) # Make The Data object d = Data(x, y, setas="xy", column_headers=["X", "Y"]) # Do the fit d.lmfit(simple_model, result=True) # Plot the result d.setas = "xyy" d.plot(fmt=["r+", "b-"]) d.title = "Simple Model Fit" d.annotate_fit(simple_model, x=0.05, y=0.5)
"""Simple use of lmfit to fit data.""" from Stoner import Data from numpy import linspace, exp, random #Make some data x = linspace(0, 10.0, 101) y = 2 + 4 * exp(-x / 1.7) + random.normal(scale=0.2, size=101) d = Data(x, y, column_headers=["Time", "Signal"], setas="xy") #Do the fitting and plot the result func = lambda x, A, B, C: A + B * exp(-x / C) fit = d.lmfit(func, result=True, header="Fit", A=1, B=1, C=1, residuals=True) #Reset labels d.labels = [] # Make nice two panel plot layout ax = d.subplot2grid((3, 1), (2, 0)) d.setas = "x..y" d.plot(fmt="g+") d.title = "" ax = d.subplot2grid((3, 1), (0, 0), rowspan=2) d.setas = "xyy" d.plot(fmt=["ro", "b-"]) d.xticklabels = [[]] d.xlabel = "" # Annotate plot with fitting parameters d.annotate_fit(func,
result.y = result.y / mu_0 # Convert to A/m result.e = result.e / mu_0 resfldr += result # Stash the results # Merge the two field signs into a single file, taking care of the error columns too result = resfldr[0].clone for c in [0, 2, 4, 6, 8, 9, 10]: result.data[:, c] = (resfldr[1][:, c] + resfldr[0][:, c]) / 2.0 for c in [1, 3, 5, 7]: result.data[:, c] = gmean((resfldr[0][:, c], resfldr[1][:, c]), axis=0) # Doing the Kittel fit with an orthogonal distance regression as we have x errors not y errors p0 = [2, 200e3, 10e3] # Some sensible guesses result.lmfit( Inverse_Kittel, p0=p0, result=True, header="Kittel Fit", output="report" ) result.setas[-1] = "y" result.template.yformatter = TexEngFormatter result.template.xformatter = TexEngFormatter result.labels = None result.figure(figsize=(6, 8)) result.subplot(211) result.plot(fmt=["r.", "b-"]) result.annotate_fit(Inverse_Kittel, x=7e9, y=1e5, fontdict={"size": 8}) result.ylabel = "$H_{res} \\mathrm{(Am^{-1})}$" result.title = "Inverse Kittel Fit" # Get alpha result.subplot(212)
d = Data(V, I, dI, setas="xye", column_headers=["Bias", "Current", "Noise"]) d.curve_fit(SF.simmons, p0=[2500, 5.2, 15.0], result=True, header="curve_fit") d.setas = "xyey" d.plot(fmt=["r.", "b-"]) d.annotate_fit( SF.simmons, x=0.25, y=0.25, prefix="simmons", fontdict={"size": "x-small", "color": "blue"}, ) d.setas = "xye" fit = SF.Simmons() p0 = [2500, 5.2, 15.0] d.lmfit(SF.Simmons, p0=p0, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-") d.annotate_fit( fit, x=0.65, y=0.25, prefix="Simmons", fontdict={"size": "x-small", "color": "green"}, ) d.ylabel = "Current" d.title = "Simmons Model test" d.tight_layout()
column_headers=["Temperature", "Magnetization", "dM"], setas="xye") d.curve_fit( blochLaw, p0=[1500, 1500], result=True, header="curve_fit", prefix="curve_fit", bounds=lambda x, r: not isnan(r.y), ) d.lmfit( BlochLaw, result=True, header="lmfit", prefix="lmfit", bounds=lambda x, r: not isnan(r.y), ) d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit( blochLaw, x=0.1, y=0.5, fontdict={ "size": "x-small", "color": "blue" },
"""Simple use of lmfit to fit data.""" from Stoner import Data from numpy import linspace,exp,random #Make some data x=linspace(0,10.0,101) y=2+4*exp(-x/1.7)+random.normal(scale=0.2,size=101) d=Data(x,y,column_headers=["Time","Signal"],setas="xy") d.plot(fmt="ro") # plot our data #Do the fitting and plot the result fit = d.lmfit(lambda x,A,B,C:A+B*exp(-x/C),result=True,header="Fit",A=1,B=1,C=1) d.setas="x.y" d.labels=[] d.plot(fmt="b-") # Make nice label of the parameters text=r"$y=A+Be^{-x/C}$"+"\n\n" text+="\n".join([d.format(k,latex=True) for k in ["Model:A","Model:B","Model:C"]]) d.text(5,4,text,fontdict={"size":"x-small"})
"""Example of using lmfit to do a bounded fit.""" from Stoner import Data from Stoner.Fit import StretchedExp #Load dat and plot d = Data("lmfit_data.txt", setas="xy") # Do the fit d.lmfit(StretchedExp, result=True, header="Fit", prefix="") # plot d.setas = "xyy" d.plot(fmt=["+", "-"]) # Make apretty label using Stoner.Util methods text = "$y=A\\exp\\left[\\left(-\\frac{x}{x_0}\\right)^\\beta\\right]$\n" text += d.annotate_fit(StretchedExp, text_only=True) d.text(6, 4E4, text) #Adjust layout NB pass-through method to pyplot used here d.tight_layout()
dG, setas="xye", column_headers=["Field $\\mu_0H (T)$", "Moment", "dM"], ) func = lambda H, M_s, m: langevin(H, M_s, m, 250) d.curve_fit(func, p0=copy(params)[0:2], result=True, header="curve_fit") d.setas = "xye" fit = Langevin() fit.params = fit.guess(G, x=B) fit.params["T"].value = 250 fit.params["T"].vary = False d.lmfit(fit, p0=fit.params, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit( func, x=0.1, y=0.5, fontdict={ "size": "x-small", "color": "blue" }, mode="eng", ) d.annotate_fit(
import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal from copy import deepcopy T = linspace(4.2, 300, 101) params = [265, 65, 1.0, 5] params2 = deepcopy(params) G = SF.blochGrueneisen(T, *params) + normal(size=len(T), scale=5e-5) dG = ones_like(T) * 5e-5 d = Data(T, G, dG, setas="xye", column_headers=["Temperature (K)", "Resistivity", "dR"]) d.curve_fit(SF.blochGrueneisen, p0=params, result=True, header="curve_fit") d.setas = "xy" d.lmfit(SF.BlochGrueneisen, p0=params2, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(SF.blochGrueneisen, x=0.65, y=0.35, fontdict={"size": "x-small"}) d.annotate_fit( SF.BlochGrueneisen, x=0.65, y=0.05, fontdict={"size": "x-small"}, prefix="BlochGrueneisen", ) d.title = "Bloch-Grueneisen Fit" d.tight_layout()
"""Simple use of lmfit to fit data.""" from Stoner import Data from numpy import linspace, exp, random # Make some data x = linspace(0, 10.0, 101) y = 2 + 4 * exp(-x / 1.7) + random.normal(scale=0.2, size=101) d = Data(x, y, column_headers=["Time", "Signal"], setas="xy") # Do the fitting and plot the result func = lambda x, A, B, C: A + B * exp(-x / C) fit = d.lmfit( func, result=True, header="Fit", A=1, B=1, C=1, residuals=True, output="report" ) # Reset labels d.labels = [] # Make nice two panel plot layout ax = d.subplot2grid((3, 1), (2, 0)) d.setas = "x..y" d.plot(fmt="g+") d.title = "" ax = d.subplot2grid((3, 1), (0, 0), rowspan=2) d.setas = "xyy" d.plot(fmt=["ro", "b-"]) d.xticklabels = [[]] d.xlabel = ""
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Fit IV data to various RSJ models """ from Stoner import Data, __home__ from Stoner.Fit import RSJ_Noiseless, RSJ_Simple import os os.chdir(os.path.join(__home__, "..", "doc", "samples", "Fitting")) data = Data("data/IV.txt", setas={"x": "Current", "y": "Voltage"}) # Fit data with both versions of the RSJ model data.lmfit(RSJ_Simple, result=True, header="Simple", prefix="simple") data.lmfit(RSJ_Noiseless, result=True, header="Noiseless", prefix="noiseless") # Set column assignments and plot the data and fits data.setas = {"x": "Current", "y": ["Voltage", "Simple", "Noiseless"]} data.plot(fmt=["r+", "b-", "g-"]) # Annotate fits data.annotate_fit( RSJ_Simple, prefix="simple", mode="eng", x=0.15, y=0.1, fontsize="small" ) data.annotate_fit( RSJ_Noiseless, prefix="noiseless", mode="eng", x=0.55, y=0.1, fontsize="small" )
d.setas = "xyey" d.plot(fmt=["r,", "b-"], capsize=1) d.annotate_fit( SF.simmons, x=0.25, y=0.25, prefix="simmons", fontdict={ "size": "x-small", "color": "blue" }, ) d.setas = "xye" fit = SF.Simmons() d.lmfit(SF.Simmons, p0=p0, result=True, header="lmfit", maxfev=2000) d.setas = "x...y" d.plot(fmt="g-", label="lmfit") d.annotate_fit( fit, x=0.65, y=0.25, prefix="Simmons", fontdict={ "size": "x-small", "color": "green" }, ) d.ylabel = "Current (A)" d.xlabel = "Bias (V)"
B = linspace(2, 100, 26) params = [12.5, 0.75, 1e3] G = SF.fluchsSondheimer(B, *params) + normal(size=len(B), scale=5e-5) dG = ones_like(B) * 5e-5 d = Data( B, G, dG, setas="xye", column_headers=["Thickness (nm)", "Conductance", "dConductance"], ) d.curve_fit(SF.fluchsSondheimer, p0=params, result=True, header="curve_fit") d.setas = "xye" d.lmfit(SF.FluchsSondheimer, p0=params, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit( SF.fluchsSondheimer, x=0.2, y=0.6, fontdict={"size": "x-small", "color": "blue"} ) d.annotate_fit( SF.FluchsSondheimer, x=0.2, y=0.4, fontdict={"size": "x-small", "color": "green"}, prefix="FluchsSondheimer", ) d.title = "Fluchs-Sondheimer Fit"
B = linspace(-8, 8, 201) params = [1e-3, 2.0, 0.25, 1.4] G = SF.wlfit(B, *params) + normal(size=len(B), scale=5e-7) dG = ones_like(B) * 5e-7 d = Data( B, G, dG, setas="xye", column_headers=["Field $\\mu_0H (T)$", "Conductance", "dConductance"], ) d.curve_fit(SF.wlfit, p0=copy(params), result=True, header="curve_fit") d.setas = "xye" d.lmfit(SF.WLfit, p0=copy(params), result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(SF.wlfit, x=0.05, y=0.75, fontdict={"size": "x-small", "color": "blue"}) d.annotate_fit( SF.WLfit, x=0.05, y=0.5, fontdict={"size": "x-small", "color": "green"}, prefix="WLfit", ) d.title = "Weak Localisation Fit" d.tight_layout()
R = vftEquation(T, *params) * normal(size=len(T), scale=noise, loc=1.0) dR = vftEquation(T, *params) * noise d = Data(T, R, dR, setas="xy.", column_headers=["T", "Rate"]) # Plot the data points. d.plot(fmt="r.", label="Data Points") # Turn on the sigma column (error bars look messy on plot due to logscale) d.setas[2] = "e" # Curve_fit on its own d.curve_fit(vftEquation, p0=params, result=True, header="curve_fit") # lmfit uses some guesses p0 = params d.lmfit(VFTEquation, result=True, header="lmfit") # Plot these results too d.setas = "x..yy" d.plot(fmt=["b-", "g-"]) # Annotate the graph d.annotate_fit( vftEquation, x=0.25, y=0.35, fontdict={ "size": "x-small", "color": "blue" }, mode="eng", )
SF.fowlerNordheim, x=0.2, y=0.6, prefix="fowlerNordheim", fontdict={"size": "x-small", "color": "blue"}, ) d.setas = "xye" fit = SF.FowlerNordheim() p0 = [2500, 5.2, 15.0] p0 = fit.guess(I, x=V) for p, v, mi, mx in zip( ["A", "phi", "d"], [2500, 3.2, 15.0], [100, 1, 5], [1e4, 20.0, 30.0] ): p0[p].value = v p0[p].bounds = [mi, mx] d.lmfit(SF.FowlerNordheim, p0=p0, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-") d.annotate_fit( fit, x=0.2, y=0.2, prefix="FowlerNordheim", fontdict={"size": "x-small", "color": "green"}, ) d.ylabel = "Current" d.title = "Fowler-Nordheim Model test" d.tight_layout()
B = linspace(2, 100, 26) params = [12.5, 0.75, 1e3] G = SF.fluchsSondheimer(B, *params) + normal(size=len(B), scale=5e-5) dG = ones_like(B) * 5e-5 d = Data( B, G, dG, setas="xye", column_headers=["Thickness (nm)", "Conductance", "dConductance"], ) d.curve_fit(SF.fluchsSondheimer, p0=params, result=True, header="curve_fit") d.setas = "xye" d.lmfit(SF.FluchsSondheimer, p0=params, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(SF.fluchsSondheimer, x=0.2, y=0.6, fontdict={ "size": "x-small", "color": "blue" }) d.annotate_fit( SF.FluchsSondheimer, x=0.2, y=0.4,
d.plot(fmt=["r.", "b-"]) d.annotate_fit( SF.simmons, x=0.25, y=0.25, prefix="simmons", fontdict={ "size": "x-small", "color": "blue" }, ) d.setas = "xye" fit = SF.Simmons() p0 = [2500, 5.2, 15.0] d.lmfit(SF.Simmons, p0=p0, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-") d.annotate_fit( fit, x=0.65, y=0.25, prefix="Simmons", fontdict={ "size": "x-small", "color": "green" }, ) d.ylabel = "Current" d.title = "Simmons Model test"
"""Example of using lmfit to do a bounded fit.""" from Stoner import Data from Stoner.Fit import StretchedExp # Load dat and plot d = Data("lmfit_data.txt", setas="xy") # Do the fit d.lmfit(StretchedExp, result=True, header="Fit", prefix="") # plot d.setas = "xyy" d.plot(fmt=["+", "-"]) # Make apretty label using Stoner.Util methods text = r"$y=A e^{-\left(\frac{x}{x_0}\right)^\beta}$" + "\n" text += d.annotate_fit(StretchedExp, text_only=True, prefix="") d.text(6, 4e4, text)
import Stoner.Fit as SF from numpy import linspace,ones_like from numpy.random import normal #Make some data V=linspace(-4,4,1000) I=SF.fowlerNordheim(V,2500,3.2,15.0)+normal(size=len(V),scale=10E-6) dI=ones_like(V)*10E-6 d=Data(V,I,dI,setas="xye",column_headers=["Bias","Current","Noise"]) d.curve_fit(SF.fowlerNordheim,p0=[2500,3.2,15.0],result=True,header="curve_fit") d.setas="xyey" d.plot(fmt=["r.","b-"]) d.annotate_fit(SF.fowlerNordheim,x=0,y=10,prefix="fowlerNordheim",fontdict={"size":"x-small"}) d.setas="xye" fit=SF.FowlerNordheim() p0=[2500,5.2,15.0] p0=fit.guess(I,x=V) for p,v,mi,mx in zip(["A","phi","d"],[2500,3.2,15.0],[100,1,5],[1E4,20.0,30.0]): p0[p].value=v p0[p].bounds=[mi,mx] d.lmfit(SF.FowlerNordheim,p0=p0,result=True,header="lmfit") d.setas="x...y" d.plot() d.annotate_fit(fit,x=-3,y=-60,prefix="FowlerNordheim",fontdict={"size":"x-small"}) d.ylabel="Current" d.title="Fowler-Nordheim Model test" d.tight_layout()
d.plot(fmt="b-", label="curve-fit") d.annotate_fit( SF.quadratic, prefix="quadratic", x=0.2, y=0.65, fontdict={ "size": "x-small", "color": "blue" }, ) d.setas = "xy" fit = SF.Quadratic() p0 = fit.guess(y, x=x) d.lmfit(SF.Quadratic, p0=p0, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-", label="lmfit") d.annotate_fit( SF.Quadratic, prefix="Quadratic", x=0.65, y=0.65, fontdict={ "size": "x-small", "color": "green" }, ) d.title = "Qudratic Fitting"
from numpy import linspace, ones_like from numpy.random import normal from copy import copy x = linspace(-1.0, 1.0, 101) params = [1, 0.1, -0.25] y = lorentzian_diff(x, *params) + normal(size=len(x), scale=0.5) dy = ones_like(x) * 5e-3 d = Data(x, y, dy, setas="xye", column_headers=["Time", "Signal", "dM"]) d.curve_fit(lorentzian_diff, p0=copy(params), result=True, header="curve_fit") d.setas = "xye" d.lmfit(Lorentzian_diff, result=True, header="lmfit", prefix="lmfit") d.setas = "xyeyy" d.plot(fmt=["r+", "b-", "g-"]) d.annotate_fit( lorentzian_diff, x=0.6, y=0.2, fontdict={"size": "x-small", "color": "blue"}, mode="eng", ) d.annotate_fit( Lorentzian_diff, x=0.05,
params = [265, 65, 1.0, 5] params2 = deepcopy(params) G = blochGrueneisen(T, *params) + normal(size=len(T), scale=5e-5) dG = ones_like(T) * 5e-5 d = Data( T, G, dG, setas="xye", column_headers=["Temperature (K)", "Resistivity", "dR"], ) d.curve_fit(blochGrueneisen, p0=params, result=True, header="curve_fit") d.setas = "xy" d.lmfit(BlochGrueneisen, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(blochGrueneisen, x=0.65, y=0.35, fontdict={"size": "x-small"}) d.annotate_fit( BlochGrueneisen, x=0.65, y=0.05, fontdict={"size": "x-small"}, prefix="BlochGrueneisen", ) d.title = "Bloch-Grueneisen Fit" d.tight_layout()
column_headers=["Field $\\mu_0H (T)$", "Moment", "dM"]) func = lambda H, M_s, m: SF.langevin(H, M_s, m, 250) d.curve_fit(func, p0=copy(params)[0:2], result=True, header="curve_fit") d.setas = "xye" fit = SF.Langevin() p0 = fit.guess(G, x=B) for p, v in zip(p0, params): p0[p].set(v) p0[p].max = v * 5 p0[p].min = 0 p0[p].vary = p != "T" d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(func, x=0.1, y=0.5, fontdict={ "size": "x-small", "color": "blue" }, mode="eng") d.annotate_fit( SF.Langevin, x=0.1,
B = logspace(log10(2), 2, 26) params = [12.5, 0.75, 1e3] G = fluchsSondheimer(B, *params) + normal(size=len(B), scale=5e-5) dG = ones_like(B) * 5e-5 d = Data( B, G, dG, setas="xye", column_headers=["Thickness (nm)", "Conductance", "dConductance"], ) d.curve_fit(fluchsSondheimer, p0=params, result=True, header="curve_fit") d.setas = "xye" d.lmfit(FluchsSondheimer, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit( fluchsSondheimer, x=0.2, y=0.6, fontdict={ "size": "x-small", "color": "blue" }, ) d.annotate_fit( FluchsSondheimer,
"""Example of nDimArrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace from numpy.random import normal # Make some data T = linspace(200, 350, 101) R = SF.modArrhenius(T, 1e6, 0.5, 1.5) * normal(scale=0.00005, loc=1.0, size=len(T)) d = Data(T, R, setas="xy", column_headers=["T", "Rate"]) # Curve_fit on its own d.curve_fit(SF.modArrhenius, p0=[1e6, 0.5, 1.5], result=True, header="curve_fit") d.setas = "xyy" d.plot(fmt=["r.", "b-"]) d.annotate_fit(SF.modArrhenius, x=0.2, y=0.5) # lmfit using lmfit guesses fit = SF.ModArrhenius() p0 = [1e6, 0.5, 1.5] d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "x..y" d.plot() d.annotate_fit(SF.ModArrhenius, x=0.2, y=0.25, prefix="ModArrhenius") d.title = "Modified Arrhenius Test Fit" d.ylabel = "Rate" d.xlabel = "Temperature (K)"
B = linspace(-8, 8, 201) params = [1e-3, 2.0, 0.25, 1.4] G = wlfit(B, *params) + normal(size=len(B), scale=5e-7) dG = ones_like(B) * 5e-7 d = Data( B, G, dG, setas="xye", column_headers=["Field $\\mu_0H (T)$", "Conductance", "dConductance"], ) d.curve_fit(wlfit, p0=copy(params), result=True, header="curve_fit") d.setas = "xye" d.lmfit(WLfit, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(wlfit, x=0.05, y=0.75, fontdict={ "size": "x-small", "color": "blue" }) d.annotate_fit( WLfit, x=0.05, y=0.5,