repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
wright-group/WrightTools | WrightTools/artists/_colors.py | grayify_cmap | def grayify_cmap(cmap):
"""Return a grayscale version of the colormap.
`Source`__
__ https://jakevdp.github.io/blog/2014/10/16/how-bad-is-your-colormap/
"""
cmap = plt.cm.get_cmap(cmap)
colors = cmap(np.arange(cmap.N))
# convert RGBA to perceived greyscale luminance
# cf. http://alienryderflex.com/hsp.html
RGB_weight = [0.299, 0.587, 0.114]
luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
colors[:, :3] = luminance[:, np.newaxis]
return mplcolors.LinearSegmentedColormap.from_list(cmap.name + "_grayscale", colors, cmap.N) | python | def grayify_cmap(cmap):
"""Return a grayscale version of the colormap.
`Source`__
__ https://jakevdp.github.io/blog/2014/10/16/how-bad-is-your-colormap/
"""
cmap = plt.cm.get_cmap(cmap)
colors = cmap(np.arange(cmap.N))
# convert RGBA to perceived greyscale luminance
# cf. http://alienryderflex.com/hsp.html
RGB_weight = [0.299, 0.587, 0.114]
luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
colors[:, :3] = luminance[:, np.newaxis]
return mplcolors.LinearSegmentedColormap.from_list(cmap.name + "_grayscale", colors, cmap.N) | [
"def",
"grayify_cmap",
"(",
"cmap",
")",
":",
"cmap",
"=",
"plt",
".",
"cm",
".",
"get_cmap",
"(",
"cmap",
")",
"colors",
"=",
"cmap",
"(",
"np",
".",
"arange",
"(",
"cmap",
".",
"N",
")",
")",
"# convert RGBA to perceived greyscale luminance",
"# cf. http... | Return a grayscale version of the colormap.
`Source`__
__ https://jakevdp.github.io/blog/2014/10/16/how-bad-is-your-colormap/ | [
"Return",
"a",
"grayscale",
"version",
"of",
"the",
"colormap",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_colors.py#L236-L250 | train | 33,700 |
wright-group/WrightTools | WrightTools/artists/_colors.py | get_color_cycle | def get_color_cycle(n, cmap="rainbow", rotations=3):
"""Get a list of RGBA colors following a colormap.
Useful for plotting lots of elements, keeping the color of each unique.
Parameters
----------
n : integer
The number of colors to return.
cmap : string (optional)
The colormap to use in the cycle. Default is rainbow.
rotations : integer (optional)
The number of times to repeat the colormap over the cycle. Default is 3.
Returns
-------
list
List of RGBA lists.
"""
cmap = colormaps[cmap]
if np.mod(n, rotations) == 0:
per = np.floor_divide(n, rotations)
else:
per = np.floor_divide(n, rotations) + 1
vals = list(np.linspace(0, 1, per))
vals = vals * rotations
vals = vals[:n]
out = cmap(vals)
return out | python | def get_color_cycle(n, cmap="rainbow", rotations=3):
"""Get a list of RGBA colors following a colormap.
Useful for plotting lots of elements, keeping the color of each unique.
Parameters
----------
n : integer
The number of colors to return.
cmap : string (optional)
The colormap to use in the cycle. Default is rainbow.
rotations : integer (optional)
The number of times to repeat the colormap over the cycle. Default is 3.
Returns
-------
list
List of RGBA lists.
"""
cmap = colormaps[cmap]
if np.mod(n, rotations) == 0:
per = np.floor_divide(n, rotations)
else:
per = np.floor_divide(n, rotations) + 1
vals = list(np.linspace(0, 1, per))
vals = vals * rotations
vals = vals[:n]
out = cmap(vals)
return out | [
"def",
"get_color_cycle",
"(",
"n",
",",
"cmap",
"=",
"\"rainbow\"",
",",
"rotations",
"=",
"3",
")",
":",
"cmap",
"=",
"colormaps",
"[",
"cmap",
"]",
"if",
"np",
".",
"mod",
"(",
"n",
",",
"rotations",
")",
"==",
"0",
":",
"per",
"=",
"np",
".",... | Get a list of RGBA colors following a colormap.
Useful for plotting lots of elements, keeping the color of each unique.
Parameters
----------
n : integer
The number of colors to return.
cmap : string (optional)
The colormap to use in the cycle. Default is rainbow.
rotations : integer (optional)
The number of times to repeat the colormap over the cycle. Default is 3.
Returns
-------
list
List of RGBA lists. | [
"Get",
"a",
"list",
"of",
"RGBA",
"colors",
"following",
"a",
"colormap",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_colors.py#L253-L281 | train | 33,701 |
wright-group/WrightTools | WrightTools/diagrams/delay.py | label_sectors | def label_sectors(
*,
labels=["I", "II", "IV", "VI", "V", "III"],
ax=None,
lw=2,
lc="k",
cs=None,
c_zlevel=2,
c_alpha=0.5,
fontsize=40
):
"""Label the six time-orderings in a three-pulse experiment.
Parameters
----------
labels : list of strings
Labels to place within sectors, starting in the upper left and
proceeding clockwise. Default is ['I', 'II', 'IV', 'VI', 'V', 'III'].
ax : matplotlib axis object (optional)
Axis to label. If None, uses current axis. Default is None.
cs : list of matplotlib colors (optional)
Color to label sectors. If None, sectors are not colored. Default is
None.
c_zlevel : number (optional)
Matplotlib zlevel of color. Default is 2.
c_alpha : number between 0 and 1.
Transparency of color. Default is 0.5
"""
if ax is None:
ax = plt.gca()
# label
factors = [
[0.25, 0.75],
[2 / 3, 5 / 6],
[5 / 6, 2 / 3],
[0.75, 0.25],
[1 / 3, 1 / 6],
[1 / 6, 1 / 3],
]
transform = ax.transAxes
for label, factor in zip(labels, factors):
ax.text(
*factor + [label], fontsize=fontsize, va="center", ha="center", transform=transform
)
# lines
if lw > 0:
ax.axhline(0, c=lc, lw=lw)
ax.axvline(0, c=lc, lw=lw)
ax.plot([0, 1], [0, 1], c=lc, lw=lw, transform=transform)
# colors
if cs is None:
cs = ["none"] * 6
xbound = ax.get_xbound()
ybound = ax.get_ybound()
factors = []
factors.append([[xbound[0], 0], [0, 0], [ybound[1], ybound[1]]])
factors.append([[0, xbound[1]], [0, ybound[1]], [ybound[1], ybound[1]]])
factors.append([[0, xbound[1]], [0, 0], [0, ybound[1]]])
factors.append([[0, xbound[1]], [ybound[0], ybound[0]], [0, 0]])
factors.append([[xbound[0], 0], [ybound[0], ybound[0]], [ybound[0], 0]])
factors.append([[xbound[0], 0], [ybound[0], 0], [0, 0]])
for color, factor in zip(cs, factors):
poly = ax.fill_between(*factor, facecolor=color, edgecolor="none", alpha=c_alpha)
poly.set_zorder(c_zlevel) | python | def label_sectors(
*,
labels=["I", "II", "IV", "VI", "V", "III"],
ax=None,
lw=2,
lc="k",
cs=None,
c_zlevel=2,
c_alpha=0.5,
fontsize=40
):
"""Label the six time-orderings in a three-pulse experiment.
Parameters
----------
labels : list of strings
Labels to place within sectors, starting in the upper left and
proceeding clockwise. Default is ['I', 'II', 'IV', 'VI', 'V', 'III'].
ax : matplotlib axis object (optional)
Axis to label. If None, uses current axis. Default is None.
cs : list of matplotlib colors (optional)
Color to label sectors. If None, sectors are not colored. Default is
None.
c_zlevel : number (optional)
Matplotlib zlevel of color. Default is 2.
c_alpha : number between 0 and 1.
Transparency of color. Default is 0.5
"""
if ax is None:
ax = plt.gca()
# label
factors = [
[0.25, 0.75],
[2 / 3, 5 / 6],
[5 / 6, 2 / 3],
[0.75, 0.25],
[1 / 3, 1 / 6],
[1 / 6, 1 / 3],
]
transform = ax.transAxes
for label, factor in zip(labels, factors):
ax.text(
*factor + [label], fontsize=fontsize, va="center", ha="center", transform=transform
)
# lines
if lw > 0:
ax.axhline(0, c=lc, lw=lw)
ax.axvline(0, c=lc, lw=lw)
ax.plot([0, 1], [0, 1], c=lc, lw=lw, transform=transform)
# colors
if cs is None:
cs = ["none"] * 6
xbound = ax.get_xbound()
ybound = ax.get_ybound()
factors = []
factors.append([[xbound[0], 0], [0, 0], [ybound[1], ybound[1]]])
factors.append([[0, xbound[1]], [0, ybound[1]], [ybound[1], ybound[1]]])
factors.append([[0, xbound[1]], [0, 0], [0, ybound[1]]])
factors.append([[0, xbound[1]], [ybound[0], ybound[0]], [0, 0]])
factors.append([[xbound[0], 0], [ybound[0], ybound[0]], [ybound[0], 0]])
factors.append([[xbound[0], 0], [ybound[0], 0], [0, 0]])
for color, factor in zip(cs, factors):
poly = ax.fill_between(*factor, facecolor=color, edgecolor="none", alpha=c_alpha)
poly.set_zorder(c_zlevel) | [
"def",
"label_sectors",
"(",
"*",
",",
"labels",
"=",
"[",
"\"I\"",
",",
"\"II\"",
",",
"\"IV\"",
",",
"\"VI\"",
",",
"\"V\"",
",",
"\"III\"",
"]",
",",
"ax",
"=",
"None",
",",
"lw",
"=",
"2",
",",
"lc",
"=",
"\"k\"",
",",
"cs",
"=",
"None",
",... | Label the six time-orderings in a three-pulse experiment.
Parameters
----------
labels : list of strings
Labels to place within sectors, starting in the upper left and
proceeding clockwise. Default is ['I', 'II', 'IV', 'VI', 'V', 'III'].
ax : matplotlib axis object (optional)
Axis to label. If None, uses current axis. Default is None.
cs : list of matplotlib colors (optional)
Color to label sectors. If None, sectors are not colored. Default is
None.
c_zlevel : number (optional)
Matplotlib zlevel of color. Default is 2.
c_alpha : number between 0 and 1.
Transparency of color. Default is 0.5 | [
"Label",
"the",
"six",
"time",
"-",
"orderings",
"in",
"a",
"three",
"-",
"pulse",
"experiment",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/delay.py#L13-L76 | train | 33,702 |
wright-group/WrightTools | WrightTools/kit/_calculate.py | fluence | def fluence(
power_mW,
color,
beam_radius,
reprate_Hz,
pulse_width,
color_units="wn",
beam_radius_units="mm",
pulse_width_units="fs_t",
area_type="even",
) -> tuple:
"""Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated power of beam.
color : number
Color of beam in units.
beam_radius : number
Radius of beam in units.
reprate_Hz : number
Laser repetition rate in inverse seconds (Hz).
pulse_width : number
Pulsewidth of laser in units
color_units : string (optional)
Valid wt.units color unit identifier. Default is wn.
beam_radius_units : string (optional)
Valid wt.units distance unit identifier. Default is mm.
pulse_width_units : number
Valid wt.units time unit identifier. Default is fs.
area_type : string (optional)
Type of calculation to accomplish for Gaussian area.
even specfies a flat-top calculation
average specifies a Gaussian average within the FWHM
Default is even.
Returns
-------
tuple
Fluence in uj/cm2, photons/cm2, and peak intensity in GW/cm2
"""
# calculate beam area
if area_type == "even":
radius_cm = wt_units.converter(beam_radius, beam_radius_units, "cm")
area_cm2 = np.pi * radius_cm ** 2 # cm^2
elif area_type == "average":
radius_cm = wt_units.converter(beam_radius, beam_radius_units, "cm")
area_cm2 = np.pi * radius_cm ** 2 # cm^2
area_cm2 /= 0.7213 # weight by average intensity felt by oscillator inside of FWHM
else:
raise NotImplementedError
# calculate fluence in uj/cm^2
ujcm2 = power_mW / reprate_Hz # mJ
ujcm2 *= 1e3 # uJ
ujcm2 /= area_cm2 # uJ/cm^2
# calculate fluence in photons/cm^2
energy = wt_units.converter(color, color_units, "eV") # eV
photonscm2 = ujcm2 * 1e-6 # J/cm2
photonscm2 /= 1.60218e-19 # eV/cm2
photonscm2 /= energy # photons/cm2
# calculate peak intensity in GW/cm^2
pulse_width_s = wt_units.converter(pulse_width, pulse_width_units, "s_t") # seconds
GWcm2 = ujcm2 / 1e6 # J/cm2
GWcm2 /= pulse_width_s # W/cm2
GWcm2 /= 1e9
# finish
return ujcm2, photonscm2, GWcm2 | python | def fluence(
power_mW,
color,
beam_radius,
reprate_Hz,
pulse_width,
color_units="wn",
beam_radius_units="mm",
pulse_width_units="fs_t",
area_type="even",
) -> tuple:
"""Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated power of beam.
color : number
Color of beam in units.
beam_radius : number
Radius of beam in units.
reprate_Hz : number
Laser repetition rate in inverse seconds (Hz).
pulse_width : number
Pulsewidth of laser in units
color_units : string (optional)
Valid wt.units color unit identifier. Default is wn.
beam_radius_units : string (optional)
Valid wt.units distance unit identifier. Default is mm.
pulse_width_units : number
Valid wt.units time unit identifier. Default is fs.
area_type : string (optional)
Type of calculation to accomplish for Gaussian area.
even specfies a flat-top calculation
average specifies a Gaussian average within the FWHM
Default is even.
Returns
-------
tuple
Fluence in uj/cm2, photons/cm2, and peak intensity in GW/cm2
"""
# calculate beam area
if area_type == "even":
radius_cm = wt_units.converter(beam_radius, beam_radius_units, "cm")
area_cm2 = np.pi * radius_cm ** 2 # cm^2
elif area_type == "average":
radius_cm = wt_units.converter(beam_radius, beam_radius_units, "cm")
area_cm2 = np.pi * radius_cm ** 2 # cm^2
area_cm2 /= 0.7213 # weight by average intensity felt by oscillator inside of FWHM
else:
raise NotImplementedError
# calculate fluence in uj/cm^2
ujcm2 = power_mW / reprate_Hz # mJ
ujcm2 *= 1e3 # uJ
ujcm2 /= area_cm2 # uJ/cm^2
# calculate fluence in photons/cm^2
energy = wt_units.converter(color, color_units, "eV") # eV
photonscm2 = ujcm2 * 1e-6 # J/cm2
photonscm2 /= 1.60218e-19 # eV/cm2
photonscm2 /= energy # photons/cm2
# calculate peak intensity in GW/cm^2
pulse_width_s = wt_units.converter(pulse_width, pulse_width_units, "s_t") # seconds
GWcm2 = ujcm2 / 1e6 # J/cm2
GWcm2 /= pulse_width_s # W/cm2
GWcm2 /= 1e9
# finish
return ujcm2, photonscm2, GWcm2 | [
"def",
"fluence",
"(",
"power_mW",
",",
"color",
",",
"beam_radius",
",",
"reprate_Hz",
",",
"pulse_width",
",",
"color_units",
"=",
"\"wn\"",
",",
"beam_radius_units",
"=",
"\"mm\"",
",",
"pulse_width_units",
"=",
"\"fs_t\"",
",",
"area_type",
"=",
"\"even\"",
... | Calculate the fluence of a beam.
Parameters
----------
power_mW : number
Time integrated power of beam.
color : number
Color of beam in units.
beam_radius : number
Radius of beam in units.
reprate_Hz : number
Laser repetition rate in inverse seconds (Hz).
pulse_width : number
Pulsewidth of laser in units
color_units : string (optional)
Valid wt.units color unit identifier. Default is wn.
beam_radius_units : string (optional)
Valid wt.units distance unit identifier. Default is mm.
pulse_width_units : number
Valid wt.units time unit identifier. Default is fs.
area_type : string (optional)
Type of calculation to accomplish for Gaussian area.
even specfies a flat-top calculation
average specifies a Gaussian average within the FWHM
Default is even.
Returns
-------
tuple
Fluence in uj/cm2, photons/cm2, and peak intensity in GW/cm2 | [
"Calculate",
"the",
"fluence",
"of",
"a",
"beam",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_calculate.py#L20-L88 | train | 33,703 |
wright-group/WrightTools | WrightTools/kit/_calculate.py | mono_resolution | def mono_resolution(
grooves_per_mm, slit_width, focal_length, output_color, output_units="wn"
) -> float:
"""Calculate the resolution of a monochromator.
Parameters
----------
grooves_per_mm : number
Grooves per millimeter.
slit_width : number
Slit width in microns.
focal_length : number
Focal length in mm.
output_color : number
Output color in nm.
output_units : string (optional)
Output units. Default is wn.
Returns
-------
float
Resolution.
"""
d_lambda = 1e6 * slit_width / (grooves_per_mm * focal_length) # nm
upper = output_color + d_lambda / 2 # nm
lower = output_color - d_lambda / 2 # nm
return abs(
wt_units.converter(upper, "nm", output_units)
- wt_units.converter(lower, "nm", output_units)
) | python | def mono_resolution(
grooves_per_mm, slit_width, focal_length, output_color, output_units="wn"
) -> float:
"""Calculate the resolution of a monochromator.
Parameters
----------
grooves_per_mm : number
Grooves per millimeter.
slit_width : number
Slit width in microns.
focal_length : number
Focal length in mm.
output_color : number
Output color in nm.
output_units : string (optional)
Output units. Default is wn.
Returns
-------
float
Resolution.
"""
d_lambda = 1e6 * slit_width / (grooves_per_mm * focal_length) # nm
upper = output_color + d_lambda / 2 # nm
lower = output_color - d_lambda / 2 # nm
return abs(
wt_units.converter(upper, "nm", output_units)
- wt_units.converter(lower, "nm", output_units)
) | [
"def",
"mono_resolution",
"(",
"grooves_per_mm",
",",
"slit_width",
",",
"focal_length",
",",
"output_color",
",",
"output_units",
"=",
"\"wn\"",
")",
"->",
"float",
":",
"d_lambda",
"=",
"1e6",
"*",
"slit_width",
"/",
"(",
"grooves_per_mm",
"*",
"focal_length",... | Calculate the resolution of a monochromator.
Parameters
----------
grooves_per_mm : number
Grooves per millimeter.
slit_width : number
Slit width in microns.
focal_length : number
Focal length in mm.
output_color : number
Output color in nm.
output_units : string (optional)
Output units. Default is wn.
Returns
-------
float
Resolution. | [
"Calculate",
"the",
"resolution",
"of",
"a",
"monochromator",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_calculate.py#L91-L120 | train | 33,704 |
wright-group/WrightTools | WrightTools/kit/_calculate.py | nm_width | def nm_width(center, width, units="wn") -> float:
"""Given a center and width, in energy units, get back a width in nm.
Parameters
----------
center : number
Center (in energy units).
width : number
Width (in energy units).
units : string (optional)
Input units. Default is wn.
Returns
-------
number
Width in nm.
"""
red = wt_units.converter(center - width / 2., units, "nm")
blue = wt_units.converter(center + width / 2., units, "nm")
return red - blue | python | def nm_width(center, width, units="wn") -> float:
"""Given a center and width, in energy units, get back a width in nm.
Parameters
----------
center : number
Center (in energy units).
width : number
Width (in energy units).
units : string (optional)
Input units. Default is wn.
Returns
-------
number
Width in nm.
"""
red = wt_units.converter(center - width / 2., units, "nm")
blue = wt_units.converter(center + width / 2., units, "nm")
return red - blue | [
"def",
"nm_width",
"(",
"center",
",",
"width",
",",
"units",
"=",
"\"wn\"",
")",
"->",
"float",
":",
"red",
"=",
"wt_units",
".",
"converter",
"(",
"center",
"-",
"width",
"/",
"2.",
",",
"units",
",",
"\"nm\"",
")",
"blue",
"=",
"wt_units",
".",
... | Given a center and width, in energy units, get back a width in nm.
Parameters
----------
center : number
Center (in energy units).
width : number
Width (in energy units).
units : string (optional)
Input units. Default is wn.
Returns
-------
number
Width in nm. | [
"Given",
"a",
"center",
"and",
"width",
"in",
"energy",
"units",
"get",
"back",
"a",
"width",
"in",
"nm",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_calculate.py#L123-L142 | train | 33,705 |
wright-group/WrightTools | WrightTools/diagrams/WMEL.py | Subplot.add_arrow | def add_arrow(
self,
index,
between,
kind,
label="",
head_length=0.1,
head_aspect=2,
font_size=14,
color="k",
):
"""Add an arrow to the WMEL diagram.
Parameters
----------
index : integer
The interaction, or start and stop interaction for the arrow.
between : 2-element iterable of integers
The inital and final state of the arrow
kind : {'ket', 'bra'}
The kind of interaction.
label : string (optional)
Interaction label. Default is empty string.
head_length: number (optional)
size of arrow head
font_size : number (optional)
Label font size. Default is 14.
color : matplotlib color (optional)
Arrow color. Default is black.
Returns
-------
[line,arrow_head,text]
"""
if hasattr(index, "index"):
x_pos = list(index)
else:
x_pos = [index] * 2
x_pos = [np.linspace(0, 1, self.interactions)[i] for i in x_pos]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
y_poss = [self.energies[between[0]], self.energies[between[1]] - head_length]
elif arrow_length < 0:
direction = -1
y_poss = [self.energies[between[0]], self.energies[between[1]] + head_length]
else:
raise ValueError("between invalid!")
length = abs(y_poss[0] - y_poss[1])
if kind == "ket":
line = self.ax.plot(x_pos, y_poss, linestyle="-", color=color, linewidth=2, zorder=9)
elif kind == "bra":
line = self.ax.plot(x_pos, y_poss, linestyle="--", color=color, linewidth=2, zorder=9)
elif kind == "out":
yi = np.linspace(y_poss[0], y_poss[1], 100)
xi = (
np.sin((yi - y_poss[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40
+ x_pos[0]
)
line = self.ax.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt", zorder=9
)
else:
raise ValueError("kind is not 'ket', 'out', or 'bra'.")
# add arrow head
arrow_head = self.ax.arrow(
x_pos[1],
arrow_end - head_length * direction,
0,
0.0001 * direction,
head_width=head_length * head_aspect,
head_length=head_length,
fc=color,
ec=color,
linestyle="solid",
linewidth=0,
zorder=10,
)
# add text
text = self.ax.text(
np.mean(x_pos), -0.15, label, fontsize=font_size, horizontalalignment="center"
)
return line, arrow_head, text | python | def add_arrow(
self,
index,
between,
kind,
label="",
head_length=0.1,
head_aspect=2,
font_size=14,
color="k",
):
"""Add an arrow to the WMEL diagram.
Parameters
----------
index : integer
The interaction, or start and stop interaction for the arrow.
between : 2-element iterable of integers
The inital and final state of the arrow
kind : {'ket', 'bra'}
The kind of interaction.
label : string (optional)
Interaction label. Default is empty string.
head_length: number (optional)
size of arrow head
font_size : number (optional)
Label font size. Default is 14.
color : matplotlib color (optional)
Arrow color. Default is black.
Returns
-------
[line,arrow_head,text]
"""
if hasattr(index, "index"):
x_pos = list(index)
else:
x_pos = [index] * 2
x_pos = [np.linspace(0, 1, self.interactions)[i] for i in x_pos]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
y_poss = [self.energies[between[0]], self.energies[between[1]] - head_length]
elif arrow_length < 0:
direction = -1
y_poss = [self.energies[between[0]], self.energies[between[1]] + head_length]
else:
raise ValueError("between invalid!")
length = abs(y_poss[0] - y_poss[1])
if kind == "ket":
line = self.ax.plot(x_pos, y_poss, linestyle="-", color=color, linewidth=2, zorder=9)
elif kind == "bra":
line = self.ax.plot(x_pos, y_poss, linestyle="--", color=color, linewidth=2, zorder=9)
elif kind == "out":
yi = np.linspace(y_poss[0], y_poss[1], 100)
xi = (
np.sin((yi - y_poss[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40
+ x_pos[0]
)
line = self.ax.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt", zorder=9
)
else:
raise ValueError("kind is not 'ket', 'out', or 'bra'.")
# add arrow head
arrow_head = self.ax.arrow(
x_pos[1],
arrow_end - head_length * direction,
0,
0.0001 * direction,
head_width=head_length * head_aspect,
head_length=head_length,
fc=color,
ec=color,
linestyle="solid",
linewidth=0,
zorder=10,
)
# add text
text = self.ax.text(
np.mean(x_pos), -0.15, label, fontsize=font_size, horizontalalignment="center"
)
return line, arrow_head, text | [
"def",
"add_arrow",
"(",
"self",
",",
"index",
",",
"between",
",",
"kind",
",",
"label",
"=",
"\"\"",
",",
"head_length",
"=",
"0.1",
",",
"head_aspect",
"=",
"2",
",",
"font_size",
"=",
"14",
",",
"color",
"=",
"\"k\"",
",",
")",
":",
"if",
"hasa... | Add an arrow to the WMEL diagram.
Parameters
----------
index : integer
The interaction, or start and stop interaction for the arrow.
between : 2-element iterable of integers
The inital and final state of the arrow
kind : {'ket', 'bra'}
The kind of interaction.
label : string (optional)
Interaction label. Default is empty string.
head_length: number (optional)
size of arrow head
font_size : number (optional)
Label font size. Default is 14.
color : matplotlib color (optional)
Arrow color. Default is black.
Returns
-------
[line,arrow_head,text] | [
"Add",
"an",
"arrow",
"to",
"the",
"WMEL",
"diagram",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/WMEL.py#L98-L184 | train | 33,706 |
wright-group/WrightTools | WrightTools/diagrams/WMEL.py | Artist.label_rows | def label_rows(self, labels, font_size=15, text_buffer=1.5):
"""Label rows.
Parameters
----------
labels : list of strings
Labels.
font_size : number (optional)
Font size. Default is 15.
text_buffer : number
Buffer around text. Default is 1.5.
"""
for i in range(len(self.subplots)):
plot = self.subplots[i][-1]
plot.text(
text_buffer,
0.5,
labels[i],
fontsize=font_size,
verticalalignment="center",
horizontalalignment="center",
) | python | def label_rows(self, labels, font_size=15, text_buffer=1.5):
"""Label rows.
Parameters
----------
labels : list of strings
Labels.
font_size : number (optional)
Font size. Default is 15.
text_buffer : number
Buffer around text. Default is 1.5.
"""
for i in range(len(self.subplots)):
plot = self.subplots[i][-1]
plot.text(
text_buffer,
0.5,
labels[i],
fontsize=font_size,
verticalalignment="center",
horizontalalignment="center",
) | [
"def",
"label_rows",
"(",
"self",
",",
"labels",
",",
"font_size",
"=",
"15",
",",
"text_buffer",
"=",
"1.5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"subplots",
")",
")",
":",
"plot",
"=",
"self",
".",
"subplots",
"[",
... | Label rows.
Parameters
----------
labels : list of strings
Labels.
font_size : number (optional)
Font size. Default is 15.
text_buffer : number
Buffer around text. Default is 1.5. | [
"Label",
"rows",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/WMEL.py#L261-L282 | train | 33,707 |
wright-group/WrightTools | WrightTools/diagrams/WMEL.py | Artist.clear_diagram | def clear_diagram(self, diagram):
"""Clear diagram.
Parameters
----------
diagram : [column, row]
Diagram to clear.
"""
plot = self.subplots[diagram[1]][diagram[0]]
plot.cla() | python | def clear_diagram(self, diagram):
"""Clear diagram.
Parameters
----------
diagram : [column, row]
Diagram to clear.
"""
plot = self.subplots[diagram[1]][diagram[0]]
plot.cla() | [
"def",
"clear_diagram",
"(",
"self",
",",
"diagram",
")",
":",
"plot",
"=",
"self",
".",
"subplots",
"[",
"diagram",
"[",
"1",
"]",
"]",
"[",
"diagram",
"[",
"0",
"]",
"]",
"plot",
".",
"cla",
"(",
")"
] | Clear diagram.
Parameters
----------
diagram : [column, row]
Diagram to clear. | [
"Clear",
"diagram",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/WMEL.py#L307-L316 | train | 33,708 |
wright-group/WrightTools | WrightTools/diagrams/WMEL.py | Artist.add_arrow | def add_arrow(
self, diagram, number, between, kind, label="", head_length=0.075, font_size=7, color="k"
):
"""Add arrow.
Parameters
----------
diagram : [column, row]
Diagram position.
number : integer
Arrow position.
between : [start, stop]
Arrow span.
kind : {'ket', 'bra', 'out'}
Arrow style.
label : string (optional)
Arrow label. Default is ''.
head_length : number (optional)
Arrow head length. Default 0.075.
font_size : number (optional)
Font size. Default is 7.
color : matplotlib color
Arrow color. Default is 'k'.
Returns
-------
list
[line, arrow_head, text]
"""
column, row = diagram
x_pos = self.x_pos[number]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
y_poss = [self.energies[between[0]], self.energies[between[1]] - head_length]
elif arrow_length < 0:
direction = -1
y_poss = [self.energies[between[0]], self.energies[between[1]] + head_length]
else:
raise ValueError("Variable between invalid")
subplot = self.subplots[row][column]
# add line
length = abs(y_poss[0] - y_poss[1])
if kind == "ket":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="-", color=color, linewidth=2)
elif kind == "bra":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="--", color=color, linewidth=2)
elif kind == "out":
yi = np.linspace(y_poss[0], y_poss[1], 100)
xi = (
np.sin((yi - y_poss[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40 + x_pos
)
line = subplot.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt"
)
# add arrow head
arrow_head = subplot.arrow(
self.x_pos[number],
arrow_end - head_length * direction,
0,
0.0001 * direction,
head_width=head_length * 2,
head_length=head_length,
fc=color,
ec=color,
linestyle="solid",
linewidth=0,
)
# add text
text = subplot.text(
self.x_pos[number], -0.1, label, fontsize=font_size, horizontalalignment="center"
)
return line, arrow_head, text | python | def add_arrow(
self, diagram, number, between, kind, label="", head_length=0.075, font_size=7, color="k"
):
"""Add arrow.
Parameters
----------
diagram : [column, row]
Diagram position.
number : integer
Arrow position.
between : [start, stop]
Arrow span.
kind : {'ket', 'bra', 'out'}
Arrow style.
label : string (optional)
Arrow label. Default is ''.
head_length : number (optional)
Arrow head length. Default 0.075.
font_size : number (optional)
Font size. Default is 7.
color : matplotlib color
Arrow color. Default is 'k'.
Returns
-------
list
[line, arrow_head, text]
"""
column, row = diagram
x_pos = self.x_pos[number]
# calculate arrow length
arrow_length = self.energies[between[1]] - self.energies[between[0]]
arrow_end = self.energies[between[1]]
if arrow_length > 0:
direction = 1
y_poss = [self.energies[between[0]], self.energies[between[1]] - head_length]
elif arrow_length < 0:
direction = -1
y_poss = [self.energies[between[0]], self.energies[between[1]] + head_length]
else:
raise ValueError("Variable between invalid")
subplot = self.subplots[row][column]
# add line
length = abs(y_poss[0] - y_poss[1])
if kind == "ket":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="-", color=color, linewidth=2)
elif kind == "bra":
line = subplot.plot([x_pos, x_pos], y_poss, linestyle="--", color=color, linewidth=2)
elif kind == "out":
yi = np.linspace(y_poss[0], y_poss[1], 100)
xi = (
np.sin((yi - y_poss[0]) * int((1 / length) * 20) * 2 * np.pi * length) / 40 + x_pos
)
line = subplot.plot(
xi, yi, linestyle="-", color=color, linewidth=2, solid_capstyle="butt"
)
# add arrow head
arrow_head = subplot.arrow(
self.x_pos[number],
arrow_end - head_length * direction,
0,
0.0001 * direction,
head_width=head_length * 2,
head_length=head_length,
fc=color,
ec=color,
linestyle="solid",
linewidth=0,
)
# add text
text = subplot.text(
self.x_pos[number], -0.1, label, fontsize=font_size, horizontalalignment="center"
)
return line, arrow_head, text | [
"def",
"add_arrow",
"(",
"self",
",",
"diagram",
",",
"number",
",",
"between",
",",
"kind",
",",
"label",
"=",
"\"\"",
",",
"head_length",
"=",
"0.075",
",",
"font_size",
"=",
"7",
",",
"color",
"=",
"\"k\"",
")",
":",
"column",
",",
"row",
"=",
"... | Add arrow.
Parameters
----------
diagram : [column, row]
Diagram position.
number : integer
Arrow position.
between : [start, stop]
Arrow span.
kind : {'ket', 'bra', 'out'}
Arrow style.
label : string (optional)
Arrow label. Default is ''.
head_length : number (optional)
Arrow head length. Default 0.075.
font_size : number (optional)
Font size. Default is 7.
color : matplotlib color
Arrow color. Default is 'k'.
Returns
-------
list
[line, arrow_head, text] | [
"Add",
"arrow",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/WMEL.py#L318-L392 | train | 33,709 |
wright-group/WrightTools | WrightTools/diagrams/WMEL.py | Artist.plot | def plot(self, save_path=None, close=False, bbox_inches="tight", pad_inches=1):
"""Plot figure.
Parameters
----------
save_path : string (optional)
Save path. Default is None.
close : boolean (optional)
Toggle automatic figure closure after plotting.
Default is False.
bbox_inches : number (optional)
Bounding box size, in inches. Default is 'tight'.
pad_inches : number (optional)
Pad inches. Default is 1.
"""
# final manipulations
for plot in self.subplots.flatten():
# set limits
plot.set_xlim(-0.1, 1.1)
plot.set_ylim(-0.1, 1.1)
# remove guff
plot.axis("off")
# save
if save_path:
plt.savefig(
save_path,
transparent=True,
dpi=300,
bbox_inches=bbox_inches,
pad_inches=pad_inches,
)
# close
if close:
plt.close() | python | def plot(self, save_path=None, close=False, bbox_inches="tight", pad_inches=1):
"""Plot figure.
Parameters
----------
save_path : string (optional)
Save path. Default is None.
close : boolean (optional)
Toggle automatic figure closure after plotting.
Default is False.
bbox_inches : number (optional)
Bounding box size, in inches. Default is 'tight'.
pad_inches : number (optional)
Pad inches. Default is 1.
"""
# final manipulations
for plot in self.subplots.flatten():
# set limits
plot.set_xlim(-0.1, 1.1)
plot.set_ylim(-0.1, 1.1)
# remove guff
plot.axis("off")
# save
if save_path:
plt.savefig(
save_path,
transparent=True,
dpi=300,
bbox_inches=bbox_inches,
pad_inches=pad_inches,
)
# close
if close:
plt.close() | [
"def",
"plot",
"(",
"self",
",",
"save_path",
"=",
"None",
",",
"close",
"=",
"False",
",",
"bbox_inches",
"=",
"\"tight\"",
",",
"pad_inches",
"=",
"1",
")",
":",
"# final manipulations",
"for",
"plot",
"in",
"self",
".",
"subplots",
".",
"flatten",
"("... | Plot figure.
Parameters
----------
save_path : string (optional)
Save path. Default is None.
close : boolean (optional)
Toggle automatic figure closure after plotting.
Default is False.
bbox_inches : number (optional)
Bounding box size, in inches. Default is 'tight'.
pad_inches : number (optional)
Pad inches. Default is 1. | [
"Plot",
"figure",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/diagrams/WMEL.py#L394-L427 | train | 33,710 |
wright-group/WrightTools | WrightTools/collection/_collection.py | Collection.create_collection | def create_collection(self, name="collection", position=None, **kwargs):
"""Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child collection instantiation.
Returns
-------
WrightTools Collection
New child.
"""
if name in self.item_names:
wt_exceptions.ObjectExistsWarning.warn(name)
return self[name]
collection = Collection(
filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs
)
if position is not None:
self.attrs["item_names"] = np.insert(
self.attrs["item_names"][:-1], position, collection.natural_name.encode()
)
setattr(self, name, collection)
return collection | python | def create_collection(self, name="collection", position=None, **kwargs):
"""Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child collection instantiation.
Returns
-------
WrightTools Collection
New child.
"""
if name in self.item_names:
wt_exceptions.ObjectExistsWarning.warn(name)
return self[name]
collection = Collection(
filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs
)
if position is not None:
self.attrs["item_names"] = np.insert(
self.attrs["item_names"][:-1], position, collection.natural_name.encode()
)
setattr(self, name, collection)
return collection | [
"def",
"create_collection",
"(",
"self",
",",
"name",
"=",
"\"collection\"",
",",
"position",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"item_names",
":",
"wt_exceptions",
".",
"ObjectExistsWarning",
".",
"warn",
"(",... | Create a new child colleciton.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child collection instantiation.
Returns
-------
WrightTools Collection
New child. | [
"Create",
"a",
"new",
"child",
"colleciton",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/collection/_collection.py#L75-L103 | train | 33,711 |
wright-group/WrightTools | WrightTools/collection/_collection.py | Collection.create_data | def create_data(self, name="data", position=None, **kwargs):
"""Create a new child data.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child data instantiation.
Returns
-------
WrightTools Data
New child.
"""
if name in self.item_names:
wt_exceptions.ObjectExistsWarning.warn(name)
return self[name]
if name == "":
data = None
natural_name = "".encode()
else:
data = wt_data.Data(
filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs
)
natural_name = data.natural_name.encode()
if position is not None:
self.attrs["item_names"] = np.insert(
self.attrs["item_names"][:-1], position, natural_name
)
setattr(self, name, data)
return data | python | def create_data(self, name="data", position=None, **kwargs):
"""Create a new child data.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child data instantiation.
Returns
-------
WrightTools Data
New child.
"""
if name in self.item_names:
wt_exceptions.ObjectExistsWarning.warn(name)
return self[name]
if name == "":
data = None
natural_name = "".encode()
else:
data = wt_data.Data(
filepath=self.filepath, parent=self.name, name=name, edit_local=True, **kwargs
)
natural_name = data.natural_name.encode()
if position is not None:
self.attrs["item_names"] = np.insert(
self.attrs["item_names"][:-1], position, natural_name
)
setattr(self, name, data)
return data | [
"def",
"create_data",
"(",
"self",
",",
"name",
"=",
"\"data\"",
",",
"position",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"in",
"self",
".",
"item_names",
":",
"wt_exceptions",
".",
"ObjectExistsWarning",
".",
"warn",
"(",
"name",
... | Create a new child data.
Parameters
----------
name : string
Unique identifier.
position : integer (optional)
Location to insert. Default is None (append).
kwargs
Additional arguments to child data instantiation.
Returns
-------
WrightTools Data
New child. | [
"Create",
"a",
"new",
"child",
"data",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/collection/_collection.py#L105-L139 | train | 33,712 |
wright-group/WrightTools | WrightTools/collection/_collection.py | Collection.flush | def flush(self):
"""Ensure contents are written to file."""
for name in self.item_names:
item = self[name]
item.flush()
self.file.flush() | python | def flush(self):
"""Ensure contents are written to file."""
for name in self.item_names:
item = self[name]
item.flush()
self.file.flush() | [
"def",
"flush",
"(",
"self",
")",
":",
"for",
"name",
"in",
"self",
".",
"item_names",
":",
"item",
"=",
"self",
"[",
"name",
"]",
"item",
".",
"flush",
"(",
")",
"self",
".",
"file",
".",
"flush",
"(",
")"
] | Ensure contents are written to file. | [
"Ensure",
"contents",
"are",
"written",
"to",
"file",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/collection/_collection.py#L158-L163 | train | 33,713 |
wright-group/WrightTools | WrightTools/kit/_array.py | closest_pair | def closest_pair(arr, give="indicies"):
"""Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method because I need it now to use on some
relatively small arrays. Feel free to refactor if you need this operation
done as fast as possible. - Blaise 2016-02-07
Parameters
----------
arr : numpy.ndarray
The array to search.
give : {'indicies', 'distance'} (optional)
Toggle return behavior. If 'distance', returns a single float - the
closest distance itself. Default is indicies.
Returns
-------
list of lists of two tuples
List containing lists of two tuples: indicies the nearest pair in the
array.
>>> arr = np.array([0, 1, 2, 3, 3, 4, 5, 6, 1])
>>> closest_pair(arr)
[[(1,), (8,)], [(3,), (4,)]]
"""
idxs = [idx for idx in np.ndindex(arr.shape)]
outs = []
min_dist = arr.max() - arr.min()
for idxa in idxs:
for idxb in idxs:
if idxa == idxb:
continue
dist = abs(arr[idxa] - arr[idxb])
if dist == min_dist:
if not [idxb, idxa] in outs:
outs.append([idxa, idxb])
elif dist < min_dist:
min_dist = dist
outs = [[idxa, idxb]]
if give == "indicies":
return outs
elif give == "distance":
return min_dist
else:
raise KeyError("give not recognized in closest_pair") | python | def closest_pair(arr, give="indicies"):
"""Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method because I need it now to use on some
relatively small arrays. Feel free to refactor if you need this operation
done as fast as possible. - Blaise 2016-02-07
Parameters
----------
arr : numpy.ndarray
The array to search.
give : {'indicies', 'distance'} (optional)
Toggle return behavior. If 'distance', returns a single float - the
closest distance itself. Default is indicies.
Returns
-------
list of lists of two tuples
List containing lists of two tuples: indicies the nearest pair in the
array.
>>> arr = np.array([0, 1, 2, 3, 3, 4, 5, 6, 1])
>>> closest_pair(arr)
[[(1,), (8,)], [(3,), (4,)]]
"""
idxs = [idx for idx in np.ndindex(arr.shape)]
outs = []
min_dist = arr.max() - arr.min()
for idxa in idxs:
for idxb in idxs:
if idxa == idxb:
continue
dist = abs(arr[idxa] - arr[idxb])
if dist == min_dist:
if not [idxb, idxa] in outs:
outs.append([idxa, idxb])
elif dist < min_dist:
min_dist = dist
outs = [[idxa, idxb]]
if give == "indicies":
return outs
elif give == "distance":
return min_dist
else:
raise KeyError("give not recognized in closest_pair") | [
"def",
"closest_pair",
"(",
"arr",
",",
"give",
"=",
"\"indicies\"",
")",
":",
"idxs",
"=",
"[",
"idx",
"for",
"idx",
"in",
"np",
".",
"ndindex",
"(",
"arr",
".",
"shape",
")",
"]",
"outs",
"=",
"[",
"]",
"min_dist",
"=",
"arr",
".",
"max",
"(",
... | Find the pair of indices corresponding to the closest elements in an array.
If multiple pairs are equally close, both pairs of indicies are returned.
Optionally returns the closest distance itself.
I am sure that this could be written as a cheaper operation. I
wrote this as a quick and dirty method because I need it now to use on some
relatively small arrays. Feel free to refactor if you need this operation
done as fast as possible. - Blaise 2016-02-07
Parameters
----------
arr : numpy.ndarray
The array to search.
give : {'indicies', 'distance'} (optional)
Toggle return behavior. If 'distance', returns a single float - the
closest distance itself. Default is indicies.
Returns
-------
list of lists of two tuples
List containing lists of two tuples: indicies the nearest pair in the
array.
>>> arr = np.array([0, 1, 2, 3, 3, 4, 5, 6, 1])
>>> closest_pair(arr)
[[(1,), (8,)], [(3,), (4,)]] | [
"Find",
"the",
"pair",
"of",
"indices",
"corresponding",
"to",
"the",
"closest",
"elements",
"in",
"an",
"array",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L35-L84 | train | 33,714 |
wright-group/WrightTools | WrightTools/kit/_array.py | diff | def diff(xi, yi, order=1) -> np.ndarray:
"""Take the numerical derivative of a 1D array.
Output is mapped onto the original coordinates using linear interpolation.
Expects monotonic xi values.
Parameters
----------
xi : 1D array-like
Coordinates.
yi : 1D array-like
Values.
order : positive integer (optional)
Order of differentiation.
Returns
-------
1D numpy array
Numerical derivative. Has the same shape as the input arrays.
"""
yi = np.array(yi).copy()
flip = False
if xi[-1] < xi[0]:
xi = np.flipud(xi.copy())
yi = np.flipud(yi)
flip = True
midpoints = (xi[1:] + xi[:-1]) / 2
for _ in range(order):
d = np.diff(yi)
d /= np.diff(xi)
yi = np.interp(xi, midpoints, d)
if flip:
yi = np.flipud(yi)
return yi | python | def diff(xi, yi, order=1) -> np.ndarray:
"""Take the numerical derivative of a 1D array.
Output is mapped onto the original coordinates using linear interpolation.
Expects monotonic xi values.
Parameters
----------
xi : 1D array-like
Coordinates.
yi : 1D array-like
Values.
order : positive integer (optional)
Order of differentiation.
Returns
-------
1D numpy array
Numerical derivative. Has the same shape as the input arrays.
"""
yi = np.array(yi).copy()
flip = False
if xi[-1] < xi[0]:
xi = np.flipud(xi.copy())
yi = np.flipud(yi)
flip = True
midpoints = (xi[1:] + xi[:-1]) / 2
for _ in range(order):
d = np.diff(yi)
d /= np.diff(xi)
yi = np.interp(xi, midpoints, d)
if flip:
yi = np.flipud(yi)
return yi | [
"def",
"diff",
"(",
"xi",
",",
"yi",
",",
"order",
"=",
"1",
")",
"->",
"np",
".",
"ndarray",
":",
"yi",
"=",
"np",
".",
"array",
"(",
"yi",
")",
".",
"copy",
"(",
")",
"flip",
"=",
"False",
"if",
"xi",
"[",
"-",
"1",
"]",
"<",
"xi",
"[",... | Take the numerical derivative of a 1D array.
Output is mapped onto the original coordinates using linear interpolation.
Expects monotonic xi values.
Parameters
----------
xi : 1D array-like
Coordinates.
yi : 1D array-like
Values.
order : positive integer (optional)
Order of differentiation.
Returns
-------
1D numpy array
Numerical derivative. Has the same shape as the input arrays. | [
"Take",
"the",
"numerical",
"derivative",
"of",
"a",
"1D",
"array",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L87-L120 | train | 33,715 |
wright-group/WrightTools | WrightTools/kit/_array.py | fft | def fft(xi, yi, axis=0) -> tuple:
"""Take the 1D FFT of an N-dimensional array and return "sensible" properly shifted arrays.
Parameters
----------
xi : numpy.ndarray
1D array over which the points to be FFT'ed are defined
yi : numpy.ndarray
ND array with values to FFT
axis : int
axis of yi to perform FFT over
Returns
-------
xi : 1D numpy.ndarray
1D array. Conjugate to input xi. Example: if input xi is in the time
domain, output xi is in frequency domain.
yi : ND numpy.ndarray
FFT. Has the same shape as the input array (yi).
"""
# xi must be 1D
if xi.ndim != 1:
raise wt_exceptions.DimensionalityError(1, xi.ndim)
# xi must be evenly spaced
spacing = np.diff(xi)
if not np.allclose(spacing, spacing.mean()):
raise RuntimeError("WrightTools.kit.fft: argument xi must be evenly spaced")
# fft
yi = np.fft.fft(yi, axis=axis)
d = (xi.max() - xi.min()) / (xi.size - 1)
xi = np.fft.fftfreq(xi.size, d=d)
# shift
xi = np.fft.fftshift(xi)
yi = np.fft.fftshift(yi, axes=axis)
return xi, yi | python | def fft(xi, yi, axis=0) -> tuple:
"""Take the 1D FFT of an N-dimensional array and return "sensible" properly shifted arrays.
Parameters
----------
xi : numpy.ndarray
1D array over which the points to be FFT'ed are defined
yi : numpy.ndarray
ND array with values to FFT
axis : int
axis of yi to perform FFT over
Returns
-------
xi : 1D numpy.ndarray
1D array. Conjugate to input xi. Example: if input xi is in the time
domain, output xi is in frequency domain.
yi : ND numpy.ndarray
FFT. Has the same shape as the input array (yi).
"""
# xi must be 1D
if xi.ndim != 1:
raise wt_exceptions.DimensionalityError(1, xi.ndim)
# xi must be evenly spaced
spacing = np.diff(xi)
if not np.allclose(spacing, spacing.mean()):
raise RuntimeError("WrightTools.kit.fft: argument xi must be evenly spaced")
# fft
yi = np.fft.fft(yi, axis=axis)
d = (xi.max() - xi.min()) / (xi.size - 1)
xi = np.fft.fftfreq(xi.size, d=d)
# shift
xi = np.fft.fftshift(xi)
yi = np.fft.fftshift(yi, axes=axis)
return xi, yi | [
"def",
"fft",
"(",
"xi",
",",
"yi",
",",
"axis",
"=",
"0",
")",
"->",
"tuple",
":",
"# xi must be 1D",
"if",
"xi",
".",
"ndim",
"!=",
"1",
":",
"raise",
"wt_exceptions",
".",
"DimensionalityError",
"(",
"1",
",",
"xi",
".",
"ndim",
")",
"# xi must be... | Take the 1D FFT of an N-dimensional array and return "sensible" properly shifted arrays.
Parameters
----------
xi : numpy.ndarray
1D array over which the points to be FFT'ed are defined
yi : numpy.ndarray
ND array with values to FFT
axis : int
axis of yi to perform FFT over
Returns
-------
xi : 1D numpy.ndarray
1D array. Conjugate to input xi. Example: if input xi is in the time
domain, output xi is in frequency domain.
yi : ND numpy.ndarray
FFT. Has the same shape as the input array (yi). | [
"Take",
"the",
"1D",
"FFT",
"of",
"an",
"N",
"-",
"dimensional",
"array",
"and",
"return",
"sensible",
"properly",
"shifted",
"arrays",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L123-L157 | train | 33,716 |
wright-group/WrightTools | WrightTools/kit/_array.py | joint_shape | def joint_shape(*args) -> tuple:
"""Given a set of arrays, return the joint shape.
Parameters
----------
args : array-likes
Returns
-------
tuple of int
Joint shape.
"""
if len(args) == 0:
return ()
shape = []
shapes = [a.shape for a in args]
ndim = args[0].ndim
for i in range(ndim):
shape.append(max([s[i] for s in shapes]))
return tuple(shape) | python | def joint_shape(*args) -> tuple:
"""Given a set of arrays, return the joint shape.
Parameters
----------
args : array-likes
Returns
-------
tuple of int
Joint shape.
"""
if len(args) == 0:
return ()
shape = []
shapes = [a.shape for a in args]
ndim = args[0].ndim
for i in range(ndim):
shape.append(max([s[i] for s in shapes]))
return tuple(shape) | [
"def",
"joint_shape",
"(",
"*",
"args",
")",
"->",
"tuple",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"(",
")",
"shape",
"=",
"[",
"]",
"shapes",
"=",
"[",
"a",
".",
"shape",
"for",
"a",
"in",
"args",
"]",
"ndim",
"=",
"ar... | Given a set of arrays, return the joint shape.
Parameters
----------
args : array-likes
Returns
-------
tuple of int
Joint shape. | [
"Given",
"a",
"set",
"of",
"arrays",
"return",
"the",
"joint",
"shape",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L160-L179 | train | 33,717 |
wright-group/WrightTools | WrightTools/kit/_array.py | orthogonal | def orthogonal(*args) -> bool:
"""Determine if a set of arrays are orthogonal.
Parameters
----------
args : array-likes or array shapes
Returns
-------
bool
Array orthogonality condition.
"""
for i, arg in enumerate(args):
if hasattr(arg, "shape"):
args[i] = arg.shape
for s in zip(*args):
if np.product(s) != max(s):
return False
return True | python | def orthogonal(*args) -> bool:
"""Determine if a set of arrays are orthogonal.
Parameters
----------
args : array-likes or array shapes
Returns
-------
bool
Array orthogonality condition.
"""
for i, arg in enumerate(args):
if hasattr(arg, "shape"):
args[i] = arg.shape
for s in zip(*args):
if np.product(s) != max(s):
return False
return True | [
"def",
"orthogonal",
"(",
"*",
"args",
")",
"->",
"bool",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"hasattr",
"(",
"arg",
",",
"\"shape\"",
")",
":",
"args",
"[",
"i",
"]",
"=",
"arg",
".",
"shape",
"for",
"s... | Determine if a set of arrays are orthogonal.
Parameters
----------
args : array-likes or array shapes
Returns
-------
bool
Array orthogonality condition. | [
"Determine",
"if",
"a",
"set",
"of",
"arrays",
"are",
"orthogonal",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L182-L200 | train | 33,718 |
wright-group/WrightTools | WrightTools/kit/_array.py | remove_nans_1D | def remove_nans_1D(*args) -> tuple:
"""Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same order as given, with nan indicies removed.
"""
vals = np.isnan(args[0])
for a in args:
vals |= np.isnan(a)
return tuple(np.array(a)[~vals] for a in args) | python | def remove_nans_1D(*args) -> tuple:
"""Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same order as given, with nan indicies removed.
"""
vals = np.isnan(args[0])
for a in args:
vals |= np.isnan(a)
return tuple(np.array(a)[~vals] for a in args) | [
"def",
"remove_nans_1D",
"(",
"*",
"args",
")",
"->",
"tuple",
":",
"vals",
"=",
"np",
".",
"isnan",
"(",
"args",
"[",
"0",
"]",
")",
"for",
"a",
"in",
"args",
":",
"vals",
"|=",
"np",
".",
"isnan",
"(",
"a",
")",
"return",
"tuple",
"(",
"np",
... | Remove nans in a set of 1D arrays.
Removes indicies in all arrays if any array is nan at that index.
All input arrays must have the same size.
Parameters
----------
args : 1D arrays
Returns
-------
tuple
Tuple of 1D arrays in same order as given, with nan indicies removed. | [
"Remove",
"nans",
"in",
"a",
"set",
"of",
"1D",
"arrays",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L203-L221 | train | 33,719 |
wright-group/WrightTools | WrightTools/kit/_array.py | share_nans | def share_nans(*arrs) -> tuple:
"""Take a list of nD arrays and return a new list of nD arrays.
The new list is in the same order as the old list.
If one indexed element in an old array is nan then every element for that
index in all new arrays in the list is then nan.
Parameters
----------
*arrs : nD arrays.
Returns
-------
list
List of nD arrays in same order as given, with nan indicies syncronized.
"""
nans = np.zeros(joint_shape(*arrs))
for arr in arrs:
nans *= arr
return tuple([a + nans for a in arrs]) | python | def share_nans(*arrs) -> tuple:
"""Take a list of nD arrays and return a new list of nD arrays.
The new list is in the same order as the old list.
If one indexed element in an old array is nan then every element for that
index in all new arrays in the list is then nan.
Parameters
----------
*arrs : nD arrays.
Returns
-------
list
List of nD arrays in same order as given, with nan indicies syncronized.
"""
nans = np.zeros(joint_shape(*arrs))
for arr in arrs:
nans *= arr
return tuple([a + nans for a in arrs]) | [
"def",
"share_nans",
"(",
"*",
"arrs",
")",
"->",
"tuple",
":",
"nans",
"=",
"np",
".",
"zeros",
"(",
"joint_shape",
"(",
"*",
"arrs",
")",
")",
"for",
"arr",
"in",
"arrs",
":",
"nans",
"*=",
"arr",
"return",
"tuple",
"(",
"[",
"a",
"+",
"nans",
... | Take a list of nD arrays and return a new list of nD arrays.
The new list is in the same order as the old list.
If one indexed element in an old array is nan then every element for that
index in all new arrays in the list is then nan.
Parameters
----------
*arrs : nD arrays.
Returns
-------
list
List of nD arrays in same order as given, with nan indicies syncronized. | [
"Take",
"a",
"list",
"of",
"nD",
"arrays",
"and",
"return",
"a",
"new",
"list",
"of",
"nD",
"arrays",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L224-L243 | train | 33,720 |
wright-group/WrightTools | WrightTools/kit/_array.py | smooth_1D | def smooth_1D(arr, n=10, smooth_type="flat") -> np.ndarray:
"""Smooth 1D data using a window function.
Edge effects will be present.
Parameters
----------
arr : array_like
Input array, 1D.
n : int (optional)
Window length.
smooth_type : {'flat', 'hanning', 'hamming', 'bartlett', 'blackman'} (optional)
Type of window function to convolve data with.
'flat' window will produce a moving average smoothing.
Returns
-------
array_like
Smoothed 1D array.
"""
# check array input
if arr.ndim != 1:
raise wt_exceptions.DimensionalityError(1, arr.ndim)
if arr.size < n:
message = "Input array size must be larger than window size."
raise wt_exceptions.ValueError(message)
if n < 3:
return arr
# construct window array
if smooth_type == "flat":
w = np.ones(n, dtype=arr.dtype)
elif smooth_type == "hanning":
w = np.hanning(n)
elif smooth_type == "hamming":
w = np.hamming(n)
elif smooth_type == "bartlett":
w = np.bartlett(n)
elif smooth_type == "blackman":
w = np.blackman(n)
else:
message = "Given smooth_type, {0}, not available.".format(str(smooth_type))
raise wt_exceptions.ValueError(message)
# convolve reflected array with window function
out = np.convolve(w / w.sum(), arr, mode="same")
return out | python | def smooth_1D(arr, n=10, smooth_type="flat") -> np.ndarray:
"""Smooth 1D data using a window function.
Edge effects will be present.
Parameters
----------
arr : array_like
Input array, 1D.
n : int (optional)
Window length.
smooth_type : {'flat', 'hanning', 'hamming', 'bartlett', 'blackman'} (optional)
Type of window function to convolve data with.
'flat' window will produce a moving average smoothing.
Returns
-------
array_like
Smoothed 1D array.
"""
# check array input
if arr.ndim != 1:
raise wt_exceptions.DimensionalityError(1, arr.ndim)
if arr.size < n:
message = "Input array size must be larger than window size."
raise wt_exceptions.ValueError(message)
if n < 3:
return arr
# construct window array
if smooth_type == "flat":
w = np.ones(n, dtype=arr.dtype)
elif smooth_type == "hanning":
w = np.hanning(n)
elif smooth_type == "hamming":
w = np.hamming(n)
elif smooth_type == "bartlett":
w = np.bartlett(n)
elif smooth_type == "blackman":
w = np.blackman(n)
else:
message = "Given smooth_type, {0}, not available.".format(str(smooth_type))
raise wt_exceptions.ValueError(message)
# convolve reflected array with window function
out = np.convolve(w / w.sum(), arr, mode="same")
return out | [
"def",
"smooth_1D",
"(",
"arr",
",",
"n",
"=",
"10",
",",
"smooth_type",
"=",
"\"flat\"",
")",
"->",
"np",
".",
"ndarray",
":",
"# check array input",
"if",
"arr",
".",
"ndim",
"!=",
"1",
":",
"raise",
"wt_exceptions",
".",
"DimensionalityError",
"(",
"1... | Smooth 1D data using a window function.
Edge effects will be present.
Parameters
----------
arr : array_like
Input array, 1D.
n : int (optional)
Window length.
smooth_type : {'flat', 'hanning', 'hamming', 'bartlett', 'blackman'} (optional)
Type of window function to convolve data with.
'flat' window will produce a moving average smoothing.
Returns
-------
array_like
Smoothed 1D array. | [
"Smooth",
"1D",
"data",
"using",
"a",
"window",
"function",
".",
"Edge",
"effects",
"will",
"be",
"present",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L246-L291 | train | 33,721 |
wright-group/WrightTools | WrightTools/kit/_array.py | svd | def svd(a, i=None) -> tuple:
"""Singular Value Decomposition.
Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v`
are unitary and `s` is a 1D array of `a`'s singular values.
Parameters
----------
a : array_like
Input array.
i : int or slice (optional)
What singular value "slice" to return.
Default is None which returns unitary 2D arrays.
Returns
-------
tuple
Decomposed arrays in order `u`, `v`, `s`
"""
u, s, v = np.linalg.svd(a, full_matrices=False, compute_uv=True)
u = u.T
if i is None:
return u, v, s
else:
return u[i], v[i], s[i] | python | def svd(a, i=None) -> tuple:
"""Singular Value Decomposition.
Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v`
are unitary and `s` is a 1D array of `a`'s singular values.
Parameters
----------
a : array_like
Input array.
i : int or slice (optional)
What singular value "slice" to return.
Default is None which returns unitary 2D arrays.
Returns
-------
tuple
Decomposed arrays in order `u`, `v`, `s`
"""
u, s, v = np.linalg.svd(a, full_matrices=False, compute_uv=True)
u = u.T
if i is None:
return u, v, s
else:
return u[i], v[i], s[i] | [
"def",
"svd",
"(",
"a",
",",
"i",
"=",
"None",
")",
"->",
"tuple",
":",
"u",
",",
"s",
",",
"v",
"=",
"np",
".",
"linalg",
".",
"svd",
"(",
"a",
",",
"full_matrices",
"=",
"False",
",",
"compute_uv",
"=",
"True",
")",
"u",
"=",
"u",
".",
"T... | Singular Value Decomposition.
Factors the matrix `a` as ``u * np.diag(s) * v``, where `u` and `v`
are unitary and `s` is a 1D array of `a`'s singular values.
Parameters
----------
a : array_like
Input array.
i : int or slice (optional)
What singular value "slice" to return.
Default is None which returns unitary 2D arrays.
Returns
-------
tuple
Decomposed arrays in order `u`, `v`, `s` | [
"Singular",
"Value",
"Decomposition",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L294-L318 | train | 33,722 |
wright-group/WrightTools | WrightTools/kit/_array.py | unique | def unique(arr, tolerance=1e-6) -> np.ndarray:
"""Return unique elements in 1D array, within tolerance.
Parameters
----------
arr : array_like
Input array. This will be flattened if it is not already 1D.
tolerance : number (optional)
The tolerance for uniqueness.
Returns
-------
array
The sorted unique values.
"""
arr = sorted(arr.flatten())
unique = []
while len(arr) > 0:
current = arr[0]
lis = [xi for xi in arr if np.abs(current - xi) < tolerance]
arr = [xi for xi in arr if not np.abs(lis[0] - xi) < tolerance]
xi_lis_average = sum(lis) / len(lis)
unique.append(xi_lis_average)
return np.array(unique) | python | def unique(arr, tolerance=1e-6) -> np.ndarray:
"""Return unique elements in 1D array, within tolerance.
Parameters
----------
arr : array_like
Input array. This will be flattened if it is not already 1D.
tolerance : number (optional)
The tolerance for uniqueness.
Returns
-------
array
The sorted unique values.
"""
arr = sorted(arr.flatten())
unique = []
while len(arr) > 0:
current = arr[0]
lis = [xi for xi in arr if np.abs(current - xi) < tolerance]
arr = [xi for xi in arr if not np.abs(lis[0] - xi) < tolerance]
xi_lis_average = sum(lis) / len(lis)
unique.append(xi_lis_average)
return np.array(unique) | [
"def",
"unique",
"(",
"arr",
",",
"tolerance",
"=",
"1e-6",
")",
"->",
"np",
".",
"ndarray",
":",
"arr",
"=",
"sorted",
"(",
"arr",
".",
"flatten",
"(",
")",
")",
"unique",
"=",
"[",
"]",
"while",
"len",
"(",
"arr",
")",
">",
"0",
":",
"current... | Return unique elements in 1D array, within tolerance.
Parameters
----------
arr : array_like
Input array. This will be flattened if it is not already 1D.
tolerance : number (optional)
The tolerance for uniqueness.
Returns
-------
array
The sorted unique values. | [
"Return",
"unique",
"elements",
"in",
"1D",
"array",
"within",
"tolerance",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L321-L344 | train | 33,723 |
wright-group/WrightTools | WrightTools/kit/_array.py | valid_index | def valid_index(index, shape) -> tuple:
"""Get a valid index for a broadcastable shape.
Parameters
----------
index : tuple
Given index.
shape : tuple of int
Shape.
Returns
-------
tuple
Valid index.
"""
# append slices to index
index = list(index)
while len(index) < len(shape):
index.append(slice(None))
# fill out, in reverse
out = []
for i, s in zip(index[::-1], shape[::-1]):
if s == 1:
if isinstance(i, slice):
out.append(slice(None))
else:
out.append(0)
else:
out.append(i)
return tuple(out[::-1]) | python | def valid_index(index, shape) -> tuple:
"""Get a valid index for a broadcastable shape.
Parameters
----------
index : tuple
Given index.
shape : tuple of int
Shape.
Returns
-------
tuple
Valid index.
"""
# append slices to index
index = list(index)
while len(index) < len(shape):
index.append(slice(None))
# fill out, in reverse
out = []
for i, s in zip(index[::-1], shape[::-1]):
if s == 1:
if isinstance(i, slice):
out.append(slice(None))
else:
out.append(0)
else:
out.append(i)
return tuple(out[::-1]) | [
"def",
"valid_index",
"(",
"index",
",",
"shape",
")",
"->",
"tuple",
":",
"# append slices to index",
"index",
"=",
"list",
"(",
"index",
")",
"while",
"len",
"(",
"index",
")",
"<",
"len",
"(",
"shape",
")",
":",
"index",
".",
"append",
"(",
"slice",... | Get a valid index for a broadcastable shape.
Parameters
----------
index : tuple
Given index.
shape : tuple of int
Shape.
Returns
-------
tuple
Valid index. | [
"Get",
"a",
"valid",
"index",
"for",
"a",
"broadcastable",
"shape",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L347-L376 | train | 33,724 |
wright-group/WrightTools | WrightTools/kit/_array.py | mask_reduce | def mask_reduce(mask):
"""Reduce a boolean mask, removing all false slices in any dimension.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
Returns
-------
A boolean mask with no all False slices.
"""
mask = mask.copy()
for i in range(len(mask.shape)):
a = mask.copy()
j = list(range(len(mask.shape)))
j.remove(i)
j = tuple(j)
a = a.max(axis=j, keepdims=True)
idx = [slice(None)] * len(mask.shape)
a = a.flatten()
idx[i] = [k for k in range(len(a)) if a[k]]
mask = mask[tuple(idx)]
return mask | python | def mask_reduce(mask):
"""Reduce a boolean mask, removing all false slices in any dimension.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
Returns
-------
A boolean mask with no all False slices.
"""
mask = mask.copy()
for i in range(len(mask.shape)):
a = mask.copy()
j = list(range(len(mask.shape)))
j.remove(i)
j = tuple(j)
a = a.max(axis=j, keepdims=True)
idx = [slice(None)] * len(mask.shape)
a = a.flatten()
idx[i] = [k for k in range(len(a)) if a[k]]
mask = mask[tuple(idx)]
return mask | [
"def",
"mask_reduce",
"(",
"mask",
")",
":",
"mask",
"=",
"mask",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"mask",
".",
"shape",
")",
")",
":",
"a",
"=",
"mask",
".",
"copy",
"(",
")",
"j",
"=",
"list",
"(",
"range",... | Reduce a boolean mask, removing all false slices in any dimension.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
Returns
-------
A boolean mask with no all False slices. | [
"Reduce",
"a",
"boolean",
"mask",
"removing",
"all",
"false",
"slices",
"in",
"any",
"dimension",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L379-L402 | train | 33,725 |
wright-group/WrightTools | WrightTools/kit/_array.py | enforce_mask_shape | def enforce_mask_shape(mask, shape):
"""Reduce a boolean mask to fit a given shape.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
shape : tuple of int
Shape which broadcasts to the mask shape.
Returns
-------
A boolean mask, collapsed along axes where the shape given has one element.
"""
red = tuple([i for i in range(len(shape)) if shape[i] == 1])
return mask.max(axis=red, keepdims=True) | python | def enforce_mask_shape(mask, shape):
"""Reduce a boolean mask to fit a given shape.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
shape : tuple of int
Shape which broadcasts to the mask shape.
Returns
-------
A boolean mask, collapsed along axes where the shape given has one element.
"""
red = tuple([i for i in range(len(shape)) if shape[i] == 1])
return mask.max(axis=red, keepdims=True) | [
"def",
"enforce_mask_shape",
"(",
"mask",
",",
"shape",
")",
":",
"red",
"=",
"tuple",
"(",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"shape",
")",
")",
"if",
"shape",
"[",
"i",
"]",
"==",
"1",
"]",
")",
"return",
"mask",
".",
"max"... | Reduce a boolean mask to fit a given shape.
Parameters
----------
mask : ndarray with bool dtype
The mask which is to be reduced
shape : tuple of int
Shape which broadcasts to the mask shape.
Returns
-------
A boolean mask, collapsed along axes where the shape given has one element. | [
"Reduce",
"a",
"boolean",
"mask",
"to",
"fit",
"a",
"given",
"shape",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_array.py#L405-L420 | train | 33,726 |
wright-group/WrightTools | WrightTools/datasets/__init__.py | DatasetContainer._from_directory | def _from_directory(self, dirname, prefix=""):
"""Add dataset from files in a directory.
Parameters
----------
dirname : string
Directory name.
prefix : string
Prefix.
"""
ps = [os.path.join(here, dirname, p) for p in os.listdir(os.path.join(here, dirname))]
n = prefix + wt_kit.string2identifier(os.path.basename(dirname))
setattr(self, n, ps) | python | def _from_directory(self, dirname, prefix=""):
"""Add dataset from files in a directory.
Parameters
----------
dirname : string
Directory name.
prefix : string
Prefix.
"""
ps = [os.path.join(here, dirname, p) for p in os.listdir(os.path.join(here, dirname))]
n = prefix + wt_kit.string2identifier(os.path.basename(dirname))
setattr(self, n, ps) | [
"def",
"_from_directory",
"(",
"self",
",",
"dirname",
",",
"prefix",
"=",
"\"\"",
")",
":",
"ps",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"here",
",",
"dirname",
",",
"p",
")",
"for",
"p",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"pa... | Add dataset from files in a directory.
Parameters
----------
dirname : string
Directory name.
prefix : string
Prefix. | [
"Add",
"dataset",
"from",
"files",
"in",
"a",
"directory",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/datasets/__init__.py#L37-L49 | train | 33,727 |
wright-group/WrightTools | WrightTools/kit/_utilities.py | string2identifier | def string2identifier(s):
"""Turn a string into a valid python identifier.
Currently only allows ASCII letters and underscore. Illegal characters
are replaced with underscore. This is slightly more opinionated than
python 3 itself, and may be refactored in future (see PEP 3131).
Parameters
----------
s : string
string to convert
Returns
-------
str
valid python identifier.
"""
# https://docs.python.org/3/reference/lexical_analysis.html#identifiers
# https://www.python.org/dev/peps/pep-3131/
if len(s) == 0:
return "_"
if s[0] not in string.ascii_letters:
s = "_" + s
valids = string.ascii_letters + string.digits + "_"
out = ""
for i, char in enumerate(s):
if char in valids:
out += char
else:
out += "_"
return out | python | def string2identifier(s):
"""Turn a string into a valid python identifier.
Currently only allows ASCII letters and underscore. Illegal characters
are replaced with underscore. This is slightly more opinionated than
python 3 itself, and may be refactored in future (see PEP 3131).
Parameters
----------
s : string
string to convert
Returns
-------
str
valid python identifier.
"""
# https://docs.python.org/3/reference/lexical_analysis.html#identifiers
# https://www.python.org/dev/peps/pep-3131/
if len(s) == 0:
return "_"
if s[0] not in string.ascii_letters:
s = "_" + s
valids = string.ascii_letters + string.digits + "_"
out = ""
for i, char in enumerate(s):
if char in valids:
out += char
else:
out += "_"
return out | [
"def",
"string2identifier",
"(",
"s",
")",
":",
"# https://docs.python.org/3/reference/lexical_analysis.html#identifiers",
"# https://www.python.org/dev/peps/pep-3131/",
"if",
"len",
"(",
"s",
")",
"==",
"0",
":",
"return",
"\"_\"",
"if",
"s",
"[",
"0",
"]",
"not",
"i... | Turn a string into a valid python identifier.
Currently only allows ASCII letters and underscore. Illegal characters
are replaced with underscore. This is slightly more opinionated than
python 3 itself, and may be refactored in future (see PEP 3131).
Parameters
----------
s : string
string to convert
Returns
-------
str
valid python identifier. | [
"Turn",
"a",
"string",
"into",
"a",
"valid",
"python",
"identifier",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_utilities.py#L20-L50 | train | 33,728 |
wright-group/WrightTools | WrightTools/units.py | converter | def converter(val, current_unit, destination_unit):
"""Convert from one unit to another.
Parameters
----------
val : number
Number to convert.
current_unit : string
Current unit.
destination_unit : string
Destination unit.
Returns
-------
number
Converted value.
"""
x = val
for dic in dicts.values():
if current_unit in dic.keys() and destination_unit in dic.keys():
try:
native = eval(dic[current_unit][0])
except ZeroDivisionError:
native = np.inf
x = native # noqa: F841
try:
out = eval(dic[destination_unit][1])
except ZeroDivisionError:
out = np.inf
return out
# if all dictionaries fail
if current_unit is None and destination_unit is None:
pass
else:
warnings.warn(
"conversion {0} to {1} not valid: returning input".format(
current_unit, destination_unit
)
)
return val | python | def converter(val, current_unit, destination_unit):
"""Convert from one unit to another.
Parameters
----------
val : number
Number to convert.
current_unit : string
Current unit.
destination_unit : string
Destination unit.
Returns
-------
number
Converted value.
"""
x = val
for dic in dicts.values():
if current_unit in dic.keys() and destination_unit in dic.keys():
try:
native = eval(dic[current_unit][0])
except ZeroDivisionError:
native = np.inf
x = native # noqa: F841
try:
out = eval(dic[destination_unit][1])
except ZeroDivisionError:
out = np.inf
return out
# if all dictionaries fail
if current_unit is None and destination_unit is None:
pass
else:
warnings.warn(
"conversion {0} to {1} not valid: returning input".format(
current_unit, destination_unit
)
)
return val | [
"def",
"converter",
"(",
"val",
",",
"current_unit",
",",
"destination_unit",
")",
":",
"x",
"=",
"val",
"for",
"dic",
"in",
"dicts",
".",
"values",
"(",
")",
":",
"if",
"current_unit",
"in",
"dic",
".",
"keys",
"(",
")",
"and",
"destination_unit",
"in... | Convert from one unit to another.
Parameters
----------
val : number
Number to convert.
current_unit : string
Current unit.
destination_unit : string
Destination unit.
Returns
-------
number
Converted value. | [
"Convert",
"from",
"one",
"unit",
"to",
"another",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/units.py#L96-L135 | train | 33,729 |
wright-group/WrightTools | WrightTools/units.py | get_symbol | def get_symbol(units) -> str:
"""Get default symbol type.
Parameters
----------
units_str : string
Units.
Returns
-------
string
LaTeX formatted symbol.
"""
if kind(units) == "energy":
d = {}
d["nm"] = r"\lambda"
d["wn"] = r"\bar\nu"
d["eV"] = r"\hslash\omega"
d["Hz"] = r"f"
d["THz"] = r"f"
d["GHz"] = r"f"
return d.get(units, "E")
elif kind(units) == "delay":
return r"\tau"
elif kind(units) == "fluence":
return r"\mathcal{F}"
elif kind(units) == "pulse_width":
return r"\sigma"
elif kind(units) == "temperature":
return r"T"
else:
return kind(units) | python | def get_symbol(units) -> str:
"""Get default symbol type.
Parameters
----------
units_str : string
Units.
Returns
-------
string
LaTeX formatted symbol.
"""
if kind(units) == "energy":
d = {}
d["nm"] = r"\lambda"
d["wn"] = r"\bar\nu"
d["eV"] = r"\hslash\omega"
d["Hz"] = r"f"
d["THz"] = r"f"
d["GHz"] = r"f"
return d.get(units, "E")
elif kind(units) == "delay":
return r"\tau"
elif kind(units) == "fluence":
return r"\mathcal{F}"
elif kind(units) == "pulse_width":
return r"\sigma"
elif kind(units) == "temperature":
return r"T"
else:
return kind(units) | [
"def",
"get_symbol",
"(",
"units",
")",
"->",
"str",
":",
"if",
"kind",
"(",
"units",
")",
"==",
"\"energy\"",
":",
"d",
"=",
"{",
"}",
"d",
"[",
"\"nm\"",
"]",
"=",
"r\"\\lambda\"",
"d",
"[",
"\"wn\"",
"]",
"=",
"r\"\\bar\\nu\"",
"d",
"[",
"\"eV\"... | Get default symbol type.
Parameters
----------
units_str : string
Units.
Returns
-------
string
LaTeX formatted symbol. | [
"Get",
"default",
"symbol",
"type",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/units.py#L141-L172 | train | 33,730 |
wright-group/WrightTools | WrightTools/units.py | kind | def kind(units):
"""Find the kind of given units.
Parameters
----------
units : string
The units of interest
Returns
-------
string
The kind of the given units. If no match is found, returns None.
"""
for k, v in dicts.items():
if units in v.keys():
return k | python | def kind(units):
"""Find the kind of given units.
Parameters
----------
units : string
The units of interest
Returns
-------
string
The kind of the given units. If no match is found, returns None.
"""
for k, v in dicts.items():
if units in v.keys():
return k | [
"def",
"kind",
"(",
"units",
")",
":",
"for",
"k",
",",
"v",
"in",
"dicts",
".",
"items",
"(",
")",
":",
"if",
"units",
"in",
"v",
".",
"keys",
"(",
")",
":",
"return",
"k"
] | Find the kind of given units.
Parameters
----------
units : string
The units of interest
Returns
-------
string
The kind of the given units. If no match is found, returns None. | [
"Find",
"the",
"kind",
"of",
"given",
"units",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/units.py#L194-L209 | train | 33,731 |
hagenw/sphinxcontrib-katex | sphinxcontrib/katex.py | latex_defs_to_katex_macros | def latex_defs_to_katex_macros(defs):
r'''Converts LaTeX \def statements to KaTeX macros.
This is a helper function that can be used in conf.py to translate your
already specified LaTeX definitions.
https://github.com/Khan/KaTeX#rendering-options, e.g.
`\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\mathrm{e}^{#1}"`'
Example
-------
import sphinxcontrib.katex as katex
# Get your LaTeX defs into `latex_defs` and then do
latex_macros = katex.import_macros_from_latex(latex_defs)
katex_options = 'macros: {' + latex_macros + '}'
'''
# Remove empty lines
defs = defs.strip()
tmp = []
for line in defs.splitlines():
# Remove spaces from every line
line = line.strip()
# Remove "\def" at the beginning of line
line = re.sub(r'^\\def[ ]?', '', line)
# Remove optional #1 parameter before {} command brackets
line = re.sub(r'(#[0-9])+', '', line, 1)
# Remove outer {} command brackets with ""
line = re.sub(r'( {)|(}$)', '"', line)
# Add "": to the new command
line = re.sub(r'(^\\[A-Za-z]+)', r'"\1":', line, 1)
# Add , at end of line
line = re.sub(r'$', ',', line, 1)
# Duplicate all \
line = re.sub(r'\\', r'\\\\', line)
tmp.append(line)
macros = '\n'.join(tmp)
return macros | python | def latex_defs_to_katex_macros(defs):
r'''Converts LaTeX \def statements to KaTeX macros.
This is a helper function that can be used in conf.py to translate your
already specified LaTeX definitions.
https://github.com/Khan/KaTeX#rendering-options, e.g.
`\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\mathrm{e}^{#1}"`'
Example
-------
import sphinxcontrib.katex as katex
# Get your LaTeX defs into `latex_defs` and then do
latex_macros = katex.import_macros_from_latex(latex_defs)
katex_options = 'macros: {' + latex_macros + '}'
'''
# Remove empty lines
defs = defs.strip()
tmp = []
for line in defs.splitlines():
# Remove spaces from every line
line = line.strip()
# Remove "\def" at the beginning of line
line = re.sub(r'^\\def[ ]?', '', line)
# Remove optional #1 parameter before {} command brackets
line = re.sub(r'(#[0-9])+', '', line, 1)
# Remove outer {} command brackets with ""
line = re.sub(r'( {)|(}$)', '"', line)
# Add "": to the new command
line = re.sub(r'(^\\[A-Za-z]+)', r'"\1":', line, 1)
# Add , at end of line
line = re.sub(r'$', ',', line, 1)
# Duplicate all \
line = re.sub(r'\\', r'\\\\', line)
tmp.append(line)
macros = '\n'.join(tmp)
return macros | [
"def",
"latex_defs_to_katex_macros",
"(",
"defs",
")",
":",
"# Remove empty lines",
"defs",
"=",
"defs",
".",
"strip",
"(",
")",
"tmp",
"=",
"[",
"]",
"for",
"line",
"in",
"defs",
".",
"splitlines",
"(",
")",
":",
"# Remove spaces from every line",
"line",
"... | r'''Converts LaTeX \def statements to KaTeX macros.
This is a helper function that can be used in conf.py to translate your
already specified LaTeX definitions.
https://github.com/Khan/KaTeX#rendering-options, e.g.
`\def \e #1{\mathrm{e}^{#1}}` => `"\\e:" "\\mathrm{e}^{#1}"`'
Example
-------
import sphinxcontrib.katex as katex
# Get your LaTeX defs into `latex_defs` and then do
latex_macros = katex.import_macros_from_latex(latex_defs)
katex_options = 'macros: {' + latex_macros + '}' | [
"r",
"Converts",
"LaTeX",
"\\",
"def",
"statements",
"to",
"KaTeX",
"macros",
"."
] | 52e235b93a2471df9a7477e04b697e4274399623 | https://github.com/hagenw/sphinxcontrib-katex/blob/52e235b93a2471df9a7477e04b697e4274399623/sphinxcontrib/katex.py#L32-L68 | train | 33,732 |
hagenw/sphinxcontrib-katex | sphinxcontrib/katex.py | katex_rendering_delimiters | def katex_rendering_delimiters(app):
"""Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html
"""
# Return if we have user defined rendering delimiters
if 'delimiters' in app.config.katex_options:
return ''
katex_inline = [d.replace('\\', '\\\\') for d in app.config.katex_inline]
katex_display = [d.replace('\\', '\\\\') for d in app.config.katex_display]
katex_delimiters = {'inline': katex_inline, 'display': katex_display}
# Set chosen delimiters for the auto-rendering options of KaTeX
delimiters = r'''delimiters: [
{{ left: "{inline[0]}", right: "{inline[1]}", display: false }},
{{ left: "{display[0]}", right: "{display[1]}", display: true }}
]'''.format(**katex_delimiters)
return delimiters | python | def katex_rendering_delimiters(app):
"""Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html
"""
# Return if we have user defined rendering delimiters
if 'delimiters' in app.config.katex_options:
return ''
katex_inline = [d.replace('\\', '\\\\') for d in app.config.katex_inline]
katex_display = [d.replace('\\', '\\\\') for d in app.config.katex_display]
katex_delimiters = {'inline': katex_inline, 'display': katex_display}
# Set chosen delimiters for the auto-rendering options of KaTeX
delimiters = r'''delimiters: [
{{ left: "{inline[0]}", right: "{inline[1]}", display: false }},
{{ left: "{display[0]}", right: "{display[1]}", display: true }}
]'''.format(**katex_delimiters)
return delimiters | [
"def",
"katex_rendering_delimiters",
"(",
"app",
")",
":",
"# Return if we have user defined rendering delimiters",
"if",
"'delimiters'",
"in",
"app",
".",
"config",
".",
"katex_options",
":",
"return",
"''",
"katex_inline",
"=",
"[",
"d",
".",
"replace",
"(",
"'\\\... | Delimiters for rendering KaTeX math.
If no delimiters are specified in katex_options, add the
katex_inline and katex_display delimiters. See also
https://khan.github.io/KaTeX/docs/autorender.html | [
"Delimiters",
"for",
"rendering",
"KaTeX",
"math",
"."
] | 52e235b93a2471df9a7477e04b697e4274399623 | https://github.com/hagenw/sphinxcontrib-katex/blob/52e235b93a2471df9a7477e04b697e4274399623/sphinxcontrib/katex.py#L159-L177 | train | 33,733 |
wright-group/WrightTools | WrightTools/data/_axis.py | Axis.label | def label(self) -> str:
"""A latex formatted label representing axis expression."""
label = self.expression.replace("_", "\\;")
if self.units_kind:
symbol = wt_units.get_symbol(self.units)
for v in self.variables:
vl = "%s_{%s}" % (symbol, v.label)
vl = vl.replace("_{}", "") # label can be empty, no empty subscripts
label = label.replace(v.natural_name, vl)
units_dictionary = getattr(wt_units, self.units_kind)
label += r"\,"
label += r"\left("
label += units_dictionary[self.units][2]
label += r"\right)"
label = r"$\mathsf{%s}$" % label
return label | python | def label(self) -> str:
"""A latex formatted label representing axis expression."""
label = self.expression.replace("_", "\\;")
if self.units_kind:
symbol = wt_units.get_symbol(self.units)
for v in self.variables:
vl = "%s_{%s}" % (symbol, v.label)
vl = vl.replace("_{}", "") # label can be empty, no empty subscripts
label = label.replace(v.natural_name, vl)
units_dictionary = getattr(wt_units, self.units_kind)
label += r"\,"
label += r"\left("
label += units_dictionary[self.units][2]
label += r"\right)"
label = r"$\mathsf{%s}$" % label
return label | [
"def",
"label",
"(",
"self",
")",
"->",
"str",
":",
"label",
"=",
"self",
".",
"expression",
".",
"replace",
"(",
"\"_\"",
",",
"\"\\\\;\"",
")",
"if",
"self",
".",
"units_kind",
":",
"symbol",
"=",
"wt_units",
".",
"get_symbol",
"(",
"self",
".",
"u... | A latex formatted label representing axis expression. | [
"A",
"latex",
"formatted",
"label",
"representing",
"axis",
"expression",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_axis.py#L94-L109 | train | 33,734 |
wright-group/WrightTools | WrightTools/data/_axis.py | Axis.natural_name | def natural_name(self) -> str:
"""Valid python identifier representation of the expession."""
name = self.expression.strip()
for op in operators:
name = name.replace(op, operator_to_identifier[op])
return wt_kit.string2identifier(name) | python | def natural_name(self) -> str:
"""Valid python identifier representation of the expession."""
name = self.expression.strip()
for op in operators:
name = name.replace(op, operator_to_identifier[op])
return wt_kit.string2identifier(name) | [
"def",
"natural_name",
"(",
"self",
")",
"->",
"str",
":",
"name",
"=",
"self",
".",
"expression",
".",
"strip",
"(",
")",
"for",
"op",
"in",
"operators",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"op",
",",
"operator_to_identifier",
"[",
"op",
... | Valid python identifier representation of the expession. | [
"Valid",
"python",
"identifier",
"representation",
"of",
"the",
"expession",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_axis.py#L112-L117 | train | 33,735 |
wright-group/WrightTools | WrightTools/data/_axis.py | Axis.masked | def masked(self) -> np.ndarray:
"""Axis expression evaluated, and masked with NaN shared from data channels."""
arr = self[:]
arr.shape = self.shape
arr = wt_kit.share_nans(arr, *self.parent.channels)[0]
return np.nanmean(
arr, keepdims=True, axis=tuple(i for i in range(self.ndim) if self.shape[i] == 1)
) | python | def masked(self) -> np.ndarray:
"""Axis expression evaluated, and masked with NaN shared from data channels."""
arr = self[:]
arr.shape = self.shape
arr = wt_kit.share_nans(arr, *self.parent.channels)[0]
return np.nanmean(
arr, keepdims=True, axis=tuple(i for i in range(self.ndim) if self.shape[i] == 1)
) | [
"def",
"masked",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"arr",
"=",
"self",
"[",
":",
"]",
"arr",
".",
"shape",
"=",
"self",
".",
"shape",
"arr",
"=",
"wt_kit",
".",
"share_nans",
"(",
"arr",
",",
"*",
"self",
".",
"parent",
".",
"c... | Axis expression evaluated, and masked with NaN shared from data channels. | [
"Axis",
"expression",
"evaluated",
"and",
"masked",
"with",
"NaN",
"shared",
"from",
"data",
"channels",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_axis.py#L166-L173 | train | 33,736 |
wright-group/WrightTools | WrightTools/data/_axis.py | Axis.convert | def convert(self, destination_units, *, convert_variables=False):
"""Convert axis to destination_units.
Parameters
----------
destination_units : string
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False.
"""
if self.units is None and (destination_units is None or destination_units == "None"):
return
if not wt_units.is_valid_conversion(self.units, destination_units):
valid = wt_units.get_valid_conversions(self.units)
raise wt_exceptions.UnitsError(valid, destination_units)
if convert_variables:
for v in self.variables:
v.convert(destination_units)
self.units = destination_units | python | def convert(self, destination_units, *, convert_variables=False):
"""Convert axis to destination_units.
Parameters
----------
destination_units : string
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False.
"""
if self.units is None and (destination_units is None or destination_units == "None"):
return
if not wt_units.is_valid_conversion(self.units, destination_units):
valid = wt_units.get_valid_conversions(self.units)
raise wt_exceptions.UnitsError(valid, destination_units)
if convert_variables:
for v in self.variables:
v.convert(destination_units)
self.units = destination_units | [
"def",
"convert",
"(",
"self",
",",
"destination_units",
",",
"*",
",",
"convert_variables",
"=",
"False",
")",
":",
"if",
"self",
".",
"units",
"is",
"None",
"and",
"(",
"destination_units",
"is",
"None",
"or",
"destination_units",
"==",
"\"None\"",
")",
... | Convert axis to destination_units.
Parameters
----------
destination_units : string
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False. | [
"Convert",
"axis",
"to",
"destination_units",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_axis.py#L175-L193 | train | 33,737 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.add_section | def add_section(self, section):
"""Add section.
Parameters
----------
section : string
Section to add.
"""
self.config.read(self.filepath)
self.config.add_section(section)
with open(self.filepath, "w") as f:
self.config.write(f) | python | def add_section(self, section):
"""Add section.
Parameters
----------
section : string
Section to add.
"""
self.config.read(self.filepath)
self.config.add_section(section)
with open(self.filepath, "w") as f:
self.config.write(f) | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"self",
".",
"config",
".",
"add_section",
"(",
"section",
")",
"with",
"open",
"(",
"self",
".",
"filepath",
",",
"\"... | Add section.
Parameters
----------
section : string
Section to add. | [
"Add",
"section",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L35-L46 | train | 33,738 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.dictionary | def dictionary(self) -> dict:
"""Get a python dictionary of contents."""
self.config.read(self.filepath)
return self.config._sections | python | def dictionary(self) -> dict:
"""Get a python dictionary of contents."""
self.config.read(self.filepath)
return self.config._sections | [
"def",
"dictionary",
"(",
"self",
")",
"->",
"dict",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"return",
"self",
".",
"config",
".",
"_sections"
] | Get a python dictionary of contents. | [
"Get",
"a",
"python",
"dictionary",
"of",
"contents",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L58-L61 | train | 33,739 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.has_option | def has_option(self, section, option) -> bool:
"""Test if file has option.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
boolean
"""
self.config.read(self.filepath)
return self.config.has_option(section, option) | python | def has_option(self, section, option) -> bool:
"""Test if file has option.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
boolean
"""
self.config.read(self.filepath)
return self.config.has_option(section, option) | [
"def",
"has_option",
"(",
"self",
",",
"section",
",",
"option",
")",
"->",
"bool",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"return",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")"
] | Test if file has option.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
boolean | [
"Test",
"if",
"file",
"has",
"option",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L78-L93 | train | 33,740 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.has_section | def has_section(self, section) -> bool:
"""Test if file has section.
Parameters
----------
section : string
Section.
Returns
-------
boolean
"""
self.config.read(self.filepath)
return self.config.has_section(section) | python | def has_section(self, section) -> bool:
"""Test if file has section.
Parameters
----------
section : string
Section.
Returns
-------
boolean
"""
self.config.read(self.filepath)
return self.config.has_section(section) | [
"def",
"has_section",
"(",
"self",
",",
"section",
")",
"->",
"bool",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"return",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")"
] | Test if file has section.
Parameters
----------
section : string
Section.
Returns
-------
boolean | [
"Test",
"if",
"file",
"has",
"section",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L95-L108 | train | 33,741 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.read | def read(self, section, option):
"""Read from file.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
string
Value.
"""
self.config.read(self.filepath)
raw = self.config.get(section, option)
out = tidy_headers._parse_item.string2item(raw, sep=", ")
return out | python | def read(self, section, option):
"""Read from file.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
string
Value.
"""
self.config.read(self.filepath)
raw = self.config.get(section, option)
out = tidy_headers._parse_item.string2item(raw, sep=", ")
return out | [
"def",
"read",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"raw",
"=",
"self",
".",
"config",
".",
"get",
"(",
"section",
",",
"option",
")",
"out",
"=",
"tidy_headers... | Read from file.
Parameters
----------
section : string
Section.
option : string
Option.
Returns
-------
string
Value. | [
"Read",
"from",
"file",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L110-L128 | train | 33,742 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.sections | def sections(self) -> list:
"""List of sections."""
self.config.read(self.filepath)
return self.config.sections() | python | def sections(self) -> list:
"""List of sections."""
self.config.read(self.filepath)
return self.config.sections() | [
"def",
"sections",
"(",
"self",
")",
"->",
"list",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"return",
"self",
".",
"config",
".",
"sections",
"(",
")"
] | List of sections. | [
"List",
"of",
"sections",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L131-L134 | train | 33,743 |
wright-group/WrightTools | WrightTools/kit/_ini.py | INI.write | def write(self, section, option, value):
"""Write to file.
Parameters
----------
section : string
Section.
option : string
Option.
value : string
Value.
"""
self.config.read(self.filepath)
string = tidy_headers._parse_item.item2string(value, sep=", ")
self.config.set(section, option, string)
with open(self.filepath, "w") as f:
self.config.write(f) | python | def write(self, section, option, value):
"""Write to file.
Parameters
----------
section : string
Section.
option : string
Option.
value : string
Value.
"""
self.config.read(self.filepath)
string = tidy_headers._parse_item.item2string(value, sep=", ")
self.config.set(section, option, string)
with open(self.filepath, "w") as f:
self.config.write(f) | [
"def",
"write",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
")",
":",
"self",
".",
"config",
".",
"read",
"(",
"self",
".",
"filepath",
")",
"string",
"=",
"tidy_headers",
".",
"_parse_item",
".",
"item2string",
"(",
"value",
",",
"sep",
... | Write to file.
Parameters
----------
section : string
Section.
option : string
Option.
value : string
Value. | [
"Write",
"to",
"file",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L136-L152 | train | 33,744 |
wright-group/WrightTools | WrightTools/kit/_timestamp.py | timestamp_from_RFC3339 | def timestamp_from_RFC3339(RFC3339):
"""Generate a Timestamp object from a RFC3339 formatted string.
`Link to RFC3339`__
__ https://www.ietf.org/rfc/rfc3339.txt
Parameters
----------
RFC3339 : string
RFC3339 formatted string.
Returns
-------
WrightTools.kit.TimeStamp
"""
dt = dateutil.parser.parse(RFC3339)
if hasattr(dt.tzinfo, "_offset"):
timezone = dt.tzinfo._offset.total_seconds()
else:
timezone = "utc"
timestamp = TimeStamp(at=dt.timestamp(), timezone=timezone)
return timestamp | python | def timestamp_from_RFC3339(RFC3339):
"""Generate a Timestamp object from a RFC3339 formatted string.
`Link to RFC3339`__
__ https://www.ietf.org/rfc/rfc3339.txt
Parameters
----------
RFC3339 : string
RFC3339 formatted string.
Returns
-------
WrightTools.kit.TimeStamp
"""
dt = dateutil.parser.parse(RFC3339)
if hasattr(dt.tzinfo, "_offset"):
timezone = dt.tzinfo._offset.total_seconds()
else:
timezone = "utc"
timestamp = TimeStamp(at=dt.timestamp(), timezone=timezone)
return timestamp | [
"def",
"timestamp_from_RFC3339",
"(",
"RFC3339",
")",
":",
"dt",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"RFC3339",
")",
"if",
"hasattr",
"(",
"dt",
".",
"tzinfo",
",",
"\"_offset\"",
")",
":",
"timezone",
"=",
"dt",
".",
"tzinfo",
".",
"_of... | Generate a Timestamp object from a RFC3339 formatted string.
`Link to RFC3339`__
__ https://www.ietf.org/rfc/rfc3339.txt
Parameters
----------
RFC3339 : string
RFC3339 formatted string.
Returns
-------
WrightTools.kit.TimeStamp | [
"Generate",
"a",
"Timestamp",
"object",
"from",
"a",
"RFC3339",
"formatted",
"string",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_timestamp.py#L25-L47 | train | 33,745 |
wright-group/WrightTools | WrightTools/kit/_timestamp.py | TimeStamp.human | def human(self):
"""Human-readable timestamp."""
# get timezone offset
delta_sec = time.timezone
m, s = divmod(delta_sec, 60)
h, m = divmod(m, 60)
# create output
format_string = "%Y-%m-%d %H:%M:%S"
out = self.datetime.strftime(format_string)
return out | python | def human(self):
"""Human-readable timestamp."""
# get timezone offset
delta_sec = time.timezone
m, s = divmod(delta_sec, 60)
h, m = divmod(m, 60)
# create output
format_string = "%Y-%m-%d %H:%M:%S"
out = self.datetime.strftime(format_string)
return out | [
"def",
"human",
"(",
"self",
")",
":",
"# get timezone offset",
"delta_sec",
"=",
"time",
".",
"timezone",
"m",
",",
"s",
"=",
"divmod",
"(",
"delta_sec",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
"# create output",
"for... | Human-readable timestamp. | [
"Human",
"-",
"readable",
"timestamp",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_timestamp.py#L135-L144 | train | 33,746 |
wright-group/WrightTools | WrightTools/kit/_timestamp.py | TimeStamp.path | def path(self):
"""Timestamp for placing into filepaths."""
out = self.datetime.strftime("%Y-%m-%d")
out += " "
ssm = (
self.datetime - self.datetime.replace(hour=0, minute=0, second=0, microsecond=0)
).total_seconds()
out += str(int(ssm)).zfill(5)
return out | python | def path(self):
"""Timestamp for placing into filepaths."""
out = self.datetime.strftime("%Y-%m-%d")
out += " "
ssm = (
self.datetime - self.datetime.replace(hour=0, minute=0, second=0, microsecond=0)
).total_seconds()
out += str(int(ssm)).zfill(5)
return out | [
"def",
"path",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"datetime",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"out",
"+=",
"\" \"",
"ssm",
"=",
"(",
"self",
".",
"datetime",
"-",
"self",
".",
"datetime",
".",
"replace",
"(",
"hour",
"=",
"0... | Timestamp for placing into filepaths. | [
"Timestamp",
"for",
"placing",
"into",
"filepaths",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_timestamp.py#L187-L195 | train | 33,747 |
wright-group/WrightTools | WrightTools/kit/_interpolate.py | zoom2D | def zoom2D(xi, yi, zi, xi_zoom=3., yi_zoom=3., order=3, mode="nearest", cval=0.):
"""Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
Zoom factor along x axis. Default is 3.
yi_zoom : float (optional)
Zoom factor along y axis. Default is 3.
order : int (optional)
The order of the spline interpolation, between 0 and 5. Default is 3.
mode : {'constant', 'nearest', 'reflect', or 'wrap'}
Points outside the boundaries of the input are filled according to the
given mode. Default is nearest.
cval : scalar (optional)
Value used for constant mode. Default is 0.0.
"""
xi = ndimage.interpolation.zoom(xi, xi_zoom, order=order, mode="nearest")
yi = ndimage.interpolation.zoom(yi, yi_zoom, order=order, mode="nearest")
zi = ndimage.interpolation.zoom(zi, (xi_zoom, yi_zoom), order=order, mode=mode, cval=cval)
return xi, yi, zi | python | def zoom2D(xi, yi, zi, xi_zoom=3., yi_zoom=3., order=3, mode="nearest", cval=0.):
"""Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
Zoom factor along x axis. Default is 3.
yi_zoom : float (optional)
Zoom factor along y axis. Default is 3.
order : int (optional)
The order of the spline interpolation, between 0 and 5. Default is 3.
mode : {'constant', 'nearest', 'reflect', or 'wrap'}
Points outside the boundaries of the input are filled according to the
given mode. Default is nearest.
cval : scalar (optional)
Value used for constant mode. Default is 0.0.
"""
xi = ndimage.interpolation.zoom(xi, xi_zoom, order=order, mode="nearest")
yi = ndimage.interpolation.zoom(yi, yi_zoom, order=order, mode="nearest")
zi = ndimage.interpolation.zoom(zi, (xi_zoom, yi_zoom), order=order, mode=mode, cval=cval)
return xi, yi, zi | [
"def",
"zoom2D",
"(",
"xi",
",",
"yi",
",",
"zi",
",",
"xi_zoom",
"=",
"3.",
",",
"yi_zoom",
"=",
"3.",
",",
"order",
"=",
"3",
",",
"mode",
"=",
"\"nearest\"",
",",
"cval",
"=",
"0.",
")",
":",
"xi",
"=",
"ndimage",
".",
"interpolation",
".",
... | Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
Zoom factor along x axis. Default is 3.
yi_zoom : float (optional)
Zoom factor along y axis. Default is 3.
order : int (optional)
The order of the spline interpolation, between 0 and 5. Default is 3.
mode : {'constant', 'nearest', 'reflect', or 'wrap'}
Points outside the boundaries of the input are filled according to the
given mode. Default is nearest.
cval : scalar (optional)
Value used for constant mode. Default is 0.0. | [
"Zoom",
"a",
"2D",
"array",
"with",
"axes",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_interpolate.py#L24-L50 | train | 33,748 |
wright-group/WrightTools | WrightTools/artists/_base.py | apply_rcparams | def apply_rcparams(kind="fast"):
"""Quickly apply rcparams for given purposes.
Parameters
----------
kind: {'default', 'fast', 'publication'} (optional)
Settings to use. Default is 'fast'.
"""
if kind == "default":
matplotlib.rcdefaults()
elif kind == "fast":
matplotlib.rcParams["text.usetex"] = False
matplotlib.rcParams["mathtext.fontset"] = "cm"
matplotlib.rcParams["font.family"] = "sans-serif"
matplotlib.rcParams["font.size"] = 14
matplotlib.rcParams["legend.edgecolor"] = "grey"
matplotlib.rcParams["contour.negative_linestyle"] = "solid"
elif kind == "publication":
matplotlib.rcParams["text.usetex"] = True
preamble = "\\usepackage[cm]{sfmath}\\usepackage{amssymb}"
matplotlib.rcParams["text.latex.preamble"] = preamble
matplotlib.rcParams["mathtext.fontset"] = "cm"
matplotlib.rcParams["font.family"] = "sans-serif"
matplotlib.rcParams["font.serif"] = "cm"
matplotlib.rcParams["font.sans-serif"] = "cm"
matplotlib.rcParams["font.size"] = 14
matplotlib.rcParams["legend.edgecolor"] = "grey"
matplotlib.rcParams["contour.negative_linestyle"] = "solid" | python | def apply_rcparams(kind="fast"):
"""Quickly apply rcparams for given purposes.
Parameters
----------
kind: {'default', 'fast', 'publication'} (optional)
Settings to use. Default is 'fast'.
"""
if kind == "default":
matplotlib.rcdefaults()
elif kind == "fast":
matplotlib.rcParams["text.usetex"] = False
matplotlib.rcParams["mathtext.fontset"] = "cm"
matplotlib.rcParams["font.family"] = "sans-serif"
matplotlib.rcParams["font.size"] = 14
matplotlib.rcParams["legend.edgecolor"] = "grey"
matplotlib.rcParams["contour.negative_linestyle"] = "solid"
elif kind == "publication":
matplotlib.rcParams["text.usetex"] = True
preamble = "\\usepackage[cm]{sfmath}\\usepackage{amssymb}"
matplotlib.rcParams["text.latex.preamble"] = preamble
matplotlib.rcParams["mathtext.fontset"] = "cm"
matplotlib.rcParams["font.family"] = "sans-serif"
matplotlib.rcParams["font.serif"] = "cm"
matplotlib.rcParams["font.sans-serif"] = "cm"
matplotlib.rcParams["font.size"] = 14
matplotlib.rcParams["legend.edgecolor"] = "grey"
matplotlib.rcParams["contour.negative_linestyle"] = "solid" | [
"def",
"apply_rcparams",
"(",
"kind",
"=",
"\"fast\"",
")",
":",
"if",
"kind",
"==",
"\"default\"",
":",
"matplotlib",
".",
"rcdefaults",
"(",
")",
"elif",
"kind",
"==",
"\"fast\"",
":",
"matplotlib",
".",
"rcParams",
"[",
"\"text.usetex\"",
"]",
"=",
"Fal... | Quickly apply rcparams for given purposes.
Parameters
----------
kind: {'default', 'fast', 'publication'} (optional)
Settings to use. Default is 'fast'. | [
"Quickly",
"apply",
"rcparams",
"for",
"given",
"purposes",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L520-L547 | train | 33,749 |
wright-group/WrightTools | WrightTools/artists/_base.py | Axes._apply_labels | def _apply_labels(
self, autolabel="none", xlabel=None, ylabel=None, data=None, channel_index=0
):
"""Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabel : string (optional)
x label. Default is None.
ylabel : string (optional)
y label. Default is None.
data : WrightTools.data.Data object (optional)
data to read labels from. Default is None.
channel_index : integer (optional)
Channel index. Default is 0.
"""
# read from data
if autolabel in ["xy", "both", "x"] and not xlabel:
xlabel = data.axes[0].label
if autolabel in ["xy", "both", "y"] and not ylabel:
if data.ndim == 1:
ylabel = data.channels[channel_index].label
elif data.ndim == 2:
ylabel = data.axes[1].label
# apply
if xlabel:
if isinstance(xlabel, bool):
xlabel = data.axes[0].label
self.set_xlabel(xlabel, fontsize=18)
if ylabel:
if isinstance(ylabel, bool):
ylabel = data.axes[1].label
self.set_ylabel(ylabel, fontsize=18) | python | def _apply_labels(
self, autolabel="none", xlabel=None, ylabel=None, data=None, channel_index=0
):
"""Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabel : string (optional)
x label. Default is None.
ylabel : string (optional)
y label. Default is None.
data : WrightTools.data.Data object (optional)
data to read labels from. Default is None.
channel_index : integer (optional)
Channel index. Default is 0.
"""
# read from data
if autolabel in ["xy", "both", "x"] and not xlabel:
xlabel = data.axes[0].label
if autolabel in ["xy", "both", "y"] and not ylabel:
if data.ndim == 1:
ylabel = data.channels[channel_index].label
elif data.ndim == 2:
ylabel = data.axes[1].label
# apply
if xlabel:
if isinstance(xlabel, bool):
xlabel = data.axes[0].label
self.set_xlabel(xlabel, fontsize=18)
if ylabel:
if isinstance(ylabel, bool):
ylabel = data.axes[1].label
self.set_ylabel(ylabel, fontsize=18) | [
"def",
"_apply_labels",
"(",
"self",
",",
"autolabel",
"=",
"\"none\"",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"data",
"=",
"None",
",",
"channel_index",
"=",
"0",
")",
":",
"# read from data",
"if",
"autolabel",
"in",
"[",
"\"xy\""... | Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabel : string (optional)
x label. Default is None.
ylabel : string (optional)
y label. Default is None.
data : WrightTools.data.Data object (optional)
data to read labels from. Default is None.
channel_index : integer (optional)
Channel index. Default is 0. | [
"Apply",
"x",
"and",
"y",
"labels",
"to",
"axes",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L49-L83 | train | 33,750 |
wright-group/WrightTools | WrightTools/artists/_base.py | Axes.add_sideplot | def add_sideplot(self, along, pad=0, height=0.75, ymin=0, ymax=1.1):
"""Add a side axis.
Parameters
----------
along : {'x', 'y'}
Axis to add along.
pad : float (optional)
Side axis pad. Default is 0.
height : float (optional)
Side axis height. Default is 0.
"""
# divider should only be created once
if hasattr(self, "divider"):
divider = self.divider
else:
divider = make_axes_locatable(self)
setattr(self, "divider", divider)
# create
if along == "x":
ax = self.sidex = divider.append_axes("top", height, pad=pad, sharex=self)
elif along == "y":
ax = self.sidey = divider.append_axes("right", height, pad=pad, sharey=self)
ax.transposed = True
# beautify
if along == "x":
ax.set_ylim(ymin, ymax)
elif along == "y":
ax.set_xlim(ymin, ymax)
ax.autoscale(enable=False)
ax.set_adjustable("box")
ax.is_sideplot = True
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.tick_params(axis="both", which="both", length=0)
return ax | python | def add_sideplot(self, along, pad=0, height=0.75, ymin=0, ymax=1.1):
"""Add a side axis.
Parameters
----------
along : {'x', 'y'}
Axis to add along.
pad : float (optional)
Side axis pad. Default is 0.
height : float (optional)
Side axis height. Default is 0.
"""
# divider should only be created once
if hasattr(self, "divider"):
divider = self.divider
else:
divider = make_axes_locatable(self)
setattr(self, "divider", divider)
# create
if along == "x":
ax = self.sidex = divider.append_axes("top", height, pad=pad, sharex=self)
elif along == "y":
ax = self.sidey = divider.append_axes("right", height, pad=pad, sharey=self)
ax.transposed = True
# beautify
if along == "x":
ax.set_ylim(ymin, ymax)
elif along == "y":
ax.set_xlim(ymin, ymax)
ax.autoscale(enable=False)
ax.set_adjustable("box")
ax.is_sideplot = True
plt.setp(ax.get_xticklabels(), visible=False)
plt.setp(ax.get_yticklabels(), visible=False)
ax.tick_params(axis="both", which="both", length=0)
return ax | [
"def",
"add_sideplot",
"(",
"self",
",",
"along",
",",
"pad",
"=",
"0",
",",
"height",
"=",
"0.75",
",",
"ymin",
"=",
"0",
",",
"ymax",
"=",
"1.1",
")",
":",
"# divider should only be created once",
"if",
"hasattr",
"(",
"self",
",",
"\"divider\"",
")",
... | Add a side axis.
Parameters
----------
along : {'x', 'y'}
Axis to add along.
pad : float (optional)
Side axis pad. Default is 0.
height : float (optional)
Side axis height. Default is 0. | [
"Add",
"a",
"side",
"axis",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L192-L227 | train | 33,751 |
wright-group/WrightTools | WrightTools/artists/_base.py | Axes.legend | def legend(self, *args, **kwargs):
"""Add a legend.
Parameters
----------
*args
matplotlib legend args.
*kwargs
matplotlib legend kwargs.
Returns
-------
legend
"""
if "fancybox" not in kwargs.keys():
kwargs["fancybox"] = False
if "framealpha" not in kwargs.keys():
kwargs["framealpha"] = 1.
return super().legend(*args, **kwargs) | python | def legend(self, *args, **kwargs):
"""Add a legend.
Parameters
----------
*args
matplotlib legend args.
*kwargs
matplotlib legend kwargs.
Returns
-------
legend
"""
if "fancybox" not in kwargs.keys():
kwargs["fancybox"] = False
if "framealpha" not in kwargs.keys():
kwargs["framealpha"] = 1.
return super().legend(*args, **kwargs) | [
"def",
"legend",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"fancybox\"",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"kwargs",
"[",
"\"fancybox\"",
"]",
"=",
"False",
"if",
"\"framealpha\"",
"not",
"in",
"kwargs... | Add a legend.
Parameters
----------
*args
matplotlib legend args.
*kwargs
matplotlib legend kwargs.
Returns
-------
legend | [
"Add",
"a",
"legend",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L327-L345 | train | 33,752 |
wright-group/WrightTools | WrightTools/artists/_base.py | Figure.add_subplot | def add_subplot(self, *args, **kwargs):
"""Add a subplot to the figure.
Parameters
----------
*args
**kwargs
Returns
-------
WrightTools.artists.Axes object
"""
kwargs.setdefault("projection", "wright")
return super().add_subplot(*args, **kwargs) | python | def add_subplot(self, *args, **kwargs):
"""Add a subplot to the figure.
Parameters
----------
*args
**kwargs
Returns
-------
WrightTools.artists.Axes object
"""
kwargs.setdefault("projection", "wright")
return super().add_subplot(*args, **kwargs) | [
"def",
"add_subplot",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"projection\"",
",",
"\"wright\"",
")",
"return",
"super",
"(",
")",
".",
"add_subplot",
"(",
"*",
"args",
",",
"*",
"*",
"kwa... | Add a subplot to the figure.
Parameters
----------
*args
**kwargs
Returns
-------
WrightTools.artists.Axes object | [
"Add",
"a",
"subplot",
"to",
"the",
"figure",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_base.py#L495-L508 | train | 33,753 |
wright-group/WrightTools | WrightTools/exceptions.py | WrongFileTypeWarning.warn | def warn(filepath, expected):
"""Raise warning.
Parameters
----------
filepath : path-like
Given filepath.
expected : string
Expected file suffix.
"""
filepath = pathlib.Path(filepath)
message = "file {0} has type {1} (expected {2})".format(
filepath, filepath.suffix, expected
)
warnings.warn(message, WrongFileTypeWarning) | python | def warn(filepath, expected):
"""Raise warning.
Parameters
----------
filepath : path-like
Given filepath.
expected : string
Expected file suffix.
"""
filepath = pathlib.Path(filepath)
message = "file {0} has type {1} (expected {2})".format(
filepath, filepath.suffix, expected
)
warnings.warn(message, WrongFileTypeWarning) | [
"def",
"warn",
"(",
"filepath",
",",
"expected",
")",
":",
"filepath",
"=",
"pathlib",
".",
"Path",
"(",
"filepath",
")",
"message",
"=",
"\"file {0} has type {1} (expected {2})\"",
".",
"format",
"(",
"filepath",
",",
"filepath",
".",
"suffix",
",",
"expected... | Raise warning.
Parameters
----------
filepath : path-like
Given filepath.
expected : string
Expected file suffix. | [
"Raise",
"warning",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/exceptions.py#L147-L161 | train | 33,754 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.channel_names | def channel_names(self) -> tuple:
"""Channel names."""
if "channel_names" not in self.attrs.keys():
self.attrs["channel_names"] = np.array([], dtype="S")
return tuple(s.decode() for s in self.attrs["channel_names"]) | python | def channel_names(self) -> tuple:
"""Channel names."""
if "channel_names" not in self.attrs.keys():
self.attrs["channel_names"] = np.array([], dtype="S")
return tuple(s.decode() for s in self.attrs["channel_names"]) | [
"def",
"channel_names",
"(",
"self",
")",
"->",
"tuple",
":",
"if",
"\"channel_names\"",
"not",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"self",
".",
"attrs",
"[",
"\"channel_names\"",
"]",
"=",
"np",
".",
"array",
"(",
"[",
"]",
",",
... | Channel names. | [
"Channel",
"names",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L110-L114 | train | 33,755 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.ndim | def ndim(self) -> int:
"""Get number of dimensions."""
try:
assert self._ndim is not None
except (AssertionError, AttributeError):
if len(self.variables) == 0:
self._ndim = 0
else:
self._ndim = self.variables[0].ndim
finally:
return self._ndim | python | def ndim(self) -> int:
"""Get number of dimensions."""
try:
assert self._ndim is not None
except (AssertionError, AttributeError):
if len(self.variables) == 0:
self._ndim = 0
else:
self._ndim = self.variables[0].ndim
finally:
return self._ndim | [
"def",
"ndim",
"(",
"self",
")",
"->",
"int",
":",
"try",
":",
"assert",
"self",
".",
"_ndim",
"is",
"not",
"None",
"except",
"(",
"AssertionError",
",",
"AttributeError",
")",
":",
"if",
"len",
"(",
"self",
".",
"variables",
")",
"==",
"0",
":",
"... | Get number of dimensions. | [
"Get",
"number",
"of",
"dimensions",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L140-L150 | train | 33,756 |
wright-group/WrightTools | WrightTools/data/_data.py | Data._on_axes_updated | def _on_axes_updated(self):
"""Method to run when axes are changed in any way.
Propagates updated axes properly.
"""
# update attrs
self.attrs["axes"] = [a.identity.encode() for a in self._axes]
# remove old attributes
while len(self._current_axis_identities_in_natural_namespace) > 0:
key = self._current_axis_identities_in_natural_namespace.pop(0)
try:
delattr(self, key)
except AttributeError:
pass # already gone
# populate new attributes
for a in self._axes:
key = a.natural_name
setattr(self, key, a)
self._current_axis_identities_in_natural_namespace.append(key) | python | def _on_axes_updated(self):
"""Method to run when axes are changed in any way.
Propagates updated axes properly.
"""
# update attrs
self.attrs["axes"] = [a.identity.encode() for a in self._axes]
# remove old attributes
while len(self._current_axis_identities_in_natural_namespace) > 0:
key = self._current_axis_identities_in_natural_namespace.pop(0)
try:
delattr(self, key)
except AttributeError:
pass # already gone
# populate new attributes
for a in self._axes:
key = a.natural_name
setattr(self, key, a)
self._current_axis_identities_in_natural_namespace.append(key) | [
"def",
"_on_axes_updated",
"(",
"self",
")",
":",
"# update attrs",
"self",
".",
"attrs",
"[",
"\"axes\"",
"]",
"=",
"[",
"a",
".",
"identity",
".",
"encode",
"(",
")",
"for",
"a",
"in",
"self",
".",
"_axes",
"]",
"# remove old attributes",
"while",
"len... | Method to run when axes are changed in any way.
Propagates updated axes properly. | [
"Method",
"to",
"run",
"when",
"axes",
"are",
"changed",
"in",
"any",
"way",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L211-L229 | train | 33,757 |
wright-group/WrightTools | WrightTools/data/_data.py | Data._on_constants_updated | def _on_constants_updated(self):
"""Method to run when constants are changed in any way.
Propagates updated constants properly.
"""
# update attrs
self.attrs["constants"] = [a.identity.encode() for a in self._constants] | python | def _on_constants_updated(self):
"""Method to run when constants are changed in any way.
Propagates updated constants properly.
"""
# update attrs
self.attrs["constants"] = [a.identity.encode() for a in self._constants] | [
"def",
"_on_constants_updated",
"(",
"self",
")",
":",
"# update attrs",
"self",
".",
"attrs",
"[",
"\"constants\"",
"]",
"=",
"[",
"a",
".",
"identity",
".",
"encode",
"(",
")",
"for",
"a",
"in",
"self",
".",
"_constants",
"]"
] | Method to run when constants are changed in any way.
Propagates updated constants properly. | [
"Method",
"to",
"run",
"when",
"constants",
"are",
"changed",
"in",
"any",
"way",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L231-L237 | train | 33,758 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.bring_to_front | def bring_to_front(self, channel):
"""Bring a specific channel to the zero-indexed position in channels.
All other channels get pushed back but remain in order.
Parameters
----------
channel : int or str
Channel index or name.
"""
channel_index = wt_kit.get_index(self.channel_names, channel)
new = list(self.channel_names)
new.insert(0, new.pop(channel_index))
self.channel_names = new | python | def bring_to_front(self, channel):
"""Bring a specific channel to the zero-indexed position in channels.
All other channels get pushed back but remain in order.
Parameters
----------
channel : int or str
Channel index or name.
"""
channel_index = wt_kit.get_index(self.channel_names, channel)
new = list(self.channel_names)
new.insert(0, new.pop(channel_index))
self.channel_names = new | [
"def",
"bring_to_front",
"(",
"self",
",",
"channel",
")",
":",
"channel_index",
"=",
"wt_kit",
".",
"get_index",
"(",
"self",
".",
"channel_names",
",",
"channel",
")",
"new",
"=",
"list",
"(",
"self",
".",
"channel_names",
")",
"new",
".",
"insert",
"(... | Bring a specific channel to the zero-indexed position in channels.
All other channels get pushed back but remain in order.
Parameters
----------
channel : int or str
Channel index or name. | [
"Bring",
"a",
"specific",
"channel",
"to",
"the",
"zero",
"-",
"indexed",
"position",
"in",
"channels",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L282-L295 | train | 33,759 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.gradient | def gradient(self, axis, *, channel=0):
"""
Compute the gradient along one axis.
New channels have names ``<channel name>_<axis name>_gradient``.
Parameters
----------
axis : int or str
The axis to differentiate along.
If given as an integer, the axis in the underlying array is used,
and unitary spacing is assumed.
If given as a string, the axis must exist, and be a 1D array-aligned axis.
(i.e. have a shape with a single value which is not ``1``)
The axis to collapse along is inferred from the shape of the axis.
channel : int or str
The channel to differentiate.
Default is the first channel.
"""
# get axis index --------------------------------------------------------------------------
if isinstance(axis, int):
axis_index = axis
elif isinstance(axis, str):
index = self.axis_names.index(axis)
axes = [i for i in range(self.ndim) if self.axes[index].shape[i] > 1]
if len(axes) > 1:
raise wt_exceptions.MultidimensionalAxisError(axis, "collapse")
elif len(axes) == 0:
raise wt_exceptions.ValueError(
"Axis '{}' is a single point, cannot compute gradient".format(axis)
)
axis_index = axes[0]
else:
raise wt_exceptions.TypeError("axis: expected {int, str}, got %s" % type(axis))
channel_index = wt_kit.get_index(self.channel_names, channel)
channel = self.channel_names[channel_index]
if self[channel].shape[axis_index] == 1:
raise wt_exceptions.ValueError(
"Channel '{}' has a single point along Axis '{}', cannot compute gradient".format(
channel, axis
)
)
rtype = np.result_type(self[channel].dtype, float)
new = self.create_channel(
"{}_{}_gradient".format(channel, axis),
values=np.empty(self[channel].shape, dtype=rtype),
)
channel = self[channel]
if axis == axis_index:
new[:] = np.gradient(channel[:], axis=axis_index)
else:
new[:] = np.gradient(channel[:], self[axis].points, axis=axis_index) | python | def gradient(self, axis, *, channel=0):
"""
Compute the gradient along one axis.
New channels have names ``<channel name>_<axis name>_gradient``.
Parameters
----------
axis : int or str
The axis to differentiate along.
If given as an integer, the axis in the underlying array is used,
and unitary spacing is assumed.
If given as a string, the axis must exist, and be a 1D array-aligned axis.
(i.e. have a shape with a single value which is not ``1``)
The axis to collapse along is inferred from the shape of the axis.
channel : int or str
The channel to differentiate.
Default is the first channel.
"""
# get axis index --------------------------------------------------------------------------
if isinstance(axis, int):
axis_index = axis
elif isinstance(axis, str):
index = self.axis_names.index(axis)
axes = [i for i in range(self.ndim) if self.axes[index].shape[i] > 1]
if len(axes) > 1:
raise wt_exceptions.MultidimensionalAxisError(axis, "collapse")
elif len(axes) == 0:
raise wt_exceptions.ValueError(
"Axis '{}' is a single point, cannot compute gradient".format(axis)
)
axis_index = axes[0]
else:
raise wt_exceptions.TypeError("axis: expected {int, str}, got %s" % type(axis))
channel_index = wt_kit.get_index(self.channel_names, channel)
channel = self.channel_names[channel_index]
if self[channel].shape[axis_index] == 1:
raise wt_exceptions.ValueError(
"Channel '{}' has a single point along Axis '{}', cannot compute gradient".format(
channel, axis
)
)
rtype = np.result_type(self[channel].dtype, float)
new = self.create_channel(
"{}_{}_gradient".format(channel, axis),
values=np.empty(self[channel].shape, dtype=rtype),
)
channel = self[channel]
if axis == axis_index:
new[:] = np.gradient(channel[:], axis=axis_index)
else:
new[:] = np.gradient(channel[:], self[axis].points, axis=axis_index) | [
"def",
"gradient",
"(",
"self",
",",
"axis",
",",
"*",
",",
"channel",
"=",
"0",
")",
":",
"# get axis index --------------------------------------------------------------------------",
"if",
"isinstance",
"(",
"axis",
",",
"int",
")",
":",
"axis_index",
"=",
"axis"... | Compute the gradient along one axis.
New channels have names ``<channel name>_<axis name>_gradient``.
Parameters
----------
axis : int or str
The axis to differentiate along.
If given as an integer, the axis in the underlying array is used,
and unitary spacing is assumed.
If given as a string, the axis must exist, and be a 1D array-aligned axis.
(i.e. have a shape with a single value which is not ``1``)
The axis to collapse along is inferred from the shape of the axis.
channel : int or str
The channel to differentiate.
Default is the first channel. | [
"Compute",
"the",
"gradient",
"along",
"one",
"axis",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L440-L494 | train | 33,760 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.convert | def convert(self, destination_units, *, convert_variables=False, verbose=True):
"""Convert all compatable axes and constants to given units.
Parameters
----------
destination_units : str
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False
verbose : bool (optional)
Toggle talkback. Default is True.
See Also
--------
Axis.convert
Convert a single axis object to compatable units. Call on an
axis object in data.axes.
"""
# get kind of units
units_kind = wt_units.kind(destination_units)
# apply to all compatible axes
for axis in self.axes:
if axis.units_kind == units_kind:
orig = axis.units
axis.convert(destination_units, convert_variables=convert_variables)
if verbose:
print(
"axis {} converted from {} to {}".format(
axis.expression, orig, destination_units
)
)
# apply to all compatible constants
for constant in self.constants:
if constant.units_kind == units_kind:
orig = constant.units
constant.convert(destination_units, convert_variables=convert_variables)
if verbose:
print(
"constant {} converted from {} to {}".format(
constant.expression, orig, destination_units
)
)
if convert_variables:
for var in self.variables:
if wt_units.kind(var.units) == units_kind:
orig = var.units
var.convert(destination_units)
if verbose:
print(
"variable {} converted from {} to {}".format(
var.natural_name, orig, destination_units
)
)
self._on_axes_updated()
self._on_constants_updated() | python | def convert(self, destination_units, *, convert_variables=False, verbose=True):
"""Convert all compatable axes and constants to given units.
Parameters
----------
destination_units : str
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False
verbose : bool (optional)
Toggle talkback. Default is True.
See Also
--------
Axis.convert
Convert a single axis object to compatable units. Call on an
axis object in data.axes.
"""
# get kind of units
units_kind = wt_units.kind(destination_units)
# apply to all compatible axes
for axis in self.axes:
if axis.units_kind == units_kind:
orig = axis.units
axis.convert(destination_units, convert_variables=convert_variables)
if verbose:
print(
"axis {} converted from {} to {}".format(
axis.expression, orig, destination_units
)
)
# apply to all compatible constants
for constant in self.constants:
if constant.units_kind == units_kind:
orig = constant.units
constant.convert(destination_units, convert_variables=convert_variables)
if verbose:
print(
"constant {} converted from {} to {}".format(
constant.expression, orig, destination_units
)
)
if convert_variables:
for var in self.variables:
if wt_units.kind(var.units) == units_kind:
orig = var.units
var.convert(destination_units)
if verbose:
print(
"variable {} converted from {} to {}".format(
var.natural_name, orig, destination_units
)
)
self._on_axes_updated()
self._on_constants_updated() | [
"def",
"convert",
"(",
"self",
",",
"destination_units",
",",
"*",
",",
"convert_variables",
"=",
"False",
",",
"verbose",
"=",
"True",
")",
":",
"# get kind of units",
"units_kind",
"=",
"wt_units",
".",
"kind",
"(",
"destination_units",
")",
"# apply to all co... | Convert all compatable axes and constants to given units.
Parameters
----------
destination_units : str
Destination units.
convert_variables : boolean (optional)
Toggle conversion of stored arrays. Default is False
verbose : bool (optional)
Toggle talkback. Default is True.
See Also
--------
Axis.convert
Convert a single axis object to compatable units. Call on an
axis object in data.axes. | [
"Convert",
"all",
"compatable",
"axes",
"and",
"constants",
"to",
"given",
"units",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L751-L805 | train | 33,761 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.create_channel | def create_channel(
self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs
) -> Channel:
"""Append a new channel.
Parameters
----------
name : string
Unique name for this channel.
values : array (optional)
Array. If None, an empty array equaling the data shape is
created. Default is None.
shape : tuple of int
Shape to use. Must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Channel units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs : dict
Additional keyword arguments passed to Channel instantiation.
Returns
-------
Channel
Created channel.
"""
if name in self.channel_names:
warnings.warn(name, wt_exceptions.ObjectExistsWarning)
return self[name]
elif name in self.variable_names:
raise wt_exceptions.NameNotUniqueError(name)
require_kwargs = {"chunks": True}
if values is None:
if shape is None:
require_kwargs["shape"] = self.shape
else:
require_kwargs["shape"] = shape
if dtype is None:
require_kwargs["dtype"] = np.dtype(np.float64)
else:
require_kwargs["dtype"] = dtype
if require_kwargs["dtype"].kind in "fcmM":
require_kwargs["fillvalue"] = np.nan
else:
require_kwargs["fillvalue"] = 0
else:
require_kwargs["data"] = values
require_kwargs["shape"] = values.shape
require_kwargs["dtype"] = values.dtype
if np.prod(require_kwargs["shape"]) == 1:
require_kwargs["chunks"] = None
# create dataset
dataset_id = self.require_dataset(name=name, **require_kwargs).id
channel = Channel(self, dataset_id, units=units, **kwargs)
# finish
self.attrs["channel_names"] = np.append(self.attrs["channel_names"], name.encode())
return channel | python | def create_channel(
self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs
) -> Channel:
"""Append a new channel.
Parameters
----------
name : string
Unique name for this channel.
values : array (optional)
Array. If None, an empty array equaling the data shape is
created. Default is None.
shape : tuple of int
Shape to use. Must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Channel units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs : dict
Additional keyword arguments passed to Channel instantiation.
Returns
-------
Channel
Created channel.
"""
if name in self.channel_names:
warnings.warn(name, wt_exceptions.ObjectExistsWarning)
return self[name]
elif name in self.variable_names:
raise wt_exceptions.NameNotUniqueError(name)
require_kwargs = {"chunks": True}
if values is None:
if shape is None:
require_kwargs["shape"] = self.shape
else:
require_kwargs["shape"] = shape
if dtype is None:
require_kwargs["dtype"] = np.dtype(np.float64)
else:
require_kwargs["dtype"] = dtype
if require_kwargs["dtype"].kind in "fcmM":
require_kwargs["fillvalue"] = np.nan
else:
require_kwargs["fillvalue"] = 0
else:
require_kwargs["data"] = values
require_kwargs["shape"] = values.shape
require_kwargs["dtype"] = values.dtype
if np.prod(require_kwargs["shape"]) == 1:
require_kwargs["chunks"] = None
# create dataset
dataset_id = self.require_dataset(name=name, **require_kwargs).id
channel = Channel(self, dataset_id, units=units, **kwargs)
# finish
self.attrs["channel_names"] = np.append(self.attrs["channel_names"], name.encode())
return channel | [
"def",
"create_channel",
"(",
"self",
",",
"name",
",",
"values",
"=",
"None",
",",
"*",
",",
"shape",
"=",
"None",
",",
"units",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Channel",
":",
"if",
"name",
"in",
"sel... | Append a new channel.
Parameters
----------
name : string
Unique name for this channel.
values : array (optional)
Array. If None, an empty array equaling the data shape is
created. Default is None.
shape : tuple of int
Shape to use. Must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Channel units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs : dict
Additional keyword arguments passed to Channel instantiation.
Returns
-------
Channel
Created channel. | [
"Append",
"a",
"new",
"channel",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L807-L867 | train | 33,762 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.create_variable | def create_variable(
self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs
) -> Variable:
"""Add new child variable.
Parameters
----------
name : string
Unique identifier.
values : array-like (optional)
Array to populate variable with. If None, an variable will be filled with NaN.
Default is None.
shape : tuple of int
Shape to use. must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Variable units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs
Additional kwargs to variable instantiation.
Returns
-------
WrightTools Variable
New child variable.
"""
if name in self.variable_names:
warnings.warn(name, wt_exceptions.ObjectExistsWarning)
return self[name]
elif name in self.channel_names:
raise wt_exceptions.NameNotUniqueError(name)
if values is None:
if shape is None:
shape = self.shape
if dtype is None:
dtype = np.dtype(np.float64)
if dtype.kind in "fcmM":
fillvalue = np.nan
else:
fillvalue = 0
else:
shape = values.shape
dtype = values.dtype
fillvalue = None
# create dataset
id = self.require_dataset(
name=name, data=values, shape=shape, dtype=dtype, fillvalue=fillvalue
).id
variable = Variable(self, id, units=units, **kwargs)
# finish
self._variables = None
self.attrs["variable_names"] = np.append(self.attrs["variable_names"], name.encode())
return variable | python | def create_variable(
self, name, values=None, *, shape=None, units=None, dtype=None, **kwargs
) -> Variable:
"""Add new child variable.
Parameters
----------
name : string
Unique identifier.
values : array-like (optional)
Array to populate variable with. If None, an variable will be filled with NaN.
Default is None.
shape : tuple of int
Shape to use. must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Variable units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs
Additional kwargs to variable instantiation.
Returns
-------
WrightTools Variable
New child variable.
"""
if name in self.variable_names:
warnings.warn(name, wt_exceptions.ObjectExistsWarning)
return self[name]
elif name in self.channel_names:
raise wt_exceptions.NameNotUniqueError(name)
if values is None:
if shape is None:
shape = self.shape
if dtype is None:
dtype = np.dtype(np.float64)
if dtype.kind in "fcmM":
fillvalue = np.nan
else:
fillvalue = 0
else:
shape = values.shape
dtype = values.dtype
fillvalue = None
# create dataset
id = self.require_dataset(
name=name, data=values, shape=shape, dtype=dtype, fillvalue=fillvalue
).id
variable = Variable(self, id, units=units, **kwargs)
# finish
self._variables = None
self.attrs["variable_names"] = np.append(self.attrs["variable_names"], name.encode())
return variable | [
"def",
"create_variable",
"(",
"self",
",",
"name",
",",
"values",
"=",
"None",
",",
"*",
",",
"shape",
"=",
"None",
",",
"units",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Variable",
":",
"if",
"name",
"in",
"s... | Add new child variable.
Parameters
----------
name : string
Unique identifier.
values : array-like (optional)
Array to populate variable with. If None, an variable will be filled with NaN.
Default is None.
shape : tuple of int
Shape to use. must broadcast with the full shape.
Only used if `values` is None.
Default is the full shape of self.
units : string (optional)
Variable units. Default is None.
dtype : numpy.dtype (optional)
dtype to use for dataset, default is np.float64.
Only used if `values` is None.
kwargs
Additional kwargs to variable instantiation.
Returns
-------
WrightTools Variable
New child variable. | [
"Add",
"new",
"child",
"variable",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L869-L924 | train | 33,763 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.get_nadir | def get_nadir(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the minimum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis.
"""
# get channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
# get indicies
idx = channel.argmin()
# finish
return tuple(a[idx] for a in self._axes) | python | def get_nadir(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the minimum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis.
"""
# get channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
# get indicies
idx = channel.argmin()
# finish
return tuple(a[idx] for a in self._axes) | [
"def",
"get_nadir",
"(",
"self",
",",
"channel",
"=",
"0",
")",
"->",
"tuple",
":",
"# get channel",
"if",
"isinstance",
"(",
"channel",
",",
"int",
")",
":",
"channel_index",
"=",
"channel",
"elif",
"isinstance",
"(",
"channel",
",",
"str",
")",
":",
... | Get the coordinates, in units, of the minimum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis. | [
"Get",
"the",
"coordinates",
"in",
"units",
"of",
"the",
"minimum",
"in",
"a",
"channel",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L926-L950 | train | 33,764 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.get_zenith | def get_zenith(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the maximum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis.
"""
# get channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
# get indicies
idx = channel.argmax()
# finish
return tuple(a[idx] for a in self._axes) | python | def get_zenith(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the maximum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis.
"""
# get channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
# get indicies
idx = channel.argmax()
# finish
return tuple(a[idx] for a in self._axes) | [
"def",
"get_zenith",
"(",
"self",
",",
"channel",
"=",
"0",
")",
"->",
"tuple",
":",
"# get channel",
"if",
"isinstance",
"(",
"channel",
",",
"int",
")",
":",
"channel_index",
"=",
"channel",
"elif",
"isinstance",
"(",
"channel",
",",
"str",
")",
":",
... | Get the coordinates, in units, of the maximum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis. | [
"Get",
"the",
"coordinates",
"in",
"units",
"of",
"the",
"maximum",
"in",
"a",
"channel",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L952-L976 | train | 33,765 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.heal | def heal(self, channel=0, method="linear", fill_value=np.nan, verbose=True):
"""
Remove nans from channel using interpolation.
Parameters
----------
channel : int or str (optional)
Channel to heal. Default is 0.
method : {'linear', 'nearest', 'cubic'} (optional)
The interpolation method. Note that cubic interpolation is only
possible for 1D and 2D data. See `griddata`__ for more information.
Default is linear.
fill_value : number-like (optional)
The value written to pixels that cannot be filled by interpolation.
Default is nan.
verbose : bool (optional)
Toggle talkback. Default is True.
__ http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html
.. note:: Healing may take several minutes for large datasets.
Interpolation time goes as nearest, linear, then cubic.
"""
warnings.warn("heal", category=wt_exceptions.EntireDatasetInMemoryWarning)
timer = wt_kit.Timer(verbose=False)
with timer:
# channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
values = self.channels[channel_index][:]
points = [axis[:] for axis in self._axes]
xi = tuple(np.meshgrid(*points, indexing="ij"))
# 'undo' gridding
arr = np.zeros((len(self._axes) + 1, values.size))
for i in range(len(self._axes)):
arr[i] = xi[i].flatten()
arr[-1] = values.flatten()
# remove nans
arr = arr[:, ~np.isnan(arr).any(axis=0)]
# grid data wants tuples
tup = tuple([arr[i] for i in range(len(arr) - 1)])
# grid data
out = griddata(tup, arr[-1], xi, method=method, fill_value=fill_value)
self.channels[channel_index][:] = out
# print
if verbose:
print(
"channel {0} healed in {1} seconds".format(
channel.name, np.around(timer.interval, decimals=3)
)
) | python | def heal(self, channel=0, method="linear", fill_value=np.nan, verbose=True):
"""
Remove nans from channel using interpolation.
Parameters
----------
channel : int or str (optional)
Channel to heal. Default is 0.
method : {'linear', 'nearest', 'cubic'} (optional)
The interpolation method. Note that cubic interpolation is only
possible for 1D and 2D data. See `griddata`__ for more information.
Default is linear.
fill_value : number-like (optional)
The value written to pixels that cannot be filled by interpolation.
Default is nan.
verbose : bool (optional)
Toggle talkback. Default is True.
__ http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html
.. note:: Healing may take several minutes for large datasets.
Interpolation time goes as nearest, linear, then cubic.
"""
warnings.warn("heal", category=wt_exceptions.EntireDatasetInMemoryWarning)
timer = wt_kit.Timer(verbose=False)
with timer:
# channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
values = self.channels[channel_index][:]
points = [axis[:] for axis in self._axes]
xi = tuple(np.meshgrid(*points, indexing="ij"))
# 'undo' gridding
arr = np.zeros((len(self._axes) + 1, values.size))
for i in range(len(self._axes)):
arr[i] = xi[i].flatten()
arr[-1] = values.flatten()
# remove nans
arr = arr[:, ~np.isnan(arr).any(axis=0)]
# grid data wants tuples
tup = tuple([arr[i] for i in range(len(arr) - 1)])
# grid data
out = griddata(tup, arr[-1], xi, method=method, fill_value=fill_value)
self.channels[channel_index][:] = out
# print
if verbose:
print(
"channel {0} healed in {1} seconds".format(
channel.name, np.around(timer.interval, decimals=3)
)
) | [
"def",
"heal",
"(",
"self",
",",
"channel",
"=",
"0",
",",
"method",
"=",
"\"linear\"",
",",
"fill_value",
"=",
"np",
".",
"nan",
",",
"verbose",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"heal\"",
",",
"category",
"=",
"wt_exceptions",
... | Remove nans from channel using interpolation.
Parameters
----------
channel : int or str (optional)
Channel to heal. Default is 0.
method : {'linear', 'nearest', 'cubic'} (optional)
The interpolation method. Note that cubic interpolation is only
possible for 1D and 2D data. See `griddata`__ for more information.
Default is linear.
fill_value : number-like (optional)
The value written to pixels that cannot be filled by interpolation.
Default is nan.
verbose : bool (optional)
Toggle talkback. Default is True.
__ http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html
.. note:: Healing may take several minutes for large datasets.
Interpolation time goes as nearest, linear, then cubic. | [
"Remove",
"nans",
"from",
"channel",
"using",
"interpolation",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L978-L1037 | train | 33,766 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.level | def level(self, channel, axis, npts, *, verbose=True):
"""Subtract the average value of npts at the edge of a given axis.
Parameters
----------
channel : int or str
Channel to level.
axis : int
Axis to level along.
npts : int
Number of points to average for each slice. Positive numbers
take points at leading indicies and negative numbers take points
at trailing indicies.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
warnings.warn("level", category=wt_exceptions.EntireDatasetInMemoryWarning)
channel_index = wt_kit.get_index(self.channel_names, channel)
channel = self.channels[channel_index]
# verify npts not zero
npts = int(npts)
if npts == 0:
raise wt_exceptions.ValueError("npts must not be zero")
# get subtrahend
ss = [slice(None)] * self.ndim
if npts > 0:
ss[axis] = slice(0, npts, None)
else:
ss[axis] = slice(npts, None, None)
subtrahend = np.nanmean(channel[ss], axis=axis)
if self.ndim > 1:
subtrahend = np.expand_dims(subtrahend, axis=axis)
# level
channel -= subtrahend
# finish
channel._null = 0
if verbose:
print("channel {0} leveled along axis {1}".format(channel.natural_name, axis)) | python | def level(self, channel, axis, npts, *, verbose=True):
"""Subtract the average value of npts at the edge of a given axis.
Parameters
----------
channel : int or str
Channel to level.
axis : int
Axis to level along.
npts : int
Number of points to average for each slice. Positive numbers
take points at leading indicies and negative numbers take points
at trailing indicies.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
warnings.warn("level", category=wt_exceptions.EntireDatasetInMemoryWarning)
channel_index = wt_kit.get_index(self.channel_names, channel)
channel = self.channels[channel_index]
# verify npts not zero
npts = int(npts)
if npts == 0:
raise wt_exceptions.ValueError("npts must not be zero")
# get subtrahend
ss = [slice(None)] * self.ndim
if npts > 0:
ss[axis] = slice(0, npts, None)
else:
ss[axis] = slice(npts, None, None)
subtrahend = np.nanmean(channel[ss], axis=axis)
if self.ndim > 1:
subtrahend = np.expand_dims(subtrahend, axis=axis)
# level
channel -= subtrahend
# finish
channel._null = 0
if verbose:
print("channel {0} leveled along axis {1}".format(channel.natural_name, axis)) | [
"def",
"level",
"(",
"self",
",",
"channel",
",",
"axis",
",",
"npts",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"level\"",
",",
"category",
"=",
"wt_exceptions",
".",
"EntireDatasetInMemoryWarning",
")",
"channel_ind... | Subtract the average value of npts at the edge of a given axis.
Parameters
----------
channel : int or str
Channel to level.
axis : int
Axis to level along.
npts : int
Number of points to average for each slice. Positive numbers
take points at leading indicies and negative numbers take points
at trailing indicies.
verbose : bool (optional)
Toggle talkback. Default is True. | [
"Subtract",
"the",
"average",
"value",
"of",
"npts",
"at",
"the",
"edge",
"of",
"a",
"given",
"axis",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1039-L1076 | train | 33,767 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.print_tree | def print_tree(self, *, verbose=True):
"""Print a ascii-formatted tree representation of the data contents."""
print("{0} ({1})".format(self.natural_name, self.filepath))
self._print_branch("", depth=0, verbose=verbose) | python | def print_tree(self, *, verbose=True):
"""Print a ascii-formatted tree representation of the data contents."""
print("{0} ({1})".format(self.natural_name, self.filepath))
self._print_branch("", depth=0, verbose=verbose) | [
"def",
"print_tree",
"(",
"self",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"print",
"(",
"\"{0} ({1})\"",
".",
"format",
"(",
"self",
".",
"natural_name",
",",
"self",
".",
"filepath",
")",
")",
"self",
".",
"_print_branch",
"(",
"\"\"",
",",
... | Print a ascii-formatted tree representation of the data contents. | [
"Print",
"a",
"ascii",
"-",
"formatted",
"tree",
"representation",
"of",
"the",
"data",
"contents",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1314-L1317 | train | 33,768 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.remove_channel | def remove_channel(self, channel, *, verbose=True):
"""Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True.
"""
channel_index = wt_kit.get_index(self.channel_names, channel)
new = list(self.channel_names)
name = new.pop(channel_index)
del self[name]
self.channel_names = new
if verbose:
print("channel {0} removed".format(name)) | python | def remove_channel(self, channel, *, verbose=True):
"""Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True.
"""
channel_index = wt_kit.get_index(self.channel_names, channel)
new = list(self.channel_names)
name = new.pop(channel_index)
del self[name]
self.channel_names = new
if verbose:
print("channel {0} removed".format(name)) | [
"def",
"remove_channel",
"(",
"self",
",",
"channel",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"channel_index",
"=",
"wt_kit",
".",
"get_index",
"(",
"self",
".",
"channel_names",
",",
"channel",
")",
"new",
"=",
"list",
"(",
"self",
".",
"chan... | Remove channel from data.
Parameters
----------
channel : int or str
Channel index or name to remove.
verbose : boolean (optional)
Toggle talkback. Default is True. | [
"Remove",
"channel",
"from",
"data",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1353-L1369 | train | 33,769 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.remove_variable | def remove_variable(self, variable, *, implied=True, verbose=True):
"""Remove variable from data.
Parameters
----------
variable : int or str
Variable index or name to remove.
implied : boolean (optional)
Toggle deletion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True.
"""
if isinstance(variable, int):
variable = self.variable_names[variable]
# find all of the implied variables
removed = []
if implied:
for n in self.variable_names:
if n.startswith(variable):
removed.append(n)
else:
removed = [variable]
# check that axes will not be ruined
for n in removed:
for a in self._axes:
if n in [v.natural_name for v in a.variables]:
message = "{0} is contained in axis {1}".format(n, a.expression)
raise RuntimeError(message)
for c in self._constants:
if n in [v.natural_name for v in c.variables]:
warnings.warn(
"Variable being removed used in a constant",
wt_exceptions.WrightToolsWarning,
)
# do removal
for n in removed:
variable_index = wt_kit.get_index(self.variable_names, n)
new = list(self.variable_names)
name = new.pop(variable_index)
del self[name]
self.variable_names = new
self._variables = None
# finish
if verbose:
print("{0} variable(s) removed:".format(len(removed)))
for n in removed:
print(" {0}".format(n)) | python | def remove_variable(self, variable, *, implied=True, verbose=True):
"""Remove variable from data.
Parameters
----------
variable : int or str
Variable index or name to remove.
implied : boolean (optional)
Toggle deletion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True.
"""
if isinstance(variable, int):
variable = self.variable_names[variable]
# find all of the implied variables
removed = []
if implied:
for n in self.variable_names:
if n.startswith(variable):
removed.append(n)
else:
removed = [variable]
# check that axes will not be ruined
for n in removed:
for a in self._axes:
if n in [v.natural_name for v in a.variables]:
message = "{0} is contained in axis {1}".format(n, a.expression)
raise RuntimeError(message)
for c in self._constants:
if n in [v.natural_name for v in c.variables]:
warnings.warn(
"Variable being removed used in a constant",
wt_exceptions.WrightToolsWarning,
)
# do removal
for n in removed:
variable_index = wt_kit.get_index(self.variable_names, n)
new = list(self.variable_names)
name = new.pop(variable_index)
del self[name]
self.variable_names = new
self._variables = None
# finish
if verbose:
print("{0} variable(s) removed:".format(len(removed)))
for n in removed:
print(" {0}".format(n)) | [
"def",
"remove_variable",
"(",
"self",
",",
"variable",
",",
"*",
",",
"implied",
"=",
"True",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"variable",
",",
"int",
")",
":",
"variable",
"=",
"self",
".",
"variable_names",
"[",
"varia... | Remove variable from data.
Parameters
----------
variable : int or str
Variable index or name to remove.
implied : boolean (optional)
Toggle deletion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True. | [
"Remove",
"variable",
"from",
"data",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1371-L1419 | train | 33,770 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.rename_channels | def rename_channels(self, *, verbose=True, **kwargs):
"""Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# ensure that items will remain unique
changed = kwargs.keys()
for k, v in kwargs.items():
if v not in changed and v in self.keys():
raise wt_exceptions.NameNotUniqueError(v)
# compile references to items that are changing
new = {}
for k, v in kwargs.items():
obj = self[k]
index = self.channel_names.index(k)
# rename
new[v] = obj, index
Group._instances.pop(obj.fullpath, None)
obj.natural_name = str(v)
# remove old references
del self[k]
# apply new references
names = list(self.channel_names)
for v, value in new.items():
obj, index = value
self[v] = obj
names[index] = v
self.channel_names = names
# finish
if verbose:
print("{0} channel(s) renamed:".format(len(kwargs)))
for k, v in kwargs.items():
print(" {0} --> {1}".format(k, v)) | python | def rename_channels(self, *, verbose=True, **kwargs):
"""Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# ensure that items will remain unique
changed = kwargs.keys()
for k, v in kwargs.items():
if v not in changed and v in self.keys():
raise wt_exceptions.NameNotUniqueError(v)
# compile references to items that are changing
new = {}
for k, v in kwargs.items():
obj = self[k]
index = self.channel_names.index(k)
# rename
new[v] = obj, index
Group._instances.pop(obj.fullpath, None)
obj.natural_name = str(v)
# remove old references
del self[k]
# apply new references
names = list(self.channel_names)
for v, value in new.items():
obj, index = value
self[v] = obj
names[index] = v
self.channel_names = names
# finish
if verbose:
print("{0} channel(s) renamed:".format(len(kwargs)))
for k, v in kwargs.items():
print(" {0} --> {1}".format(k, v)) | [
"def",
"rename_channels",
"(",
"self",
",",
"*",
",",
"verbose",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# ensure that items will remain unique",
"changed",
"=",
"kwargs",
".",
"keys",
"(",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items"... | Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True | [
"Rename",
"a",
"set",
"of",
"channels",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1421-L1458 | train | 33,771 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.rename_variables | def rename_variables(self, *, implied=True, verbose=True, **kwargs):
"""Rename a set of variables.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
implied : boolean (optional)
Toggle inclusion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# find all of the implied variables
kwargs = collections.OrderedDict(kwargs)
if implied:
new = collections.OrderedDict()
for k, v in kwargs.items():
for n in self.variable_names:
if n.startswith(k):
new[n] = n.replace(k, v, 1)
kwargs = new
# ensure that items will remain unique
changed = kwargs.keys()
for k, v in kwargs.items():
if v not in changed and v in self.keys():
raise wt_exceptions.NameNotUniqueError(v)
# compile references to items that are changing
new = {}
for k, v in kwargs.items():
obj = self[k]
index = self.variable_names.index(k)
# rename
new[v] = obj, index
Group._instances.pop(obj.fullpath, None)
obj.natural_name = str(v)
# remove old references
del self[k]
# apply new references
names = list(self.variable_names)
for v, value in new.items():
obj, index = value
self[v] = obj
names[index] = v
self.variable_names = names
units = self.units
new = list(self.axis_expressions)
for i, v in enumerate(kwargs.keys()):
for j, n in enumerate(new):
new[j] = n.replace(v, "{%i}" % i)
for i, n in enumerate(new):
new[i] = n.format(*kwargs.values())
self.transform(*new)
for a, u in zip(self._axes, units):
a.convert(u)
units = self.constant_units
new = list(self.constant_expressions)
for i, v in enumerate(kwargs.keys()):
for j, n in enumerate(new):
new[j] = n.replace(v, "{%i}" % i)
for i, n in enumerate(new):
new[i] = n.format(*kwargs.values())
self.set_constants(*new)
for c, u in zip(self._constants, units):
c.convert(u)
# finish
if verbose:
print("{0} variable(s) renamed:".format(len(kwargs)))
for k, v in kwargs.items():
print(" {0} --> {1}".format(k, v)) | python | def rename_variables(self, *, implied=True, verbose=True, **kwargs):
"""Rename a set of variables.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
implied : boolean (optional)
Toggle inclusion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# find all of the implied variables
kwargs = collections.OrderedDict(kwargs)
if implied:
new = collections.OrderedDict()
for k, v in kwargs.items():
for n in self.variable_names:
if n.startswith(k):
new[n] = n.replace(k, v, 1)
kwargs = new
# ensure that items will remain unique
changed = kwargs.keys()
for k, v in kwargs.items():
if v not in changed and v in self.keys():
raise wt_exceptions.NameNotUniqueError(v)
# compile references to items that are changing
new = {}
for k, v in kwargs.items():
obj = self[k]
index = self.variable_names.index(k)
# rename
new[v] = obj, index
Group._instances.pop(obj.fullpath, None)
obj.natural_name = str(v)
# remove old references
del self[k]
# apply new references
names = list(self.variable_names)
for v, value in new.items():
obj, index = value
self[v] = obj
names[index] = v
self.variable_names = names
units = self.units
new = list(self.axis_expressions)
for i, v in enumerate(kwargs.keys()):
for j, n in enumerate(new):
new[j] = n.replace(v, "{%i}" % i)
for i, n in enumerate(new):
new[i] = n.format(*kwargs.values())
self.transform(*new)
for a, u in zip(self._axes, units):
a.convert(u)
units = self.constant_units
new = list(self.constant_expressions)
for i, v in enumerate(kwargs.keys()):
for j, n in enumerate(new):
new[j] = n.replace(v, "{%i}" % i)
for i, n in enumerate(new):
new[i] = n.format(*kwargs.values())
self.set_constants(*new)
for c, u in zip(self._constants, units):
c.convert(u)
# finish
if verbose:
print("{0} variable(s) renamed:".format(len(kwargs)))
for k, v in kwargs.items():
print(" {0} --> {1}".format(k, v)) | [
"def",
"rename_variables",
"(",
"self",
",",
"*",
",",
"implied",
"=",
"True",
",",
"verbose",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# find all of the implied variables",
"kwargs",
"=",
"collections",
".",
"OrderedDict",
"(",
"kwargs",
")",
"if",
... | Rename a set of variables.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
implied : boolean (optional)
Toggle inclusion of other variables that start with the same
name. Default is True.
verbose : boolean (optional)
Toggle talkback. Default is True | [
"Rename",
"a",
"set",
"of",
"variables",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1460-L1529 | train | 33,772 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.share_nans | def share_nans(self):
"""Share not-a-numbers between all channels.
If any channel is nan at a given index, all channels will be nan
at that index after this operation.
Uses the share_nans method found in wt.kit.
"""
def f(_, s, channels):
outs = wt_kit.share_nans(*[c[s] for c in channels])
for c, o in zip(channels, outs):
c[s] = o
self.channels[0].chunkwise(f, self.channels) | python | def share_nans(self):
"""Share not-a-numbers between all channels.
If any channel is nan at a given index, all channels will be nan
at that index after this operation.
Uses the share_nans method found in wt.kit.
"""
def f(_, s, channels):
outs = wt_kit.share_nans(*[c[s] for c in channels])
for c, o in zip(channels, outs):
c[s] = o
self.channels[0].chunkwise(f, self.channels) | [
"def",
"share_nans",
"(",
"self",
")",
":",
"def",
"f",
"(",
"_",
",",
"s",
",",
"channels",
")",
":",
"outs",
"=",
"wt_kit",
".",
"share_nans",
"(",
"*",
"[",
"c",
"[",
"s",
"]",
"for",
"c",
"in",
"channels",
"]",
")",
"for",
"c",
",",
"o",
... | Share not-a-numbers between all channels.
If any channel is nan at a given index, all channels will be nan
at that index after this operation.
Uses the share_nans method found in wt.kit. | [
"Share",
"not",
"-",
"a",
"-",
"numbers",
"between",
"all",
"channels",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1531-L1545 | train | 33,773 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.smooth | def smooth(self, factors, channel=None, verbose=True) -> "Data":
"""Smooth a channel using an n-dimenional kaiser window.
Note, all arrays are loaded into memory.
For more info see `Kaiser_window`__ wikipedia entry.
__ https://en.wikipedia.org/wiki/Kaiser_window
Parameters
----------
factors : int or list of int
The smoothing factor. You may provide a list of smoothing factors
for each axis.
channel : int or str or None (optional)
The channel to smooth. If None, all channels will be smoothed.
Default is None.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
warnings.warn("smooth", category=wt_exceptions.EntireDatasetInMemoryWarning)
# get factors -----------------------------------------------------------------------------
if isinstance(factors, list):
pass
else:
dummy = np.zeros(len(self._axes))
dummy[::] = factors
factors = list(dummy)
# get channels ----------------------------------------------------------------------------
if channel is None:
channels = self.channels
else:
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channels = [self.channels[channel_index]]
# smooth ----------------------------------------------------------------------------------
for channel in channels:
values = channel[:]
for axis_index in range(len(factors)):
factor = factors[axis_index]
# transpose so the axis of interest is last
transpose_order = range(len(values.shape))
# replace axis_index with zero
transpose_order = [
len(values.shape) - 1 if i == axis_index else i for i in transpose_order
]
transpose_order[len(values.shape) - 1] = axis_index
values = values.transpose(transpose_order)
# get kaiser window
beta = 5.0
w = np.kaiser(2 * factor + 1, beta)
# for all slices...
for index in np.ndindex(values[..., 0].shape):
current_slice = values[index]
temp_slice = np.pad(current_slice, int(factor), mode=str("edge"))
values[index] = np.convolve(temp_slice, w / w.sum(), mode=str("valid"))
# transpose out
values = values.transpose(transpose_order)
# return array to channel object
channel[:] = values
if verbose:
print("smoothed data") | python | def smooth(self, factors, channel=None, verbose=True) -> "Data":
"""Smooth a channel using an n-dimenional kaiser window.
Note, all arrays are loaded into memory.
For more info see `Kaiser_window`__ wikipedia entry.
__ https://en.wikipedia.org/wiki/Kaiser_window
Parameters
----------
factors : int or list of int
The smoothing factor. You may provide a list of smoothing factors
for each axis.
channel : int or str or None (optional)
The channel to smooth. If None, all channels will be smoothed.
Default is None.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
warnings.warn("smooth", category=wt_exceptions.EntireDatasetInMemoryWarning)
# get factors -----------------------------------------------------------------------------
if isinstance(factors, list):
pass
else:
dummy = np.zeros(len(self._axes))
dummy[::] = factors
factors = list(dummy)
# get channels ----------------------------------------------------------------------------
if channel is None:
channels = self.channels
else:
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channels = [self.channels[channel_index]]
# smooth ----------------------------------------------------------------------------------
for channel in channels:
values = channel[:]
for axis_index in range(len(factors)):
factor = factors[axis_index]
# transpose so the axis of interest is last
transpose_order = range(len(values.shape))
# replace axis_index with zero
transpose_order = [
len(values.shape) - 1 if i == axis_index else i for i in transpose_order
]
transpose_order[len(values.shape) - 1] = axis_index
values = values.transpose(transpose_order)
# get kaiser window
beta = 5.0
w = np.kaiser(2 * factor + 1, beta)
# for all slices...
for index in np.ndindex(values[..., 0].shape):
current_slice = values[index]
temp_slice = np.pad(current_slice, int(factor), mode=str("edge"))
values[index] = np.convolve(temp_slice, w / w.sum(), mode=str("valid"))
# transpose out
values = values.transpose(transpose_order)
# return array to channel object
channel[:] = values
if verbose:
print("smoothed data") | [
"def",
"smooth",
"(",
"self",
",",
"factors",
",",
"channel",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
"->",
"\"Data\"",
":",
"warnings",
".",
"warn",
"(",
"\"smooth\"",
",",
"category",
"=",
"wt_exceptions",
".",
"EntireDatasetInMemoryWarning",
")",
... | Smooth a channel using an n-dimenional kaiser window.
Note, all arrays are loaded into memory.
For more info see `Kaiser_window`__ wikipedia entry.
__ https://en.wikipedia.org/wiki/Kaiser_window
Parameters
----------
factors : int or list of int
The smoothing factor. You may provide a list of smoothing factors
for each axis.
channel : int or str or None (optional)
The channel to smooth. If None, all channels will be smoothed.
Default is None.
verbose : bool (optional)
Toggle talkback. Default is True. | [
"Smooth",
"a",
"channel",
"using",
"an",
"n",
"-",
"dimenional",
"kaiser",
"window",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1547-L1613 | train | 33,774 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.transform | def transform(self, *axes, verbose=True):
"""Transform the data.
Parameters
----------
axes : strings
Expressions for the new set of axes.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Similar method except for constants
"""
# TODO: ensure that transform does not break data
# create
new = []
newt = "newt" in self.axis_expressions
current = {a.expression: a for a in self._axes}
for expression in axes:
axis = current.get(expression, Axis(self, expression))
new.append(axis)
self._axes = new
# units
for a in self._axes:
if a.units is None:
a.convert(a.variables[0].units)
# finish
self.flush()
self._on_axes_updated()
nownewt = "newt" in self.axis_expressions
if verbose and nownewt and not newt:
print("Look she turned me into a newt")
elif verbose and newt and not nownewt:
print("I got better") | python | def transform(self, *axes, verbose=True):
"""Transform the data.
Parameters
----------
axes : strings
Expressions for the new set of axes.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Similar method except for constants
"""
# TODO: ensure that transform does not break data
# create
new = []
newt = "newt" in self.axis_expressions
current = {a.expression: a for a in self._axes}
for expression in axes:
axis = current.get(expression, Axis(self, expression))
new.append(axis)
self._axes = new
# units
for a in self._axes:
if a.units is None:
a.convert(a.variables[0].units)
# finish
self.flush()
self._on_axes_updated()
nownewt = "newt" in self.axis_expressions
if verbose and nownewt and not newt:
print("Look she turned me into a newt")
elif verbose and newt and not nownewt:
print("I got better") | [
"def",
"transform",
"(",
"self",
",",
"*",
"axes",
",",
"verbose",
"=",
"True",
")",
":",
"# TODO: ensure that transform does not break data",
"# create",
"new",
"=",
"[",
"]",
"newt",
"=",
"\"newt\"",
"in",
"self",
".",
"axis_expressions",
"current",
"=",
"{"... | Transform the data.
Parameters
----------
axes : strings
Expressions for the new set of axes.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Similar method except for constants | [
"Transform",
"the",
"data",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1764-L1799 | train | 33,775 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.set_constants | def set_constants(self, *constants, verbose=True):
"""Set the constants associated with the data.
Parameters
----------
constants : str
Expressions for the new set of constants.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
transform
Similar method except for axes.
create_constant
Add an individual constant.
remove_constant
Remove an individual constant.
"""
# create
new = []
current = {c.expression: c for c in self._constants}
for expression in constants:
constant = current.get(expression, Constant(self, expression))
new.append(constant)
self._constants = new
# units
for c in self._constants:
if c.units is None:
c.convert(c.variables[0].units)
# finish
self.flush()
self._on_constants_updated() | python | def set_constants(self, *constants, verbose=True):
"""Set the constants associated with the data.
Parameters
----------
constants : str
Expressions for the new set of constants.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
transform
Similar method except for axes.
create_constant
Add an individual constant.
remove_constant
Remove an individual constant.
"""
# create
new = []
current = {c.expression: c for c in self._constants}
for expression in constants:
constant = current.get(expression, Constant(self, expression))
new.append(constant)
self._constants = new
# units
for c in self._constants:
if c.units is None:
c.convert(c.variables[0].units)
# finish
self.flush()
self._on_constants_updated() | [
"def",
"set_constants",
"(",
"self",
",",
"*",
"constants",
",",
"verbose",
"=",
"True",
")",
":",
"# create",
"new",
"=",
"[",
"]",
"current",
"=",
"{",
"c",
".",
"expression",
":",
"c",
"for",
"c",
"in",
"self",
".",
"_constants",
"}",
"for",
"ex... | Set the constants associated with the data.
Parameters
----------
constants : str
Expressions for the new set of constants.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
transform
Similar method except for axes.
create_constant
Add an individual constant.
remove_constant
Remove an individual constant. | [
"Set",
"the",
"constants",
"associated",
"with",
"the",
"data",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1801-L1833 | train | 33,776 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.create_constant | def create_constant(self, expression, *, verbose=True):
"""Append a constant to the stored list.
Parameters
----------
expression : str
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
remove_constant
Remove an individual constant.
"""
if expression in self.constant_expressions:
wt_exceptions.ObjectExistsWarning.warn(expression)
return self.constants[self.constant_expressions.index(expression)]
constant = Constant(self, expression)
if constant.units is None:
constant.convert(constant.variables[0].units)
self._constants.append(constant)
self.flush()
self._on_constants_updated()
if verbose:
print("Constant '{}' added".format(constant.expression))
return constant | python | def create_constant(self, expression, *, verbose=True):
"""Append a constant to the stored list.
Parameters
----------
expression : str
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
remove_constant
Remove an individual constant.
"""
if expression in self.constant_expressions:
wt_exceptions.ObjectExistsWarning.warn(expression)
return self.constants[self.constant_expressions.index(expression)]
constant = Constant(self, expression)
if constant.units is None:
constant.convert(constant.variables[0].units)
self._constants.append(constant)
self.flush()
self._on_constants_updated()
if verbose:
print("Constant '{}' added".format(constant.expression))
return constant | [
"def",
"create_constant",
"(",
"self",
",",
"expression",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"expression",
"in",
"self",
".",
"constant_expressions",
":",
"wt_exceptions",
".",
"ObjectExistsWarning",
".",
"warn",
"(",
"expression",
")",
"... | Append a constant to the stored list.
Parameters
----------
expression : str
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
remove_constant
Remove an individual constant. | [
"Append",
"a",
"constant",
"to",
"the",
"stored",
"list",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1835-L1863 | train | 33,777 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.remove_constant | def remove_constant(self, constant, *, verbose=True):
"""Remove a constant from the stored list.
Parameters
----------
constant : str or Constant or int
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
create_constant
Add an individual constant.
"""
if isinstance(constant, (str, int)):
constant_index = wt_kit.get_index(self.constant_expressions, constant)
elif isinstance(constant, Constant):
constant_index = wt_kit.get_index(self.constants, constant)
constant = self._constants[constant_index]
self._constants.pop(constant_index)
self.flush()
self._on_constants_updated()
if verbose:
print("Constant '{}' removed".format(constant.expression)) | python | def remove_constant(self, constant, *, verbose=True):
"""Remove a constant from the stored list.
Parameters
----------
constant : str or Constant or int
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
create_constant
Add an individual constant.
"""
if isinstance(constant, (str, int)):
constant_index = wt_kit.get_index(self.constant_expressions, constant)
elif isinstance(constant, Constant):
constant_index = wt_kit.get_index(self.constants, constant)
constant = self._constants[constant_index]
self._constants.pop(constant_index)
self.flush()
self._on_constants_updated()
if verbose:
print("Constant '{}' removed".format(constant.expression)) | [
"def",
"remove_constant",
"(",
"self",
",",
"constant",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"constant",
",",
"(",
"str",
",",
"int",
")",
")",
":",
"constant_index",
"=",
"wt_kit",
".",
"get_index",
"(",
"self",
... | Remove a constant from the stored list.
Parameters
----------
constant : str or Constant or int
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
create_constant
Add an individual constant. | [
"Remove",
"a",
"constant",
"from",
"the",
"stored",
"list",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1865-L1891 | train | 33,778 |
wright-group/WrightTools | WrightTools/data/_data.py | Data.zoom | def zoom(self, factor, order=1, verbose=True):
"""Zoom the data array using spline interpolation of the requested order.
The number of points along each axis is increased by factor.
See `scipy ndimage`__ for more info.
__ http://docs.scipy.org/doc/scipy/reference/
generated/scipy.ndimage.interpolation.zoom.html
Parameters
----------
factor : float
The number of points along each axis will increase by this factor.
order : int (optional)
The order of the spline used to interpolate onto new points.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
raise NotImplementedError
import scipy.ndimage
# axes
for axis in self._axes:
axis[:] = scipy.ndimage.interpolation.zoom(axis[:], factor, order=order)
# channels
for channel in self.channels:
channel[:] = scipy.ndimage.interpolation.zoom(channel[:], factor, order=order)
# return
if verbose:
print("data zoomed to new shape:", self.shape) | python | def zoom(self, factor, order=1, verbose=True):
"""Zoom the data array using spline interpolation of the requested order.
The number of points along each axis is increased by factor.
See `scipy ndimage`__ for more info.
__ http://docs.scipy.org/doc/scipy/reference/
generated/scipy.ndimage.interpolation.zoom.html
Parameters
----------
factor : float
The number of points along each axis will increase by this factor.
order : int (optional)
The order of the spline used to interpolate onto new points.
verbose : bool (optional)
Toggle talkback. Default is True.
"""
raise NotImplementedError
import scipy.ndimage
# axes
for axis in self._axes:
axis[:] = scipy.ndimage.interpolation.zoom(axis[:], factor, order=order)
# channels
for channel in self.channels:
channel[:] = scipy.ndimage.interpolation.zoom(channel[:], factor, order=order)
# return
if verbose:
print("data zoomed to new shape:", self.shape) | [
"def",
"zoom",
"(",
"self",
",",
"factor",
",",
"order",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"raise",
"NotImplementedError",
"import",
"scipy",
".",
"ndimage",
"# axes",
"for",
"axis",
"in",
"self",
".",
"_axes",
":",
"axis",
"[",
":",
"... | Zoom the data array using spline interpolation of the requested order.
The number of points along each axis is increased by factor.
See `scipy ndimage`__ for more info.
__ http://docs.scipy.org/doc/scipy/reference/
generated/scipy.ndimage.interpolation.zoom.html
Parameters
----------
factor : float
The number of points along each axis will increase by this factor.
order : int (optional)
The order of the spline used to interpolate onto new points.
verbose : bool (optional)
Toggle talkback. Default is True. | [
"Zoom",
"the",
"data",
"array",
"using",
"spline",
"interpolation",
"of",
"the",
"requested",
"order",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_data.py#L1893-L1922 | train | 33,779 |
wright-group/WrightTools | WrightTools/kit/_path.py | get_path_matching | def get_path_matching(name):
"""Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
"""
# first try looking in the user folder
p = os.path.join(os.path.expanduser("~"), name)
# then try expanding upwards from cwd
if not os.path.isdir(p):
p = None
drive, folders = os.path.splitdrive(os.getcwd())
folders = folders.split(os.sep)
folders.insert(0, os.sep)
if name in folders:
p = os.path.join(drive, *folders[: folders.index(name) + 1])
# TODO: something more robust to catch the rest of the cases?
return p | python | def get_path_matching(name):
"""Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath.
"""
# first try looking in the user folder
p = os.path.join(os.path.expanduser("~"), name)
# then try expanding upwards from cwd
if not os.path.isdir(p):
p = None
drive, folders = os.path.splitdrive(os.getcwd())
folders = folders.split(os.sep)
folders.insert(0, os.sep)
if name in folders:
p = os.path.join(drive, *folders[: folders.index(name) + 1])
# TODO: something more robust to catch the rest of the cases?
return p | [
"def",
"get_path_matching",
"(",
"name",
")",
":",
"# first try looking in the user folder",
"p",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
",",
"name",
")",
"# then try expanding upwards from cwd",
"if",
... | Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath. | [
"Get",
"path",
"matching",
"a",
"name",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_path.py#L20-L44 | train | 33,780 |
wright-group/WrightTools | WrightTools/kit/_path.py | glob_handler | def glob_handler(extension, folder=None, identifier=None):
"""Return a list of all files matching specified inputs.
Parameters
----------
extension : string
File extension.
folder : string (optional)
Folder to search within. Default is None (current working
directory).
identifier : string
Unique identifier. Default is None.
Returns
-------
list of strings
Full path of matching files.
"""
filepaths = []
if folder:
# comment out [ and ]...
folder = folder.replace("[", "?")
folder = folder.replace("]", "*")
folder = folder.replace("?", "[[]")
folder = folder.replace("*", "[]]")
glob_str = os.path.join(folder, "*" + extension)
else:
glob_str = "*" + extension + "*"
for filepath in glob.glob(glob_str):
if identifier:
if identifier in filepath:
filepaths.append(filepath)
else:
filepaths.append(filepath)
return filepaths | python | def glob_handler(extension, folder=None, identifier=None):
"""Return a list of all files matching specified inputs.
Parameters
----------
extension : string
File extension.
folder : string (optional)
Folder to search within. Default is None (current working
directory).
identifier : string
Unique identifier. Default is None.
Returns
-------
list of strings
Full path of matching files.
"""
filepaths = []
if folder:
# comment out [ and ]...
folder = folder.replace("[", "?")
folder = folder.replace("]", "*")
folder = folder.replace("?", "[[]")
folder = folder.replace("*", "[]]")
glob_str = os.path.join(folder, "*" + extension)
else:
glob_str = "*" + extension + "*"
for filepath in glob.glob(glob_str):
if identifier:
if identifier in filepath:
filepaths.append(filepath)
else:
filepaths.append(filepath)
return filepaths | [
"def",
"glob_handler",
"(",
"extension",
",",
"folder",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"filepaths",
"=",
"[",
"]",
"if",
"folder",
":",
"# comment out [ and ]...",
"folder",
"=",
"folder",
".",
"replace",
"(",
"\"[\"",
",",
"\"?\"",... | Return a list of all files matching specified inputs.
Parameters
----------
extension : string
File extension.
folder : string (optional)
Folder to search within. Default is None (current working
directory).
identifier : string
Unique identifier. Default is None.
Returns
-------
list of strings
Full path of matching files. | [
"Return",
"a",
"list",
"of",
"all",
"files",
"matching",
"specified",
"inputs",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_path.py#L47-L81 | train | 33,781 |
wright-group/WrightTools | WrightTools/data/_channel.py | Channel.major_extent | def major_extent(self) -> complex:
"""Maximum deviation from null."""
return max((self.max() - self.null, self.null - self.min())) | python | def major_extent(self) -> complex:
"""Maximum deviation from null."""
return max((self.max() - self.null, self.null - self.min())) | [
"def",
"major_extent",
"(",
"self",
")",
"->",
"complex",
":",
"return",
"max",
"(",
"(",
"self",
".",
"max",
"(",
")",
"-",
"self",
".",
"null",
",",
"self",
".",
"null",
"-",
"self",
".",
"min",
"(",
")",
")",
")"
] | Maximum deviation from null. | [
"Maximum",
"deviation",
"from",
"null",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L82-L84 | train | 33,782 |
wright-group/WrightTools | WrightTools/data/_channel.py | Channel.minor_extent | def minor_extent(self) -> complex:
"""Minimum deviation from null."""
return min((self.max() - self.null, self.null - self.min())) | python | def minor_extent(self) -> complex:
"""Minimum deviation from null."""
return min((self.max() - self.null, self.null - self.min())) | [
"def",
"minor_extent",
"(",
"self",
")",
"->",
"complex",
":",
"return",
"min",
"(",
"(",
"self",
".",
"max",
"(",
")",
"-",
"self",
".",
"null",
",",
"self",
".",
"null",
"-",
"self",
".",
"min",
"(",
")",
")",
")"
] | Minimum deviation from null. | [
"Minimum",
"deviation",
"from",
"null",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L87-L89 | train | 33,783 |
wright-group/WrightTools | WrightTools/data/_channel.py | Channel.normalize | def normalize(self, mag=1.):
"""Normalize a Channel, set `null` to 0 and the mag to given value.
Parameters
----------
mag : float (optional)
New value of mag. Default is 1.
"""
def f(dataset, s, null, mag):
dataset[s] -= null
dataset[s] /= mag
if self.signed:
mag = self.mag() / mag
else:
mag = self.max() / mag
self.chunkwise(f, null=self.null, mag=mag)
self._null = 0 | python | def normalize(self, mag=1.):
"""Normalize a Channel, set `null` to 0 and the mag to given value.
Parameters
----------
mag : float (optional)
New value of mag. Default is 1.
"""
def f(dataset, s, null, mag):
dataset[s] -= null
dataset[s] /= mag
if self.signed:
mag = self.mag() / mag
else:
mag = self.max() / mag
self.chunkwise(f, null=self.null, mag=mag)
self._null = 0 | [
"def",
"normalize",
"(",
"self",
",",
"mag",
"=",
"1.",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
",",
"null",
",",
"mag",
")",
":",
"dataset",
"[",
"s",
"]",
"-=",
"null",
"dataset",
"[",
"s",
"]",
"/=",
"mag",
"if",
"self",
".",
"sign... | Normalize a Channel, set `null` to 0 and the mag to given value.
Parameters
----------
mag : float (optional)
New value of mag. Default is 1. | [
"Normalize",
"a",
"Channel",
"set",
"null",
"to",
"0",
"and",
"the",
"mag",
"to",
"given",
"value",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L115-L133 | train | 33,784 |
wright-group/WrightTools | WrightTools/data/_channel.py | Channel.trim | def trim(self, neighborhood, method="ztest", factor=3, replace="nan", verbose=True):
"""Remove outliers from the dataset.
Identifies outliers by comparing each point to its
neighbors using a statistical test.
Parameters
----------
neighborhood : list of integers
Size of the neighborhood in each dimension. Length of the list must
be equal to the dimensionality of the channel.
method : {'ztest'} (optional)
Statistical test used to detect outliers. Default is ztest.
ztest
Compare point deviation from neighborhood mean to neighborhood
standard deviation.
factor : number (optional)
Tolerance factor. Default is 3.
replace : {'nan', 'mean', 'exclusive_mean', number} (optional)
Behavior of outlier replacement. Default is nan.
nan
Outliers are replaced by numpy nans.
mean
Outliers are replaced by the mean of its neighborhood, including itself.
exclusive_mean
Outilers are replaced by the mean of its neighborhood, not including itself.
number
Array becomes given number.
Returns
-------
list of tuples
Indicies of trimmed outliers.
See Also
--------
clip
Remove pixels outside of a certain range.
"""
warnings.warn("trim", category=wt_exceptions.EntireDatasetInMemoryWarning)
outliers = []
means = []
ex_means = []
# find outliers
for idx in np.ndindex(self.shape):
slices = []
for i, di, size in zip(idx, neighborhood, self.shape):
start = max(0, i - di)
stop = min(size, i + di + 1)
slices.append(slice(start, stop, 1))
neighbors = self[slices]
mean = np.nanmean(neighbors)
sum_ = np.nansum(neighbors)
limit = np.nanstd(neighbors) * factor
if np.abs(self[idx] - mean) > limit:
outliers.append(idx)
means.append(mean)
# Note, "- 1" is to exclude the point itself, which is not nan, in order
# to enter this if block, as `np.abs(nan - mean)` is nan, which would
# evaluate to False
ex_means.append((sum_ - self[idx]) / (np.sum(~np.isnan(neighbors)) - 1))
# replace outliers
i = tuple(zip(*outliers))
if len(i) == 0:
if verbose:
print("No outliers found")
return []
replace = {"nan": np.nan, "mean": means, "exclusive_mean": ex_means}.get(replace, replace)
# This may someday be available in h5py directly, but seems that day is not yet.
# This is annoying because it is the only reason we hold the whole set in memory.
# KFS 2019-03-21
arr = self[:]
arr[i] = replace
self[:] = arr
# finish
if verbose:
print("%i outliers removed" % len(outliers))
return outliers | python | def trim(self, neighborhood, method="ztest", factor=3, replace="nan", verbose=True):
"""Remove outliers from the dataset.
Identifies outliers by comparing each point to its
neighbors using a statistical test.
Parameters
----------
neighborhood : list of integers
Size of the neighborhood in each dimension. Length of the list must
be equal to the dimensionality of the channel.
method : {'ztest'} (optional)
Statistical test used to detect outliers. Default is ztest.
ztest
Compare point deviation from neighborhood mean to neighborhood
standard deviation.
factor : number (optional)
Tolerance factor. Default is 3.
replace : {'nan', 'mean', 'exclusive_mean', number} (optional)
Behavior of outlier replacement. Default is nan.
nan
Outliers are replaced by numpy nans.
mean
Outliers are replaced by the mean of its neighborhood, including itself.
exclusive_mean
Outilers are replaced by the mean of its neighborhood, not including itself.
number
Array becomes given number.
Returns
-------
list of tuples
Indicies of trimmed outliers.
See Also
--------
clip
Remove pixels outside of a certain range.
"""
warnings.warn("trim", category=wt_exceptions.EntireDatasetInMemoryWarning)
outliers = []
means = []
ex_means = []
# find outliers
for idx in np.ndindex(self.shape):
slices = []
for i, di, size in zip(idx, neighborhood, self.shape):
start = max(0, i - di)
stop = min(size, i + di + 1)
slices.append(slice(start, stop, 1))
neighbors = self[slices]
mean = np.nanmean(neighbors)
sum_ = np.nansum(neighbors)
limit = np.nanstd(neighbors) * factor
if np.abs(self[idx] - mean) > limit:
outliers.append(idx)
means.append(mean)
# Note, "- 1" is to exclude the point itself, which is not nan, in order
# to enter this if block, as `np.abs(nan - mean)` is nan, which would
# evaluate to False
ex_means.append((sum_ - self[idx]) / (np.sum(~np.isnan(neighbors)) - 1))
# replace outliers
i = tuple(zip(*outliers))
if len(i) == 0:
if verbose:
print("No outliers found")
return []
replace = {"nan": np.nan, "mean": means, "exclusive_mean": ex_means}.get(replace, replace)
# This may someday be available in h5py directly, but seems that day is not yet.
# This is annoying because it is the only reason we hold the whole set in memory.
# KFS 2019-03-21
arr = self[:]
arr[i] = replace
self[:] = arr
# finish
if verbose:
print("%i outliers removed" % len(outliers))
return outliers | [
"def",
"trim",
"(",
"self",
",",
"neighborhood",
",",
"method",
"=",
"\"ztest\"",
",",
"factor",
"=",
"3",
",",
"replace",
"=",
"\"nan\"",
",",
"verbose",
"=",
"True",
")",
":",
"warnings",
".",
"warn",
"(",
"\"trim\"",
",",
"category",
"=",
"wt_except... | Remove outliers from the dataset.
Identifies outliers by comparing each point to its
neighbors using a statistical test.
Parameters
----------
neighborhood : list of integers
Size of the neighborhood in each dimension. Length of the list must
be equal to the dimensionality of the channel.
method : {'ztest'} (optional)
Statistical test used to detect outliers. Default is ztest.
ztest
Compare point deviation from neighborhood mean to neighborhood
standard deviation.
factor : number (optional)
Tolerance factor. Default is 3.
replace : {'nan', 'mean', 'exclusive_mean', number} (optional)
Behavior of outlier replacement. Default is nan.
nan
Outliers are replaced by numpy nans.
mean
Outliers are replaced by the mean of its neighborhood, including itself.
exclusive_mean
Outilers are replaced by the mean of its neighborhood, not including itself.
number
Array becomes given number.
Returns
-------
list of tuples
Indicies of trimmed outliers.
See Also
--------
clip
Remove pixels outside of a certain range. | [
"Remove",
"outliers",
"from",
"the",
"dataset",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_channel.py#L135-L223 | train | 33,785 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.units | def units(self, value):
"""Set units."""
if value is None:
if "units" in self.attrs.keys():
self.attrs.pop("units")
else:
try:
self.attrs["units"] = value
except AttributeError:
self.attrs["units"] = value | python | def units(self, value):
"""Set units."""
if value is None:
if "units" in self.attrs.keys():
self.attrs.pop("units")
else:
try:
self.attrs["units"] = value
except AttributeError:
self.attrs["units"] = value | [
"def",
"units",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"if",
"\"units\"",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"self",
".",
"attrs",
".",
"pop",
"(",
"\"units\"",
")",
"else",
":",
"try",
":",
... | Set units. | [
"Set",
"units",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L179-L188 | train | 33,786 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.argmax | def argmax(self):
"""Index of the maximum, ignorning nans."""
if "argmax" not in self.attrs.keys():
def f(dataset, s):
arr = dataset[s]
try:
amin = np.nanargmax(arr)
except ValueError:
amin = 0
idx = np.unravel_index(amin, arr.shape)
val = arr[idx]
return (tuple(i + (ss.start if ss.start else 0) for i, ss in zip(idx, s)), val)
chunk_res = self.chunkwise(f)
idxs = [i[0] for i in chunk_res.values()]
vals = [i[1] for i in chunk_res.values()]
self.attrs["argmax"] = idxs[np.nanargmax(vals)]
return tuple(self.attrs["argmax"]) | python | def argmax(self):
"""Index of the maximum, ignorning nans."""
if "argmax" not in self.attrs.keys():
def f(dataset, s):
arr = dataset[s]
try:
amin = np.nanargmax(arr)
except ValueError:
amin = 0
idx = np.unravel_index(amin, arr.shape)
val = arr[idx]
return (tuple(i + (ss.start if ss.start else 0) for i, ss in zip(idx, s)), val)
chunk_res = self.chunkwise(f)
idxs = [i[0] for i in chunk_res.values()]
vals = [i[1] for i in chunk_res.values()]
self.attrs["argmax"] = idxs[np.nanargmax(vals)]
return tuple(self.attrs["argmax"]) | [
"def",
"argmax",
"(",
"self",
")",
":",
"if",
"\"argmax\"",
"not",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
")",
":",
"arr",
"=",
"dataset",
"[",
"s",
"]",
"try",
":",
"amin",
"=",
"np",
".... | Index of the maximum, ignorning nans. | [
"Index",
"of",
"the",
"maximum",
"ignorning",
"nans",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L190-L208 | train | 33,787 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.chunkwise | def chunkwise(self, func, *args, **kwargs):
"""Execute a function for each chunk in the dataset.
Order of excecution is not guaranteed.
Parameters
----------
func : function
Function to execute. First two arguments must be dataset,
slices.
args (optional)
Additional (unchanging) arguments passed to func.
kwargs (optional)
Additional (unchanging) keyword arguments passed to func.
Returns
-------
collections OrderedDict
Dictionary of index: function output. Index is to lowest corner
of each chunk.
"""
out = collections.OrderedDict()
for s in self.slices():
key = tuple(sss.start for sss in s)
out[key] = func(self, s, *args, **kwargs)
self._clear_array_attributes_cache()
return out | python | def chunkwise(self, func, *args, **kwargs):
"""Execute a function for each chunk in the dataset.
Order of excecution is not guaranteed.
Parameters
----------
func : function
Function to execute. First two arguments must be dataset,
slices.
args (optional)
Additional (unchanging) arguments passed to func.
kwargs (optional)
Additional (unchanging) keyword arguments passed to func.
Returns
-------
collections OrderedDict
Dictionary of index: function output. Index is to lowest corner
of each chunk.
"""
out = collections.OrderedDict()
for s in self.slices():
key = tuple(sss.start for sss in s)
out[key] = func(self, s, *args, **kwargs)
self._clear_array_attributes_cache()
return out | [
"def",
"chunkwise",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"s",
"in",
"self",
".",
"slices",
"(",
")",
":",
"key",
"=",
"tuple",
"(",
"sss",
... | Execute a function for each chunk in the dataset.
Order of excecution is not guaranteed.
Parameters
----------
func : function
Function to execute. First two arguments must be dataset,
slices.
args (optional)
Additional (unchanging) arguments passed to func.
kwargs (optional)
Additional (unchanging) keyword arguments passed to func.
Returns
-------
collections OrderedDict
Dictionary of index: function output. Index is to lowest corner
of each chunk. | [
"Execute",
"a",
"function",
"for",
"each",
"chunk",
"in",
"the",
"dataset",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L230-L256 | train | 33,788 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.clip | def clip(self, min=None, max=None, replace=np.nan):
"""Clip values outside of a defined range.
Parameters
----------
min : number (optional)
New channel minimum. Default is None.
max : number (optional)
New channel maximum. Default is None.
replace : number or 'value' (optional)
Replace behavior. Default is nan.
"""
if max is None:
max = self.max()
if min is None:
min = self.min()
def f(dataset, s, min, max, replace):
if hasattr(min, "shape"):
min = min[wt_kit.valid_index(s, min.shape)]
if hasattr(max, "shape"):
max = max[wt_kit.valid_index(s, max.shape)]
if hasattr(replace, "shape"):
replace = replace[wt_kit.valid_index(s, replace.shape)]
arr = dataset[s]
if replace == "value":
dataset[s] = np.clip(arr, min, max)
else:
arr[arr < min] = replace
arr[arr > max] = replace
dataset[s] = arr
self.chunkwise(f, min=min, max=max, replace=replace) | python | def clip(self, min=None, max=None, replace=np.nan):
"""Clip values outside of a defined range.
Parameters
----------
min : number (optional)
New channel minimum. Default is None.
max : number (optional)
New channel maximum. Default is None.
replace : number or 'value' (optional)
Replace behavior. Default is nan.
"""
if max is None:
max = self.max()
if min is None:
min = self.min()
def f(dataset, s, min, max, replace):
if hasattr(min, "shape"):
min = min[wt_kit.valid_index(s, min.shape)]
if hasattr(max, "shape"):
max = max[wt_kit.valid_index(s, max.shape)]
if hasattr(replace, "shape"):
replace = replace[wt_kit.valid_index(s, replace.shape)]
arr = dataset[s]
if replace == "value":
dataset[s] = np.clip(arr, min, max)
else:
arr[arr < min] = replace
arr[arr > max] = replace
dataset[s] = arr
self.chunkwise(f, min=min, max=max, replace=replace) | [
"def",
"clip",
"(",
"self",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"replace",
"=",
"np",
".",
"nan",
")",
":",
"if",
"max",
"is",
"None",
":",
"max",
"=",
"self",
".",
"max",
"(",
")",
"if",
"min",
"is",
"None",
":",
"min",
... | Clip values outside of a defined range.
Parameters
----------
min : number (optional)
New channel minimum. Default is None.
max : number (optional)
New channel maximum. Default is None.
replace : number or 'value' (optional)
Replace behavior. Default is nan. | [
"Clip",
"values",
"outside",
"of",
"a",
"defined",
"range",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L258-L290 | train | 33,789 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.convert | def convert(self, destination_units):
"""Convert units.
Parameters
----------
destination_units : string (optional)
Units to convert into.
"""
if not wt_units.is_valid_conversion(self.units, destination_units):
kind = wt_units.kind(self.units)
valid = list(wt_units.dicts[kind].keys())
raise wt_exceptions.UnitsError(valid, destination_units)
if self.units is None:
return
def f(dataset, s, destination_units):
dataset[s] = wt_units.converter(dataset[s], dataset.units, destination_units)
self.chunkwise(f, destination_units=destination_units)
self.units = destination_units | python | def convert(self, destination_units):
"""Convert units.
Parameters
----------
destination_units : string (optional)
Units to convert into.
"""
if not wt_units.is_valid_conversion(self.units, destination_units):
kind = wt_units.kind(self.units)
valid = list(wt_units.dicts[kind].keys())
raise wt_exceptions.UnitsError(valid, destination_units)
if self.units is None:
return
def f(dataset, s, destination_units):
dataset[s] = wt_units.converter(dataset[s], dataset.units, destination_units)
self.chunkwise(f, destination_units=destination_units)
self.units = destination_units | [
"def",
"convert",
"(",
"self",
",",
"destination_units",
")",
":",
"if",
"not",
"wt_units",
".",
"is_valid_conversion",
"(",
"self",
".",
"units",
",",
"destination_units",
")",
":",
"kind",
"=",
"wt_units",
".",
"kind",
"(",
"self",
".",
"units",
")",
"... | Convert units.
Parameters
----------
destination_units : string (optional)
Units to convert into. | [
"Convert",
"units",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L292-L311 | train | 33,790 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.log | def log(self, base=np.e, floor=None):
"""Take the log of the entire dataset.
Parameters
----------
base : number (optional)
Base of log. Default is e.
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, base, floor):
arr = dataset[s]
arr = np.log(arr)
if base != np.e:
arr /= np.log(base)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, base=base, floor=floor) | python | def log(self, base=np.e, floor=None):
"""Take the log of the entire dataset.
Parameters
----------
base : number (optional)
Base of log. Default is e.
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, base, floor):
arr = dataset[s]
arr = np.log(arr)
if base != np.e:
arr /= np.log(base)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, base=base, floor=floor) | [
"def",
"log",
"(",
"self",
",",
"base",
"=",
"np",
".",
"e",
",",
"floor",
"=",
"None",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
",",
"base",
",",
"floor",
")",
":",
"arr",
"=",
"dataset",
"[",
"s",
"]",
"arr",
"=",
"np",
".",
"log",... | Take the log of the entire dataset.
Parameters
----------
base : number (optional)
Base of log. Default is e.
floor : number (optional)
Clip values below floor after log. Default is None. | [
"Take",
"the",
"log",
"of",
"the",
"entire",
"dataset",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L313-L333 | train | 33,791 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.log10 | def log10(self, floor=None):
"""Take the log base 10 of the entire dataset.
Parameters
----------
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, floor):
arr = dataset[s]
arr = np.log10(arr)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, floor=floor) | python | def log10(self, floor=None):
"""Take the log base 10 of the entire dataset.
Parameters
----------
floor : number (optional)
Clip values below floor after log. Default is None.
"""
def f(dataset, s, floor):
arr = dataset[s]
arr = np.log10(arr)
if floor is not None:
arr[arr < floor] = floor
dataset[s] = arr
self.chunkwise(f, floor=floor) | [
"def",
"log10",
"(",
"self",
",",
"floor",
"=",
"None",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
",",
"floor",
")",
":",
"arr",
"=",
"dataset",
"[",
"s",
"]",
"arr",
"=",
"np",
".",
"log10",
"(",
"arr",
")",
"if",
"floor",
"is",
"not",... | Take the log base 10 of the entire dataset.
Parameters
----------
floor : number (optional)
Clip values below floor after log. Default is None. | [
"Take",
"the",
"log",
"base",
"10",
"of",
"the",
"entire",
"dataset",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L335-L351 | train | 33,792 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.max | def max(self):
"""Maximum, ignorning nans."""
if "max" not in self.attrs.keys():
def f(dataset, s):
return np.nanmax(dataset[s])
self.attrs["max"] = np.nanmax(list(self.chunkwise(f).values()))
return self.attrs["max"] | python | def max(self):
"""Maximum, ignorning nans."""
if "max" not in self.attrs.keys():
def f(dataset, s):
return np.nanmax(dataset[s])
self.attrs["max"] = np.nanmax(list(self.chunkwise(f).values()))
return self.attrs["max"] | [
"def",
"max",
"(",
"self",
")",
":",
"if",
"\"max\"",
"not",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
")",
":",
"return",
"np",
".",
"nanmax",
"(",
"dataset",
"[",
"s",
"]",
")",
"self",
".... | Maximum, ignorning nans. | [
"Maximum",
"ignorning",
"nans",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L371-L379 | train | 33,793 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.min | def min(self):
"""Minimum, ignoring nans."""
if "min" not in self.attrs.keys():
def f(dataset, s):
return np.nanmin(dataset[s])
self.attrs["min"] = np.nanmin(list(self.chunkwise(f).values()))
return self.attrs["min"] | python | def min(self):
"""Minimum, ignoring nans."""
if "min" not in self.attrs.keys():
def f(dataset, s):
return np.nanmin(dataset[s])
self.attrs["min"] = np.nanmin(list(self.chunkwise(f).values()))
return self.attrs["min"] | [
"def",
"min",
"(",
"self",
")",
":",
"if",
"\"min\"",
"not",
"in",
"self",
".",
"attrs",
".",
"keys",
"(",
")",
":",
"def",
"f",
"(",
"dataset",
",",
"s",
")",
":",
"return",
"np",
".",
"nanmin",
"(",
"dataset",
"[",
"s",
"]",
")",
"self",
".... | Minimum, ignoring nans. | [
"Minimum",
"ignoring",
"nans",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L381-L389 | train | 33,794 |
wright-group/WrightTools | WrightTools/_dataset.py | Dataset.slices | def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
for idx in np.ndindex(ceilings): # could also use itertools.product
out = []
for i, c, s in zip(idx, self.chunks, self.shape):
start = i * c
stop = min(start + c, s + 1)
out.append(slice(start, stop, 1))
yield tuple(out) | python | def slices(self):
"""Returns a generator yielding tuple of slice objects.
Order is not guaranteed.
"""
if self.chunks is None:
yield tuple(slice(None, s) for s in self.shape)
else:
ceilings = tuple(-(-s // c) for s, c in zip(self.shape, self.chunks))
for idx in np.ndindex(ceilings): # could also use itertools.product
out = []
for i, c, s in zip(idx, self.chunks, self.shape):
start = i * c
stop = min(start + c, s + 1)
out.append(slice(start, stop, 1))
yield tuple(out) | [
"def",
"slices",
"(",
"self",
")",
":",
"if",
"self",
".",
"chunks",
"is",
"None",
":",
"yield",
"tuple",
"(",
"slice",
"(",
"None",
",",
"s",
")",
"for",
"s",
"in",
"self",
".",
"shape",
")",
"else",
":",
"ceilings",
"=",
"tuple",
"(",
"-",
"(... | Returns a generator yielding tuple of slice objects.
Order is not guaranteed. | [
"Returns",
"a",
"generator",
"yielding",
"tuple",
"of",
"slice",
"objects",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_dataset.py#L391-L406 | train | 33,795 |
wright-group/WrightTools | WrightTools/data/_constant.py | Constant.label | def label(self) -> str:
"""A latex formatted label representing constant expression and united value."""
label = self.expression.replace("_", "\\;")
if self.units_kind:
symbol = wt_units.get_symbol(self.units)
for v in self.variables:
vl = "%s_{%s}" % (symbol, v.label)
vl = vl.replace("_{}", "") # label can be empty, no empty subscripts
label = label.replace(v.natural_name, vl)
val = (
round(self.value, self.round_spec)
if self.round_spec is not None
else self.value
)
label += r"\,=\,{}".format(format(val, self.format_spec))
if self.units_kind:
units_dictionary = getattr(wt_units, self.units_kind)
label += r"\,"
label += units_dictionary[self.units][2]
label = r"$\mathsf{%s}$" % label
return label | python | def label(self) -> str:
"""A latex formatted label representing constant expression and united value."""
label = self.expression.replace("_", "\\;")
if self.units_kind:
symbol = wt_units.get_symbol(self.units)
for v in self.variables:
vl = "%s_{%s}" % (symbol, v.label)
vl = vl.replace("_{}", "") # label can be empty, no empty subscripts
label = label.replace(v.natural_name, vl)
val = (
round(self.value, self.round_spec)
if self.round_spec is not None
else self.value
)
label += r"\,=\,{}".format(format(val, self.format_spec))
if self.units_kind:
units_dictionary = getattr(wt_units, self.units_kind)
label += r"\,"
label += units_dictionary[self.units][2]
label = r"$\mathsf{%s}$" % label
return label | [
"def",
"label",
"(",
"self",
")",
"->",
"str",
":",
"label",
"=",
"self",
".",
"expression",
".",
"replace",
"(",
"\"_\"",
",",
"\"\\\\;\"",
")",
"if",
"self",
".",
"units_kind",
":",
"symbol",
"=",
"wt_units",
".",
"get_symbol",
"(",
"self",
".",
"u... | A latex formatted label representing constant expression and united value. | [
"A",
"latex",
"formatted",
"label",
"representing",
"constant",
"expression",
"and",
"united",
"value",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_constant.py#L61-L81 | train | 33,796 |
wright-group/WrightTools | WrightTools/collection/_directory.py | from_directory | def from_directory(filepath, from_methods, *, name=None, parent=None, verbose=True):
"""Create a WrightTools Collection from a directory of source files.
Parameters
----------
filepath: path-like
Path to the directory on the file system
from_methods: dict<str, callable>
Dictionary which maps patterns (using Unix-like glob wildcard patterns)
to functions which take a filepath, plus the keyword arguments
['name', 'parent', and 'verbose'].
(e.g. most from_<kind> methods within WrightTools)
The value can be `None` which results in that item being ignored.
The *first* matching pattern encountered will be used.
Therefore, if multiple patterns will match the same file, use and `OrderedDict`.
Patterns are matched on the file name level, not using the full path.
Keyword Arguments
-----------------
name: str
Name to use for the root data object. Default is the directory name.
parent: Collection
Parent collection to insert the directory structure into. Default is a new
collection in temp file.
verbose: bool
Print information as objects are created. Passed to the functions.
Examples
--------
>>> from_dict = {'*.data':wt.data.from_PyCMDS,
... '*.csv':wt.collections.from_Cary,
... 'unused':None,
... }
>>> col = wt.collection.from_directory('path/to/folder', from_dict)
"""
filepath = pathlib.Path(filepath).resolve()
if name is None:
name = filepath.name
if verbose:
print("Creating Collection:", name)
root = Collection(name=name, parent=parent)
q = queue.Queue()
for i in filepath.iterdir():
q.put((filepath, i.name, root))
while not q.empty():
path, fname, parent = q.get()
for pattern, func in from_methods.items():
if fnmatch.fnmatch(fname, pattern):
if func is not None:
func(
path / fname,
name=os.path.splitext(fname)[0],
parent=parent,
verbose=verbose,
)
break
else:
if (path / fname).is_dir():
if verbose:
print("Creating Collection at", pathlib.PurePosixPath(parent.name) / fname)
col = parent.create_collection(name=fname)
for i in (path / fname).iterdir():
q.put((path / fname, i.name, col))
return root | python | def from_directory(filepath, from_methods, *, name=None, parent=None, verbose=True):
"""Create a WrightTools Collection from a directory of source files.
Parameters
----------
filepath: path-like
Path to the directory on the file system
from_methods: dict<str, callable>
Dictionary which maps patterns (using Unix-like glob wildcard patterns)
to functions which take a filepath, plus the keyword arguments
['name', 'parent', and 'verbose'].
(e.g. most from_<kind> methods within WrightTools)
The value can be `None` which results in that item being ignored.
The *first* matching pattern encountered will be used.
Therefore, if multiple patterns will match the same file, use and `OrderedDict`.
Patterns are matched on the file name level, not using the full path.
Keyword Arguments
-----------------
name: str
Name to use for the root data object. Default is the directory name.
parent: Collection
Parent collection to insert the directory structure into. Default is a new
collection in temp file.
verbose: bool
Print information as objects are created. Passed to the functions.
Examples
--------
>>> from_dict = {'*.data':wt.data.from_PyCMDS,
... '*.csv':wt.collections.from_Cary,
... 'unused':None,
... }
>>> col = wt.collection.from_directory('path/to/folder', from_dict)
"""
filepath = pathlib.Path(filepath).resolve()
if name is None:
name = filepath.name
if verbose:
print("Creating Collection:", name)
root = Collection(name=name, parent=parent)
q = queue.Queue()
for i in filepath.iterdir():
q.put((filepath, i.name, root))
while not q.empty():
path, fname, parent = q.get()
for pattern, func in from_methods.items():
if fnmatch.fnmatch(fname, pattern):
if func is not None:
func(
path / fname,
name=os.path.splitext(fname)[0],
parent=parent,
verbose=verbose,
)
break
else:
if (path / fname).is_dir():
if verbose:
print("Creating Collection at", pathlib.PurePosixPath(parent.name) / fname)
col = parent.create_collection(name=fname)
for i in (path / fname).iterdir():
q.put((path / fname, i.name, col))
return root | [
"def",
"from_directory",
"(",
"filepath",
",",
"from_methods",
",",
"*",
",",
"name",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"filepath",
"=",
"pathlib",
".",
"Path",
"(",
"filepath",
")",
".",
"resolve",
"(",
... | Create a WrightTools Collection from a directory of source files.
Parameters
----------
filepath: path-like
Path to the directory on the file system
from_methods: dict<str, callable>
Dictionary which maps patterns (using Unix-like glob wildcard patterns)
to functions which take a filepath, plus the keyword arguments
['name', 'parent', and 'verbose'].
(e.g. most from_<kind> methods within WrightTools)
The value can be `None` which results in that item being ignored.
The *first* matching pattern encountered will be used.
Therefore, if multiple patterns will match the same file, use and `OrderedDict`.
Patterns are matched on the file name level, not using the full path.
Keyword Arguments
-----------------
name: str
Name to use for the root data object. Default is the directory name.
parent: Collection
Parent collection to insert the directory structure into. Default is a new
collection in temp file.
verbose: bool
Print information as objects are created. Passed to the functions.
Examples
--------
>>> from_dict = {'*.data':wt.data.from_PyCMDS,
... '*.csv':wt.collections.from_Cary,
... 'unused':None,
... }
>>> col = wt.collection.from_directory('path/to/folder', from_dict) | [
"Create",
"a",
"WrightTools",
"Collection",
"from",
"a",
"directory",
"of",
"source",
"files",
"."
] | 80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb | https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/collection/_directory.py#L24-L92 | train | 33,797 |
thombashi/allpairspy | examples/example2.2.py | is_valid_combination | def is_valid_combination(values, names):
dictionary = dict(zip(names, values))
"""
Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
rules = [
# Brand Y does not support Windows 98
# Brand X does not work with XP
# Contractors are billed in 30 min increments
lambda d: "98" == d["os"] and "Brand Y" == d["brand"],
lambda d: "XP" == d["os"] and "Brand X" == d["brand"],
lambda d: "Contr." == d["employee"] and d["increment"] < 30,
]
for rule in rules:
try:
if rule(dictionary):
return False
except KeyError:
pass
return True | python | def is_valid_combination(values, names):
dictionary = dict(zip(names, values))
"""
Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
rules = [
# Brand Y does not support Windows 98
# Brand X does not work with XP
# Contractors are billed in 30 min increments
lambda d: "98" == d["os"] and "Brand Y" == d["brand"],
lambda d: "XP" == d["os"] and "Brand X" == d["brand"],
lambda d: "Contr." == d["employee"] and d["increment"] < 30,
]
for rule in rules:
try:
if rule(dictionary):
return False
except KeyError:
pass
return True | [
"def",
"is_valid_combination",
"(",
"values",
",",
"names",
")",
":",
"dictionary",
"=",
"dict",
"(",
"zip",
"(",
"names",
",",
"values",
")",
")",
"rules",
"=",
"[",
"# Brand Y does not support Windows 98",
"# Brand X does not work with XP",
"# Contractors are billed... | Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it. | [
"Should",
"return",
"True",
"if",
"combination",
"is",
"valid",
"and",
"False",
"otherwise",
"."
] | 9dd256d7ccdc1348c5807d4a814294d9c5192293 | https://github.com/thombashi/allpairspy/blob/9dd256d7ccdc1348c5807d4a814294d9c5192293/examples/example2.2.py#L14-L42 | train | 33,798 |
thombashi/allpairspy | examples/example2.1.py | is_valid_combination | def is_valid_combination(row):
"""
This is a filtering function. Filtering functions should return True
if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if n > 1:
# Brand Y does not support Windows 98
if "98" == row[1] and "Brand Y" == row[0]:
return False
# Brand X does not work with XP
if "XP" == row[1] and "Brand X" == row[0]:
return False
if n > 4:
# Contractors are billed in 30 min increments
if "Contr." == row[3] and row[4] < 30:
return False
return True | python | def is_valid_combination(row):
"""
This is a filtering function. Filtering functions should return True
if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
n = len(row)
if n > 1:
# Brand Y does not support Windows 98
if "98" == row[1] and "Brand Y" == row[0]:
return False
# Brand X does not work with XP
if "XP" == row[1] and "Brand X" == row[0]:
return False
if n > 4:
# Contractors are billed in 30 min increments
if "Contr." == row[3] and row[4] < 30:
return False
return True | [
"def",
"is_valid_combination",
"(",
"row",
")",
":",
"n",
"=",
"len",
"(",
"row",
")",
"if",
"n",
">",
"1",
":",
"# Brand Y does not support Windows 98",
"if",
"\"98\"",
"==",
"row",
"[",
"1",
"]",
"and",
"\"Brand Y\"",
"==",
"row",
"[",
"0",
"]",
":",... | This is a filtering function. Filtering functions should return True
if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it. | [
"This",
"is",
"a",
"filtering",
"function",
".",
"Filtering",
"functions",
"should",
"return",
"True",
"if",
"combination",
"is",
"valid",
"and",
"False",
"otherwise",
"."
] | 9dd256d7ccdc1348c5807d4a814294d9c5192293 | https://github.com/thombashi/allpairspy/blob/9dd256d7ccdc1348c5807d4a814294d9c5192293/examples/example2.1.py#L13-L39 | train | 33,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.