class Plottest(unittest.TestCase): """Path to sample Data File""" datadir=path.join(pth,"sample-data") def setUp(self): self.d=Data(path.join(__home__,"..","sample-data","New-XRay-Data.dql")) def test_set_no_figs(self): self.assertTrue(Options.no_figs,"Default setting for no_figs option is incorrect.") Options.no_figs=True e=self.d.clone ret=e.plot() self.assertTrue(ret is None,"Output of Data.plot() was not None when no_figs is True and showfig is not set({})".format(type(ret))) Options.no_figs=False e.showfig=False ret=e.plot() self.assertTrue(isinstance(ret,Data),"Return value of Data.plot() was not self when Data.showfig=False ({})".format(type(ret))) e.showfig=True ret=e.plot() self.assertTrue(isinstance(ret,Figure),"Return value of Data.plot() was not Figure when Data.showfig=False({})".format(type(ret))) e.showfig=None ret=e.plot() self.assertTrue(ret is None,"Output of Data.plot() was not None when Data.showfig is None ({})".format(type(ret))) Options.no_figs=True self.assertTrue(Options.no_figs,"set_option no_figs failed.") self.d=Data(path.join(__home__,"..","sample-data","New-XRay-Data.dql")) self.d.showfig=False ret=self.d.plot() self.assertTrue(ret is None,"Output of Data.plot() was not None when no_figs is True ({})".format(type(ret))) Options.no_figs=True plt.close("all") def test_template_settings(self): template=DefaultPlotStyle(font__weight="bold") self.assertEqual(template["font.weight"],"bold","Setting ytemplate parameter in init failed.") template(font__weight="normal") self.assertEqual(template["font.weight"],"normal","Setting ytemplate parameter in call failed.") template["font.weight"]="bold" self.assertEqual(template["font.weight"],"bold","Setting ytemplate parameter in setitem failed.") del template["font.weight"] self.assertEqual(template["font.weight"],"normal","Resettting template parameter failed.") keys=sorted([x for x in template]) self.assertEqual(sorted(template.keys()),keys,"template.keys() and template.iter() disagree.") attrs=[x for x in dir(template) if template._allowed_attr(x)] length=len(dict(plt.rcParams))+len(attrs) self.assertEqual(len(template),length,"templa length wrong.")
"""Smoothing Data methods example.""" from Stoner import Data import matplotlib.pyplot as plt fig = plt.figure(figsize=(9, 6)) d = Data("Noisy_Data.txt", setas="xy") d.fig = fig d.plot(color="grey") # Filter with Savitsky-Golay filter, linear over 7 ppoints d.SG_Filter(result=True, points=11, header="S-G Filtered") d.setas = "x.y" d.plot(lw=2, label="SG Filter") d.setas = "xy" # Filter with cubic splines d.spline(replace=2, order=3, smoothing=4, header="Spline") d.setas = "x.y" d.plot(lw=2, label="Spline") d.setas = "xy" # Rebin data d.smooth("hamming", size=0.2, result=True, replace=False, header="Smoothed") d.setas = "x...y" d.plot(lw=2, label="Smoooth", color="green") d.setas = "xy" d2 = d.bin(bins=100, mode="lin") d2.fig = d.fig d2.plot(lw=2, label="Re-binned", color="blue") d2.xlim(3.5, 6.5) d2.ylim(-0.2, 0.4)
"""Independent sub plots for multiple y data.""" # pylint: disable=invalid-name from Stoner import Data p = Data("sample.txt", setas="xyy") # Quick plot p.plot(multiple="subplots") # Helps to fix layout ! p.tight_layout()
"""Add an inset to a plot.""" from Stoner import Data p = Data("sample.txt", setas="xy") p.plot() p.inset(loc=1, width="50%", height="50%") p.setas = "x.y" p.plot() p.title = "" # Turn off the inset title
#!/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)$"
"""Example plot style using Seaborn plot styling template.""" from Stoner import Data, __home__ from Stoner.plot.formats import SeabornPlotStyle import os.path as path filename = path.realpath( path.join(__home__, "..", "doc", "samples", "sample.txt")) d = Data( filename, setas="xyy", template=SeabornPlotStyle(stylename="dark", context="talk", palette="muted"), ) d.plot(multiple="y2")
class Plottest(unittest.TestCase): """Path to sample Data File""" datadir = path.join(pth, "sample-data") def setUp(self): self.d = Data( path.join(__home__, "..", "sample-data", "New-XRay-Data.dql")) def test_set_no_figs(self): self.assertTrue(Options.no_figs, "Default setting for no_figs option is incorrect.") Options.no_figs = True e = self.d.clone ret = e.plot() self.assertTrue( ret is None, "Output of Data.plot() was not None when no_figs is True and showfig is not set({})" .format(type(ret))) Options.no_figs = False e.showfig = False ret = e.plot() self.assertTrue( isinstance(ret, Data), "Return value of Data.plot() was not self when Data.showfig=False ({})" .format(type(ret))) e.showfig = True ret = e.plot() self.assertTrue( isinstance(ret, Figure), "Return value of Data.plot() was not Figure when Data.showfig=False({})" .format(type(ret))) e.showfig = None ret = e.plot() self.assertTrue( ret is None, "Output of Data.plot() was not None when Data.showfig is None ({})" .format(type(ret))) Options.no_figs = True self.assertTrue(Options.no_figs, "set_option no_figs failed.") self.d = Data( path.join(__home__, "..", "sample-data", "New-XRay-Data.dql")) self.d.showfig = False ret = self.d.plot() self.assertTrue( ret is None, "Output of Data.plot() was not None when no_figs is True ({})". format(type(ret))) Options.no_figs = True plt.close("all") def test_template_settings(self): template = DefaultPlotStyle(font__weight="bold") self.assertEqual(template["font.weight"], "bold", "Setting ytemplate parameter in init failed.") template(font__weight="normal") self.assertEqual(template["font.weight"], "normal", "Setting ytemplate parameter in call failed.") template["font.weight"] = "bold" self.assertEqual(template["font.weight"], "bold", "Setting ytemplate parameter in setitem failed.") del template["font.weight"] self.assertEqual(template["font.weight"], "normal", "Resettting template parameter failed.") keys = sorted([x for x in template]) self.assertEqual(sorted(template.keys()), keys, "template.keys() and template.iter() disagree.") attrs = [x for x in dir(template) if template._allowed_attr(x)] length = len(dict(plt.rcParams)) + len(attrs) self.assertEqual(len(template), length, "templa length wrong.") def test_plot_magic(self): self.d.figure() dpi = self.d.fig_dpi self.d.fig_dpi = dpi * 2 self.assertEqual(self.d.fig.dpi, dpi * 2, "Failed to get/set attributes on current figure") vis = self.d.fig_visible self.d.fig_visible = not vis self.assertFalse(self.d.fig_visible, "Setting/Getting figure.visible failed") plt.close("all") plt.figure() fn = plt.get_fignums()[0] self.d.fig = fn self.d.plot() self.assertEqual(len(plt.get_fignums()), 1, "Setting Data.fig by integer failed.") plt.close("all") self.d.plot(plotter=plt.semilogy) self.assertEqual(self.d.ax_lines[0].get_c(), "k", "Auto formatting of plot failed") self.d.plot(figure=False) self.d.plot(figure=1) self.assertEqual(len(plt.get_fignums()), 2, "Plotting setting figure failed") self.assertEqual(len(self.d.ax_lines), 2, "Plotting setting figure failed") self.d.figure(2) self.d.plot() self.d.plot(figure=True) self.assertEqual(len(plt.get_fignums()), 2, "Plotting setting figure failed") self.assertEqual(len(self.d.ax_lines), 3, "Plotting setting figure failed") plt.close("all") d = Data() def test_extra_plots(self): x = np.random.uniform(-np.pi, np.pi, size=5001) y = np.random.uniform(-np.pi, np.pi, size=5001) z = (np.cos(4 * np.sqrt(x**2 + y**2)) * np.exp(-np.sqrt(x**2 + y**2) / 3.0))**2 self.d2 = Data(x, y, z, column_headers=["X", "Y", "Z"], setas="xyz") self.d2.contour_xyz(projection="2d") # self.assertEqual(len(plt.get_fignums()), 1, "Setting Data.fig by integer failed.") plt.close("all") X, Y, Z = self.d2.griddata(xlim=(-np.pi, np.pi), ylim=(-np.pi, np.pi)) plt.imshow(Z) self.assertEqual(len(plt.get_fignums()), 1, "Setting Data.fig by integer failed.") plt.imshow(Z) plt.close("all") x, y = np.meshgrid(np.linspace(-np.pi, np.pi, 10), np.linspace(-np.pi, np.pi, 10)) z = np.zeros_like(x) w = np.cos(np.sqrt(x**2 + y**2)) q = np.arctan2(x, y) u = np.abs(w) * np.cos(q) v = np.abs(w) * np.sin(q) self.d3 = Data(x.ravel(), y.ravel(), z.ravel(), u.ravel(), v.ravel(), w.ravel(), setas="xyzuvw") self.d3.plot() self.assertEqual(len(plt.get_fignums()), 1, "Setting Data.fig by integer failed.") plt.close("all") # i=ImageFile(path.join(__home__,"..","sample-data","Kermit.png")) # self.d3=Data(i) # self.d3.data=i.data # self.d3.plot_matrix() def test_misc_funcs(self): self.assertTrue( np.all(hsl2rgb(0.5, 0.5, 0.5) == np.array([[63, 191, 191]]))) self.d.load(self.d.filename, Q=True) self.d.plot() self.d.x2() self.d.setas = ".yx" self.d.plot() self.d.tight_layout() self.assertEqual(len(self.d.fig_axes), 2, "Creating a second X axis failed") plt.close("all") for i in range(4): self.d.subplot(2, 2, i + 1) self.d.plot() self.assertEqual(len(self.d.fig_axes), 4, "Creating subplots failed") self.d.close()
"""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 func = lambda x, A, B, C: A + B * exp(-x / C) # Do the fitting and plot the result fit = d.differential_evolution( func, result=True, header="Fit", A=1, B=1, C=1, prefix="Model", 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"
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 = "" # Annotate plot with fitting parameters d.annotate_fit(func, prefix="Model", x=7.2, y=3, fontdict={"size": "x-small"}) text = r"$y=A+Be^{-x/C}$" + "\n\n" d.text(7.2, 3.9, text, fontdict={"size": "x-small"}) d.title = u"Levenberg-Marquardt Fit"
from Stoner import Data from numpy import linspace, ones_like, sin, cos, pi from numpy.random import normal from Stoner.plot.utils import errorfill x = linspace(0, 10 * pi, 101) e = 0.01 * ones_like(x) y = 0.1 * sin(x) + normal(size=len(x), scale=0.01) + 0.1 e2 = 0.01 * cos(x) y2 = 0.1 * ones_like(x) d = Data( x, y, e, y2, e2, column_headers=["$X$", "$Y_+$", r"$\delta Y_+$", "$Y_-$", r"$\delta Y_-$"], setas="xyeye", ) a = tuple(d.column_headers[1:3]) b = tuple(d.column_headers[3:5]) d.add(a, b, replace=False) d.subtract(a, b, replace=False) d.multiply(a, b, replace=False) d.divide(a, b, replace=False) d.diffsum(a, b, replace=False) d.setas = "xyeyeyeyeyeyeye" d.plot(multiple="panels", plotter=errorfill, color="red", alpha_fill=0.2)
"""Example of Arrhenius Fit.""" from Stoner import Data from Stoner.Fit import vftEquation, VFTEquation from numpy import logspace, log10 from numpy.random import normal # 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
@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)
"""Scale data to stitch it together.""" from Stoner import Data from Stoner.Util import format_error import matplotlib.pyplot as plt # Load and plot two sets of data s1 = Data("Stitch-scan1.txt", setas="xy") s2 = Data("Stitch-scan2.txt", setas="xy") s1.plot(label="Set 1") s2.fig = s1.fig s2.plot(label="Set 2") # Stitch scan 2 onto scan 1 s2.stitch(s1) s2.plot(label="Stictched") s2.title = "Stictching Example" # Tidy up the plot by adding annotation fo the stirching co-efficients labels = ["A", "B", "C"] txt = [] lead = r"$x'\rightarrow x+A$" + "\n" + r"$y'=\rightarrow By+C$" + "\n" for l, v, e in zip( labels, s2["Stitching Coefficients"], s2["Stitching Coeffient Errors"] ): txt.append(format_error(v, e, latex=True, prefix=l + "=")) plt.text(0.7, 0.65, lead + "\n".join(txt), fontdict={"size": "x-small"}) plt.draw()
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) result.setas(y="Delta_H", e="Delta_H.stderr", x="Freq") result.y /= mu_0 result.e /= mu_0 result.lmfit(Linear, result=True, header="Width", output="report") result.setas[-1] = "y" result.plot(fmt=["r.", "b-"]) result.annotate_fit(Linear, x=5.5e9, y=2.8e3, fontdict={"size": 8})
"""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)
"""Simple ploting with a template.""" from Stoner import Data from Stoner.plot.formats import DefaultPlotStyle from cycler import cycler p = Data("sample.txt", setas="xy", template=DefaultPlotStyle()) p.template( # pylint: disable=not-callable axes__prop_cycle=cycler("color", ["r", "g", "b"])) # pylint: disable=not-callable p.plot() p.y += 1.0 p.plot() p.y += 1.0 p.plot()
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."])
# 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 %= "Envelope" 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) main_fig = d.plot(figure=t.fig, plotter=pyplot.semilogy) d.show() #Now convert the angle to sin^2 t.apply(lambda x: np.sin(np.radians(x[0] / 2.0))**2, 0, header=r"$sin^2\theta$") # Now create the m^2 order m = np.arange(len(t)) + fringe_offset m = m**2 #And add it to t t.add_column(m, column_header='$m^2$') #Now we can it a straight line t.setas = "x..y" fit = t.lmfit(Linear, result=True, replace=False, header="Fit") g = t["LinearModel:slope"]
"""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"})
"""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()
from numpy import linspace, sin, exp, pi, column_stack from numpy.random import normal import matplotlib as mpl from tabulate import tabulate mpl.rc("text", usetex=True) x = linspace(0, 10 * pi, 201) x2 = x * 1.5 + 0.23 y = 10 * exp(-x / (2 * pi)) * sin(x) + normal(size=len(x), scale=0.1) y2 = 3 * exp(-x / (2 * pi)) * sin(x) - 1 + normal(size=len(x), scale=0.1) d = Data(x, y, column_headers=["Time", "Signal 1"], setas="xy") d2 = Data(x2, y2, column_headers=["Time", "Signal 2"], setas="xy") d.plot(label="1$^\\mathrm{st}$ signal") d2.plot(figure=d.fig, label="2$^\\mathrm{nd}$ signal") d3 = d2.scale(d, header="Signal 2 scaled", xmode="affine") d3.plot(figure=d.fig, label="1$^\\mathrm{st}$ scaled signals") d3["test"] = linspace(1, 10, 10) txt = tabulate(d3["Transform"], floatfmt=".2f", tablefmt="grid") d3.text(10, 4, "Transform\n{}".format(txt), fontdict={"size": "x-small"}) np_data = column_stack((x2, y2)) d4 = d.scale(np_data, header="Signal 2 scaled", xmode="affine", use_estimate=True) d4.plot(figure=d.fig, label="2$^\\mathrm{nd}$ scaled signal") d4.ylim = (-7, 9) txt = tabulate(d4["Transform"], floatfmt=".2f", tablefmt="grid")
"""Detect outlying points from a lione.""" from Stoner import Data from Stoner.analysis.utils import poly_outlier import numpy as np x = np.linspace(0, 100, 201) y = 0.01 * x**2 + 5 * np.sin(x / 10.0) i = np.random.randint(len(x) - 20, size=20) + 10 y[i] += np.random.normal(size=len(i), scale=20) d = Data(np.column_stack((x, y)), column_headers=["x", "y"], setas="xy") d.plot(fmt="b.", label="raw data") e = d.clone e.outlier_detection(window=5, action="delete") e.plot(fmt="r-", label="Default Outliers removed") f = d.clone f.outlier_detection(window=21, order=3, certainty=2, width=3, action="delete", func=poly_outlier) f.plot(fmt="g-", label="Poly Outliers removed") g = d.clone g = g.outlier_detection(window=21, order=3, certainty=3, width=3, action="delete", func=poly_outlier)
"""Scale data to stitch it together.""" from Stoner import Data from Stoner.Util import format_error import matplotlib.pyplot as plt # Load and plot two sets of data s1 = Data("Stitch-scan1.txt", setas="xy") s2 = Data("Stitch-scan2.txt", setas="xy") s1.plot(label="Set 1") s2.fig = s1.fig s2.plot(label="Set 2") # Stitch scan 2 onto scan 1 s2.stitch(s1) s2.plot(label="Stictched") s2.title = "Stictching Example" # Tidy up the plot by adding annotation fo the stirching co-efficients labels = ["A", "B", "C"] txt = [] lead = r"$x'\rightarrow x+A$" + "\n" + r"$y'=\rightarrow By+C$" + "\n" for l, v, e in zip(labels, s2["Stitching Coefficients"], s2["Stitching Coeffient Errors"]): txt.append(format_error(v, e, latex=True, prefix=l + "=")) plt.text(0.7, 0.65, lead + "\n".join(txt), fontdict={"size": "x-small"}) plt.draw()
"""Example plot style using Seaborn plot styling template.""" from Stoner import Data, __home__ from Stoner.plot.formats import SeabornPlotStyle import os.path as path filename = path.realpath(path.join(__home__, "..", "doc", "samples", "sample.txt")) d = Data( filename, setas="xyy", template=SeabornPlotStyle(stylename="dark", context="talk", palette="muted"), ) d.plot(multiple="y2")
noise = 0.5 R = SF.vftEquation(T, *params) * normal(size=len(T), scale=noise, loc=1.0) dR = SF.vftEquation(T, *params) * noise d = Data(T, R, dR, setas="xye", column_headers=["T", "Rate"]) #Curve_fit on its own d.curve_fit(SF.vftEquation, p0=params, result=True, header="curve_fit") # lmfit using lmfit guesses fit = SF.VFTEquation() p0 = params d.lmfit(fit, p0=p0, result=True, header="lmfit") d.setas = "xyeyyy" d.plot(fmt=["k+", "r-", "b-"]) d.yscale = "log" d.ylim = (1E-43, 1) d.annotate_fit(SF.vftEquation, x=270, y=1E-27, fontdict={"size": "x-small"}, mode="eng") d.annotate_fit(SF.VFTEquation, x=240, y=1E-40, prefix="VFTEquation", fontdict={"size": "x-small"}, mode="eng")
d = Data( column_stack([ x, (2 * x**2 - x + 2) + normal(size=len(x), scale=2.0), ones_like(x) * 2 ]), setas="xye", column_headers=["x", "y"], ) extra_x = linspace(8, 15, 11) y3 = d.extrapolate(extra_x, overlap=80, kind="cubic") y2 = d.extrapolate(extra_x, overlap=3.0, kind="quadratic") y1 = d.extrapolate(extra_x, overlap=1.0, kind="linear") d.plot(fmt="k.") d.title = "Extrapolation Demo" errorfill(extra_x, y2[:, 0], color="green", yerr=y2[:, 1], label="Quadratic Extrapolation") errorfill(extra_x, y3[:, 0], color="red", yerr=y3[:, 1], label="Cubic Extrapolation") errorfill(extra_x, y1[:, 0], color="blue",
"""Example of Quadratic Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace from numpy.random import normal import matplotlib.pyplot as plt # Make some data x = linspace(-10, 10, 101) y = SF.quadratic(x + normal(size=len(x), scale=0.1), 4, -2, 11) * normal( size=len(x), scale=0.05, loc=1.0) 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")
"""Example using select method to pick out data.""" from Stoner import Data d = Data("sample.txt", setas="xy") d.plot(fmt="b-") d.select(Temp__gt=75).select(Res__between=(5.3, 6.3)).plot(fmt="ro", label="portion 1") d.select(Temp__lt=30).plot(fmt="g<", label="portion 2")
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" d.plot(fmt="g+", label="Fit residuals") d.setas = "x....y" d.plot(fmt="b+", label="ODRModel Residuals") d.title = "" ax = d.subplot2grid((3, 1), (0, 0), rowspan=2) d.setas = "xyy.y" d.plot(fmt=["ro", "g-", "b-"]) d.xticklabels = [[]] d.ax_xlabel = "" # Annotate plot with fitting parameters d.annotate_fit(PowerLaw, x=0.1, y=0.25, fontdict={"size": "x-small"}) d.annotate_fit( ODRModel, x=0.65, y=0.15, fontdict={"size": "x-small"}, prefix="ODRModel" )
"""Simple use of lmfit to fit data.""" # pylint: disable=invalid-name 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 func = lambda x, A, B, C: A + B * exp(-x / C) # Do the fitting and plot the result fit = d.differential_evolution( func, result=True, header="Fit", A=1, B=1, C=1, prefix="Model", residuals=True, ) # Reset labels d.labels = []
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" d.plot(fmt="g+", label="Fit residuals") d.setas = "x....y" d.plot(fmt="b+", label="ODRModel Residuals") d.title = "" ax = d.subplot2grid((3, 1), (0, 0), rowspan=2) d.setas = "xyy.y" d.plot(fmt=["ro", "g-", "b-"]) d.xticklabels = [[]] d.ax_xlabel = "" # Annotate plot with fitting parameters d.annotate_fit(PowerLaw, x=0.1, y=0.25, fontdict={"size": "x-small"}) d.annotate_fit(ODRModel, x=0.65, y=0.15,
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], ): p0[p].value = v
"""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(
"""Plot data using mutiple sub-plots.""" from Stoner import Data p = Data("sample.txt", setas="xyy") # Quick plot p.plot(multiple="panels") # Helps to fix layout ! p.tight_layout()
"""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"
from Stoner import Data from numpy import linspace, ones_like, column_stack from numpy.random import normal import matplotlib.pyplot as plt from Stoner.plot.utils import errorfill x = linspace(1, 10, 101) d = Data( column_stack( [x, (2 * x ** 2 - x + 2) + normal(size=len(x), scale=2.0), ones_like(x) * 2] ), setas="xye", column_headers=["x", "y"], ) extra_x = linspace(8, 15, 11) y3 = d.extrapolate(extra_x, overlap=80, kind="cubic") y2 = d.extrapolate(extra_x, overlap=3.0, kind="quadratic") y1 = d.extrapolate(extra_x, overlap=1.0, kind="linear") d.plot(fmt="k.") d.title = "Extrapolation Demo" errorfill( extra_x, y2[:, 0], color="green", yerr=y2[:, 1], label="Quadratic Extrapolation" ) errorfill(extra_x, y3[:, 0], color="red", yerr=y3[:, 1], label="Cubic Extrapolation") errorfill(extra_x, y1[:, 0], color="blue", yerr=y1[:, 1], label="Linear Extrapolation") plt.legend(loc=2)
"""Detect peaks in a dataset.""" from Stoner import Data d = Data("../../sample-data/New-XRay-Data.dql") d.plot() d.peaks(width=0.08, poly=4, significance=100, modify=True) d.labels[1] = "Peaks" d.plot(fmt="ro")
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) main_fig = d.plot(figure=t.fig, plotter=pyplot.semilogy) d.show() # Now convert the angle to sin^2 t.apply(lambda x: np.sin(np.radians(x[0] / 2.0)) ** 2, 0, header=r"$sin^2\theta$") # Now create the m^2 order m = np.arange(len(t)) + fringe_offset m = m ** 2 # And add it to t t.add_column(m, column_header="$m^2$") # Now we can it a straight line t.setas = "x..y" fit = t.lmfit(Linear, result=True, replace=False, header="Fit") g = t["LinearModel:slope"] gerr = t["LinearModel:slope err"] / g g = np.sqrt(1.0 / g)
"""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()
"""Detect outlying points from a lione.""" from Stoner import Data from Stoner.Analysis import _poly_outlier import numpy as np x = np.linspace(0, 100, 201) y = 0.01 * x ** 2 + 5 * np.sin(x / 10.0) i = np.random.randint(len(x) - 20, size=20) + 10 y[i] += np.random.normal(size=len(i), scale=20) d = Data(np.column_stack((x, y)), column_headers=["x", "y"], setas="xy") d.plot(fmt="b.", label="raw data") e = d.clone e.outlier_detection(window=5, action="delete") e.plot(fmt="r-", label="Default Outliers removed") f = d.clone f.outlier_detection( window=21, order=3, certainty=2, width=3, action="delete", func=_poly_outlier ) f.plot(fmt="g-", label="Poly Outliers removed") g = d.clone g = g.outlier_detection( window=21, order=3, certainty=3, width=3, action="delete", func=_poly_outlier ) g.plot(color="purple", label="Masked outliers") g = d.clone e.title = "Outlier detection test"
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, y=0.25, fontdict={ "size": "x-small",
"""Example of Quadratic Fit.""" from Stoner import Data import Stoner.Fit as SF from numpy import linspace from numpy.random import normal import matplotlib.pyplot as plt # Make some data x = linspace(-10, 10, 101) y = SF.quadratic(x + normal(size=len(x), scale=0.1), 4, -2, 11) * normal( size=len(x), scale=0.05, loc=1.0 ) 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(
"""Example plot using Joe Batley's plot style.""" from Stoner import Data, __home__ from Stoner.plot.formats import JTBPlotStyle import os.path as path filename = path.realpath(path.join(__home__, "..", "doc", "samples", "sample.txt")) d = Data(filename, setas="xy", template=JTBPlotStyle) d.plot()
# pylint: disable=invalid-name from Stoner import Data from Stoner.analysis.fitting.models.thermal import vftEquation, VFTEquation from numpy import logspace, log10 from numpy.random import normal # 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
"""Smoothing Data methods example.""" from Stoner import Data import matplotlib.pyplot as plt fig = plt.figure(figsize=(9, 6)) d = Data("Noisy_Data.txt", setas="xy") d.fig = fig d.plot(color='grey') # Filter with Savitsky-Golay filter, linear over 7 ppoints d.SG_Filter(result=True, points=11, header="S-G Filtered") d.setas = "x.y" d.plot(lw=2, label="SG Filter") d.setas = "xy" #Filter with cubic splines d.spline(replace=2, order=3, smoothing=4, header="Spline") d.setas = "x.y" d.plot(lw=2, label="Spline") d.setas = "xy" # Rebin data d.smooth("hamming", size=0.2, result=True, replace=False, header="Smoothed") d.setas = "x...y" d.plot(lw=2, label="Smoooth", color="green") d.setas = "xy" d2 = d.bin(bins=100, mode="lin") d2.fig = d.fig d2.plot(lw=2, label="Re-binned", color="blue") d2.xlim = (3.5, 6.5) d2.ylim = (-0.2, 0.4)
"""Double y axis plot.""" from Stoner import Data p = Data("sample.txt", setas="xyy") # Quick plot p.plot(multiple="y2")
"""Example plot using experimental GBStyle.""" # pylint: disable=invalid-name import os.path as path from Stoner import Data, __home__ from Stoner.plot.formats import GBPlotStyle filename = path.realpath( path.join(__home__, "..", "doc", "samples", "sample.txt")) d = Data(filename, setas="xy", template=GBPlotStyle) d.y = d.y - (max(d.y) / 2) d.plot()
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) main_fig=d.plot(figure=t.fig, plotter=pyplot.semilogy) d.show() #Now convert the angle to sin^2 t.apply(lambda x: np.sin(np.radians(x[0]/2.0))**2, 0,header=r"$sin^2\theta$") # Now create the m^2 order m=np.arange(len(t))+fringe_offset m=m**2 #And add it to t t.add_column(m, column_header='$m^2$') #Now we can it a straight line t.setas="x..y" fit=t.lmfit(Linear,result=True,replace=False,header="Fit") g=t["LinearModel:slope"] gerr=t["LinearModel:slope err"]/g g=np.sqrt(1.0/g)
"""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)"
"""Independent sub plots for multiple y data.""" from Stoner import Data p = Data("sample.txt", setas="xyy") # Quick plot p.plot(multiple="subplots") # Helps to fix layout ! p.tight_layout()