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 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(
# Make some data T = logspace(log10(200), log10(350), 51) params = (1e16, 0.5, 150) noise = 0.5 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",
"""Function to define a plane""" return c - (coord[0] * a + coord[1] * b) coeefs = [1, -0.5, -1] col = linspace(-10, 10, 8) X, Y = meshgrid(col, col) Z = plane((X, Y), *coeefs) + normal(size=X.shape, scale=2.0) d = Data( column_stack((X.ravel(), Y.ravel(), Z.ravel())), filename="Fitting a Plane", setas="xyz", ) d.column_headers = ["X", "Y", "Z"] d.figure(projection="3d") d.plot_xyz(plotter="scatter") popt, pcov = d.curve_fit(plane, [0, 1], 2, result=True) d.setas = "xy.z" d.plot_xyz(linewidth=0, cmap=cmap.jet) txt = "$z=c-ax+by$\n" txt += "\n".join( [d.format("plane:{}".format(k), latex=True) for k in ["a", "b", "c"]]) ax = plt.gca(projection="3d") ax.text(15, 5, -50, txt) d.draw()
"""Test langevin fitting.""" from Stoner import Data from Stoner.analysis.fitting.models.generic import Lorentzian_diff, lorentzian_diff 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", )
Ms = 1714 Tc = 1046 M = where(T > 300, nan, blochLaw(T, Ms, Tc) + normal(scale=Ms / 200, size=len(T))) dM = ones_like(T) * Ms / 200 d = Data(T, M, dM, 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-"])
"""USe curve_fit to fit a straight line.""" from Stoner import Data def linear(x, m, c): """Straight line function.""" return m * x + c d = Data("curve_fit_data.dat", setas="xye") d.plot(fmt="ro") fit = d.curve_fit(linear, result=True, replace=False, header="Fit", output="report") d.setas = "x..y" d.plot(fmt="b-") d.annotate_fit(linear) d.draw() print(fit.fit_report())
"""Example of PowerLaw Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace from numpy.random import normal # Make some data T = linspace(50, 500, 101) R = SF.powerLaw(T, 1e-2, 0.6666666) * normal(size=len(T), scale=0.1, loc=1.0) d = Data(T, R, setas="xy", column_headers=["T", "Rate"]) # Curve_fit on its own d.curve_fit(SF.powerLaw, p0=[1, 0.5], result=True, header="curve_fit") d.setas = "xyy" d.plot(fmt=["r.", "b-"]) d.annotate_fit(SF.powerLaw, x=0.5, y=0.25) # lmfit using lmfit guesses fit = SF.PowerLaw() p0 = fit.guess(R, x=T) d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "x..y" d.plot(fmt="g-") d.annotate_fit(SF.PowerLaw, x=0.5, y=0.05, prefix="PowerLaw") d.title = "Powerlaw Test Fit" d.ylabel = "Rate" d.xlabel = "Temperature (K)"
from copy import copy B = linspace(1e3, 5e4, 51) params = [2.2, 1e5, 2e2] G = SF.kittelEquation(B, *params) + normal(size=len(B), scale=5e7) dG = ones_like(B) * 5e7 d = Data( B, G, dG, setas="xye", column_headers=["Field $Oe$", r"$\nu (Hz)$", r"\delta $\nu (Hz)$"], ) d.curve_fit(SF.kittelEquation, p0=copy(params), result=True, header="curve_fit") fit = SF.KittelEquation() p0 = fit.guess(G, x=B) d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit( SF.kittelEquation, x=0.5, y=0.25, fontdict={"size": "x-small", "color": "blue"}, mode="eng",
# Make some data T = logspace(log10(200), log10(350), 51) params = (1e16, 0.5, 150) noise = 0.5 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",
r_col = r_col[0] break else: r_col = select_col(d, "Select column for resistance data :") rho0 = d.min(r_col)[0] A = rho0 * 40 thetaD = 300.0 p0 = [thetaD, rho0, A] print("Initial guesses: {}".format(p0)) d.del_rows(0, lambda x, r: np.any(np.isnan(r))) popt, pcov = d.curve_fit(bg_wrapper, xcol=t_col, ycol=r_col, p0=p0, absolute_sigma=False) perr = np.sqrt(np.diag(pcov)) labels = [r"\theta_D", r"\rho_0", r"A"] units = ["K", r"\Omega m", r"\Omega m"] annotation = [ "${}$: {}\n".format(l, format_error(v, e, latex=True, mode="eng", units=u)) for l, v, e, u in zip(labels, popt, perr, units) ] annotation = "\n".join(annotation) popt = np.append(popt, 5) T = d.column(t_col) d.add_column(blochGrueneisen(T, *popt), header=r"Bloch")
"""Example of Arrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ceil, log10, abs from numpy.random import normal # Make some data T = linspace(200, 350, 101) R = SF.arrhenius(T + normal(size=len(T), scale=3.0, loc=0.0), 1e6, 0.5) E = 10 ** ceil(log10(abs(R - SF.arrhenius(T, 1e6, 0.5)))) d = Data(T, R, E, setas="xye", column_headers=["T", "Rate"]) # Curve_fit on its own d.curve_fit(SF.arrhenius, p0=(1e6, 0.5), result=True, header="curve_fit") d.setas = "xyey" d.plot(fmt=["r.", "b-"]) d.annotate_fit( SF.arrhenius, x=0.5, y=0.5, mode="eng", fontdict={"size": "x-small", "color": "blue"}, ) # lmfit using lmfit guesses fit = SF.Arrhenius() d.setas = "xye" d.lmfit(fit, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-") d.annotate_fit(
"""Example of nDimArrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal # Make some data V = linspace(-4, 4, 1001) I = SF.simmons(V, 2500, 5.2, 15.0) + normal(size=len(V), scale=100e-9) dI = ones_like(V) * 100e-9 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(
r=normal(loc=3.0,size=250,scale=0.5) x,y,z=transform(r,q,p) x+=3.0 y-=4.0 z+=2.0 # Construct the DataFile object d=Data(column_stack((x,y,z)),setas="xyz",filename="Best fit sphere") d.template.fig_width=5.2 d.template.fig_height=5.0 # Square aspect ratio d.plot_xyz(plotter="scatter") #curve_fit does the hard work popt,pcov=d.curve_fit(sphere,(0,1,2),zeros_like(d.x)) # This manually constructs the best fit sphere a,b,c,r=popt p=linspace(-pi/2,pi/2,16) q=linspace(-pi,pi,31) P,Q=meshgrid(p,q) R=ones_like(P)*r x,y,z=transform(R,Q,P) x+=a y+=b z+=c ax=plt.gca(projection="3d") ax.plot_surface(x,y,z,rstride=1,cstride=1,color=(1.0,0.0,0.0,0.25),linewidth=0) plt.draw()
"""Example of nDimArrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal # Make some data V = linspace(-4, 4, 101) I = SF.simmons(V, 2500, 3.2, 15.0) + normal(size=len(V), scale=5e-7) dI = ones_like(V) * 500e-9 p0 = p0 = [2500, 3, 10.0] d = Data(V, I, dI, setas="xye", column_headers=["Bias", "Current", "Noise"]) d.curve_fit(SF.simmons, p0=p0, result=True, header="curve_fit", maxfev=2000) 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()
"""Example of nDimArrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal # Make some data V = linspace(-10, 10, 1000) I = SF.bdr(V, 2.5, 3.2, 0.3, 15.0, 1.0) + normal(size=len(V), scale=1.0e-3) dI = ones_like(V) * 1.0e-3 # Curve fit d = Data(V, I, dI, setas="xye", column_headers=["Bias", "Current", "Noise"]) d.curve_fit(SF.bdr, p0=[2.5, 3.2, 0.3, 15.0, 1.0], result=True, header="curve_fit") d.setas = "xyey" d.plot(fmt=["r.", "b-"]) d.annotate_fit( SF.bdr, x=0.6, y=0.05, prefix="bdr", fontdict={"size": "x-small", "color": "blue"} ) # lmfit d.setas = "xy" fit = SF.BDR(missing="drop") p0 = fit.guess(I, x=V) for p, v, mi, mx in zip( ["A", "phi", "dphi", "d", "mass"], [2.500, 3.2, 0.3, 15.0, 1.0], [0.100, 1.0, 0.05, 5.0, 0.5], [10, 10.0, 2.0, 30.0, 5.0], ):
from numpy import linspace, ones_like from numpy.random import normal 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"},
"""Example of Arrhenius 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.arrhenius(T+normal(size=len(T),scale=1.0,loc=1.0),1E6,0.5) d=Data(T,R,setas="xy",column_headers=["T","Rate"]) #Curve_fit on its own d.curve_fit(SF.arrhenius,p0=[1E6,0.5],result=True,header="curve_fit") d.setas="xyy" d.plot() d.annotate_fit(SF.arrhenius,x=200,y=0.04) # lmfit using lmfit guesses fit=SF.Arrhenius() p0=fit.guess(R,x=T) d.lmfit(fit,p0=p0,result=True,header="lmfit") d.setas="x..y" d.plot() d.annotate_fit(SF.Arrhenius,x=200,y=0.02,prefix="Arrhenius") d.title="Arrhenius Test Fit" d.ylabel="Rate" d.xlabel="Temperature (K)"
result=Data() for data in fldr: #For each iteration ramp in the Tc data row=[data.mean(iterator)] data.figure(figsize=(8,4)) for i,r_col in enumerate(r_cols): data.setas(x=t_col,y=r_col) data.del_rows(isnan(data.y)) #Normalise data on y axis between +/- 1 data.normalise(base=(-1.,1.), replace=True) #Swap x and y axes around so that R is x and T is y data=~data #Curve fit a straight line, using only the central 90% of the resistance transition data.curve_fit(linear,bounds=lambda x,r:-threshold<x<threshold,result=True,p0=[7.0,0.0]) #result=True to record fit into metadata #Plot the results data.setas[-1]="y" data.subplot(1,len(r_cols),i+1) data.plot(fmt=["k.","r-"]) data.annotate_fit(linear,x=-1.,y=7.3c,fontsize="small") data.title="Ramp {}".format(data[iterator][0]) row.extend([data["linear:intercept"],data["linear:intercept err"]]) data.tight_layout() result+=np.array(row) result.column_headers=["Ramp","Sample 4 R","dR","Sample 7 R","dR"] result.setas="xyeye" result.plot(fmt=["k.","r."])
from numpy import linspace,meshgrid,column_stack import matplotlib.cm as cmap import matplotlib.pyplot as plt def plane(coord,a,b,c): """Function to define a plane""" return c-(coord[0]*a+coord[1]*b) coeefs=[1,-0.5,-1] col=linspace(-10,10,6) X,Y=meshgrid(col,col) Z=plane((X,Y),*coeefs)+normal(size=X.shape,scale=7.0) d=Data(column_stack((X.ravel(),Y.ravel(),Z.ravel())),filename="Fitting a Plane",setas="xyz") d.column_headers=["X","Y","Z"] d.figure(projection="3d") d.plot_xyz(plotter="scatter",c=cmap.jet(d.z)) d.curve_fit(plane,[0,1],2,result=True) d.setas="xy.z" d.plot_xyz(linewidth=0,cmap=cmap.jet) txt="$z=c-ax+by$\n" txt+="\n".join([d.format("plane:{}".format(k),latex=True) for k in ["a","b","c"]]) ax=plt.gca(projection="3d") ax.text(15,5,-50,txt) d.draw()
r = normal(loc=3.0, size=250, scale=0.5) x, y, z = transform(r, q, p) x += 3.0 y -= 4.0 z += 2.0 # Construct the DataFile object d = Data(column_stack((x, y, z)), setas="xyz", filename="Best fit sphere") d.template.fig_width = 5.2 d.template.fig_height = 5.0 # Square aspect ratio d.plot_xyz(plotter="scatter") # curve_fit does the hard work popt, pcov = d.curve_fit(sphere, (0, 1, 2), zeros_like(d.x)) # This manually constructs the best fit sphere a, b, c, r = popt p = linspace(-pi / 2, pi / 2, 16) q = linspace(-pi, pi, 31) P, Q = meshgrid(p, q) R = ones_like(P) * r x, y, z = transform(R, Q, P) x += a y += b z += c ax = plt.gca(projection="3d") ax.plot_surface(x, y, z, rstride=1, cstride=1, color=(1.0, 0.0, 0.0, 0.25), linewidth=0) plt.draw()
s = y * 0.05 d = Data(x, y, s, setas="xye", column_headers=["X", "Y"]) d.plot(fmt="r.") d.polyfit(result=True, header="Polyfit") d.setas = "x..y" d.plot(fmt="m-", label="Polyfit") d.text( -9, 450, "Polynominal co-efficients\n{}".format(d["2nd-order polyfit coefficients"]), fontdict={"size": "x-small", "color": "magenta"}, ) 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")
from numpy.random import normal from copy import copy 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", )
"""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(50, 500, 101) R = SF.nDimArrhenius(T + normal(size=len(T), scale=5.0, loc=1.0), 1e6, 0.5, 2) d = Data(T, R, setas="xy", column_headers=["T", "Rate"]) # Curve_fit on its own d.curve_fit(SF.nDimArrhenius, p0=[1e6, 0.5, 2], result=True, header="curve_fit") d.setas = "xyy" d.plot(fmt=["r.", "b-"]) d.annotate_fit(SF.nDimArrhenius, x=0.25, y=0.3) # lmfit using lmfit guesses fit = SF.NDimArrhenius() p0 = fit.guess(R, x=T) d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "x..y" d.plot(fmt="g-") d.annotate_fit(SF.NDimArrhenius, x=0.25, y=0.05, prefix="NDimArrhenius") d.title = "n-D Arrhenius Test Fit" d.ylabel = "Rate" d.xlabel = "Temperature (K)"
"""Example of nDimArrhenius Fit.""" from Stoner import Data 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=1e-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.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] ):
def plane(coord, a, b, c): """Function to define a plane""" return c - (coord[0] * a + coord[1] * b) coeefs = [1, -0.5, -1] col = linspace(-10, 10, 6) X, Y = meshgrid(col, col) Z = plane((X, Y), *coeefs) + normal(size=X.shape, scale=7.0) d = Data( column_stack((X.ravel(), Y.ravel(), Z.ravel())), filename="Fitting a Plane", setas="xyz", ) d.column_headers = ["X", "Y", "Z"] d.figure(projection="3d") d.plot_xyz(plotter="scatter") popt, pcov = d.curve_fit(plane, [0, 1], 2, result=True) d.setas = "xy.z" d.plot_xyz(linewidth=0, cmap=cmap.jet) txt = "$z=c-ax+by$\n" txt += "\n".join([d.format("plane:{}".format(k), latex=True) for k in ["a", "b", "c"]]) ax = plt.gca(projection="3d") ax.text(15, 5, -50, txt) d.draw()
"""USe curve_fit to fit a straight line.""" from Stoner import Data def linear(x, m, c): """Straight line function.""" return m * x + c d = Data("curve_fit_data.dat", setas="xye") d.plot(fmt="ro") popt, pcov = d.curve_fit(linear, result=True, replace=False, header="Fit") d.setas = "x..y" d.plot(fmt="b-") d.annotate_fit(linear) d.draw()
"""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(50, 500, 101) R = SF.nDimArrhenius(T + normal(size=len(T), scale=5.0, loc=1.0), 1E6, 0.5, 2) d = Data(T, R, setas="xy", column_headers=["T", "Rate"]) #Curve_fit on its own d.curve_fit(SF.nDimArrhenius, p0=[1E6, 0.5, 2], result=True, header="curve_fit") d.setas = "xyy" d.plot() d.annotate_fit(SF.nDimArrhenius, x=150, y=6E5) # lmfit using lmfit guesses fit = SF.NDimArrhenius() p0 = fit.guess(R, x=T) d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "x..y" d.plot() d.annotate_fit(SF.NDimArrhenius, x=150, y=3.5E5, prefix="NDimArrhenius") d.title = "n-D Arrhenius Test Fit" d.ylabel = "Rate" d.xlabel = "Temperature (K)"
"""Example of nDimArrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal # Make some data V = linspace(-4, 4, 1001) I = SF.simmons(V, 2500, 5.2, 15.0) + normal(size=len(V), scale=100e-9) dI = ones_like(V) * 100e-9 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")
from numpy.random import normal from copy import copy B = linspace(0, 5E4, 51) params = [2.2, 1E5, 2E2] G = SF.kittelEquation(B, *params) + normal(size=len(B), scale=5E7) dG = ones_like(B) * 5E7 d = Data(B, G, dG, setas="xye", column_headers=["Field $Oe$", r"$\nu (Hz)$", r"\delta $\nu (Hz)$"]) d.curve_fit(SF.kittelEquation, p0=copy(params), result=True, header="curve_fit") fit = SF.KittelEquation() p0 = fit.guess(G, x=B) d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "xyeyy" d.plot(fmt=["r.", "b-", "g-"]) d.annotate_fit(SF.kittelEquation, x=4000, y=2E8, fontdict={"size": "x-small"}, mode="eng")
"""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"
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()
"""Test Weak-localisation fitting.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ones_like from numpy.random import normal from copy import copy B = linspace(-0.01, 0.01, 100) params = [1, 1.0e-11, 250] G = SF.langevin(B, *params) + normal(size=len(B), scale=5e-3) dG = ones_like(B) * 5e-3 d = Data(B, G, dG, setas="xye", 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-"])
"""Example of Arrhenius Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace, ceil, log10, abs as np_abs from numpy.random import normal # Make some data T = linspace(200, 350, 101) R = SF.arrhenius(T + normal(size=len(T), scale=3.0, loc=0.0), 1e6, 0.5) E = 10 ** ceil(log10(np_abs(R - SF.arrhenius(T, 1e6, 0.5)))) d = Data(T, R, E, setas="xye", column_headers=["T", "Rate"]) # Curve_fit on its own d.curve_fit(SF.arrhenius, p0=(1e6, 0.5), result=True, header="curve_fit") d.setas = "xyey" d.plot(fmt=["r.", "b-"]) d.annotate_fit( SF.arrhenius, x=0.5, y=0.5, mode="eng", fontdict={"size": "x-small", "color": "blue"}, ) # lmfit using lmfit guesses fit = SF.Arrhenius() d.setas = "xye" d.lmfit(fit, result=True, header="lmfit") d.setas = "x...y" d.plot(fmt="g-") d.annotate_fit(
d.polyfit(result=True, header="Polyfit") d.setas = "x..y" d.plot(fmt="m-", label="Polyfit") d.text( -9, 450, "Polynominal co-efficients\n{}".format( d["2nd-order polyfit coefficients"]), fontdict={ "size": "x-small", "color": "magenta" }, ) 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()
"""Example of nDimArrhenius Fit.""" from Stoner import Data 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"
"""Simple use of lmfit to fit data.""" from Stoner import Data from Stoner.Fit import PowerLaw from Stoner.analysis.fitting import odr_Model from numpy import linspace, exp, random # Make some data x = linspace(0, 10.0, 101) y = PowerLaw().func(x, 1e-1, 1.64) * random.normal(loc=1.0, scale=0.05, size=101) d = Data(x, y, column_headers=["Time", "Signal"], setas="xy") # Do the fitting and plot the result fit = d.curve_fit( PowerLaw, result=True, header="LM-Model Fit", residuals=True, output="report" ) ODRModel = odr_Model(PowerLaw, p0=(1, 1)) fit = d.curve_fit( ODRModel, result=True, header="ODR-Fit", residuals=True, output="report", prefix="ODRModel", ) # Reset labels d.labels = [] # Make nice two panel plot layout ax = d.subplot2grid((3, 1), (2, 0)) d.setas = "x..y"
from numpy.random import normal from copy import copy B = linspace(-0.01, 0.01, 100) params = [1, 1.0e-11, 250] G = SF.langevin(B, *params) + normal(size=len(B), scale=5e-3) dG = ones_like(B) * 5e-3 d = Data(B, G, dG, setas="xye", 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-"])
from Stoner import Data from Stoner.analysis.fitting.models.generic import PowerLaw from Stoner.analysis.fitting import odr_Model from numpy import linspace, random # Make some data x = linspace(0, 10.0, 101) y = PowerLaw().func(x, 1e-1, 1.64) * random.normal( loc=1.0, scale=0.05, size=101) d = Data(x, y, column_headers=["Time", "Signal"], setas="xy") # Do the fitting and plot the result fit = d.curve_fit( PowerLaw, result=True, header="LM-Model Fit", residuals=True, output="report", ) ODRModel = odr_Model(PowerLaw, p0=(1, 1)) fit = d.curve_fit( ODRModel, result=True, header="ODR-Fit", residuals=True, output="report", prefix="ODRModel", ) # Reset labels d.labels = []
"""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)"
"""Test Weak-localisation fitting.""" from Stoner import Data 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"