本文整理汇总了Python中Stoner.Data.setas方法的典型用法代码示例。如果您正苦于以下问题:Python Data.setas方法的具体用法?Python Data.setas怎么用?Python Data.setas使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Stoner.Data
的用法示例。
在下文中一共展示了Data.setas方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: profile_line
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
def profile_line(img, src=None, dst=None, linewidth=1, order=1, mode="constant", cval=0.0, constrain=True, **kargs):
"""Wrapper for sckit-image method of the same name to get a line_profile.
Parameters:
img(ImageArray): Image data to take line section of
src, dst (2-tuple of int or float): start and end of line profile. If the co-ordinates
are given as intergers then they are assumed to be pxiel co-ordinates, floats are
assumed to be real-space co-ordinates using the embedded metadata.
linewidth (int): the wideth of the profile to be taken.
order (int 1-3): Order of interpolation used to find image data when not aligned to a point
mode (str): How to handle data outside of the image.
cval (float): The constant value to assume for data outside of the image is mode is "constant"
constrain (bool): Ensure the src and dst are within the image (default True).
Returns:
A :py:class:`Stoner.Data` object containing the line profile data and the metadata from the image.
"""
scale = img.get("MicronsPerPixel", 1.0)
r, c = img.shape
if src is None and dst is None:
if "x" in kargs:
src = (kargs["x"], 0)
dst = (kargs["x"], r)
if "y" in kargs:
src = (0, kargs["y"])
dst = (c, kargs["y"])
if isinstance(src, float):
src = (src, src)
if isinstance(dst, float):
dst = (dst, dst)
dst = _scale(dst, scale)
src = _scale(src, scale)
if not istuple(src, int, int):
raise ValueError("src co-ordinates are not a 2-tuple of ints.")
if not istuple(dst, int, int):
raise ValueError("dst co-ordinates are not a 2-tuple of ints.")
if constrain:
fix = lambda x, mx: int(round(sorted([0, x, mx])[1]))
r, c = img.shape
src = list(src)
src = (fix(src[0], r), fix(src[1], c))
dst = (fix(dst[0], r), fix(dst[1], c))
result = measure.profile_line(img, src, dst, linewidth, order, mode, cval)
points = measure.profile._line_profile_coordinates(src, dst, linewidth)[:, :, 0]
ret = Data()
ret.data = points.T
ret.setas = "xy"
ret &= np.sqrt(ret.x ** 2 + ret.y ** 2) * scale
ret &= result
ret.column_headers = ["X", "Y", "Distance", "Intensity"]
ret.setas = "..xy"
ret.metadata = img.metadata.copy()
return ret
示例2: hist
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
def hist(im, *args, **kargs):
"""Pass through to :py:func:`matplotlib.pyplot.hist` function."""
counts, edges = np.histogram(im.ravel(), *args, **kargs)
centres = (edges[1:] + edges[:-1]) / 2
new = Data(np.column_stack((centres, counts)))
new.column_headers = ["Intensity", "Frequency"]
new.setas = "xy"
return new
示例3: linspace
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
"""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],
):
示例4: Data
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
"""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)
示例5:
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
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)
main_fig=d.plot(figure=t.fig, plotter=pyplot.semilogy)
d.show()
示例6: plane
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
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()
示例7: linspace
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
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-"])
d.annotate_fit(
示例8: Data
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
###############################################################################################
#################### Important - if using multiprocessing on Windows, this block must be ######
#################### Inside a if __name__=="__main__": test. ###################################
###############################################################################################
if __name__ == "__main__":
# Load data
d = Data(join(__home__, "..", "sample-data", "FMR-data.txt"))
# Rename columns and reset plot labels
d.rename("multi[1]:y", "Field").rename("multi[0]:y", "Frequency").rename(
"Absorption::X", "FMR"
)
d.labels = None
# Deine x and y columns and normalise to a big number
d.setas(x="Field", y="FMR")
d.normalise(base=(-1e6, 1e6))
fldr = d.split(field_sign, "Frequency")
# Split the data file into separate files by frequencies and sign of field
fldr = PlotFolder(fldr) # Convert to a PlotFolder
fldr.template = template # Set my custom plot template
for f in fldr[-1]: # Invert the negative field side
f.x = -f.x[::-1]
f.y = -f.y[::-1]
resfldr = PlotFolder() # Somewhere to keep the results from +ve and -ve fields
for s in fldr.groups: # Fit each FMR spectra
subfldr = fldr[s]
subfldr.metadata["Field Sign"] = s
示例9: linear
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
"""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())
示例10: Data
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
"""3D surface plot example."""
from Stoner import Data
import numpy as np
import matplotlib.cm
x, y = np.meshgrid(np.linspace(-2, 2, 100), np.linspace(-2, 2, 100))
x = x.ravel()
y = y.ravel()
z = np.cos(4 * np.pi * np.sqrt(x ** 2 + y ** 2)) * np.exp(-np.sqrt(x ** 2 + y ** 2))
p = Data()
p = p & x & y & z
p.column_headers = ["X", "Y", "Z"]
p.setas = "xyz"
p.plot_xyz(cmap=matplotlib.cm.jet)
p.title = "Surface plot"
示例11: enumerate
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
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"
data.subplot(1,len(r_cols),i+1)
data.plot(fmt=["k.","r-"])
示例12: SetasTest
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
class SetasTest(unittest.TestCase):
"""Path to sample Data File"""
datadir=path.join(pth,"sample-data")
def setUp(self):
self.d=Data(path.join(path.dirname(__file__),"..","CoreTest.dat"),setas="xy")
self.d2=Data(path.join(__home__,"..","sample-data","TDI_Format_RT.txt"))
self.d3=Data(path.join(__home__,"..","sample-data","New-XRay-Data.dql"))
self.d4=Data(path.join(__home__,"..","sample-data","Cu_resistivity_vs_T.txt"))
def test_setas_basics(self):
self.d4.setas="2.y.x3."
self.assertEqual(self.d4.setas.x,4,"Failed to set set as from string with numbers.")
tmp=list(self.d4.setas)
self.d4.setas="..y.x..."
self.assertEqual(list(self.d4.setas),tmp,"Explicit exapnsion of setas not the same as with numbers.")
self.d4.setas(x="T (K)")
self.d4.setas(y="rho",reset=False)
self.assertEqual(list(self.d4.setas),tmp,"setas from calls with and without reset failed")
s=self.d4.setas.clone
self.d4.setas=[]
self.assertEqual(list(self.d4.setas),["." for i in range(8)],"Failed to clear setas")
self.d4.setas(s)
self.assertEqual(list(self.d4.setas),tmp,"setas from call with setas failed")
self.d4.setas(reset="Yes")
self.assertEqual(list(self.d4.setas),["." for i in range(8)],"Failed to clear setas")
self.assertEqual(self.d4.setas._size,8,"Size attribute failed.")
self.assertEqual(self.d4[0,:].setas._size,8,"Size attribute for array row failed.")
self.assertEqual(self.d4[:,0].setas._size,1,"Size attribute for array column failed.")
self.d4.column_headers[-3:]=["Column","Column","Column"]
self.assertEqual(self.d4.setas._unique_headers,['Voltage', 'Current', '$\\rho$ ($\\Omega$m)', 'Resistance', 'T (K)', 'Column', 6, 7],
"Unique Headers failed in setas.")
self.d4.setas("2.y.x3.")
s=self.d4.setas.clone
self.d4.setas.clear()
self.d4.setas(s)
self.assertTrue(self.d4.setas=="..y.x...","setas set by call with setas argument failed")
self.d4.setas(self.d4.setas)
self.assertTrue(self.d4.setas=="..y.x...","setas set by call with self argument failed")
self.d4.setas()
self.assertTrue(self.d4.setas=="..y.x...","setas set by call with no argument failed")
self.d4.setas-=["x","y"]
self.assertTrue(self.d4.setas=="8.","setas __sub__ with iterable failed")
self.d4.setas("2.y.x3.")
self.assertTrue(self.d4.setas=="..y.x...","Equality test by string failed.")
self.assertTrue(self.d4.setas=="2.y.x3.","Equality test by numbered string failed.")
self.assertEqual(self.d4.setas.to_string(),"..y.x...","To_string() failed.")
self.assertEqual(self.d4.setas.to_string(encode=True),"..y.x3.","To_string() failed.")
self.d4.setas.clear()
self.d4.setas+="2.y.x3."
self.assertTrue(self.d4.setas=="2.y.x3.","Equality test by numbered string failed.")
self.d4.setas-="2.y"
self.assertTrue(self.d4.setas=="4.x3.","Deletion Operator failed.")
self.d4.setas="2.y.x3."
self.assertEqual(self.d4.setas["rho"],"y","Getitem by type failed.")
self.assertEqual(self.d4.setas["x"],"T (K)","Getitem by name failed.")
self.assertEqual(self.d4.setas.x,4,"setas x attribute failed.")
self.assertEqual(self.d4.setas.y,[2],"setas y attribute failed.")
self.assertEqual(self.d4.setas.z,[],"setas z attribute failed.")
self.assertTrue(all(self.d4.setas.set==np.array([False,False,True,False,True,False,False,False])),"setas.set attribute not working.")
self.assertTrue(all(self.d4.setas.not_set==np.array([True,True,False,True,False,True,True,True])),"setas.set attribute not working.")
self.assertTrue("x" in self.d4.setas,"set.__contains__ failed")
del self.d4.setas["x"]
self.assertFalse("x" in self.d4.setas,"setas del item by column type failed.")
del self.d4.setas["rho"]
self.assertFalse("y" in self.d4.setas,"setas del by column named failed")
self.d4.setas({"T (K)":"x","y":"rho"})
self.assertTrue(self.d4.setas=="..y.x...","Setting setas by call with dictionary failed")
def test_setas_dict_interface(self):
self.assertEqual(list(self.d.setas.items()),[('X-Data', 'x'), ('Y-Data', 'y')],"Items method of setas failed.")
self.assertEqual(list(self.d.setas.keys()),["X-Data","Y-Data"],"setas keys method fails.")
self.assertEqual(list(self.d.setas.values()),["x","y"],"setas values method fails.")
self.assertEqual(self.d.setas.get("x"),"X-Data","Simple get with key on setas failed.")
self.assertEqual(self.d.setas.get("e","Help"),"Help","get on setas with non-existant key failed.")
self.assertEqual(self.d.setas.get("X-Data"),"x","get on setas by column named failed.")
self.assertEqual(self.d.setas.pop("x"),"X-Data","pop on setas failed.")
self.assertEqual(self.d.setas,".y","Residual setas after pop wrong.")
self.d.setas.clear()
self.assertEqual(self.d.setas,"","setas clear failed.")
self.d.setas.update({"x":0,"y":1})
self.assertEqual(self.d.setas.popitem(),("x","X-Data"),"Popitem method failed.")
self.assertEqual(self.d.setas,".y","residual after popitem wrong on setas.")
self.assertEqual(self.d.setas.setdefault("x","X-Data"),"X-Data","setas setdefault failed.")
self.assertEqual(self.d.setas,"xy","Result after set default wrong.")
self.d4.setas="2.y.x3."
self.assertEqual(self.d4.setas["#x"],4,"Indexing setas by #type failed.")
self.assertEqual(self.d4.setas[1::2],['.', '.', '.', '.'],"Indexing setas with a slice failed.")
self.assertEqual(self.d4.setas[[1,3,5,7]],['.', '.', '.', '.'],"Indexing setas with a slice failed.")
self.d4.setas.clear()
self.d4.setas+={"x":"T (K)","rho":"y"}
self.assertEqual(self.d4.setas,"2.y.x3.","Adding dictionary with type:column and column:type to setas failed.")
self.assertTrue(self.d4.setas.pop("x")=="T (K)" and self.d4.setas=="2.y5.","Pop from setas failed.")
self.assertEqual(self.d4.setas.pop("z",False),False,"Pop with non existent key and default value failed")
self.d4.setas.update({"x":"T (K)","rho":"y"})
#.........这里部分代码省略.........
示例13: linspace
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
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)
示例14: column
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
# 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,
y=0.35,
prefix="VFTEquation",
fontdict={"size": "x-small", "color": "green"},
示例15: Data
# 需要导入模块: from Stoner import Data [as 别名]
# 或者: from Stoner.Data import setas [as 别名]
"""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