Esempio n. 1
0
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()
Esempio n. 2
0
"""Re-binning data example."""
from Stoner import Data
from Stoner.plot.utils import errorfill

d = Data("Noisy_Data.txt", setas="xy")

d.template.fig_height = 6
d.template.fig_width = 8
d.figure(figsize=(6, 8))
d.subplot(411)

e = d.bin(bins=0.05, mode="lin")
f = d.bin(bins=0.25, mode="lin")
g = d.bin(bins=0.05, mode="log")
h = d.bin(bins=50, mode="log")

for i, (binned, label) in enumerate(
    zip([e, f, g, h], ["0.05 Linear", "0.25 Linear", "0.05 Log", "50 log"])
):
    binned.subplot(411 + i)
    d.plot()
    binned.fig = d.fig
    binned.plot(plotter=errorfill, label=label)

    d.xlim = (1, 6)
    d.ylim(-0.1, 0.4)
    d.title = "Bin demo" if i == 0 else ""
d.tight_layout()
Esempio n. 3
0
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()
Esempio n. 4
0
t_col=": T2" # Temperature column label
r_cols=("Sample 4::R","Sample 7::R") #Resistance Column Labels
iterator="iterator" #Temperature ramp iteration column label
threshold=0.85 #Fraction of transition to fit to

data=Data(filename)  #Use FALSE to get a dialog box to the file containing Tc data

#Define my working x and y axes
#Split one file into a folder of two files by the iterator column
fldr=data.split(iterator)

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"
Esempio n. 5
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()
Esempio n. 6
0
    path.join(__home__, "..", "doc", "samples", "sample.txt"))

d = Data(filename, setas="xyy", template=DefaultPlotStyle)
d.normalise(2, scale=(0.0, 10.0))  # Just to keep the plot sane!

# Change the color and line style cycles
d.template["axes.prop_cycle"] = cycler(color=["Blue", "Purple"]) + cycler(
    linestyle=["-", "--"])

# Can also access as an attribute
d.template.template_lines__linewidth = 2.0

# Set the default figure size
d.template["figure.figsize"] = (6, 8)
d.template["figure.autolayout"] = True
# Make figure (before using subplot method) and select first subplot
d.figure()
d.subplot(211)
# Pkot with our customised defaults
d.plot()
d.grid(True, color="green", linestyle="-.")
d.title = "Customised Plot settings"
# Reset the template to defaults and switch to next subplot
d.template.clear()
d.subplot(212)
# Plot with defaults
d.plot()
d.title = "Style Default settings"
# Fixup layout
d.figwidth = 7  # Magic pass through attribute access
Esempio n. 7
0
t_col=": T2" # Temperature column label
r_cols=("Sample 4::R","Sample 7::R") #Resistance Column Labels
iterator="iterator" #Temperature ramp iteration column label
threshold=0.85 #Fraction of transition to fit to

data=Data(filename)  #Use FALSE to get a dialog box to the file containing Tc data

#Define my working x and y axes
#Split one file into a folder of two files by the iterator column
fldr=data.split(iterator)

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"
Esempio n. 8
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})
Esempio n. 9
0
d = Data(filename, setas="xyy", template=DefaultPlotStyle)
d.normalise(2, scale=(0.0, 10.0))  # Just to keep the plot sane!

# Change the color and line style cycles
d.template["axes.prop_cycle"] = cycler(color=["Blue", "Purple"]) + cycler(
    linestyle=["-", "--"]
)

# Can also access as an attribute
d.template.template_lines__linewidth = 2.0

# Set the default figure size
d.template["figure.figsize"] = (6, 8)
d.template["figure.autolayout"] = True
# Make figure (before using subplot method) and select first subplot
d.figure()
d.subplot(211)
# Pkot with our customised defaults
d.plot()
d.grid(True, color="green", linestyle="-.")
d.title = "Customised Plot settings"
# Reset the template to defaults and switch to next subplot
d.template.clear()
d.subplot(212)
# Plot with defaults
d.plot()
d.title = "Style Default settings"
# Fixup layout
d.figwidth = 7  # Magic pass through attribute access
Esempio n. 10
0
    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)
    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})