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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mathandy/svgpathtools | svgpathtools/path.py | transform | def transform(curve, tf):
"""Transforms the curve by the homogeneous transformation matrix tf"""
def to_point(p):
return np.array([[p.real], [p.imag], [1.0]])
def to_vector(z):
return np.array([[z.real], [z.imag], [0.0]])
def to_complex(v):
return v.item(0) + 1j * v.item(1)
if isinstance(curve, Path):
return Path(*[transform(segment, tf) for segment in curve])
elif is_bezier_segment(curve):
return bpoints2bezier([to_complex(tf.dot(to_point(p)))
for p in curve.bpoints()])
elif isinstance(curve, Arc):
new_start = to_complex(tf.dot(to_point(curve.start)))
new_end = to_complex(tf.dot(to_point(curve.end)))
new_radius = to_complex(tf.dot(to_vector(curve.radius)))
return Arc(new_start, radius=new_radius, rotation=curve.rotation,
large_arc=curve.large_arc, sweep=curve.sweep, end=new_end)
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.") | python | def transform(curve, tf):
"""Transforms the curve by the homogeneous transformation matrix tf"""
def to_point(p):
return np.array([[p.real], [p.imag], [1.0]])
def to_vector(z):
return np.array([[z.real], [z.imag], [0.0]])
def to_complex(v):
return v.item(0) + 1j * v.item(1)
if isinstance(curve, Path):
return Path(*[transform(segment, tf) for segment in curve])
elif is_bezier_segment(curve):
return bpoints2bezier([to_complex(tf.dot(to_point(p)))
for p in curve.bpoints()])
elif isinstance(curve, Arc):
new_start = to_complex(tf.dot(to_point(curve.start)))
new_end = to_complex(tf.dot(to_point(curve.end)))
new_radius = to_complex(tf.dot(to_vector(curve.radius)))
return Arc(new_start, radius=new_radius, rotation=curve.rotation,
large_arc=curve.large_arc, sweep=curve.sweep, end=new_end)
else:
raise TypeError("Input `curve` should be a Path, Line, "
"QuadraticBezier, CubicBezier, or Arc object.") | [
"def",
"transform",
"(",
"curve",
",",
"tf",
")",
":",
"def",
"to_point",
"(",
"p",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"p",
".",
"real",
"]",
",",
"[",
"p",
".",
"imag",
"]",
",",
"[",
"1.0",
"]",
"]",
")",
"def",
"to_ve... | Transforms the curve by the homogeneous transformation matrix tf | [
"Transforms",
"the",
"curve",
"by",
"the",
"homogeneous",
"transformation",
"matrix",
"tf"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L258-L282 | train | 200,000 |
mathandy/svgpathtools | svgpathtools/path.py | bezier_unit_tangent | def bezier_unit_tangent(seg, t):
"""Returns the unit tangent of the segment at t.
Notes
-----
If you receive a RuntimeWarning, try the following:
>>> import numpy
>>> old_numpy_error_settings = numpy.seterr(invalid='raise')
This can be undone with:
>>> numpy.seterr(**old_numpy_error_settings)
"""
assert 0 <= t <= 1
dseg = seg.derivative(t)
# Note: dseg might be numpy value, use np.seterr(invalid='raise')
try:
unit_tangent = dseg/abs(dseg)
except (ZeroDivisionError, FloatingPointError):
# This may be a removable singularity, if so we just need to compute
# the limit.
# Note: limit{{dseg / abs(dseg)} = sqrt(limit{dseg**2 / abs(dseg)**2})
dseg_poly = seg.poly().deriv()
dseg_abs_squared_poly = (real(dseg_poly) ** 2 +
imag(dseg_poly) ** 2)
try:
unit_tangent = csqrt(rational_limit(dseg_poly**2,
dseg_abs_squared_poly, t))
except ValueError:
bef = seg.poly().deriv()(t - 1e-4)
aft = seg.poly().deriv()(t + 1e-4)
mes = ("Unit tangent appears to not be well-defined at "
"t = {}, \n".format(t) +
"seg.poly().deriv()(t - 1e-4) = {}\n".format(bef) +
"seg.poly().deriv()(t + 1e-4) = {}".format(aft))
raise ValueError(mes)
return unit_tangent | python | def bezier_unit_tangent(seg, t):
"""Returns the unit tangent of the segment at t.
Notes
-----
If you receive a RuntimeWarning, try the following:
>>> import numpy
>>> old_numpy_error_settings = numpy.seterr(invalid='raise')
This can be undone with:
>>> numpy.seterr(**old_numpy_error_settings)
"""
assert 0 <= t <= 1
dseg = seg.derivative(t)
# Note: dseg might be numpy value, use np.seterr(invalid='raise')
try:
unit_tangent = dseg/abs(dseg)
except (ZeroDivisionError, FloatingPointError):
# This may be a removable singularity, if so we just need to compute
# the limit.
# Note: limit{{dseg / abs(dseg)} = sqrt(limit{dseg**2 / abs(dseg)**2})
dseg_poly = seg.poly().deriv()
dseg_abs_squared_poly = (real(dseg_poly) ** 2 +
imag(dseg_poly) ** 2)
try:
unit_tangent = csqrt(rational_limit(dseg_poly**2,
dseg_abs_squared_poly, t))
except ValueError:
bef = seg.poly().deriv()(t - 1e-4)
aft = seg.poly().deriv()(t + 1e-4)
mes = ("Unit tangent appears to not be well-defined at "
"t = {}, \n".format(t) +
"seg.poly().deriv()(t - 1e-4) = {}\n".format(bef) +
"seg.poly().deriv()(t + 1e-4) = {}".format(aft))
raise ValueError(mes)
return unit_tangent | [
"def",
"bezier_unit_tangent",
"(",
"seg",
",",
"t",
")",
":",
"assert",
"0",
"<=",
"t",
"<=",
"1",
"dseg",
"=",
"seg",
".",
"derivative",
"(",
"t",
")",
"# Note: dseg might be numpy value, use np.seterr(invalid='raise')",
"try",
":",
"unit_tangent",
"=",
"dseg",... | Returns the unit tangent of the segment at t.
Notes
-----
If you receive a RuntimeWarning, try the following:
>>> import numpy
>>> old_numpy_error_settings = numpy.seterr(invalid='raise')
This can be undone with:
>>> numpy.seterr(**old_numpy_error_settings) | [
"Returns",
"the",
"unit",
"tangent",
"of",
"the",
"segment",
"at",
"t",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L285-L320 | train | 200,001 |
mathandy/svgpathtools | svgpathtools/path.py | segment_curvature | def segment_curvature(self, t, use_inf=False):
"""returns the curvature of the segment at t.
Notes
-----
If you receive a RuntimeWarning, run command
>>> old = np.seterr(invalid='raise')
This can be undone with
>>> np.seterr(**old)
"""
dz = self.derivative(t)
ddz = self.derivative(t, n=2)
dx, dy = dz.real, dz.imag
ddx, ddy = ddz.real, ddz.imag
old_np_seterr = np.seterr(invalid='raise')
try:
kappa = abs(dx*ddy - dy*ddx)/sqrt(dx*dx + dy*dy)**3
except (ZeroDivisionError, FloatingPointError):
# tangent vector is zero at t, use polytools to find limit
p = self.poly()
dp = p.deriv()
ddp = dp.deriv()
dx, dy = real(dp), imag(dp)
ddx, ddy = real(ddp), imag(ddp)
f2 = (dx*ddy - dy*ddx)**2
g2 = (dx*dx + dy*dy)**3
lim2 = rational_limit(f2, g2, t)
if lim2 < 0: # impossible, must be numerical error
return 0
kappa = sqrt(lim2)
finally:
np.seterr(**old_np_seterr)
return kappa | python | def segment_curvature(self, t, use_inf=False):
"""returns the curvature of the segment at t.
Notes
-----
If you receive a RuntimeWarning, run command
>>> old = np.seterr(invalid='raise')
This can be undone with
>>> np.seterr(**old)
"""
dz = self.derivative(t)
ddz = self.derivative(t, n=2)
dx, dy = dz.real, dz.imag
ddx, ddy = ddz.real, ddz.imag
old_np_seterr = np.seterr(invalid='raise')
try:
kappa = abs(dx*ddy - dy*ddx)/sqrt(dx*dx + dy*dy)**3
except (ZeroDivisionError, FloatingPointError):
# tangent vector is zero at t, use polytools to find limit
p = self.poly()
dp = p.deriv()
ddp = dp.deriv()
dx, dy = real(dp), imag(dp)
ddx, ddy = real(ddp), imag(ddp)
f2 = (dx*ddy - dy*ddx)**2
g2 = (dx*dx + dy*dy)**3
lim2 = rational_limit(f2, g2, t)
if lim2 < 0: # impossible, must be numerical error
return 0
kappa = sqrt(lim2)
finally:
np.seterr(**old_np_seterr)
return kappa | [
"def",
"segment_curvature",
"(",
"self",
",",
"t",
",",
"use_inf",
"=",
"False",
")",
":",
"dz",
"=",
"self",
".",
"derivative",
"(",
"t",
")",
"ddz",
"=",
"self",
".",
"derivative",
"(",
"t",
",",
"n",
"=",
"2",
")",
"dx",
",",
"dy",
"=",
"dz"... | returns the curvature of the segment at t.
Notes
-----
If you receive a RuntimeWarning, run command
>>> old = np.seterr(invalid='raise')
This can be undone with
>>> np.seterr(**old) | [
"returns",
"the",
"curvature",
"of",
"the",
"segment",
"at",
"t",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L323-L356 | train | 200,002 |
mathandy/svgpathtools | svgpathtools/path.py | segment_length | def segment_length(curve, start, end, start_point, end_point,
error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0):
"""Recursively approximates the length by straight lines"""
mid = (start + end)/2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = abs(end_point - mid_point)
length2 = first_half + second_half
if (length2 - length > error) or (depth < min_depth):
# Calculate the length of each segment:
depth += 1
return (segment_length(curve, start, mid, start_point, mid_point,
error, min_depth, depth) +
segment_length(curve, mid, end, mid_point, end_point,
error, min_depth, depth))
# This is accurate enough.
return length2 | python | def segment_length(curve, start, end, start_point, end_point,
error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0):
"""Recursively approximates the length by straight lines"""
mid = (start + end)/2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half = abs(mid_point - start_point)
second_half = abs(end_point - mid_point)
length2 = first_half + second_half
if (length2 - length > error) or (depth < min_depth):
# Calculate the length of each segment:
depth += 1
return (segment_length(curve, start, mid, start_point, mid_point,
error, min_depth, depth) +
segment_length(curve, mid, end, mid_point, end_point,
error, min_depth, depth))
# This is accurate enough.
return length2 | [
"def",
"segment_length",
"(",
"curve",
",",
"start",
",",
"end",
",",
"start_point",
",",
"end_point",
",",
"error",
"=",
"LENGTH_ERROR",
",",
"min_depth",
"=",
"LENGTH_MIN_DEPTH",
",",
"depth",
"=",
"0",
")",
":",
"mid",
"=",
"(",
"start",
"+",
"end",
... | Recursively approximates the length by straight lines | [
"Recursively",
"approximates",
"the",
"length",
"by",
"straight",
"lines"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L416-L434 | train | 200,003 |
mathandy/svgpathtools | svgpathtools/path.py | Line.length | def length(self, t0=0, t1=1, error=None, min_depth=None):
"""returns the length of the line segment between t0 and t1."""
return abs(self.end - self.start)*(t1-t0) | python | def length(self, t0=0, t1=1, error=None, min_depth=None):
"""returns the length of the line segment between t0 and t1."""
return abs(self.end - self.start)*(t1-t0) | [
"def",
"length",
"(",
"self",
",",
"t0",
"=",
"0",
",",
"t1",
"=",
"1",
",",
"error",
"=",
"None",
",",
"min_depth",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"self",
".",
"end",
"-",
"self",
".",
"start",
")",
"*",
"(",
"t1",
"-",
"t0",
... | returns the length of the line segment between t0 and t1. | [
"returns",
"the",
"length",
"of",
"the",
"line",
"segment",
"between",
"t0",
"and",
"t1",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L573-L575 | train | 200,004 |
mathandy/svgpathtools | svgpathtools/path.py | Line.unit_tangent | def unit_tangent(self, t=None):
"""returns the unit tangent of the segment at t."""
assert self.end != self.start
dseg = self.end - self.start
return dseg/abs(dseg) | python | def unit_tangent(self, t=None):
"""returns the unit tangent of the segment at t."""
assert self.end != self.start
dseg = self.end - self.start
return dseg/abs(dseg) | [
"def",
"unit_tangent",
"(",
"self",
",",
"t",
"=",
"None",
")",
":",
"assert",
"self",
".",
"end",
"!=",
"self",
".",
"start",
"dseg",
"=",
"self",
".",
"end",
"-",
"self",
".",
"start",
"return",
"dseg",
"/",
"abs",
"(",
"dseg",
")"
] | returns the unit tangent of the segment at t. | [
"returns",
"the",
"unit",
"tangent",
"of",
"the",
"segment",
"at",
"t",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L607-L611 | train | 200,005 |
mathandy/svgpathtools | svgpathtools/path.py | Line.point_to_t | def point_to_t(self, point):
"""If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None."""
# Single-precision floats have only 7 significant figures of
# resolution, so test that we're within 6 sig figs.
if np.isclose(point, self.start, rtol=0, atol=1e-6):
return 0.0
elif np.isclose(point, self.end, rtol=0, atol=1e-6):
return 1.0
# Finding the point "by hand" here is much faster than calling
# radialrange(), see the discussion on PR #40:
# https://github.com/mathandy/svgpathtools/pull/40#issuecomment-358134261
p = self.poly()
# p(t) = (p_1 * t) + p_0 = point
# t = (point - p_0) / p_1
t = (point - p[0]) / p[1]
if np.isclose(t.imag, 0) and (t.real >= 0.0) and (t.real <= 1.0):
return t.real
return None | python | def point_to_t(self, point):
"""If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None."""
# Single-precision floats have only 7 significant figures of
# resolution, so test that we're within 6 sig figs.
if np.isclose(point, self.start, rtol=0, atol=1e-6):
return 0.0
elif np.isclose(point, self.end, rtol=0, atol=1e-6):
return 1.0
# Finding the point "by hand" here is much faster than calling
# radialrange(), see the discussion on PR #40:
# https://github.com/mathandy/svgpathtools/pull/40#issuecomment-358134261
p = self.poly()
# p(t) = (p_1 * t) + p_0 = point
# t = (point - p_0) / p_1
t = (point - p[0]) / p[1]
if np.isclose(t.imag, 0) and (t.real >= 0.0) and (t.real <= 1.0):
return t.real
return None | [
"def",
"point_to_t",
"(",
"self",
",",
"point",
")",
":",
"# Single-precision floats have only 7 significant figures of",
"# resolution, so test that we're within 6 sig figs.",
"if",
"np",
".",
"isclose",
"(",
"point",
",",
"self",
".",
"start",
",",
"rtol",
"=",
"0",
... | If the point lies on the Line, returns its `t` parameter.
If the point does not lie on the Line, returns None. | [
"If",
"the",
"point",
"lies",
"on",
"the",
"Line",
"returns",
"its",
"t",
"parameter",
".",
"If",
"the",
"point",
"does",
"not",
"lie",
"on",
"the",
"Line",
"returns",
"None",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L689-L710 | train | 200,006 |
mathandy/svgpathtools | svgpathtools/path.py | Line.scaled | def scaled(self, sx, sy=None, origin=0j):
"""Scale transform. See `scale` function for further explanation."""
return scale(self, sx=sx, sy=sy, origin=origin) | python | def scaled(self, sx, sy=None, origin=0j):
"""Scale transform. See `scale` function for further explanation."""
return scale(self, sx=sx, sy=sy, origin=origin) | [
"def",
"scaled",
"(",
"self",
",",
"sx",
",",
"sy",
"=",
"None",
",",
"origin",
"=",
"0j",
")",
":",
"return",
"scale",
"(",
"self",
",",
"sx",
"=",
"sx",
",",
"sy",
"=",
"sy",
",",
"origin",
"=",
"origin",
")"
] | Scale transform. See `scale` function for further explanation. | [
"Scale",
"transform",
".",
"See",
"scale",
"function",
"for",
"further",
"explanation",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L741-L743 | train | 200,007 |
mathandy/svgpathtools | svgpathtools/path.py | QuadraticBezier.poly | def poly(self, return_coeffs=False):
"""returns the quadratic as a Polynomial object."""
p = self.bpoints()
coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0])
if return_coeffs:
return coeffs
else:
return np.poly1d(coeffs) | python | def poly(self, return_coeffs=False):
"""returns the quadratic as a Polynomial object."""
p = self.bpoints()
coeffs = (p[0] - 2*p[1] + p[2], 2*(p[1] - p[0]), p[0])
if return_coeffs:
return coeffs
else:
return np.poly1d(coeffs) | [
"def",
"poly",
"(",
"self",
",",
"return_coeffs",
"=",
"False",
")",
":",
"p",
"=",
"self",
".",
"bpoints",
"(",
")",
"coeffs",
"=",
"(",
"p",
"[",
"0",
"]",
"-",
"2",
"*",
"p",
"[",
"1",
"]",
"+",
"p",
"[",
"2",
"]",
",",
"2",
"*",
"(",
... | returns the quadratic as a Polynomial object. | [
"returns",
"the",
"quadratic",
"as",
"a",
"Polynomial",
"object",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L866-L873 | train | 200,008 |
mathandy/svgpathtools | svgpathtools/path.py | QuadraticBezier.reversed | def reversed(self):
"""returns a copy of the QuadraticBezier object with its orientation
reversed."""
new_quad = QuadraticBezier(self.end, self.control, self.start)
if self._length_info['length']:
new_quad._length_info = self._length_info
new_quad._length_info['bpoints'] = (
self.end, self.control, self.start)
return new_quad | python | def reversed(self):
"""returns a copy of the QuadraticBezier object with its orientation
reversed."""
new_quad = QuadraticBezier(self.end, self.control, self.start)
if self._length_info['length']:
new_quad._length_info = self._length_info
new_quad._length_info['bpoints'] = (
self.end, self.control, self.start)
return new_quad | [
"def",
"reversed",
"(",
"self",
")",
":",
"new_quad",
"=",
"QuadraticBezier",
"(",
"self",
".",
"end",
",",
"self",
".",
"control",
",",
"self",
".",
"start",
")",
"if",
"self",
".",
"_length_info",
"[",
"'length'",
"]",
":",
"new_quad",
".",
"_length_... | returns a copy of the QuadraticBezier object with its orientation
reversed. | [
"returns",
"a",
"copy",
"of",
"the",
"QuadraticBezier",
"object",
"with",
"its",
"orientation",
"reversed",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L916-L924 | train | 200,009 |
mathandy/svgpathtools | svgpathtools/path.py | CubicBezier.point | def point(self, t):
"""Evaluate the cubic Bezier curve at t using Horner's rule."""
# algebraically equivalent to
# P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3
# for (P0, P1, P2, P3) = self.bpoints()
return self.start + t*(
3*(self.control1 - self.start) + t*(
3*(self.start + self.control2) - 6*self.control1 + t*(
-self.start + 3*(self.control1 - self.control2) + self.end
))) | python | def point(self, t):
"""Evaluate the cubic Bezier curve at t using Horner's rule."""
# algebraically equivalent to
# P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3
# for (P0, P1, P2, P3) = self.bpoints()
return self.start + t*(
3*(self.control1 - self.start) + t*(
3*(self.start + self.control2) - 6*self.control1 + t*(
-self.start + 3*(self.control1 - self.control2) + self.end
))) | [
"def",
"point",
"(",
"self",
",",
"t",
")",
":",
"# algebraically equivalent to",
"# P0*(1-t)**3 + 3*P1*t*(1-t)**2 + 3*P2*(1-t)*t**2 + P3*t**3",
"# for (P0, P1, P2, P3) = self.bpoints()",
"return",
"self",
".",
"start",
"+",
"t",
"*",
"(",
"3",
"*",
"(",
"self",
".",
... | Evaluate the cubic Bezier curve at t using Horner's rule. | [
"Evaluate",
"the",
"cubic",
"Bezier",
"curve",
"at",
"t",
"using",
"Horner",
"s",
"rule",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1059-L1068 | train | 200,010 |
mathandy/svgpathtools | svgpathtools/path.py | CubicBezier.bpoints | def bpoints(self):
"""returns the Bezier control points of the segment."""
return self.start, self.control1, self.control2, self.end | python | def bpoints(self):
"""returns the Bezier control points of the segment."""
return self.start, self.control1, self.control2, self.end | [
"def",
"bpoints",
"(",
"self",
")",
":",
"return",
"self",
".",
"start",
",",
"self",
".",
"control1",
",",
"self",
".",
"control2",
",",
"self",
".",
"end"
] | returns the Bezier control points of the segment. | [
"returns",
"the",
"Bezier",
"control",
"points",
"of",
"the",
"segment",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1102-L1104 | train | 200,011 |
mathandy/svgpathtools | svgpathtools/path.py | CubicBezier.reversed | def reversed(self):
"""returns a copy of the CubicBezier object with its orientation
reversed."""
new_cub = CubicBezier(self.end, self.control2, self.control1,
self.start)
if self._length_info['length']:
new_cub._length_info = self._length_info
new_cub._length_info['bpoints'] = (
self.end, self.control2, self.control1, self.start)
return new_cub | python | def reversed(self):
"""returns a copy of the CubicBezier object with its orientation
reversed."""
new_cub = CubicBezier(self.end, self.control2, self.control1,
self.start)
if self._length_info['length']:
new_cub._length_info = self._length_info
new_cub._length_info['bpoints'] = (
self.end, self.control2, self.control1, self.start)
return new_cub | [
"def",
"reversed",
"(",
"self",
")",
":",
"new_cub",
"=",
"CubicBezier",
"(",
"self",
".",
"end",
",",
"self",
".",
"control2",
",",
"self",
".",
"control1",
",",
"self",
".",
"start",
")",
"if",
"self",
".",
"_length_info",
"[",
"'length'",
"]",
":"... | returns a copy of the CubicBezier object with its orientation
reversed. | [
"returns",
"a",
"copy",
"of",
"the",
"CubicBezier",
"object",
"with",
"its",
"orientation",
"reversed",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1163-L1172 | train | 200,012 |
mathandy/svgpathtools | svgpathtools/path.py | Arc.length | def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH):
"""The length of an elliptical large_arc segment requires numerical
integration, and in that case it's simpler to just do a geometric
approximation, as for cubic bezier curves."""
assert 0 <= t0 <= 1 and 0 <= t1 <= 1
if _quad_available:
return quad(lambda tau: abs(self.derivative(tau)), t0, t1,
epsabs=error, limit=1000)[0]
else:
return segment_length(self, t0, t1, self.point(t0), self.point(t1),
error, min_depth, 0) | python | def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH):
"""The length of an elliptical large_arc segment requires numerical
integration, and in that case it's simpler to just do a geometric
approximation, as for cubic bezier curves."""
assert 0 <= t0 <= 1 and 0 <= t1 <= 1
if _quad_available:
return quad(lambda tau: abs(self.derivative(tau)), t0, t1,
epsabs=error, limit=1000)[0]
else:
return segment_length(self, t0, t1, self.point(t0), self.point(t1),
error, min_depth, 0) | [
"def",
"length",
"(",
"self",
",",
"t0",
"=",
"0",
",",
"t1",
"=",
"1",
",",
"error",
"=",
"LENGTH_ERROR",
",",
"min_depth",
"=",
"LENGTH_MIN_DEPTH",
")",
":",
"assert",
"0",
"<=",
"t0",
"<=",
"1",
"and",
"0",
"<=",
"t1",
"<=",
"1",
"if",
"_quad_... | The length of an elliptical large_arc segment requires numerical
integration, and in that case it's simpler to just do a geometric
approximation, as for cubic bezier curves. | [
"The",
"length",
"of",
"an",
"elliptical",
"large_arc",
"segment",
"requires",
"numerical",
"integration",
"and",
"in",
"that",
"case",
"it",
"s",
"simpler",
"to",
"just",
"do",
"a",
"geometric",
"approximation",
"as",
"for",
"cubic",
"bezier",
"curves",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1620-L1630 | train | 200,013 |
mathandy/svgpathtools | svgpathtools/path.py | Arc.reversed | def reversed(self):
"""returns a copy of the Arc object with its orientation reversed."""
return Arc(self.end, self.radius, self.rotation, self.large_arc,
not self.sweep, self.start) | python | def reversed(self):
"""returns a copy of the Arc object with its orientation reversed."""
return Arc(self.end, self.radius, self.rotation, self.large_arc,
not self.sweep, self.start) | [
"def",
"reversed",
"(",
"self",
")",
":",
"return",
"Arc",
"(",
"self",
".",
"end",
",",
"self",
".",
"radius",
",",
"self",
".",
"rotation",
",",
"self",
".",
"large_arc",
",",
"not",
"self",
".",
"sweep",
",",
"self",
".",
"start",
")"
] | returns a copy of the Arc object with its orientation reversed. | [
"returns",
"a",
"copy",
"of",
"the",
"Arc",
"object",
"with",
"its",
"orientation",
"reversed",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L1727-L1730 | train | 200,014 |
mathandy/svgpathtools | svgpathtools/path.py | Path.reversed | def reversed(self):
"""returns a copy of the Path object with its orientation reversed."""
newpath = [seg.reversed() for seg in self]
newpath.reverse()
return Path(*newpath) | python | def reversed(self):
"""returns a copy of the Path object with its orientation reversed."""
newpath = [seg.reversed() for seg in self]
newpath.reverse()
return Path(*newpath) | [
"def",
"reversed",
"(",
"self",
")",
":",
"newpath",
"=",
"[",
"seg",
".",
"reversed",
"(",
")",
"for",
"seg",
"in",
"self",
"]",
"newpath",
".",
"reverse",
"(",
")",
"return",
"Path",
"(",
"*",
"newpath",
")"
] | returns a copy of the Path object with its orientation reversed. | [
"returns",
"a",
"copy",
"of",
"the",
"Path",
"object",
"with",
"its",
"orientation",
"reversed",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L2104-L2108 | train | 200,015 |
mathandy/svgpathtools | svgpathtools/path.py | Path.iscontinuous | def iscontinuous(self):
"""Checks if a path is continuous with respect to its
parameterization."""
return all(self[i].end == self[i+1].start for i in range(len(self) - 1)) | python | def iscontinuous(self):
"""Checks if a path is continuous with respect to its
parameterization."""
return all(self[i].end == self[i+1].start for i in range(len(self) - 1)) | [
"def",
"iscontinuous",
"(",
"self",
")",
":",
"return",
"all",
"(",
"self",
"[",
"i",
"]",
".",
"end",
"==",
"self",
"[",
"i",
"+",
"1",
"]",
".",
"start",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
"-",
"1",
")",
")"
] | Checks if a path is continuous with respect to its
parameterization. | [
"Checks",
"if",
"a",
"path",
"is",
"continuous",
"with",
"respect",
"to",
"its",
"parameterization",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L2183-L2186 | train | 200,016 |
mathandy/svgpathtools | svgpathtools/path.py | Path.isclosed | def isclosed(self):
"""This function determines if a connected path is closed."""
assert len(self) != 0
assert self.iscontinuous()
return self.start == self.end | python | def isclosed(self):
"""This function determines if a connected path is closed."""
assert len(self) != 0
assert self.iscontinuous()
return self.start == self.end | [
"def",
"isclosed",
"(",
"self",
")",
":",
"assert",
"len",
"(",
"self",
")",
"!=",
"0",
"assert",
"self",
".",
"iscontinuous",
"(",
")",
"return",
"self",
".",
"start",
"==",
"self",
".",
"end"
] | This function determines if a connected path is closed. | [
"This",
"function",
"determines",
"if",
"a",
"connected",
"path",
"is",
"closed",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L2205-L2209 | train | 200,017 |
mathandy/svgpathtools | svgpathtools/path.py | Path.d | def d(self, useSandT=False, use_closed_attrib=False):
"""Returns a path d-string for the path object.
For an explanation of useSandT and use_closed_attrib, see the
compatibility notes in the README."""
if use_closed_attrib:
self_closed = self.closed(warning_on=False)
if self_closed:
segments = self[:-1]
else:
segments = self[:]
else:
self_closed = False
segments = self[:]
current_pos = None
parts = []
previous_segment = None
end = self[-1].end
for segment in segments:
seg_start = segment.start
# If the start of this segment does not coincide with the end of
# the last segment or if this segment is actually the close point
# of a closed path, then we should start a new subpath here.
if current_pos != seg_start or \
(self_closed and seg_start == end and use_closed_attrib):
parts.append('M {},{}'.format(seg_start.real, seg_start.imag))
if isinstance(segment, Line):
args = segment.end.real, segment.end.imag
parts.append('L {},{}'.format(*args))
elif isinstance(segment, CubicBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = (segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('S {},{} {},{}'.format(*args))
else:
args = (segment.control1.real, segment.control1.imag,
segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('C {},{} {},{} {},{}'.format(*args))
elif isinstance(segment, QuadraticBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = segment.end.real, segment.end.imag
parts.append('T {},{}'.format(*args))
else:
args = (segment.control.real, segment.control.imag,
segment.end.real, segment.end.imag)
parts.append('Q {},{} {},{}'.format(*args))
elif isinstance(segment, Arc):
args = (segment.radius.real, segment.radius.imag,
segment.rotation,int(segment.large_arc),
int(segment.sweep),segment.end.real, segment.end.imag)
parts.append('A {},{} {} {:d},{:d} {},{}'.format(*args))
current_pos = segment.end
previous_segment = segment
if self_closed:
parts.append('Z')
return ' '.join(parts) | python | def d(self, useSandT=False, use_closed_attrib=False):
"""Returns a path d-string for the path object.
For an explanation of useSandT and use_closed_attrib, see the
compatibility notes in the README."""
if use_closed_attrib:
self_closed = self.closed(warning_on=False)
if self_closed:
segments = self[:-1]
else:
segments = self[:]
else:
self_closed = False
segments = self[:]
current_pos = None
parts = []
previous_segment = None
end = self[-1].end
for segment in segments:
seg_start = segment.start
# If the start of this segment does not coincide with the end of
# the last segment or if this segment is actually the close point
# of a closed path, then we should start a new subpath here.
if current_pos != seg_start or \
(self_closed and seg_start == end and use_closed_attrib):
parts.append('M {},{}'.format(seg_start.real, seg_start.imag))
if isinstance(segment, Line):
args = segment.end.real, segment.end.imag
parts.append('L {},{}'.format(*args))
elif isinstance(segment, CubicBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = (segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('S {},{} {},{}'.format(*args))
else:
args = (segment.control1.real, segment.control1.imag,
segment.control2.real, segment.control2.imag,
segment.end.real, segment.end.imag)
parts.append('C {},{} {},{} {},{}'.format(*args))
elif isinstance(segment, QuadraticBezier):
if useSandT and segment.is_smooth_from(previous_segment,
warning_on=False):
args = segment.end.real, segment.end.imag
parts.append('T {},{}'.format(*args))
else:
args = (segment.control.real, segment.control.imag,
segment.end.real, segment.end.imag)
parts.append('Q {},{} {},{}'.format(*args))
elif isinstance(segment, Arc):
args = (segment.radius.real, segment.radius.imag,
segment.rotation,int(segment.large_arc),
int(segment.sweep),segment.end.real, segment.end.imag)
parts.append('A {},{} {} {:d},{:d} {},{}'.format(*args))
current_pos = segment.end
previous_segment = segment
if self_closed:
parts.append('Z')
return ' '.join(parts) | [
"def",
"d",
"(",
"self",
",",
"useSandT",
"=",
"False",
",",
"use_closed_attrib",
"=",
"False",
")",
":",
"if",
"use_closed_attrib",
":",
"self_closed",
"=",
"self",
".",
"closed",
"(",
"warning_on",
"=",
"False",
")",
"if",
"self_closed",
":",
"segments",... | Returns a path d-string for the path object.
For an explanation of useSandT and use_closed_attrib, see the
compatibility notes in the README. | [
"Returns",
"a",
"path",
"d",
"-",
"string",
"for",
"the",
"path",
"object",
".",
"For",
"an",
"explanation",
"of",
"useSandT",
"and",
"use_closed_attrib",
"see",
"the",
"compatibility",
"notes",
"in",
"the",
"README",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L2264-L2328 | train | 200,018 |
mathandy/svgpathtools | svgpathtools/path.py | Path.cropped | def cropped(self, T0, T1):
"""returns a cropped copy of the path."""
assert 0 <= T0 <= 1 and 0 <= T1<= 1
assert T0 != T1
assert not (T0 == 1 and T1 == 0)
if T0 == 1 and 0 < T1 < 1 and self.isclosed():
return self.cropped(0, T1)
if T1 == 1:
seg1 = self[-1]
t_seg1 = 1
i1 = len(self) - 1
else:
seg1_idx, t_seg1 = self.T2t(T1)
seg1 = self[seg1_idx]
if np.isclose(t_seg1, 0):
i1 = (self.index(seg1) - 1) % len(self)
seg1 = self[i1]
t_seg1 = 1
else:
i1 = self.index(seg1)
if T0 == 0:
seg0 = self[0]
t_seg0 = 0
i0 = 0
else:
seg0_idx, t_seg0 = self.T2t(T0)
seg0 = self[seg0_idx]
if np.isclose(t_seg0, 1):
i0 = (self.index(seg0) + 1) % len(self)
seg0 = self[i0]
t_seg0 = 0
else:
i0 = self.index(seg0)
if T0 < T1 and i0 == i1:
new_path = Path(seg0.cropped(t_seg0, t_seg1))
else:
new_path = Path(seg0.cropped(t_seg0, 1))
# T1<T0 must cross discontinuity case
if T1 < T0:
if not self.isclosed():
raise ValueError("This path is not closed, thus T0 must "
"be less than T1.")
else:
for i in range(i0 + 1, len(self)):
new_path.append(self[i])
for i in range(0, i1):
new_path.append(self[i])
# T0<T1 straight-forward case
else:
for i in range(i0 + 1, i1):
new_path.append(self[i])
if t_seg1 != 0:
new_path.append(seg1.cropped(0, t_seg1))
return new_path | python | def cropped(self, T0, T1):
"""returns a cropped copy of the path."""
assert 0 <= T0 <= 1 and 0 <= T1<= 1
assert T0 != T1
assert not (T0 == 1 and T1 == 0)
if T0 == 1 and 0 < T1 < 1 and self.isclosed():
return self.cropped(0, T1)
if T1 == 1:
seg1 = self[-1]
t_seg1 = 1
i1 = len(self) - 1
else:
seg1_idx, t_seg1 = self.T2t(T1)
seg1 = self[seg1_idx]
if np.isclose(t_seg1, 0):
i1 = (self.index(seg1) - 1) % len(self)
seg1 = self[i1]
t_seg1 = 1
else:
i1 = self.index(seg1)
if T0 == 0:
seg0 = self[0]
t_seg0 = 0
i0 = 0
else:
seg0_idx, t_seg0 = self.T2t(T0)
seg0 = self[seg0_idx]
if np.isclose(t_seg0, 1):
i0 = (self.index(seg0) + 1) % len(self)
seg0 = self[i0]
t_seg0 = 0
else:
i0 = self.index(seg0)
if T0 < T1 and i0 == i1:
new_path = Path(seg0.cropped(t_seg0, t_seg1))
else:
new_path = Path(seg0.cropped(t_seg0, 1))
# T1<T0 must cross discontinuity case
if T1 < T0:
if not self.isclosed():
raise ValueError("This path is not closed, thus T0 must "
"be less than T1.")
else:
for i in range(i0 + 1, len(self)):
new_path.append(self[i])
for i in range(0, i1):
new_path.append(self[i])
# T0<T1 straight-forward case
else:
for i in range(i0 + 1, i1):
new_path.append(self[i])
if t_seg1 != 0:
new_path.append(seg1.cropped(0, t_seg1))
return new_path | [
"def",
"cropped",
"(",
"self",
",",
"T0",
",",
"T1",
")",
":",
"assert",
"0",
"<=",
"T0",
"<=",
"1",
"and",
"0",
"<=",
"T1",
"<=",
"1",
"assert",
"T0",
"!=",
"T1",
"assert",
"not",
"(",
"T0",
"==",
"1",
"and",
"T1",
"==",
"0",
")",
"if",
"T... | returns a cropped copy of the path. | [
"returns",
"a",
"cropped",
"copy",
"of",
"the",
"path",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L2548-L2607 | train | 200,019 |
mathandy/svgpathtools | svgpathtools/bezier.py | split_bezier | def split_bezier(bpoints, t):
"""Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order."""
def split_bezier_recursion(bpoints_left_, bpoints_right_, bpoints_, t_):
if len(bpoints_) == 1:
bpoints_left_.append(bpoints_[0])
bpoints_right_.append(bpoints_[0])
else:
new_points = [None]*(len(bpoints_) - 1)
bpoints_left_.append(bpoints_[0])
bpoints_right_.append(bpoints_[-1])
for i in range(len(bpoints_) - 1):
new_points[i] = (1 - t_)*bpoints_[i] + t_*bpoints_[i + 1]
bpoints_left_, bpoints_right_ = split_bezier_recursion(
bpoints_left_, bpoints_right_, new_points, t_)
return bpoints_left_, bpoints_right_
bpoints_left = []
bpoints_right = []
bpoints_left, bpoints_right = \
split_bezier_recursion(bpoints_left, bpoints_right, bpoints, t)
bpoints_right.reverse()
return bpoints_left, bpoints_right | python | def split_bezier(bpoints, t):
"""Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order."""
def split_bezier_recursion(bpoints_left_, bpoints_right_, bpoints_, t_):
if len(bpoints_) == 1:
bpoints_left_.append(bpoints_[0])
bpoints_right_.append(bpoints_[0])
else:
new_points = [None]*(len(bpoints_) - 1)
bpoints_left_.append(bpoints_[0])
bpoints_right_.append(bpoints_[-1])
for i in range(len(bpoints_) - 1):
new_points[i] = (1 - t_)*bpoints_[i] + t_*bpoints_[i + 1]
bpoints_left_, bpoints_right_ = split_bezier_recursion(
bpoints_left_, bpoints_right_, new_points, t_)
return bpoints_left_, bpoints_right_
bpoints_left = []
bpoints_right = []
bpoints_left, bpoints_right = \
split_bezier_recursion(bpoints_left, bpoints_right, bpoints, t)
bpoints_right.reverse()
return bpoints_left, bpoints_right | [
"def",
"split_bezier",
"(",
"bpoints",
",",
"t",
")",
":",
"def",
"split_bezier_recursion",
"(",
"bpoints_left_",
",",
"bpoints_right_",
",",
"bpoints_",
",",
"t_",
")",
":",
"if",
"len",
"(",
"bpoints_",
")",
"==",
"1",
":",
"bpoints_left_",
".",
"append"... | Uses deCasteljau's recursion to split the Bezier curve at t into two
Bezier curves of the same order. | [
"Uses",
"deCasteljau",
"s",
"recursion",
"to",
"split",
"the",
"Bezier",
"curve",
"at",
"t",
"into",
"two",
"Bezier",
"curves",
"of",
"the",
"same",
"order",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/bezier.py#L122-L144 | train | 200,020 |
mathandy/svgpathtools | svgpathtools/bezier.py | bezier_real_minmax | def bezier_real_minmax(p):
"""returns the minimum and maximum for any real cubic bezier"""
local_extremizers = [0, 1]
if len(p) == 4: # cubic case
a = [p.real for p in p]
denom = a[0] - 3*a[1] + 3*a[2] - a[3]
if denom != 0:
delta = a[1]**2 - (a[0] + a[1])*a[2] + a[2]**2 + (a[0] - a[1])*a[3]
if delta >= 0: # otherwise no local extrema
sqdelta = sqrt(delta)
tau = a[0] - 2*a[1] + a[2]
r1 = (tau + sqdelta)/denom
r2 = (tau - sqdelta)/denom
if 0 < r1 < 1:
local_extremizers.append(r1)
if 0 < r2 < 1:
local_extremizers.append(r2)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema)
# find reverse standard coefficients of the derivative
dcoeffs = bezier2polynomial(a, return_poly1d=True).deriv().coeffs
# find real roots, r, such that 0 <= r <= 1
local_extremizers += polyroots01(dcoeffs)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema) | python | def bezier_real_minmax(p):
"""returns the minimum and maximum for any real cubic bezier"""
local_extremizers = [0, 1]
if len(p) == 4: # cubic case
a = [p.real for p in p]
denom = a[0] - 3*a[1] + 3*a[2] - a[3]
if denom != 0:
delta = a[1]**2 - (a[0] + a[1])*a[2] + a[2]**2 + (a[0] - a[1])*a[3]
if delta >= 0: # otherwise no local extrema
sqdelta = sqrt(delta)
tau = a[0] - 2*a[1] + a[2]
r1 = (tau + sqdelta)/denom
r2 = (tau - sqdelta)/denom
if 0 < r1 < 1:
local_extremizers.append(r1)
if 0 < r2 < 1:
local_extremizers.append(r2)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema)
# find reverse standard coefficients of the derivative
dcoeffs = bezier2polynomial(a, return_poly1d=True).deriv().coeffs
# find real roots, r, such that 0 <= r <= 1
local_extremizers += polyroots01(dcoeffs)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema) | [
"def",
"bezier_real_minmax",
"(",
"p",
")",
":",
"local_extremizers",
"=",
"[",
"0",
",",
"1",
"]",
"if",
"len",
"(",
"p",
")",
"==",
"4",
":",
"# cubic case",
"a",
"=",
"[",
"p",
".",
"real",
"for",
"p",
"in",
"p",
"]",
"denom",
"=",
"a",
"[",... | returns the minimum and maximum for any real cubic bezier | [
"returns",
"the",
"minimum",
"and",
"maximum",
"for",
"any",
"real",
"cubic",
"bezier"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/bezier.py#L168-L194 | train | 200,021 |
mathandy/svgpathtools | svgpathtools/document.py | flatten_group | def flatten_group(group_to_flatten, root, recursive=True,
group_filter=lambda x: True, path_filter=lambda x: True,
path_conversions=CONVERSIONS,
group_search_xpath=SVG_GROUP_TAG):
"""Flatten all the paths in a specific group.
The paths will be flattened into the 'root' frame. Note that root
needs to be an ancestor of the group that is being flattened.
Otherwise, no paths will be returned."""
if not any(group_to_flatten is descendant for descendant in root.iter()):
warnings.warn('The requested group_to_flatten is not a '
'descendant of root')
# We will shortcut here, because it is impossible for any paths
# to be returned anyhow.
return []
# We create a set of the unique IDs of each element that we wish to
# flatten, if those elements are groups. Any groups outside of this
# set will be skipped while we flatten the paths.
desired_groups = set()
if recursive:
for group in group_to_flatten.iter():
desired_groups.add(id(group))
else:
desired_groups.add(id(group_to_flatten))
def desired_group_filter(x):
return (id(x) in desired_groups) and group_filter(x)
return flatten_all_paths(root, desired_group_filter, path_filter,
path_conversions, group_search_xpath) | python | def flatten_group(group_to_flatten, root, recursive=True,
group_filter=lambda x: True, path_filter=lambda x: True,
path_conversions=CONVERSIONS,
group_search_xpath=SVG_GROUP_TAG):
"""Flatten all the paths in a specific group.
The paths will be flattened into the 'root' frame. Note that root
needs to be an ancestor of the group that is being flattened.
Otherwise, no paths will be returned."""
if not any(group_to_flatten is descendant for descendant in root.iter()):
warnings.warn('The requested group_to_flatten is not a '
'descendant of root')
# We will shortcut here, because it is impossible for any paths
# to be returned anyhow.
return []
# We create a set of the unique IDs of each element that we wish to
# flatten, if those elements are groups. Any groups outside of this
# set will be skipped while we flatten the paths.
desired_groups = set()
if recursive:
for group in group_to_flatten.iter():
desired_groups.add(id(group))
else:
desired_groups.add(id(group_to_flatten))
def desired_group_filter(x):
return (id(x) in desired_groups) and group_filter(x)
return flatten_all_paths(root, desired_group_filter, path_filter,
path_conversions, group_search_xpath) | [
"def",
"flatten_group",
"(",
"group_to_flatten",
",",
"root",
",",
"recursive",
"=",
"True",
",",
"group_filter",
"=",
"lambda",
"x",
":",
"True",
",",
"path_filter",
"=",
"lambda",
"x",
":",
"True",
",",
"path_conversions",
"=",
"CONVERSIONS",
",",
"group_s... | Flatten all the paths in a specific group.
The paths will be flattened into the 'root' frame. Note that root
needs to be an ancestor of the group that is being flattened.
Otherwise, no paths will be returned. | [
"Flatten",
"all",
"the",
"paths",
"in",
"a",
"specific",
"group",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/document.py#L150-L181 | train | 200,022 |
mathandy/svgpathtools | svgpathtools/document.py | Document.flatten_all_paths | def flatten_all_paths(self, group_filter=lambda x: True,
path_filter=lambda x: True,
path_conversions=CONVERSIONS):
"""Forward the tree of this document into the more general
flatten_all_paths function and return the result."""
return flatten_all_paths(self.tree.getroot(), group_filter,
path_filter, path_conversions) | python | def flatten_all_paths(self, group_filter=lambda x: True,
path_filter=lambda x: True,
path_conversions=CONVERSIONS):
"""Forward the tree of this document into the more general
flatten_all_paths function and return the result."""
return flatten_all_paths(self.tree.getroot(), group_filter,
path_filter, path_conversions) | [
"def",
"flatten_all_paths",
"(",
"self",
",",
"group_filter",
"=",
"lambda",
"x",
":",
"True",
",",
"path_filter",
"=",
"lambda",
"x",
":",
"True",
",",
"path_conversions",
"=",
"CONVERSIONS",
")",
":",
"return",
"flatten_all_paths",
"(",
"self",
".",
"tree"... | Forward the tree of this document into the more general
flatten_all_paths function and return the result. | [
"Forward",
"the",
"tree",
"of",
"this",
"document",
"into",
"the",
"more",
"general",
"flatten_all_paths",
"function",
"and",
"return",
"the",
"result",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/document.py#L213-L219 | train | 200,023 |
mathandy/svgpathtools | svgpathtools/document.py | Document.add_path | def add_path(self, path, attribs=None, group=None):
"""Add a new path to the SVG."""
# If not given a parent, assume that the path does not have a group
if group is None:
group = self.tree.getroot()
# If given a list of strings (one or more), assume it represents
# a sequence of nested group names
elif all(isinstance(elem, str) for elem in group):
group = self.get_or_add_group(group)
elif not isinstance(group, Element):
raise TypeError(
'Must provide a list of strings or an xml.etree.Element '
'object. Instead you provided {0}'.format(group))
else:
# Make sure that the group belongs to this Document object
if not self.contains_group(group):
warnings.warn('The requested group does not belong to '
'this Document')
# TODO: It might be better to use duck-typing here with a try-except
if isinstance(path, Path):
path_svg = path.d()
elif is_path_segment(path):
path_svg = Path(path).d()
elif isinstance(path, str):
# Assume this is a valid d-string.
# TODO: Should we sanity check the input string?
path_svg = path
else:
raise TypeError(
'Must provide a Path, a path segment type, or a valid '
'SVG path d-string. Instead you provided {0}'.format(path))
if attribs is None:
attribs = {}
else:
attribs = attribs.copy()
attribs['d'] = path_svg
return SubElement(group, 'path', attribs) | python | def add_path(self, path, attribs=None, group=None):
"""Add a new path to the SVG."""
# If not given a parent, assume that the path does not have a group
if group is None:
group = self.tree.getroot()
# If given a list of strings (one or more), assume it represents
# a sequence of nested group names
elif all(isinstance(elem, str) for elem in group):
group = self.get_or_add_group(group)
elif not isinstance(group, Element):
raise TypeError(
'Must provide a list of strings or an xml.etree.Element '
'object. Instead you provided {0}'.format(group))
else:
# Make sure that the group belongs to this Document object
if not self.contains_group(group):
warnings.warn('The requested group does not belong to '
'this Document')
# TODO: It might be better to use duck-typing here with a try-except
if isinstance(path, Path):
path_svg = path.d()
elif is_path_segment(path):
path_svg = Path(path).d()
elif isinstance(path, str):
# Assume this is a valid d-string.
# TODO: Should we sanity check the input string?
path_svg = path
else:
raise TypeError(
'Must provide a Path, a path segment type, or a valid '
'SVG path d-string. Instead you provided {0}'.format(path))
if attribs is None:
attribs = {}
else:
attribs = attribs.copy()
attribs['d'] = path_svg
return SubElement(group, 'path', attribs) | [
"def",
"add_path",
"(",
"self",
",",
"path",
",",
"attribs",
"=",
"None",
",",
"group",
"=",
"None",
")",
":",
"# If not given a parent, assume that the path does not have a group",
"if",
"group",
"is",
"None",
":",
"group",
"=",
"self",
".",
"tree",
".",
"get... | Add a new path to the SVG. | [
"Add",
"a",
"new",
"path",
"to",
"the",
"SVG",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/document.py#L236-L280 | train | 200,024 |
mathandy/svgpathtools | svgpathtools/document.py | Document.get_or_add_group | def get_or_add_group(self, nested_names, name_attr='id'):
"""Get a group from the tree, or add a new one with the given
name structure.
`nested_names` is a list of strings which represent group names.
Each group name will be nested inside of the previous group name.
`name_attr` is the group attribute that is being used to
represent the group's name. Default is 'id', but some SVGs may
contain custom name labels, like 'inkscape:label'.
Returns the requested group. If the requested group did not
exist, this function will create it, as well as all parent
groups that it requires. All created groups will be left with
blank attributes.
"""
group = self.tree.getroot()
# Drill down through the names until we find the desired group
while len(nested_names):
prev_group = group
next_name = nested_names.pop(0)
for elem in group.iterfind(SVG_GROUP_TAG, SVG_NAMESPACE):
if elem.get(name_attr) == next_name:
group = elem
break
if prev_group is group:
# The group we're looking for does not exist, so let's
# create the group structure
nested_names.insert(0, next_name)
while nested_names:
next_name = nested_names.pop(0)
group = self.add_group({'id': next_name}, group)
# Now nested_names will be empty, so the topmost
# while-loop will end
return group | python | def get_or_add_group(self, nested_names, name_attr='id'):
"""Get a group from the tree, or add a new one with the given
name structure.
`nested_names` is a list of strings which represent group names.
Each group name will be nested inside of the previous group name.
`name_attr` is the group attribute that is being used to
represent the group's name. Default is 'id', but some SVGs may
contain custom name labels, like 'inkscape:label'.
Returns the requested group. If the requested group did not
exist, this function will create it, as well as all parent
groups that it requires. All created groups will be left with
blank attributes.
"""
group = self.tree.getroot()
# Drill down through the names until we find the desired group
while len(nested_names):
prev_group = group
next_name = nested_names.pop(0)
for elem in group.iterfind(SVG_GROUP_TAG, SVG_NAMESPACE):
if elem.get(name_attr) == next_name:
group = elem
break
if prev_group is group:
# The group we're looking for does not exist, so let's
# create the group structure
nested_names.insert(0, next_name)
while nested_names:
next_name = nested_names.pop(0)
group = self.add_group({'id': next_name}, group)
# Now nested_names will be empty, so the topmost
# while-loop will end
return group | [
"def",
"get_or_add_group",
"(",
"self",
",",
"nested_names",
",",
"name_attr",
"=",
"'id'",
")",
":",
"group",
"=",
"self",
".",
"tree",
".",
"getroot",
"(",
")",
"# Drill down through the names until we find the desired group",
"while",
"len",
"(",
"nested_names",
... | Get a group from the tree, or add a new one with the given
name structure.
`nested_names` is a list of strings which represent group names.
Each group name will be nested inside of the previous group name.
`name_attr` is the group attribute that is being used to
represent the group's name. Default is 'id', but some SVGs may
contain custom name labels, like 'inkscape:label'.
Returns the requested group. If the requested group did not
exist, this function will create it, as well as all parent
groups that it requires. All created groups will be left with
blank attributes. | [
"Get",
"a",
"group",
"from",
"the",
"tree",
"or",
"add",
"a",
"new",
"one",
"with",
"the",
"given",
"name",
"structure",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/document.py#L285-L322 | train | 200,025 |
mathandy/svgpathtools | svgpathtools/document.py | Document.add_group | def add_group(self, group_attribs=None, parent=None):
"""Add an empty group element to the SVG."""
if parent is None:
parent = self.tree.getroot()
elif not self.contains_group(parent):
warnings.warn('The requested group {0} does not belong to '
'this Document'.format(parent))
if group_attribs is None:
group_attribs = {}
else:
group_attribs = group_attribs.copy()
return SubElement(parent, '{{{0}}}g'.format(
SVG_NAMESPACE['svg']), group_attribs) | python | def add_group(self, group_attribs=None, parent=None):
"""Add an empty group element to the SVG."""
if parent is None:
parent = self.tree.getroot()
elif not self.contains_group(parent):
warnings.warn('The requested group {0} does not belong to '
'this Document'.format(parent))
if group_attribs is None:
group_attribs = {}
else:
group_attribs = group_attribs.copy()
return SubElement(parent, '{{{0}}}g'.format(
SVG_NAMESPACE['svg']), group_attribs) | [
"def",
"add_group",
"(",
"self",
",",
"group_attribs",
"=",
"None",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"self",
".",
"tree",
".",
"getroot",
"(",
")",
"elif",
"not",
"self",
".",
"contains_group",
"... | Add an empty group element to the SVG. | [
"Add",
"an",
"empty",
"group",
"element",
"to",
"the",
"SVG",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/document.py#L324-L338 | train | 200,026 |
mathandy/svgpathtools | svgpathtools/parser.py | parse_transform | def parse_transform(transform_str):
"""Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix"""
if not transform_str:
return np.identity(3)
elif not isinstance(transform_str, str):
raise TypeError('Must provide a string to parse')
total_transform = np.identity(3)
transform_substrs = transform_str.split(')')[:-1] # Skip the last element, because it should be empty
for substr in transform_substrs:
total_transform = total_transform.dot(_parse_transform_substr(substr))
return total_transform | python | def parse_transform(transform_str):
"""Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix"""
if not transform_str:
return np.identity(3)
elif not isinstance(transform_str, str):
raise TypeError('Must provide a string to parse')
total_transform = np.identity(3)
transform_substrs = transform_str.split(')')[:-1] # Skip the last element, because it should be empty
for substr in transform_substrs:
total_transform = total_transform.dot(_parse_transform_substr(substr))
return total_transform | [
"def",
"parse_transform",
"(",
"transform_str",
")",
":",
"if",
"not",
"transform_str",
":",
"return",
"np",
".",
"identity",
"(",
"3",
")",
"elif",
"not",
"isinstance",
"(",
"transform_str",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Must provide a ... | Converts a valid SVG transformation string into a 3x3 matrix.
If the string is empty or null, this returns a 3x3 identity matrix | [
"Converts",
"a",
"valid",
"SVG",
"transformation",
"string",
"into",
"a",
"3x3",
"matrix",
".",
"If",
"the",
"string",
"is",
"empty",
"or",
"null",
"this",
"returns",
"a",
"3x3",
"identity",
"matrix"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/parser.py#L287-L300 | train | 200,027 |
mathandy/svgpathtools | svgpathtools/smoothing.py | kinks | def kinks(path, tol=1e-8):
"""returns indices of segments that start on a non-differentiable joint."""
kink_list = []
for idx in range(len(path)):
if idx == 0 and not path.isclosed():
continue
try:
u = path[(idx - 1) % len(path)].unit_tangent(1)
v = path[idx].unit_tangent(0)
u_dot_v = u.real*v.real + u.imag*v.imag
flag = False
except ValueError:
flag = True
if flag or abs(u_dot_v - 1) > tol:
kink_list.append(idx)
return kink_list | python | def kinks(path, tol=1e-8):
"""returns indices of segments that start on a non-differentiable joint."""
kink_list = []
for idx in range(len(path)):
if idx == 0 and not path.isclosed():
continue
try:
u = path[(idx - 1) % len(path)].unit_tangent(1)
v = path[idx].unit_tangent(0)
u_dot_v = u.real*v.real + u.imag*v.imag
flag = False
except ValueError:
flag = True
if flag or abs(u_dot_v - 1) > tol:
kink_list.append(idx)
return kink_list | [
"def",
"kinks",
"(",
"path",
",",
"tol",
"=",
"1e-8",
")",
":",
"kink_list",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"path",
")",
")",
":",
"if",
"idx",
"==",
"0",
"and",
"not",
"path",
".",
"isclosed",
"(",
")",
":",
"co... | returns indices of segments that start on a non-differentiable joint. | [
"returns",
"indices",
"of",
"segments",
"that",
"start",
"on",
"a",
"non",
"-",
"differentiable",
"joint",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/smoothing.py#L23-L39 | train | 200,028 |
mathandy/svgpathtools | svgpathtools/smoothing.py | smoothed_path | def smoothed_path(path, maxjointsize=3, tightness=1.99, ignore_unfixable_kinks=False):
"""returns a path with no non-differentiable joints."""
if len(path) == 1:
return path
assert path.iscontinuous()
sharp_kinks = []
new_path = [path[0]]
for idx in range(len(path)):
if idx == len(path)-1:
if not path.isclosed():
continue
else:
seg1 = new_path[0]
else:
seg1 = path[idx + 1]
seg0 = new_path[-1]
try:
unit_tangent0 = seg0.unit_tangent(1)
unit_tangent1 = seg1.unit_tangent(0)
flag = False
except ValueError:
flag = True # unit tangent not well-defined
if not flag and isclose(unit_tangent0, unit_tangent1): # joint is already smooth
if idx != len(path)-1:
new_path.append(seg1)
continue
else:
kink_idx = (idx + 1) % len(path) # kink at start of this seg
if not flag and isclose(-unit_tangent0, unit_tangent1):
# joint is sharp 180 deg (must be fixed manually)
new_path.append(seg1)
sharp_kinks.append(kink_idx)
else: # joint is not smooth, let's smooth it.
args = (seg0, seg1, maxjointsize, tightness)
new_seg0, elbow_segs, new_seg1 = smoothed_joint(*args)
new_path[-1] = new_seg0
new_path += elbow_segs
if idx == len(path) - 1:
new_path[0] = new_seg1
else:
new_path.append(new_seg1)
# If unfixable kinks were found, let the user know
if sharp_kinks and not ignore_unfixable_kinks:
_report_unfixable_kinks(path, sharp_kinks)
return Path(*new_path) | python | def smoothed_path(path, maxjointsize=3, tightness=1.99, ignore_unfixable_kinks=False):
"""returns a path with no non-differentiable joints."""
if len(path) == 1:
return path
assert path.iscontinuous()
sharp_kinks = []
new_path = [path[0]]
for idx in range(len(path)):
if idx == len(path)-1:
if not path.isclosed():
continue
else:
seg1 = new_path[0]
else:
seg1 = path[idx + 1]
seg0 = new_path[-1]
try:
unit_tangent0 = seg0.unit_tangent(1)
unit_tangent1 = seg1.unit_tangent(0)
flag = False
except ValueError:
flag = True # unit tangent not well-defined
if not flag and isclose(unit_tangent0, unit_tangent1): # joint is already smooth
if idx != len(path)-1:
new_path.append(seg1)
continue
else:
kink_idx = (idx + 1) % len(path) # kink at start of this seg
if not flag and isclose(-unit_tangent0, unit_tangent1):
# joint is sharp 180 deg (must be fixed manually)
new_path.append(seg1)
sharp_kinks.append(kink_idx)
else: # joint is not smooth, let's smooth it.
args = (seg0, seg1, maxjointsize, tightness)
new_seg0, elbow_segs, new_seg1 = smoothed_joint(*args)
new_path[-1] = new_seg0
new_path += elbow_segs
if idx == len(path) - 1:
new_path[0] = new_seg1
else:
new_path.append(new_seg1)
# If unfixable kinks were found, let the user know
if sharp_kinks and not ignore_unfixable_kinks:
_report_unfixable_kinks(path, sharp_kinks)
return Path(*new_path) | [
"def",
"smoothed_path",
"(",
"path",
",",
"maxjointsize",
"=",
"3",
",",
"tightness",
"=",
"1.99",
",",
"ignore_unfixable_kinks",
"=",
"False",
")",
":",
"if",
"len",
"(",
"path",
")",
"==",
"1",
":",
"return",
"path",
"assert",
"path",
".",
"iscontinuou... | returns a path with no non-differentiable joints. | [
"returns",
"a",
"path",
"with",
"no",
"non",
"-",
"differentiable",
"joints",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/smoothing.py#L151-L201 | train | 200,029 |
mathandy/svgpathtools | svgpathtools/misctools.py | hex2rgb | def hex2rgb(value):
"""Converts a hexadeximal color string to an RGB 3-tuple
EXAMPLE
-------
>>> hex2rgb('#0000FF')
(0, 0, 255)
"""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) | python | def hex2rgb(value):
"""Converts a hexadeximal color string to an RGB 3-tuple
EXAMPLE
-------
>>> hex2rgb('#0000FF')
(0, 0, 255)
"""
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) | [
"def",
"hex2rgb",
"(",
"value",
")",
":",
"value",
"=",
"value",
".",
"lstrip",
"(",
"'#'",
")",
"lv",
"=",
"len",
"(",
"value",
")",
"return",
"tuple",
"(",
"int",
"(",
"value",
"[",
"i",
":",
"i",
"+",
"lv",
"//",
"3",
"]",
",",
"16",
")",
... | Converts a hexadeximal color string to an RGB 3-tuple
EXAMPLE
-------
>>> hex2rgb('#0000FF')
(0, 0, 255) | [
"Converts",
"a",
"hexadeximal",
"color",
"string",
"to",
"an",
"RGB",
"3",
"-",
"tuple"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/misctools.py#L12-L22 | train | 200,030 |
mathandy/svgpathtools | svgpathtools/misctools.py | isclose | def isclose(a, b, rtol=1e-5, atol=1e-8):
"""This is essentially np.isclose, but slightly faster."""
return abs(a - b) < (atol + rtol * abs(b)) | python | def isclose(a, b, rtol=1e-5, atol=1e-8):
"""This is essentially np.isclose, but slightly faster."""
return abs(a - b) < (atol + rtol * abs(b)) | [
"def",
"isclose",
"(",
"a",
",",
"b",
",",
"rtol",
"=",
"1e-5",
",",
"atol",
"=",
"1e-8",
")",
":",
"return",
"abs",
"(",
"a",
"-",
"b",
")",
"<",
"(",
"atol",
"+",
"rtol",
"*",
"abs",
"(",
"b",
")",
")"
] | This is essentially np.isclose, but slightly faster. | [
"This",
"is",
"essentially",
"np",
".",
"isclose",
"but",
"slightly",
"faster",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/misctools.py#L37-L39 | train | 200,031 |
mathandy/svgpathtools | svgpathtools/misctools.py | open_in_browser | def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), file_location)
if not os.path.isfile(file_location):
raise IOError("\n\nFile not found.")
# For some reason OSX requires this adjustment (tested on 10.10.4)
if sys.platform == "darwin":
file_location = "file:///"+file_location
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new) | python | def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), file_location)
if not os.path.isfile(file_location):
raise IOError("\n\nFile not found.")
# For some reason OSX requires this adjustment (tested on 10.10.4)
if sys.platform == "darwin":
file_location = "file:///"+file_location
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new) | [
"def",
"open_in_browser",
"(",
"file_location",
")",
":",
"# If just the name of the file was given, check if it's in the Current",
"# Working Directory.",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_location",
")",
":",
"file_location",
"=",
"os",
".",
"p... | Attempt to open file located at file_location in the default web
browser. | [
"Attempt",
"to",
"open",
"file",
"located",
"at",
"file_location",
"in",
"the",
"default",
"web",
"browser",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/misctools.py#L42-L58 | train | 200,032 |
mathandy/svgpathtools | svgpathtools/svg_to_paths.py | ellipse2pathd | def ellipse2pathd(ellipse):
"""converts the parameters from an ellipse or a circle to a string for a
Path object d-attribute"""
cx = ellipse.get('cx', 0)
cy = ellipse.get('cy', 0)
rx = ellipse.get('rx', None)
ry = ellipse.get('ry', None)
r = ellipse.get('r', None)
if r is not None:
rx = ry = float(r)
else:
rx = float(rx)
ry = float(ry)
cx = float(cx)
cy = float(cy)
d = ''
d += 'M' + str(cx - rx) + ',' + str(cy)
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(2 * rx) + ',0'
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(-2 * rx) + ',0'
return d | python | def ellipse2pathd(ellipse):
"""converts the parameters from an ellipse or a circle to a string for a
Path object d-attribute"""
cx = ellipse.get('cx', 0)
cy = ellipse.get('cy', 0)
rx = ellipse.get('rx', None)
ry = ellipse.get('ry', None)
r = ellipse.get('r', None)
if r is not None:
rx = ry = float(r)
else:
rx = float(rx)
ry = float(ry)
cx = float(cx)
cy = float(cy)
d = ''
d += 'M' + str(cx - rx) + ',' + str(cy)
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(2 * rx) + ',0'
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(-2 * rx) + ',0'
return d | [
"def",
"ellipse2pathd",
"(",
"ellipse",
")",
":",
"cx",
"=",
"ellipse",
".",
"get",
"(",
"'cx'",
",",
"0",
")",
"cy",
"=",
"ellipse",
".",
"get",
"(",
"'cy'",
",",
"0",
")",
"rx",
"=",
"ellipse",
".",
"get",
"(",
"'rx'",
",",
"None",
")",
"ry",... | converts the parameters from an ellipse or a circle to a string for a
Path object d-attribute | [
"converts",
"the",
"parameters",
"from",
"an",
"ellipse",
"or",
"a",
"circle",
"to",
"a",
"string",
"for",
"a",
"Path",
"object",
"d",
"-",
"attribute"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/svg_to_paths.py#L23-L47 | train | 200,033 |
mathandy/svgpathtools | svgpathtools/svg_to_paths.py | polyline2pathd | def polyline2pathd(polyline_d, is_polygon=False):
"""converts the string from a polyline points-attribute to a string for a
Path object d-attribute"""
points = COORD_PAIR_TMPLT.findall(polyline_d)
closed = (float(points[0][0]) == float(points[-1][0]) and
float(points[0][1]) == float(points[-1][1]))
# The `parse_path` call ignores redundant 'z' (closure) commands
# e.g. `parse_path('M0 0L100 100Z') == parse_path('M0 0L100 100L0 0Z')`
# This check ensures that an n-point polygon is converted to an n-Line path.
if is_polygon and closed:
points.append(points[0])
d = 'M' + 'L'.join('{0} {1}'.format(x,y) for x,y in points)
if is_polygon or closed:
d += 'z'
return d | python | def polyline2pathd(polyline_d, is_polygon=False):
"""converts the string from a polyline points-attribute to a string for a
Path object d-attribute"""
points = COORD_PAIR_TMPLT.findall(polyline_d)
closed = (float(points[0][0]) == float(points[-1][0]) and
float(points[0][1]) == float(points[-1][1]))
# The `parse_path` call ignores redundant 'z' (closure) commands
# e.g. `parse_path('M0 0L100 100Z') == parse_path('M0 0L100 100L0 0Z')`
# This check ensures that an n-point polygon is converted to an n-Line path.
if is_polygon and closed:
points.append(points[0])
d = 'M' + 'L'.join('{0} {1}'.format(x,y) for x,y in points)
if is_polygon or closed:
d += 'z'
return d | [
"def",
"polyline2pathd",
"(",
"polyline_d",
",",
"is_polygon",
"=",
"False",
")",
":",
"points",
"=",
"COORD_PAIR_TMPLT",
".",
"findall",
"(",
"polyline_d",
")",
"closed",
"=",
"(",
"float",
"(",
"points",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"==",
"floa... | converts the string from a polyline points-attribute to a string for a
Path object d-attribute | [
"converts",
"the",
"string",
"from",
"a",
"polyline",
"points",
"-",
"attribute",
"to",
"a",
"string",
"for",
"a",
"Path",
"object",
"d",
"-",
"attribute"
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/svg_to_paths.py#L50-L66 | train | 200,034 |
mathandy/svgpathtools | svgpathtools/svg_to_paths.py | svg2paths | def svg2paths(svg_file_location,
return_svg_attributes=False,
convert_circles_to_paths=True,
convert_ellipses_to_paths=True,
convert_lines_to_paths=True,
convert_polylines_to_paths=True,
convert_polygons_to_paths=True,
convert_rectangles_to_paths=True):
"""Converts an SVG into a list of Path objects and attribute dictionaries.
Converts an SVG file into a list of Path objects and a list of
dictionaries containing their attributes. This currently supports
SVG Path, Line, Polyline, Polygon, Circle, and Ellipse elements.
Args:
svg_file_location (string): the location of the svg file
return_svg_attributes (bool): Set to True and a dictionary of
svg-attributes will be extracted and returned. See also the
`svg2paths2()` function.
convert_circles_to_paths: Set to False to exclude SVG-Circle
elements (converted to Paths). By default circles are included as
paths of two `Arc` objects.
convert_ellipses_to_paths (bool): Set to False to exclude SVG-Ellipse
elements (converted to Paths). By default ellipses are included as
paths of two `Arc` objects.
convert_lines_to_paths (bool): Set to False to exclude SVG-Line elements
(converted to Paths)
convert_polylines_to_paths (bool): Set to False to exclude SVG-Polyline
elements (converted to Paths)
convert_polygons_to_paths (bool): Set to False to exclude SVG-Polygon
elements (converted to Paths)
convert_rectangles_to_paths (bool): Set to False to exclude SVG-Rect
elements (converted to Paths).
Returns:
list: The list of Path objects.
list: The list of corresponding path attribute dictionaries.
dict (optional): A dictionary of svg-attributes (see `svg2paths2()`).
"""
if os_path.dirname(svg_file_location) == '':
svg_file_location = os_path.join(getcwd(), svg_file_location)
doc = parse(svg_file_location)
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values)))
# Use minidom to extract path strings from input SVG
paths = [dom2dict(el) for el in doc.getElementsByTagName('path')]
d_strings = [el['d'] for el in paths]
attribute_dictionary_list = paths
# Use minidom to extract polyline strings from input SVG, convert to
# path strings, add to list
if convert_polylines_to_paths:
plins = [dom2dict(el) for el in doc.getElementsByTagName('polyline')]
d_strings += [polyline2pathd(pl['points']) for pl in plins]
attribute_dictionary_list += plins
# Use minidom to extract polygon strings from input SVG, convert to
# path strings, add to list
if convert_polygons_to_paths:
pgons = [dom2dict(el) for el in doc.getElementsByTagName('polygon')]
d_strings += [polygon2pathd(pg['points']) for pg in pgons]
attribute_dictionary_list += pgons
if convert_lines_to_paths:
lines = [dom2dict(el) for el in doc.getElementsByTagName('line')]
d_strings += [('M' + l['x1'] + ' ' + l['y1'] +
'L' + l['x2'] + ' ' + l['y2']) for l in lines]
attribute_dictionary_list += lines
if convert_ellipses_to_paths:
ellipses = [dom2dict(el) for el in doc.getElementsByTagName('ellipse')]
d_strings += [ellipse2pathd(e) for e in ellipses]
attribute_dictionary_list += ellipses
if convert_circles_to_paths:
circles = [dom2dict(el) for el in doc.getElementsByTagName('circle')]
d_strings += [ellipse2pathd(c) for c in circles]
attribute_dictionary_list += circles
if convert_rectangles_to_paths:
rectangles = [dom2dict(el) for el in doc.getElementsByTagName('rect')]
d_strings += [rect2pathd(r) for r in rectangles]
attribute_dictionary_list += rectangles
if return_svg_attributes:
svg_attributes = dom2dict(doc.getElementsByTagName('svg')[0])
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list, svg_attributes
else:
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list | python | def svg2paths(svg_file_location,
return_svg_attributes=False,
convert_circles_to_paths=True,
convert_ellipses_to_paths=True,
convert_lines_to_paths=True,
convert_polylines_to_paths=True,
convert_polygons_to_paths=True,
convert_rectangles_to_paths=True):
"""Converts an SVG into a list of Path objects and attribute dictionaries.
Converts an SVG file into a list of Path objects and a list of
dictionaries containing their attributes. This currently supports
SVG Path, Line, Polyline, Polygon, Circle, and Ellipse elements.
Args:
svg_file_location (string): the location of the svg file
return_svg_attributes (bool): Set to True and a dictionary of
svg-attributes will be extracted and returned. See also the
`svg2paths2()` function.
convert_circles_to_paths: Set to False to exclude SVG-Circle
elements (converted to Paths). By default circles are included as
paths of two `Arc` objects.
convert_ellipses_to_paths (bool): Set to False to exclude SVG-Ellipse
elements (converted to Paths). By default ellipses are included as
paths of two `Arc` objects.
convert_lines_to_paths (bool): Set to False to exclude SVG-Line elements
(converted to Paths)
convert_polylines_to_paths (bool): Set to False to exclude SVG-Polyline
elements (converted to Paths)
convert_polygons_to_paths (bool): Set to False to exclude SVG-Polygon
elements (converted to Paths)
convert_rectangles_to_paths (bool): Set to False to exclude SVG-Rect
elements (converted to Paths).
Returns:
list: The list of Path objects.
list: The list of corresponding path attribute dictionaries.
dict (optional): A dictionary of svg-attributes (see `svg2paths2()`).
"""
if os_path.dirname(svg_file_location) == '':
svg_file_location = os_path.join(getcwd(), svg_file_location)
doc = parse(svg_file_location)
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values)))
# Use minidom to extract path strings from input SVG
paths = [dom2dict(el) for el in doc.getElementsByTagName('path')]
d_strings = [el['d'] for el in paths]
attribute_dictionary_list = paths
# Use minidom to extract polyline strings from input SVG, convert to
# path strings, add to list
if convert_polylines_to_paths:
plins = [dom2dict(el) for el in doc.getElementsByTagName('polyline')]
d_strings += [polyline2pathd(pl['points']) for pl in plins]
attribute_dictionary_list += plins
# Use minidom to extract polygon strings from input SVG, convert to
# path strings, add to list
if convert_polygons_to_paths:
pgons = [dom2dict(el) for el in doc.getElementsByTagName('polygon')]
d_strings += [polygon2pathd(pg['points']) for pg in pgons]
attribute_dictionary_list += pgons
if convert_lines_to_paths:
lines = [dom2dict(el) for el in doc.getElementsByTagName('line')]
d_strings += [('M' + l['x1'] + ' ' + l['y1'] +
'L' + l['x2'] + ' ' + l['y2']) for l in lines]
attribute_dictionary_list += lines
if convert_ellipses_to_paths:
ellipses = [dom2dict(el) for el in doc.getElementsByTagName('ellipse')]
d_strings += [ellipse2pathd(e) for e in ellipses]
attribute_dictionary_list += ellipses
if convert_circles_to_paths:
circles = [dom2dict(el) for el in doc.getElementsByTagName('circle')]
d_strings += [ellipse2pathd(c) for c in circles]
attribute_dictionary_list += circles
if convert_rectangles_to_paths:
rectangles = [dom2dict(el) for el in doc.getElementsByTagName('rect')]
d_strings += [rect2pathd(r) for r in rectangles]
attribute_dictionary_list += rectangles
if return_svg_attributes:
svg_attributes = dom2dict(doc.getElementsByTagName('svg')[0])
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list, svg_attributes
else:
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list | [
"def",
"svg2paths",
"(",
"svg_file_location",
",",
"return_svg_attributes",
"=",
"False",
",",
"convert_circles_to_paths",
"=",
"True",
",",
"convert_ellipses_to_paths",
"=",
"True",
",",
"convert_lines_to_paths",
"=",
"True",
",",
"convert_polylines_to_paths",
"=",
"Tr... | Converts an SVG into a list of Path objects and attribute dictionaries.
Converts an SVG file into a list of Path objects and a list of
dictionaries containing their attributes. This currently supports
SVG Path, Line, Polyline, Polygon, Circle, and Ellipse elements.
Args:
svg_file_location (string): the location of the svg file
return_svg_attributes (bool): Set to True and a dictionary of
svg-attributes will be extracted and returned. See also the
`svg2paths2()` function.
convert_circles_to_paths: Set to False to exclude SVG-Circle
elements (converted to Paths). By default circles are included as
paths of two `Arc` objects.
convert_ellipses_to_paths (bool): Set to False to exclude SVG-Ellipse
elements (converted to Paths). By default ellipses are included as
paths of two `Arc` objects.
convert_lines_to_paths (bool): Set to False to exclude SVG-Line elements
(converted to Paths)
convert_polylines_to_paths (bool): Set to False to exclude SVG-Polyline
elements (converted to Paths)
convert_polygons_to_paths (bool): Set to False to exclude SVG-Polygon
elements (converted to Paths)
convert_rectangles_to_paths (bool): Set to False to exclude SVG-Rect
elements (converted to Paths).
Returns:
list: The list of Path objects.
list: The list of corresponding path attribute dictionaries.
dict (optional): A dictionary of svg-attributes (see `svg2paths2()`). | [
"Converts",
"an",
"SVG",
"into",
"a",
"list",
"of",
"Path",
"objects",
"and",
"attribute",
"dictionaries",
"."
] | fd7348a1dfd88b65ea61da02325c6605aedf8c4f | https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/svg_to_paths.py#L96-L194 | train | 200,035 |
trombastic/PyScada | pyscada/export/hdf5_file.py | dtype_to_matlab_class | def dtype_to_matlab_class(dtype):
"""
convert dtype to matlab class string
"""
if dtype.str in ['<f8']:
return 'double'
elif dtype.str in ['<f4']:
return 'single'
elif dtype.str in ['<i8']:
return 'int64'
elif dtype.str in ['<u8']:
return 'uint64'
elif dtype.str in ['<i4']:
return 'int32'
elif dtype.str in ['<u4']:
return 'uint32'
elif dtype.str in ['<i2']:
return 'int16'
elif dtype.str in ['<u2']:
return 'uint16'
elif dtype.str in ['|i1']:
return 'int8'
elif dtype.str in ['|u1']:
return 'uint8' | python | def dtype_to_matlab_class(dtype):
"""
convert dtype to matlab class string
"""
if dtype.str in ['<f8']:
return 'double'
elif dtype.str in ['<f4']:
return 'single'
elif dtype.str in ['<i8']:
return 'int64'
elif dtype.str in ['<u8']:
return 'uint64'
elif dtype.str in ['<i4']:
return 'int32'
elif dtype.str in ['<u4']:
return 'uint32'
elif dtype.str in ['<i2']:
return 'int16'
elif dtype.str in ['<u2']:
return 'uint16'
elif dtype.str in ['|i1']:
return 'int8'
elif dtype.str in ['|u1']:
return 'uint8' | [
"def",
"dtype_to_matlab_class",
"(",
"dtype",
")",
":",
"if",
"dtype",
".",
"str",
"in",
"[",
"'<f8'",
"]",
":",
"return",
"'double'",
"elif",
"dtype",
".",
"str",
"in",
"[",
"'<f4'",
"]",
":",
"return",
"'single'",
"elif",
"dtype",
".",
"str",
"in",
... | convert dtype to matlab class string | [
"convert",
"dtype",
"to",
"matlab",
"class",
"string"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/export/hdf5_file.py#L26-L49 | train | 200,036 |
trombastic/PyScada | pyscada/visa/devices/__init__.py | GenericDevice.connect | def connect(self):
"""
establish a connection to the Instrument
"""
if not driver_ok:
logger.error("Visa driver NOT ok")
return False
visa_backend = '@py' # use PyVISA-py as backend
if hasattr(settings, 'VISA_BACKEND'):
visa_backend = settings.VISA_BACKEND
try:
self.rm = visa.ResourceManager(visa_backend)
except:
logger.error("Visa ResourceManager cannot load resources : %s" %self)
return False
try:
resource_prefix = self._device.visadevice.resource_name.split('::')[0]
extras = {}
if hasattr(settings, 'VISA_DEVICE_SETTINGS'):
if resource_prefix in settings.VISA_DEVICE_SETTINGS:
extras = settings.VISA_DEVICE_SETTINGS[resource_prefix]
logger.debug('VISA_DEVICE_SETTINGS for %s: %r'%(resource_prefix,extras))
self.inst = self.rm.open_resource(self._device.visadevice.resource_name, **extras)
except:
logger.error("Visa ResourceManager cannot open resource : %s" %self._device.visadevice.resource_name)
return False
logger.debug('connected visa device')
return True | python | def connect(self):
"""
establish a connection to the Instrument
"""
if not driver_ok:
logger.error("Visa driver NOT ok")
return False
visa_backend = '@py' # use PyVISA-py as backend
if hasattr(settings, 'VISA_BACKEND'):
visa_backend = settings.VISA_BACKEND
try:
self.rm = visa.ResourceManager(visa_backend)
except:
logger.error("Visa ResourceManager cannot load resources : %s" %self)
return False
try:
resource_prefix = self._device.visadevice.resource_name.split('::')[0]
extras = {}
if hasattr(settings, 'VISA_DEVICE_SETTINGS'):
if resource_prefix in settings.VISA_DEVICE_SETTINGS:
extras = settings.VISA_DEVICE_SETTINGS[resource_prefix]
logger.debug('VISA_DEVICE_SETTINGS for %s: %r'%(resource_prefix,extras))
self.inst = self.rm.open_resource(self._device.visadevice.resource_name, **extras)
except:
logger.error("Visa ResourceManager cannot open resource : %s" %self._device.visadevice.resource_name)
return False
logger.debug('connected visa device')
return True | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"not",
"driver_ok",
":",
"logger",
".",
"error",
"(",
"\"Visa driver NOT ok\"",
")",
"return",
"False",
"visa_backend",
"=",
"'@py'",
"# use PyVISA-py as backend",
"if",
"hasattr",
"(",
"settings",
",",
"'VISA_BACKE... | establish a connection to the Instrument | [
"establish",
"a",
"connection",
"to",
"the",
"Instrument"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/visa/devices/__init__.py#L26-L54 | train | 200,037 |
trombastic/PyScada | pyscada/utils/__init__.py | decode_bcd | def decode_bcd(values):
"""
decode bcd as int to dec
"""
bin_str_out = ''
if isinstance(values, integer_types):
bin_str_out = bin(values)[2:].zfill(16)
bin_str_out = bin_str_out[::-1]
else:
for value in values:
bin_str = bin(value)[2:].zfill(16)
bin_str = bin_str[::-1]
bin_str_out = bin_str + bin_str_out
dec_num = 0
for i in range(len(bin_str_out) / 4):
bcd_num = int(bin_str_out[(i * 4):(i + 1) * 4][::-1], 2)
if bcd_num > 9:
dec_num = -dec_num
else:
dec_num = dec_num + (bcd_num * pow(10, i))
return dec_num | python | def decode_bcd(values):
"""
decode bcd as int to dec
"""
bin_str_out = ''
if isinstance(values, integer_types):
bin_str_out = bin(values)[2:].zfill(16)
bin_str_out = bin_str_out[::-1]
else:
for value in values:
bin_str = bin(value)[2:].zfill(16)
bin_str = bin_str[::-1]
bin_str_out = bin_str + bin_str_out
dec_num = 0
for i in range(len(bin_str_out) / 4):
bcd_num = int(bin_str_out[(i * 4):(i + 1) * 4][::-1], 2)
if bcd_num > 9:
dec_num = -dec_num
else:
dec_num = dec_num + (bcd_num * pow(10, i))
return dec_num | [
"def",
"decode_bcd",
"(",
"values",
")",
":",
"bin_str_out",
"=",
"''",
"if",
"isinstance",
"(",
"values",
",",
"integer_types",
")",
":",
"bin_str_out",
"=",
"bin",
"(",
"values",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"16",
")",
"bin_str_out",
... | decode bcd as int to dec | [
"decode",
"bcd",
"as",
"int",
"to",
"dec"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/__init__.py#L25-L47 | train | 200,038 |
trombastic/PyScada | pyscada/modbus/device.py | find_gap | def find_gap(l, value):
"""
try to find a address gap in the list of modbus registers
"""
for index in range(len(l)):
if l[index] == value:
return None
if l[index] > value:
return index | python | def find_gap(l, value):
"""
try to find a address gap in the list of modbus registers
"""
for index in range(len(l)):
if l[index] == value:
return None
if l[index] > value:
return index | [
"def",
"find_gap",
"(",
"l",
",",
"value",
")",
":",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"l",
")",
")",
":",
"if",
"l",
"[",
"index",
"]",
"==",
"value",
":",
"return",
"None",
"if",
"l",
"[",
"index",
"]",
">",
"value",
":",
"ret... | try to find a address gap in the list of modbus registers | [
"try",
"to",
"find",
"a",
"address",
"gap",
"in",
"the",
"list",
"of",
"modbus",
"registers"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/modbus/device.py#L25-L33 | train | 200,039 |
trombastic/PyScada | pyscada/modbus/device.py | Device.write_data | def write_data(self, variable_id, value, task):
"""
write value to single modbus register or coil
"""
if variable_id not in self.variables:
return False
if not self.variables[variable_id].writeable:
return False
if self.variables[variable_id].modbusvariable.function_code_read == 3:
# write register
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
if self.variables[variable_id].get_bits_by_class() / 16 == 1:
# just write the value to one register
self.slave.write_register(self.variables[variable_id].modbusvariable.address, int(value),
unit=self._unit_id)
else:
# encode it first
self.slave.write_registers(self.variables[variable_id].modbusvariable.address,
list(self.variables[variable_id].encode_value(value)),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
return False
elif self.variables[variable_id].modbusvariable.function_code_read == 1:
# write coil
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
self.slave.write_coil(self.variables[variable_id].modbusvariable.address, bool(value),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
else:
logger.error('wrong type of function code %d' %
self.variables[variable_id].modbusvariable.function_code_read)
return False | python | def write_data(self, variable_id, value, task):
"""
write value to single modbus register or coil
"""
if variable_id not in self.variables:
return False
if not self.variables[variable_id].writeable:
return False
if self.variables[variable_id].modbusvariable.function_code_read == 3:
# write register
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
if self.variables[variable_id].get_bits_by_class() / 16 == 1:
# just write the value to one register
self.slave.write_register(self.variables[variable_id].modbusvariable.address, int(value),
unit=self._unit_id)
else:
# encode it first
self.slave.write_registers(self.variables[variable_id].modbusvariable.address,
list(self.variables[variable_id].encode_value(value)),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
return False
elif self.variables[variable_id].modbusvariable.function_code_read == 1:
# write coil
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
self.slave.write_coil(self.variables[variable_id].modbusvariable.address, bool(value),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
else:
logger.error('wrong type of function code %d' %
self.variables[variable_id].modbusvariable.function_code_read)
return False | [
"def",
"write_data",
"(",
"self",
",",
"variable_id",
",",
"value",
",",
"task",
")",
":",
"if",
"variable_id",
"not",
"in",
"self",
".",
"variables",
":",
"return",
"False",
"if",
"not",
"self",
".",
"variables",
"[",
"variable_id",
"]",
".",
"writeable... | write value to single modbus register or coil | [
"write",
"value",
"to",
"single",
"modbus",
"register",
"or",
"coil"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/modbus/device.py#L335-L383 | train | 200,040 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.demonize | def demonize(self):
"""
do the double fork magic
"""
# check if a process is already running
if access(self.pid_file_name, F_OK):
# read the pid file
pid = self.read_pid()
try:
kill(pid, 0) # check if process is running
self.stderr.write("process is already running\n")
return False
except OSError as e:
if e.errno == errno.ESRCH:
# process is dead
self.delete_pid(force_del=True)
else:
self.stderr.write("demonize failed, something went wrong: %d (%s)\n" % (e.errno, e.strerror))
return False
try:
pid = fork()
if pid > 0:
# Exit from the first parent
timeout = time() + 60
while self.read_pid() is None:
self.stderr.write("waiting for pid..\n")
sleep(0.5)
if time() > timeout:
break
self.stderr.write("pid is %d\n" % self.read_pid())
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 1. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment
# os.chdir("/")
setsid()
umask(0)
# Do the Second fork
try:
pid = fork()
if pid > 0:
# Exit from the second parent
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 2. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
# sys.stdout.flush()
# sys.stderr.flush()
# si = file(self.stdin, 'r')
# so = file(self.stdout, 'a+')
# se = file(self.stderr, 'a+',
# os.dup2(si.fileno(), sys.stdin.fileno())
# os.dup2(so.fileno(), sys.stdout.fileno())
# os.dup2(se.fileno(), sys.stderr.fileno())
# Write the PID file
#atexit.register(self.delete_pid)
self.write_pid()
return True | python | def demonize(self):
"""
do the double fork magic
"""
# check if a process is already running
if access(self.pid_file_name, F_OK):
# read the pid file
pid = self.read_pid()
try:
kill(pid, 0) # check if process is running
self.stderr.write("process is already running\n")
return False
except OSError as e:
if e.errno == errno.ESRCH:
# process is dead
self.delete_pid(force_del=True)
else:
self.stderr.write("demonize failed, something went wrong: %d (%s)\n" % (e.errno, e.strerror))
return False
try:
pid = fork()
if pid > 0:
# Exit from the first parent
timeout = time() + 60
while self.read_pid() is None:
self.stderr.write("waiting for pid..\n")
sleep(0.5)
if time() > timeout:
break
self.stderr.write("pid is %d\n" % self.read_pid())
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 1. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment
# os.chdir("/")
setsid()
umask(0)
# Do the Second fork
try:
pid = fork()
if pid > 0:
# Exit from the second parent
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 2. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
# sys.stdout.flush()
# sys.stderr.flush()
# si = file(self.stdin, 'r')
# so = file(self.stdout, 'a+')
# se = file(self.stderr, 'a+',
# os.dup2(si.fileno(), sys.stdin.fileno())
# os.dup2(so.fileno(), sys.stdout.fileno())
# os.dup2(se.fileno(), sys.stderr.fileno())
# Write the PID file
#atexit.register(self.delete_pid)
self.write_pid()
return True | [
"def",
"demonize",
"(",
"self",
")",
":",
"# check if a process is already running",
"if",
"access",
"(",
"self",
".",
"pid_file_name",
",",
"F_OK",
")",
":",
"# read the pid file",
"pid",
"=",
"self",
".",
"read_pid",
"(",
")",
"try",
":",
"kill",
"(",
"pid... | do the double fork magic | [
"do",
"the",
"double",
"fork",
"magic"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L142-L207 | train | 200,041 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.delete_pid | def delete_pid(self, force_del=False):
"""
delete the pid file
"""
pid = self.read_pid()
if pid != getpid() or force_del:
logger.debug('process %d tried to delete pid' % getpid())
return False
if access(self.pid_file_name, F_OK):
try:
remove(self.pid_file_name) # remove the old pid file
logger.debug('delete pid (%d)' % getpid())
except:
logger.debug("can't delete pid file") | python | def delete_pid(self, force_del=False):
"""
delete the pid file
"""
pid = self.read_pid()
if pid != getpid() or force_del:
logger.debug('process %d tried to delete pid' % getpid())
return False
if access(self.pid_file_name, F_OK):
try:
remove(self.pid_file_name) # remove the old pid file
logger.debug('delete pid (%d)' % getpid())
except:
logger.debug("can't delete pid file") | [
"def",
"delete_pid",
"(",
"self",
",",
"force_del",
"=",
"False",
")",
":",
"pid",
"=",
"self",
".",
"read_pid",
"(",
")",
"if",
"pid",
"!=",
"getpid",
"(",
")",
"or",
"force_del",
":",
"logger",
".",
"debug",
"(",
"'process %d tried to delete pid'",
"%"... | delete the pid file | [
"delete",
"the",
"pid",
"file"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L224-L238 | train | 200,042 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.start | def start(self):
"""
start the scheduler
"""
# demonize
if self.run_as_daemon:
if not self.demonize():
self.delete_pid()
sys.exit(0)
# recreate the DB connection
if connection.connection is not None:
connection.connection.close()
connection.connection = None
master_process = BackgroundProcess.objects.filter(parent_process__isnull=True,
label=self.label,
enabled=True).first()
self.pid = getpid()
if not master_process:
self.delete_pid(force_del=True)
logger.debug('no such process in BackgroundProcesses\n')
sys.exit(0)
self.process_id = master_process.pk
master_process.pid = self.pid
master_process.last_update = now()
master_process.running_since = now()
master_process.done = False
master_process.failed = False
master_process.message = 'init master process'
master_process.save()
BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False).update(message='stopped')
for parent_process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False):
for process in BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False):
try:
kill(process.pid, 0)
except OSError as e:
if e.errno == errno.ESRCH:
process.delete()
continue
logger.debug('process %d is alive' % process.pk)
process.stop()
# clean up
BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False).delete()
# register signals
[signal.signal(s, self.signal) for s in self.SIGNALS]
#signal.signal(signal.SIGCHLD, self.handle_chld)
# start the main loop
self.run()
self.delete_pid()
sys.exit(0) | python | def start(self):
"""
start the scheduler
"""
# demonize
if self.run_as_daemon:
if not self.demonize():
self.delete_pid()
sys.exit(0)
# recreate the DB connection
if connection.connection is not None:
connection.connection.close()
connection.connection = None
master_process = BackgroundProcess.objects.filter(parent_process__isnull=True,
label=self.label,
enabled=True).first()
self.pid = getpid()
if not master_process:
self.delete_pid(force_del=True)
logger.debug('no such process in BackgroundProcesses\n')
sys.exit(0)
self.process_id = master_process.pk
master_process.pid = self.pid
master_process.last_update = now()
master_process.running_since = now()
master_process.done = False
master_process.failed = False
master_process.message = 'init master process'
master_process.save()
BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False).update(message='stopped')
for parent_process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False):
for process in BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False):
try:
kill(process.pid, 0)
except OSError as e:
if e.errno == errno.ESRCH:
process.delete()
continue
logger.debug('process %d is alive' % process.pk)
process.stop()
# clean up
BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False).delete()
# register signals
[signal.signal(s, self.signal) for s in self.SIGNALS]
#signal.signal(signal.SIGCHLD, self.handle_chld)
# start the main loop
self.run()
self.delete_pid()
sys.exit(0) | [
"def",
"start",
"(",
"self",
")",
":",
"# demonize",
"if",
"self",
".",
"run_as_daemon",
":",
"if",
"not",
"self",
".",
"demonize",
"(",
")",
":",
"self",
".",
"delete_pid",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"# recreate the DB connection",
... | start the scheduler | [
"start",
"the",
"scheduler"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L240-L291 | train | 200,043 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.run | def run(self):
"""
the main loop
"""
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
master_process.save()
else:
self.delete_pid(force_del=True)
self.stderr.write("no such process in BackgroundProcesses")
sys.exit(0)
self.manage_processes()
while True:
# handle signals
sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None
# check the DB connection
check_db_connection()
# update the P
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='running..')
if sig is None:
self.manage_processes()
elif sig not in self.SIGNALS:
logger.error('%s, unhandled signal %d' % (self.label, sig))
continue
elif sig == signal.SIGTERM:
logger.debug('%s, termination signal' % self.label)
raise StopIteration
elif sig == signal.SIGHUP:
# todo handle sighup
pass
elif sig == signal.SIGUSR1:
# restart all child processes
logger.debug('PID %d, processed SIGUSR1 (%d) signal' % (self.pid, sig))
self.restart()
elif sig == signal.SIGUSR2:
# write the process status to stdout
self.status()
pass
sleep(5)
except StopIteration:
self.stop()
self.delete_pid()
sys.exit(0)
except SystemExit:
raise
except:
logger.error('%s(%d), unhandled exception\n%s' % (self.label, getpid(), traceback.format_exc())) | python | def run(self):
"""
the main loop
"""
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
master_process.save()
else:
self.delete_pid(force_del=True)
self.stderr.write("no such process in BackgroundProcesses")
sys.exit(0)
self.manage_processes()
while True:
# handle signals
sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None
# check the DB connection
check_db_connection()
# update the P
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='running..')
if sig is None:
self.manage_processes()
elif sig not in self.SIGNALS:
logger.error('%s, unhandled signal %d' % (self.label, sig))
continue
elif sig == signal.SIGTERM:
logger.debug('%s, termination signal' % self.label)
raise StopIteration
elif sig == signal.SIGHUP:
# todo handle sighup
pass
elif sig == signal.SIGUSR1:
# restart all child processes
logger.debug('PID %d, processed SIGUSR1 (%d) signal' % (self.pid, sig))
self.restart()
elif sig == signal.SIGUSR2:
# write the process status to stdout
self.status()
pass
sleep(5)
except StopIteration:
self.stop()
self.delete_pid()
sys.exit(0)
except SystemExit:
raise
except:
logger.error('%s(%d), unhandled exception\n%s' % (self.label, getpid(), traceback.format_exc())) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"master_process",
"=",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"first",
"(",
")",
"if",
"master_process",
":",
"master_process",
".",
"last_... | the main loop | [
"the",
"main",
"loop"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L293-L347 | train | 200,044 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.restart | def restart(self):
"""
restart all child processes
"""
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='restarting..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
sleep(0.1)
self.kill_processes(signal.SIGKILL)
self.manage_processes()
logger.debug('BD %d: restarted'%self.process_id) | python | def restart(self):
"""
restart all child processes
"""
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='restarting..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
sleep(0.1)
self.kill_processes(signal.SIGKILL)
self.manage_processes()
logger.debug('BD %d: restarted'%self.process_id) | [
"def",
"restart",
"(",
"self",
")",
":",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"update",
"(",
"last_update",
"=",
"now",
"(",
")",
",",
"message",
"=",
"'restarting..'",
")",
"timeout",
... | restart all child processes | [
"restart",
"all",
"child",
"processes"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L428-L441 | train | 200,045 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.stop | def stop(self, sig=signal.SIGTERM):
"""
stop the scheduler and stop all processes
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
logger.error("can't determine process id exiting.")
return False
if self.pid != getpid():
# calling from outside the daemon instance
logger.debug('send sigterm to daemon')
try:
kill(self.pid, sig)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
logger.debug('start termination of the daemon')
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopping..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
self.kill_processes(signal.SIGTERM)
sleep(1)
self.kill_processes(signal.SIGKILL)
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopped')
logger.debug('termination of the daemon done')
return True | python | def stop(self, sig=signal.SIGTERM):
"""
stop the scheduler and stop all processes
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
logger.error("can't determine process id exiting.")
return False
if self.pid != getpid():
# calling from outside the daemon instance
logger.debug('send sigterm to daemon')
try:
kill(self.pid, sig)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
logger.debug('start termination of the daemon')
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopping..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
self.kill_processes(signal.SIGTERM)
sleep(1)
self.kill_processes(signal.SIGKILL)
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopped')
logger.debug('termination of the daemon done')
return True | [
"def",
"stop",
"(",
"self",
",",
"sig",
"=",
"signal",
".",
"SIGTERM",
")",
":",
"if",
"self",
".",
"pid",
"is",
"None",
":",
"self",
".",
"pid",
"=",
"self",
".",
"read_pid",
"(",
")",
"if",
"self",
".",
"pid",
"is",
"None",
":",
"sp",
"=",
... | stop the scheduler and stop all processes | [
"stop",
"the",
"scheduler",
"and",
"stop",
"all",
"processes"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L443-L484 | train | 200,046 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.spawn_process | def spawn_process(self, process=None):
"""
spawn a new process
"""
if process is None:
return False
# start new child process
pid = fork()
if pid != 0:
# parent process
process.pid = pid
self.PROCESSES[process.process_id] = process
connections.close_all()
return True
# child process
process.pid = getpid()
# connection.connection.close()
# connection.connection = None
process.pre_init_process()
process.init_process()
process.run()
sys.exit(0) | python | def spawn_process(self, process=None):
"""
spawn a new process
"""
if process is None:
return False
# start new child process
pid = fork()
if pid != 0:
# parent process
process.pid = pid
self.PROCESSES[process.process_id] = process
connections.close_all()
return True
# child process
process.pid = getpid()
# connection.connection.close()
# connection.connection = None
process.pre_init_process()
process.init_process()
process.run()
sys.exit(0) | [
"def",
"spawn_process",
"(",
"self",
",",
"process",
"=",
"None",
")",
":",
"if",
"process",
"is",
"None",
":",
"return",
"False",
"# start new child process",
"pid",
"=",
"fork",
"(",
")",
"if",
"pid",
"!=",
"0",
":",
"# parent process",
"process",
".",
... | spawn a new process | [
"spawn",
"a",
"new",
"process"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L520-L541 | train | 200,047 |
trombastic/PyScada | pyscada/utils/scheduler.py | Scheduler.status | def status(self):
"""
write the current daemon status to stdout
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
return False
if self.pid != getpid():
# calling from outside the daemon instance
try:
kill(self.pid, signal.SIGUSR2)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
process_list = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
process_list.append(process)
process_list += list(process.backgroundprocess_set.filter())
for process in process_list:
logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
logger.debug('%s, process_id %d' % (self.label, self.process_id)) | python | def status(self):
"""
write the current daemon status to stdout
"""
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
return False
if self.pid != getpid():
# calling from outside the daemon instance
try:
kill(self.pid, signal.SIGUSR2)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
process_list = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
process_list.append(process)
process_list += list(process.backgroundprocess_set.filter())
for process in process_list:
logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
logger.debug('%s, process_id %d' % (self.label, self.process_id)) | [
"def",
"status",
"(",
"self",
")",
":",
"if",
"self",
".",
"pid",
"is",
"None",
":",
"self",
".",
"pid",
"=",
"self",
".",
"read_pid",
"(",
")",
"if",
"self",
".",
"pid",
"is",
"None",
":",
"sp",
"=",
"BackgroundProcess",
".",
"objects",
".",
"fi... | write the current daemon status to stdout | [
"write",
"the",
"current",
"daemon",
"status",
"to",
"stdout"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L543-L574 | train | 200,048 |
trombastic/PyScada | pyscada/utils/scheduler.py | Process.pre_init_process | def pre_init_process(self):
"""
will be executed after process fork
"""
db.connections.close_all()
# update process info
BackgroundProcess.objects.filter(pk=self.process_id).update(
pid=self.pid,
last_update=now(),
running_since=now(),
done=False,
failed=False,
message='init process..',
)
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS] # reset
[signal.signal(s, self.signal) for s in self.SIGNALS] | python | def pre_init_process(self):
"""
will be executed after process fork
"""
db.connections.close_all()
# update process info
BackgroundProcess.objects.filter(pk=self.process_id).update(
pid=self.pid,
last_update=now(),
running_since=now(),
done=False,
failed=False,
message='init process..',
)
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS] # reset
[signal.signal(s, self.signal) for s in self.SIGNALS] | [
"def",
"pre_init_process",
"(",
"self",
")",
":",
"db",
".",
"connections",
".",
"close_all",
"(",
")",
"# update process info",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"update",
"(",
"pid",
... | will be executed after process fork | [
"will",
"be",
"executed",
"after",
"process",
"fork"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L598-L614 | train | 200,049 |
trombastic/PyScada | pyscada/utils/scheduler.py | Process.stop | def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
BackgroundProcess.objects.filter(pk=self.process_id).update(pid=0,
last_update=now(),
message='stopped') | python | def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
BackgroundProcess.objects.filter(pk=self.process_id).update(pid=0,
last_update=now(),
message='stopped') | [
"def",
"stop",
"(",
"self",
",",
"signum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"BackgroundProcess",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"self",
".",
"process_id",
")",
".",
"update",
"(",
"pid",
"=",
"0",
",",
"last_update",
... | handel's a termination signal | [
"handel",
"s",
"a",
"termination",
"signal"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L709-L719 | train | 200,050 |
trombastic/PyScada | pyscada/utils/scheduler.py | SingleDeviceDAQProcess.init_process | def init_process(self):
"""
init a standard daq process for a single device
"""
self.device = Device.objects.filter(protocol__daq_daemon=1, active=1, id=self.device_id).first()
if not self.device:
logger.error("Error init_process for %s" % self.device_id)
return False
self.dt_set = min(self.dt_set, self.device.polling_interval)
self.dt_query_data = self.device.polling_interval
try:
self.device = self.device.get_device_instance()
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
self.device_id, linesep, var))
return True | python | def init_process(self):
"""
init a standard daq process for a single device
"""
self.device = Device.objects.filter(protocol__daq_daemon=1, active=1, id=self.device_id).first()
if not self.device:
logger.error("Error init_process for %s" % self.device_id)
return False
self.dt_set = min(self.dt_set, self.device.polling_interval)
self.dt_query_data = self.device.polling_interval
try:
self.device = self.device.get_device_instance()
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
self.device_id, linesep, var))
return True | [
"def",
"init_process",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"Device",
".",
"objects",
".",
"filter",
"(",
"protocol__daq_daemon",
"=",
"1",
",",
"active",
"=",
"1",
",",
"id",
"=",
"self",
".",
"device_id",
")",
".",
"first",
"(",
")",
... | init a standard daq process for a single device | [
"init",
"a",
"standard",
"daq",
"process",
"for",
"a",
"single",
"device"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L736-L753 | train | 200,051 |
trombastic/PyScada | pyscada/utils/scheduler.py | MultiDeviceDAQProcess.init_process | def init_process(self):
"""
init a standard daq process for multiple devices
"""
for item in Device.objects.filter(protocol__daq_daemon=1, active=1, id__in=self.device_ids):
try:
tmp_device = item.get_device_instance()
if tmp_device is not None:
self.devices[item.pk] = tmp_device
self.dt_set = min(self.dt_set, item.polling_interval)
self.dt_query_data = min(self.dt_query_data, item.polling_interval)
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
item.pk, linesep, var))
return True | python | def init_process(self):
"""
init a standard daq process for multiple devices
"""
for item in Device.objects.filter(protocol__daq_daemon=1, active=1, id__in=self.device_ids):
try:
tmp_device = item.get_device_instance()
if tmp_device is not None:
self.devices[item.pk] = tmp_device
self.dt_set = min(self.dt_set, item.polling_interval)
self.dt_query_data = min(self.dt_query_data, item.polling_interval)
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
item.pk, linesep, var))
return True | [
"def",
"init_process",
"(",
"self",
")",
":",
"for",
"item",
"in",
"Device",
".",
"objects",
".",
"filter",
"(",
"protocol__daq_daemon",
"=",
"1",
",",
"active",
"=",
"1",
",",
"id__in",
"=",
"self",
".",
"device_ids",
")",
":",
"try",
":",
"tmp_device... | init a standard daq process for multiple devices | [
"init",
"a",
"standard",
"daq",
"process",
"for",
"multiple",
"devices"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/utils/scheduler.py#L818-L835 | train | 200,052 |
trombastic/PyScada | pyscada/hmi/signals.py | _delete_widget_content | def _delete_widget_content(sender, instance, **kwargs):
"""
delete the widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return
# delete WidgetContent Entry
wcs = WidgetContent.objects.filter(
content_pk=instance.pk,
content_model=('%s' % instance.__class__).replace("<class '", '').replace("'>", ''))
for wc in wcs:
logger.debug('delete wc %r'%wc)
wc.delete() | python | def _delete_widget_content(sender, instance, **kwargs):
"""
delete the widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return
# delete WidgetContent Entry
wcs = WidgetContent.objects.filter(
content_pk=instance.pk,
content_model=('%s' % instance.__class__).replace("<class '", '').replace("'>", ''))
for wc in wcs:
logger.debug('delete wc %r'%wc)
wc.delete() | [
"def",
"_delete_widget_content",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"issubclass",
"(",
"sender",
",",
"WidgetContentModel",
")",
":",
"return",
"# delete WidgetContent Entry",
"wcs",
"=",
"WidgetContent",
".",
"object... | delete the widget content instance when a WidgetContentModel is deleted | [
"delete",
"the",
"widget",
"content",
"instance",
"when",
"a",
"WidgetContentModel",
"is",
"deleted"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/hmi/signals.py#L15-L28 | train | 200,053 |
trombastic/PyScada | pyscada/hmi/signals.py | _create_widget_content | def _create_widget_content(sender, instance, created=False, **kwargs):
"""
create a widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return
# create a WidgetContent Entry
if created:
instance.create_widget_content_entry()
return | python | def _create_widget_content(sender, instance, created=False, **kwargs):
"""
create a widget content instance when a WidgetContentModel is deleted
"""
if not issubclass(sender, WidgetContentModel):
return
# create a WidgetContent Entry
if created:
instance.create_widget_content_entry()
return | [
"def",
"_create_widget_content",
"(",
"sender",
",",
"instance",
",",
"created",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"issubclass",
"(",
"sender",
",",
"WidgetContentModel",
")",
":",
"return",
"# create a WidgetContent Entry",
"if",
"... | create a widget content instance when a WidgetContentModel is deleted | [
"create",
"a",
"widget",
"content",
"instance",
"when",
"a",
"WidgetContentModel",
"is",
"deleted"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/hmi/signals.py#L32-L42 | train | 200,054 |
trombastic/PyScada | pyscada/export/export.py | _cast_value | def _cast_value(value, _type):
"""
cast value to _type
"""
if _type.upper() == 'FLOAT64':
return float64(value)
elif _type.upper() == 'FLOAT32':
return float32(value)
elif _type.upper() == 'INT32':
return int32(value)
elif _type.upper() == 'UINT16':
return uint16(value)
elif _type.upper() == 'INT16':
return int16(value)
elif _type.upper() == 'BOOLEAN':
return uint8(value)
else:
return float64(value) | python | def _cast_value(value, _type):
"""
cast value to _type
"""
if _type.upper() == 'FLOAT64':
return float64(value)
elif _type.upper() == 'FLOAT32':
return float32(value)
elif _type.upper() == 'INT32':
return int32(value)
elif _type.upper() == 'UINT16':
return uint16(value)
elif _type.upper() == 'INT16':
return int16(value)
elif _type.upper() == 'BOOLEAN':
return uint8(value)
else:
return float64(value) | [
"def",
"_cast_value",
"(",
"value",
",",
"_type",
")",
":",
"if",
"_type",
".",
"upper",
"(",
")",
"==",
"'FLOAT64'",
":",
"return",
"float64",
"(",
"value",
")",
"elif",
"_type",
".",
"upper",
"(",
")",
"==",
"'FLOAT32'",
":",
"return",
"float32",
"... | cast value to _type | [
"cast",
"value",
"to",
"_type"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/export/export.py#L310-L327 | train | 200,055 |
trombastic/PyScada | pyscada/mail/worker.py | Process.loop | def loop(self):
"""
check for mails and send them
"""
for mail in Mail.objects.filter(done=False, send_fail_count__lt=3):
# send all emails that are not already send or failed to send less
# then three times
mail.send_mail()
for mail in Mail.objects.filter(done=True, timestamp__lt=time() - 60 * 60 * 24 * 7):
# delete all done emails older then one week
mail.delete()
return 1, None | python | def loop(self):
"""
check for mails and send them
"""
for mail in Mail.objects.filter(done=False, send_fail_count__lt=3):
# send all emails that are not already send or failed to send less
# then three times
mail.send_mail()
for mail in Mail.objects.filter(done=True, timestamp__lt=time() - 60 * 60 * 24 * 7):
# delete all done emails older then one week
mail.delete()
return 1, None | [
"def",
"loop",
"(",
"self",
")",
":",
"for",
"mail",
"in",
"Mail",
".",
"objects",
".",
"filter",
"(",
"done",
"=",
"False",
",",
"send_fail_count__lt",
"=",
"3",
")",
":",
"# send all emails that are not already send or failed to send less",
"# then three times",
... | check for mails and send them | [
"check",
"for",
"mails",
"and",
"send",
"them"
] | c5fc348a25f0df1340336f694ee9bc1aea62516a | https://github.com/trombastic/PyScada/blob/c5fc348a25f0df1340336f694ee9bc1aea62516a/pyscada/mail/worker.py#L18-L30 | train | 200,056 |
marcharper/python-ternary | ternary/helpers.py | normalize | def normalize(l):
"""
Normalizes input list.
Parameters
----------
l: list
The list to be normalized
Returns
-------
The normalized list or numpy array
Raises
------
ValueError, if the list sums to zero
"""
s = float(sum(l))
if s == 0:
raise ValueError("Cannot normalize list with sum 0")
return [x / s for x in l] | python | def normalize(l):
"""
Normalizes input list.
Parameters
----------
l: list
The list to be normalized
Returns
-------
The normalized list or numpy array
Raises
------
ValueError, if the list sums to zero
"""
s = float(sum(l))
if s == 0:
raise ValueError("Cannot normalize list with sum 0")
return [x / s for x in l] | [
"def",
"normalize",
"(",
"l",
")",
":",
"s",
"=",
"float",
"(",
"sum",
"(",
"l",
")",
")",
"if",
"s",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot normalize list with sum 0\"",
")",
"return",
"[",
"x",
"/",
"s",
"for",
"x",
"in",
"l",
"]"
... | Normalizes input list.
Parameters
----------
l: list
The list to be normalized
Returns
-------
The normalized list or numpy array
Raises
------
ValueError, if the list sums to zero | [
"Normalizes",
"input",
"list",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L21-L42 | train | 200,057 |
marcharper/python-ternary | ternary/helpers.py | simplex_iterator | def simplex_iterator(scale, boundary=True):
"""
Systematically iterates through a lattice of points on the 2-simplex.
Parameters
----------
scale: Int
The normalized scale of the simplex, i.e. N such that points (x,y,z)
satisify x + y + z == N
boundary: bool, True
Include the boundary points (tuples where at least one
coordinate is zero)
Yields
------
3-tuples, There are binom(n+2, 2) points (the triangular
number for scale + 1, less 3*(scale+1) if boundary=False
"""
start = 0
if not boundary:
start = 1
for i in range(start, scale + (1 - start)):
for j in range(start, scale + (1 - start) - i):
k = scale - i - j
yield (i, j, k) | python | def simplex_iterator(scale, boundary=True):
"""
Systematically iterates through a lattice of points on the 2-simplex.
Parameters
----------
scale: Int
The normalized scale of the simplex, i.e. N such that points (x,y,z)
satisify x + y + z == N
boundary: bool, True
Include the boundary points (tuples where at least one
coordinate is zero)
Yields
------
3-tuples, There are binom(n+2, 2) points (the triangular
number for scale + 1, less 3*(scale+1) if boundary=False
"""
start = 0
if not boundary:
start = 1
for i in range(start, scale + (1 - start)):
for j in range(start, scale + (1 - start) - i):
k = scale - i - j
yield (i, j, k) | [
"def",
"simplex_iterator",
"(",
"scale",
",",
"boundary",
"=",
"True",
")",
":",
"start",
"=",
"0",
"if",
"not",
"boundary",
":",
"start",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"scale",
"+",
"(",
"1",
"-",
"start",
")",
")",
":"... | Systematically iterates through a lattice of points on the 2-simplex.
Parameters
----------
scale: Int
The normalized scale of the simplex, i.e. N such that points (x,y,z)
satisify x + y + z == N
boundary: bool, True
Include the boundary points (tuples where at least one
coordinate is zero)
Yields
------
3-tuples, There are binom(n+2, 2) points (the triangular
number for scale + 1, less 3*(scale+1) if boundary=False | [
"Systematically",
"iterates",
"through",
"a",
"lattice",
"of",
"points",
"on",
"the",
"2",
"-",
"simplex",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L45-L71 | train | 200,058 |
marcharper/python-ternary | ternary/helpers.py | permute_point | def permute_point(p, permutation=None):
"""
Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201"."""
if not permutation:
return p
return [p[int(permutation[i])] for i in range(len(p))] | python | def permute_point(p, permutation=None):
"""
Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201"."""
if not permutation:
return p
return [p[int(permutation[i])] for i in range(len(p))] | [
"def",
"permute_point",
"(",
"p",
",",
"permutation",
"=",
"None",
")",
":",
"if",
"not",
"permutation",
":",
"return",
"p",
"return",
"[",
"p",
"[",
"int",
"(",
"permutation",
"[",
"i",
"]",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
... | Permutes the point according to the permutation keyword argument. The
default permutation is "012" which does not change the order of the
coordinate. To rotate counterclockwise, use "120" and to rotate clockwise
use "201". | [
"Permutes",
"the",
"point",
"according",
"to",
"the",
"permutation",
"keyword",
"argument",
".",
"The",
"default",
"permutation",
"is",
"012",
"which",
"does",
"not",
"change",
"the",
"order",
"of",
"the",
"coordinate",
".",
"To",
"rotate",
"counterclockwise",
... | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L76-L84 | train | 200,059 |
marcharper/python-ternary | ternary/helpers.py | project_sequence | def project_sequence(s, permutation=None):
"""
Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The sequence of projected points in coordinates as two lists
"""
xs, ys = unzip([project_point(p, permutation=permutation) for p in s])
return xs, ys | python | def project_sequence(s, permutation=None):
"""
Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The sequence of projected points in coordinates as two lists
"""
xs, ys = unzip([project_point(p, permutation=permutation) for p in s])
return xs, ys | [
"def",
"project_sequence",
"(",
"s",
",",
"permutation",
"=",
"None",
")",
":",
"xs",
",",
"ys",
"=",
"unzip",
"(",
"[",
"project_point",
"(",
"p",
",",
"permutation",
"=",
"permutation",
")",
"for",
"p",
"in",
"s",
"]",
")",
"return",
"xs",
",",
"... | Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The sequence of projected points in coordinates as two lists | [
"Projects",
"a",
"point",
"or",
"sequence",
"of",
"points",
"using",
"project_point",
"to",
"lists",
"xs",
"ys",
"for",
"plotting",
"with",
"Matplotlib",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L106-L122 | train | 200,060 |
marcharper/python-ternary | ternary/helpers.py | convert_coordinates | def convert_coordinates(q, conversion, axisorder):
"""
Convert a 3-tuple in data coordinates into to simplex data
coordinates for plotting.
Parameters
----------
q: 3-tuple
the point to be plotted in data coordinates
conversion: dict
keys = ['b','l','r']
values = lambda function giving the conversion
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
p: 3-tuple
The point converted to simplex coordinates.
"""
p = []
for k in range(3):
p.append(conversion[axisorder[k]](q[k]))
return tuple(p) | python | def convert_coordinates(q, conversion, axisorder):
"""
Convert a 3-tuple in data coordinates into to simplex data
coordinates for plotting.
Parameters
----------
q: 3-tuple
the point to be plotted in data coordinates
conversion: dict
keys = ['b','l','r']
values = lambda function giving the conversion
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
p: 3-tuple
The point converted to simplex coordinates.
"""
p = []
for k in range(3):
p.append(conversion[axisorder[k]](q[k]))
return tuple(p) | [
"def",
"convert_coordinates",
"(",
"q",
",",
"conversion",
",",
"axisorder",
")",
":",
"p",
"=",
"[",
"]",
"for",
"k",
"in",
"range",
"(",
"3",
")",
":",
"p",
".",
"append",
"(",
"conversion",
"[",
"axisorder",
"[",
"k",
"]",
"]",
"(",
"q",
"[",
... | Convert a 3-tuple in data coordinates into to simplex data
coordinates for plotting.
Parameters
----------
q: 3-tuple
the point to be plotted in data coordinates
conversion: dict
keys = ['b','l','r']
values = lambda function giving the conversion
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
p: 3-tuple
The point converted to simplex coordinates. | [
"Convert",
"a",
"3",
"-",
"tuple",
"in",
"data",
"coordinates",
"into",
"to",
"simplex",
"data",
"coordinates",
"for",
"plotting",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L127-L152 | train | 200,061 |
marcharper/python-ternary | ternary/helpers.py | get_conversion | def get_conversion(scale, limits):
"""
Get the conversion equations for each axis.
limits: dict of min and max values for the axes in the order blr.
"""
fb = float(scale) / float(limits['b'][1] - limits['b'][0])
fl = float(scale) / float(limits['l'][1] - limits['l'][0])
fr = float(scale) / float(limits['r'][1] - limits['r'][0])
conversion = {"b": lambda x: (x - limits['b'][0]) * fb,
"l": lambda x: (x - limits['l'][0]) * fl,
"r": lambda x: (x - limits['r'][0]) * fr}
return conversion | python | def get_conversion(scale, limits):
"""
Get the conversion equations for each axis.
limits: dict of min and max values for the axes in the order blr.
"""
fb = float(scale) / float(limits['b'][1] - limits['b'][0])
fl = float(scale) / float(limits['l'][1] - limits['l'][0])
fr = float(scale) / float(limits['r'][1] - limits['r'][0])
conversion = {"b": lambda x: (x - limits['b'][0]) * fb,
"l": lambda x: (x - limits['l'][0]) * fl,
"r": lambda x: (x - limits['r'][0]) * fr}
return conversion | [
"def",
"get_conversion",
"(",
"scale",
",",
"limits",
")",
":",
"fb",
"=",
"float",
"(",
"scale",
")",
"/",
"float",
"(",
"limits",
"[",
"'b'",
"]",
"[",
"1",
"]",
"-",
"limits",
"[",
"'b'",
"]",
"[",
"0",
"]",
")",
"fl",
"=",
"float",
"(",
"... | Get the conversion equations for each axis.
limits: dict of min and max values for the axes in the order blr. | [
"Get",
"the",
"conversion",
"equations",
"for",
"each",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L155-L169 | train | 200,062 |
marcharper/python-ternary | ternary/helpers.py | convert_coordinates_sequence | def convert_coordinates_sequence(qs, scale, limits, axisorder):
"""
Take a sequence of 3-tuples in data coordinates and convert them
to simplex coordinates for plotting. This is needed for custom
plots where the scale of the simplex axes is set within limits rather
than being defined by the scale parameter.
Parameters
----------
qs, sequence of 3-tuples
The points to be plotted in data coordinates.
scale: int
The scale parameter for the plot.
limits: dict
keys = ['b','l','r']
values = min,max data values for this axis.
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
s, list of 3-tuples
the points converted to simplex coordinates
"""
conversion = get_conversion(scale, limits)
return [convert_coordinates(q, conversion, axisorder) for q in qs] | python | def convert_coordinates_sequence(qs, scale, limits, axisorder):
"""
Take a sequence of 3-tuples in data coordinates and convert them
to simplex coordinates for plotting. This is needed for custom
plots where the scale of the simplex axes is set within limits rather
than being defined by the scale parameter.
Parameters
----------
qs, sequence of 3-tuples
The points to be plotted in data coordinates.
scale: int
The scale parameter for the plot.
limits: dict
keys = ['b','l','r']
values = min,max data values for this axis.
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
s, list of 3-tuples
the points converted to simplex coordinates
"""
conversion = get_conversion(scale, limits)
return [convert_coordinates(q, conversion, axisorder) for q in qs] | [
"def",
"convert_coordinates_sequence",
"(",
"qs",
",",
"scale",
",",
"limits",
",",
"axisorder",
")",
":",
"conversion",
"=",
"get_conversion",
"(",
"scale",
",",
"limits",
")",
"return",
"[",
"convert_coordinates",
"(",
"q",
",",
"conversion",
",",
"axisorder... | Take a sequence of 3-tuples in data coordinates and convert them
to simplex coordinates for plotting. This is needed for custom
plots where the scale of the simplex axes is set within limits rather
than being defined by the scale parameter.
Parameters
----------
qs, sequence of 3-tuples
The points to be plotted in data coordinates.
scale: int
The scale parameter for the plot.
limits: dict
keys = ['b','l','r']
values = min,max data values for this axis.
axisorder: String giving the order of the axes for the coordinate tuple
e.g. 'blr' for bottom, left, right coordinates.
Returns
-------
s, list of 3-tuples
the points converted to simplex coordinates | [
"Take",
"a",
"sequence",
"of",
"3",
"-",
"tuples",
"in",
"data",
"coordinates",
"and",
"convert",
"them",
"to",
"simplex",
"coordinates",
"for",
"plotting",
".",
"This",
"is",
"needed",
"for",
"custom",
"plots",
"where",
"the",
"scale",
"of",
"the",
"simpl... | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/helpers.py#L172-L199 | train | 200,063 |
marcharper/python-ternary | ternary/plotting.py | resize_drawing_canvas | def resize_drawing_canvas(ax, scale=1.):
"""
Makes sure the drawing surface is large enough to display projected
content.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float, 1.0
Simplex scale size.
"""
ax.set_ylim((-0.10 * scale, .90 * scale))
ax.set_xlim((-0.05 * scale, 1.05 * scale)) | python | def resize_drawing_canvas(ax, scale=1.):
"""
Makes sure the drawing surface is large enough to display projected
content.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float, 1.0
Simplex scale size.
"""
ax.set_ylim((-0.10 * scale, .90 * scale))
ax.set_xlim((-0.05 * scale, 1.05 * scale)) | [
"def",
"resize_drawing_canvas",
"(",
"ax",
",",
"scale",
"=",
"1.",
")",
":",
"ax",
".",
"set_ylim",
"(",
"(",
"-",
"0.10",
"*",
"scale",
",",
".90",
"*",
"scale",
")",
")",
"ax",
".",
"set_xlim",
"(",
"(",
"-",
"0.05",
"*",
"scale",
",",
"1.05",... | Makes sure the drawing surface is large enough to display projected
content.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float, 1.0
Simplex scale size. | [
"Makes",
"sure",
"the",
"drawing",
"surface",
"is",
"large",
"enough",
"to",
"display",
"projected",
"content",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/plotting.py#L15-L28 | train | 200,064 |
marcharper/python-ternary | ternary/plotting.py | clear_matplotlib_ticks | def clear_matplotlib_ticks(ax=None, axis="both"):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y" or "vertical", or "both"
"""
if not ax:
return
if axis.lower() in ["both", "x", "horizontal"]:
ax.set_xticks([], [])
if axis.lower() in ["both", "y", "vertical"]:
ax.set_yticks([], []) | python | def clear_matplotlib_ticks(ax=None, axis="both"):
"""
Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y" or "vertical", or "both"
"""
if not ax:
return
if axis.lower() in ["both", "x", "horizontal"]:
ax.set_xticks([], [])
if axis.lower() in ["both", "y", "vertical"]:
ax.set_yticks([], []) | [
"def",
"clear_matplotlib_ticks",
"(",
"ax",
"=",
"None",
",",
"axis",
"=",
"\"both\"",
")",
":",
"if",
"not",
"ax",
":",
"return",
"if",
"axis",
".",
"lower",
"(",
")",
"in",
"[",
"\"both\"",
",",
"\"x\"",
",",
"\"horizontal\"",
"]",
":",
"ax",
".",
... | Clears the default matplotlib axes, or the one specified by the axis
argument.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
axis: string, "both"
The axis to clear: "x" or "horizontal", "y" or "vertical", or "both" | [
"Clears",
"the",
"default",
"matplotlib",
"axes",
"or",
"the",
"one",
"specified",
"by",
"the",
"axis",
"argument",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/plotting.py#L31-L48 | train | 200,065 |
marcharper/python-ternary | ternary/plotting.py | scatter | def scatter(points, ax=None, permutation=None, colorbar=False, colormap=None,
vmin=0, vmax=1, scientific=False, cbarlabel=None, cb_kwargs=None,
**kwargs):
"""
Plots trajectory points where each point satisfies x + y + z = scale.
First argument is a list or numpy array of tuples of length 3.
Parameters
----------
points: List of 3-tuples
The list of tuples to be scatter-plotted.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
colorbar: bool, False
Show colorbar.
colormap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
vmin: int, 0
Minimum value for colorbar.
vmax: int, 1
Maximum value for colorbar.
cb_kwargs: dict
Any additional kwargs to pass to colorbar
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not ax:
fig, ax = pyplot.subplots()
xs, ys = project_sequence(points, permutation=permutation)
ax.scatter(xs, ys, vmin=vmin, vmax=vmax, **kwargs)
if colorbar and (colormap != None):
if cb_kwargs != None:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
else:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel)
return ax | python | def scatter(points, ax=None, permutation=None, colorbar=False, colormap=None,
vmin=0, vmax=1, scientific=False, cbarlabel=None, cb_kwargs=None,
**kwargs):
"""
Plots trajectory points where each point satisfies x + y + z = scale.
First argument is a list or numpy array of tuples of length 3.
Parameters
----------
points: List of 3-tuples
The list of tuples to be scatter-plotted.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
colorbar: bool, False
Show colorbar.
colormap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
vmin: int, 0
Minimum value for colorbar.
vmax: int, 1
Maximum value for colorbar.
cb_kwargs: dict
Any additional kwargs to pass to colorbar
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not ax:
fig, ax = pyplot.subplots()
xs, ys = project_sequence(points, permutation=permutation)
ax.scatter(xs, ys, vmin=vmin, vmax=vmax, **kwargs)
if colorbar and (colormap != None):
if cb_kwargs != None:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
else:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel)
return ax | [
"def",
"scatter",
"(",
"points",
",",
"ax",
"=",
"None",
",",
"permutation",
"=",
"None",
",",
"colorbar",
"=",
"False",
",",
"colormap",
"=",
"None",
",",
"vmin",
"=",
"0",
",",
"vmax",
"=",
"1",
",",
"scientific",
"=",
"False",
",",
"cbarlabel",
... | Plots trajectory points where each point satisfies x + y + z = scale.
First argument is a list or numpy array of tuples of length 3.
Parameters
----------
points: List of 3-tuples
The list of tuples to be scatter-plotted.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
colorbar: bool, False
Show colorbar.
colormap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
vmin: int, 0
Minimum value for colorbar.
vmax: int, 1
Maximum value for colorbar.
cb_kwargs: dict
Any additional kwargs to pass to colorbar
kwargs:
Any kwargs to pass through to matplotlib. | [
"Plots",
"trajectory",
"points",
"where",
"each",
"point",
"satisfies",
"x",
"+",
"y",
"+",
"z",
"=",
"scale",
".",
"First",
"argument",
"is",
"a",
"list",
"or",
"numpy",
"array",
"of",
"tuples",
"of",
"length",
"3",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/plotting.py#L119-L158 | train | 200,066 |
marcharper/python-ternary | examples/scatter_colorbar.py | _en_to_enth | def _en_to_enth(energy,concs,A,B,C):
"""Converts an energy to an enthalpy.
Converts energy to enthalpy using the following formula:
Enthalpy = energy - (energy contribution from A) - (energy contribution from B) -
(energy contribution from C)
An absolute value is taken afterward for convenience.
Parameters
----------
energy : float
The energy of the structure
concs : list of floats
The concentrations of each element
A : float
The energy of pure A
B : float
The energy of pure B
C : float
The energy of pure C
Returns
-------
enth : float
The enthalpy of formation.
"""
enth = abs(energy - concs[0]*A -concs[1]*B -concs[2]*C)
return enth | python | def _en_to_enth(energy,concs,A,B,C):
"""Converts an energy to an enthalpy.
Converts energy to enthalpy using the following formula:
Enthalpy = energy - (energy contribution from A) - (energy contribution from B) -
(energy contribution from C)
An absolute value is taken afterward for convenience.
Parameters
----------
energy : float
The energy of the structure
concs : list of floats
The concentrations of each element
A : float
The energy of pure A
B : float
The energy of pure B
C : float
The energy of pure C
Returns
-------
enth : float
The enthalpy of formation.
"""
enth = abs(energy - concs[0]*A -concs[1]*B -concs[2]*C)
return enth | [
"def",
"_en_to_enth",
"(",
"energy",
",",
"concs",
",",
"A",
",",
"B",
",",
"C",
")",
":",
"enth",
"=",
"abs",
"(",
"energy",
"-",
"concs",
"[",
"0",
"]",
"*",
"A",
"-",
"concs",
"[",
"1",
"]",
"*",
"B",
"-",
"concs",
"[",
"2",
"]",
"*",
... | Converts an energy to an enthalpy.
Converts energy to enthalpy using the following formula:
Enthalpy = energy - (energy contribution from A) - (energy contribution from B) -
(energy contribution from C)
An absolute value is taken afterward for convenience.
Parameters
----------
energy : float
The energy of the structure
concs : list of floats
The concentrations of each element
A : float
The energy of pure A
B : float
The energy of pure B
C : float
The energy of pure C
Returns
-------
enth : float
The enthalpy of formation. | [
"Converts",
"an",
"energy",
"to",
"an",
"enthalpy",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L6-L34 | train | 200,067 |
marcharper/python-ternary | examples/scatter_colorbar.py | _energy_to_enthalpy | def _energy_to_enthalpy(energy):
"""Converts energy to enthalpy.
This function take the energies stored in the energy array and
converts them to formation enthalpy.
Parameters
---------
energy : list of lists of floats
Returns
-------
enthalpy : list of lists containing the enthalpies.
"""
pureA = [energy[0][0],energy[0][1]]
pureB = [energy[1][0],energy[1][1]]
pureC = [energy[2][0],energy[2][1]]
enthalpy = []
for en in energy:
c = en[2]
conc = [float(i)/sum(c) for i in c]
CE = _en_to_enth(en[0],conc,pureA[0],pureB[0],pureC[0])
VASP = _en_to_enth(en[1],conc,pureA[1],pureB[1],pureC[1])
enthalpy.append([CE,VASP,c])
return enthalpy | python | def _energy_to_enthalpy(energy):
"""Converts energy to enthalpy.
This function take the energies stored in the energy array and
converts them to formation enthalpy.
Parameters
---------
energy : list of lists of floats
Returns
-------
enthalpy : list of lists containing the enthalpies.
"""
pureA = [energy[0][0],energy[0][1]]
pureB = [energy[1][0],energy[1][1]]
pureC = [energy[2][0],energy[2][1]]
enthalpy = []
for en in energy:
c = en[2]
conc = [float(i)/sum(c) for i in c]
CE = _en_to_enth(en[0],conc,pureA[0],pureB[0],pureC[0])
VASP = _en_to_enth(en[1],conc,pureA[1],pureB[1],pureC[1])
enthalpy.append([CE,VASP,c])
return enthalpy | [
"def",
"_energy_to_enthalpy",
"(",
"energy",
")",
":",
"pureA",
"=",
"[",
"energy",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"energy",
"[",
"0",
"]",
"[",
"1",
"]",
"]",
"pureB",
"=",
"[",
"energy",
"[",
"1",
"]",
"[",
"0",
"]",
",",
"energy",
"[",... | Converts energy to enthalpy.
This function take the energies stored in the energy array and
converts them to formation enthalpy.
Parameters
---------
energy : list of lists of floats
Returns
-------
enthalpy : list of lists containing the enthalpies. | [
"Converts",
"energy",
"to",
"enthalpy",
".",
"This",
"function",
"take",
"the",
"energies",
"stored",
"in",
"the",
"energy",
"array",
"and",
"converts",
"them",
"to",
"formation",
"enthalpy",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L37-L66 | train | 200,068 |
marcharper/python-ternary | examples/scatter_colorbar.py | _find_error | def _find_error(vals):
"""Find the errors in the energy values.
This function finds the errors in the enthalpys.
Parameters
----------
vals : list of lists of floats
Returns
-------
err_vals : list of lists containing the errors.
"""
err_vals = []
for en in vals:
c = en[2]
conc = [float(i)/sum(c) for i in c]
err = abs(en[0]-en[1])
err_vals.append([conc,err])
return err_vals | python | def _find_error(vals):
"""Find the errors in the energy values.
This function finds the errors in the enthalpys.
Parameters
----------
vals : list of lists of floats
Returns
-------
err_vals : list of lists containing the errors.
"""
err_vals = []
for en in vals:
c = en[2]
conc = [float(i)/sum(c) for i in c]
err = abs(en[0]-en[1])
err_vals.append([conc,err])
return err_vals | [
"def",
"_find_error",
"(",
"vals",
")",
":",
"err_vals",
"=",
"[",
"]",
"for",
"en",
"in",
"vals",
":",
"c",
"=",
"en",
"[",
"2",
"]",
"conc",
"=",
"[",
"float",
"(",
"i",
")",
"/",
"sum",
"(",
"c",
")",
"for",
"i",
"in",
"c",
"]",
"err",
... | Find the errors in the energy values.
This function finds the errors in the enthalpys.
Parameters
----------
vals : list of lists of floats
Returns
-------
err_vals : list of lists containing the errors. | [
"Find",
"the",
"errors",
"in",
"the",
"energy",
"values",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L69-L92 | train | 200,069 |
marcharper/python-ternary | examples/scatter_colorbar.py | _read_data | def _read_data(fname):
"""Reads data from file.
Reads the data in 'fname' into a list where each list entry contains
[energy predicted, energy calculated, list of concentrations].
Parameters
----------
fname : str
The name and path to the data file.
Returns
-------
energy : list of lists of floats
A list of the energies and the concentrations.
"""
energy = []
with open(fname,'r') as f:
for line in f:
CE = abs(float(line.strip().split()[0]))
VASP = abs(float(line.strip().split()[1]))
conc = [i for i in line.strip().split()[2:]]
conc_f = []
for c in conc:
if '[' in c and ']' in c:
conc_f.append(int(c[1:-1]))
elif '[' in c:
conc_f.append(int(c[1:-1]))
elif ']' in c or ',' in c:
conc_f.append(int(c[:-1]))
else:
conc_f.append(int(c))
energy.append([CE,VASP,conc_f])
return energy | python | def _read_data(fname):
"""Reads data from file.
Reads the data in 'fname' into a list where each list entry contains
[energy predicted, energy calculated, list of concentrations].
Parameters
----------
fname : str
The name and path to the data file.
Returns
-------
energy : list of lists of floats
A list of the energies and the concentrations.
"""
energy = []
with open(fname,'r') as f:
for line in f:
CE = abs(float(line.strip().split()[0]))
VASP = abs(float(line.strip().split()[1]))
conc = [i for i in line.strip().split()[2:]]
conc_f = []
for c in conc:
if '[' in c and ']' in c:
conc_f.append(int(c[1:-1]))
elif '[' in c:
conc_f.append(int(c[1:-1]))
elif ']' in c or ',' in c:
conc_f.append(int(c[:-1]))
else:
conc_f.append(int(c))
energy.append([CE,VASP,conc_f])
return energy | [
"def",
"_read_data",
"(",
"fname",
")",
":",
"energy",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"CE",
"=",
"abs",
"(",
"float",
"(",
"line",
".",
"strip",
"(",
")",
".",
"spl... | Reads data from file.
Reads the data in 'fname' into a list where each list entry contains
[energy predicted, energy calculated, list of concentrations].
Parameters
----------
fname : str
The name and path to the data file.
Returns
-------
energy : list of lists of floats
A list of the energies and the concentrations. | [
"Reads",
"data",
"from",
"file",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L95-L130 | train | 200,070 |
marcharper/python-ternary | examples/scatter_colorbar.py | conc_err_plot | def conc_err_plot(fname):
"""Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name.
"""
energies = _read_data(fname)
enthalpy = _energy_to_enthalpy(energies)
this_errors = _find_error(enthalpy)
points = []
colors = []
for er in this_errors:
concs = er[0]
points.append((concs[0]*100,concs[1]*100,concs[2]*100))
colors.append(er[1])
scale = 100
figure, tax = ternary.figure(scale=scale)
tax.boundary(linewidth = 1.0)
tax.set_title("Errors in Convex Hull Predictions.",fontsize=20)
tax.gridlines(multiple=10,color="blue")
tax.scatter(points,vmax=max(colors),colormap=plt.cm.viridis,colorbar=True,c=colors,cmap=plt.cm.viridis)
tax.show() | python | def conc_err_plot(fname):
"""Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name.
"""
energies = _read_data(fname)
enthalpy = _energy_to_enthalpy(energies)
this_errors = _find_error(enthalpy)
points = []
colors = []
for er in this_errors:
concs = er[0]
points.append((concs[0]*100,concs[1]*100,concs[2]*100))
colors.append(er[1])
scale = 100
figure, tax = ternary.figure(scale=scale)
tax.boundary(linewidth = 1.0)
tax.set_title("Errors in Convex Hull Predictions.",fontsize=20)
tax.gridlines(multiple=10,color="blue")
tax.scatter(points,vmax=max(colors),colormap=plt.cm.viridis,colorbar=True,c=colors,cmap=plt.cm.viridis)
tax.show() | [
"def",
"conc_err_plot",
"(",
"fname",
")",
":",
"energies",
"=",
"_read_data",
"(",
"fname",
")",
"enthalpy",
"=",
"_energy_to_enthalpy",
"(",
"energies",
")",
"this_errors",
"=",
"_find_error",
"(",
"enthalpy",
")",
"points",
"=",
"[",
"]",
"colors",
"=",
... | Plots the error in the CE data.
This plots the error in the CE predictions within a ternary concentration diagram.
Parameters
----------
fname : string containing the input file name. | [
"Plots",
"the",
"error",
"in",
"the",
"CE",
"data",
".",
"This",
"plots",
"the",
"error",
"in",
"the",
"CE",
"predictions",
"within",
"a",
"ternary",
"concentration",
"diagram",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/examples/scatter_colorbar.py#L133-L161 | train | 200,071 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot._connect_callbacks | def _connect_callbacks(self):
"""Connect resize matplotlib callbacks."""
figure = self.get_figure()
callback = partial(mpl_redraw_callback, tax=self)
event_names = ('resize_event', 'draw_event')
for event_name in event_names:
figure.canvas.mpl_connect(event_name, callback) | python | def _connect_callbacks(self):
"""Connect resize matplotlib callbacks."""
figure = self.get_figure()
callback = partial(mpl_redraw_callback, tax=self)
event_names = ('resize_event', 'draw_event')
for event_name in event_names:
figure.canvas.mpl_connect(event_name, callback) | [
"def",
"_connect_callbacks",
"(",
"self",
")",
":",
"figure",
"=",
"self",
".",
"get_figure",
"(",
")",
"callback",
"=",
"partial",
"(",
"mpl_redraw_callback",
",",
"tax",
"=",
"self",
")",
"event_names",
"=",
"(",
"'resize_event'",
",",
"'draw_event'",
")",... | Connect resize matplotlib callbacks. | [
"Connect",
"resize",
"matplotlib",
"callbacks",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L74-L80 | train | 200,072 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.set_title | def set_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot."""
ax = self.get_axes()
ax.set_title(title, **kwargs) | python | def set_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot."""
ax = self.get_axes()
ax.set_title(title, **kwargs) | [
"def",
"set_title",
"(",
"self",
",",
"title",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"self",
".",
"get_axes",
"(",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"*",
"*",
"kwargs",
")"
] | Sets the title on the underlying matplotlib AxesSubplot. | [
"Sets",
"the",
"title",
"on",
"the",
"underlying",
"matplotlib",
"AxesSubplot",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L117-L120 | train | 200,073 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.left_axis_label | def left_axis_label(self, label, position=None, rotation=60, offset=0.08,
**kwargs):
"""
Sets the label on the left axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, 60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not position:
position = (-offset, 3./5, 2./5)
self._labels["left"] = (label, position, rotation, kwargs) | python | def left_axis_label(self, label, position=None, rotation=60, offset=0.08,
**kwargs):
"""
Sets the label on the left axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, 60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not position:
position = (-offset, 3./5, 2./5)
self._labels["left"] = (label, position, rotation, kwargs) | [
"def",
"left_axis_label",
"(",
"self",
",",
"label",
",",
"position",
"=",
"None",
",",
"rotation",
"=",
"60",
",",
"offset",
"=",
"0.08",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"position",
":",
"position",
"=",
"(",
"-",
"offset",
",",
"3... | Sets the label on the left axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, 60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib. | [
"Sets",
"the",
"label",
"on",
"the",
"left",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L122-L143 | train | 200,074 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.right_axis_label | def right_axis_label(self, label, position=None, rotation=-60, offset=0.08,
**kwargs):
"""
Sets the label on the right axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, -60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not position:
position = (2. / 5 + offset, 3. / 5, 0)
self._labels["right"] = (label, position, rotation, kwargs) | python | def right_axis_label(self, label, position=None, rotation=-60, offset=0.08,
**kwargs):
"""
Sets the label on the right axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, -60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib.
"""
if not position:
position = (2. / 5 + offset, 3. / 5, 0)
self._labels["right"] = (label, position, rotation, kwargs) | [
"def",
"right_axis_label",
"(",
"self",
",",
"label",
",",
"position",
"=",
"None",
",",
"rotation",
"=",
"-",
"60",
",",
"offset",
"=",
"0.08",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"position",
":",
"position",
"=",
"(",
"2.",
"/",
"5",
... | Sets the label on the right axis.
Parameters
----------
label: String
The axis label
position: 3-Tuple of floats, None
The position of the text label
rotation: float, -60
The angle of rotation of the label
offset: float,
Used to compute the distance of the label from the axis
kwargs:
Any kwargs to pass through to matplotlib. | [
"Sets",
"the",
"label",
"on",
"the",
"right",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L145-L167 | train | 200,075 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.clear_matplotlib_ticks | def clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks."""
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis) | python | def clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks."""
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis) | [
"def",
"clear_matplotlib_ticks",
"(",
"self",
",",
"axis",
"=",
"\"both\"",
")",
":",
"ax",
"=",
"self",
".",
"get_axes",
"(",
")",
"plotting",
".",
"clear_matplotlib_ticks",
"(",
"ax",
"=",
"ax",
",",
"axis",
"=",
"axis",
")"
] | Clears the default matplotlib ticks. | [
"Clears",
"the",
"default",
"matplotlib",
"ticks",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L327-L330 | train | 200,076 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.get_ticks_from_axis_limits | def get_ticks_from_axis_limits(self, multiple=1):
"""
Taking self._axis_limits and self._boundary_scale get the scaled
ticks for all three axes and store them in self._ticks under the
keys 'b' for bottom, 'l' for left and 'r' for right axes.
"""
for k in ['b', 'l', 'r']:
self._ticks[k] = numpy.linspace(
self._axis_limits[k][0],
self._axis_limits[k][1],
self._boundary_scale / float(multiple) + 1
).tolist() | python | def get_ticks_from_axis_limits(self, multiple=1):
"""
Taking self._axis_limits and self._boundary_scale get the scaled
ticks for all three axes and store them in self._ticks under the
keys 'b' for bottom, 'l' for left and 'r' for right axes.
"""
for k in ['b', 'l', 'r']:
self._ticks[k] = numpy.linspace(
self._axis_limits[k][0],
self._axis_limits[k][1],
self._boundary_scale / float(multiple) + 1
).tolist() | [
"def",
"get_ticks_from_axis_limits",
"(",
"self",
",",
"multiple",
"=",
"1",
")",
":",
"for",
"k",
"in",
"[",
"'b'",
",",
"'l'",
",",
"'r'",
"]",
":",
"self",
".",
"_ticks",
"[",
"k",
"]",
"=",
"numpy",
".",
"linspace",
"(",
"self",
".",
"_axis_lim... | Taking self._axis_limits and self._boundary_scale get the scaled
ticks for all three axes and store them in self._ticks under the
keys 'b' for bottom, 'l' for left and 'r' for right axes. | [
"Taking",
"self",
".",
"_axis_limits",
"and",
"self",
".",
"_boundary_scale",
"get",
"the",
"scaled",
"ticks",
"for",
"all",
"three",
"axes",
"and",
"store",
"them",
"in",
"self",
".",
"_ticks",
"under",
"the",
"keys",
"b",
"for",
"bottom",
"l",
"for",
"... | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L332-L343 | train | 200,077 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.set_custom_ticks | def set_custom_ticks(self, locations=None, clockwise=False, multiple=1,
axes_colors=None, tick_formats=None, **kwargs):
"""
Having called get_ticks_from_axis_limits, set the custom ticks on the
plot.
"""
for k in ['b', 'l', 'r']:
self.ticks(ticks=self._ticks[k], locations=locations,
axis=k, clockwise=clockwise, multiple=multiple,
axes_colors=axes_colors, tick_formats=tick_formats,
**kwargs) | python | def set_custom_ticks(self, locations=None, clockwise=False, multiple=1,
axes_colors=None, tick_formats=None, **kwargs):
"""
Having called get_ticks_from_axis_limits, set the custom ticks on the
plot.
"""
for k in ['b', 'l', 'r']:
self.ticks(ticks=self._ticks[k], locations=locations,
axis=k, clockwise=clockwise, multiple=multiple,
axes_colors=axes_colors, tick_formats=tick_formats,
**kwargs) | [
"def",
"set_custom_ticks",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"clockwise",
"=",
"False",
",",
"multiple",
"=",
"1",
",",
"axes_colors",
"=",
"None",
",",
"tick_formats",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
"in",
... | Having called get_ticks_from_axis_limits, set the custom ticks on the
plot. | [
"Having",
"called",
"get_ticks_from_axis_limits",
"set",
"the",
"custom",
"ticks",
"on",
"the",
"plot",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L345-L355 | train | 200,078 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot._redraw_labels | def _redraw_labels(self):
"""Redraw axis labels, typically after draw or resize events."""
ax = self.get_axes()
# Remove any previous labels
for mpl_object in self._to_remove:
mpl_object.remove()
self._to_remove = []
# Redraw the labels with the appropriate angles
label_data = list(self._labels.values())
label_data.extend(self._corner_labels.values())
for (label, position, rotation, kwargs) in label_data:
transform = ax.transAxes
x, y = project_point(position)
# Calculate the new angle.
position = numpy.array([x, y])
new_rotation = ax.transData.transform_angles(
numpy.array((rotation,)), position.reshape((1, 2)))[0]
text = ax.text(x, y, label, rotation=new_rotation,
transform=transform, horizontalalignment="center",
**kwargs)
text.set_rotation_mode("anchor")
self._to_remove.append(text) | python | def _redraw_labels(self):
"""Redraw axis labels, typically after draw or resize events."""
ax = self.get_axes()
# Remove any previous labels
for mpl_object in self._to_remove:
mpl_object.remove()
self._to_remove = []
# Redraw the labels with the appropriate angles
label_data = list(self._labels.values())
label_data.extend(self._corner_labels.values())
for (label, position, rotation, kwargs) in label_data:
transform = ax.transAxes
x, y = project_point(position)
# Calculate the new angle.
position = numpy.array([x, y])
new_rotation = ax.transData.transform_angles(
numpy.array((rotation,)), position.reshape((1, 2)))[0]
text = ax.text(x, y, label, rotation=new_rotation,
transform=transform, horizontalalignment="center",
**kwargs)
text.set_rotation_mode("anchor")
self._to_remove.append(text) | [
"def",
"_redraw_labels",
"(",
"self",
")",
":",
"ax",
"=",
"self",
".",
"get_axes",
"(",
")",
"# Remove any previous labels",
"for",
"mpl_object",
"in",
"self",
".",
"_to_remove",
":",
"mpl_object",
".",
"remove",
"(",
")",
"self",
".",
"_to_remove",
"=",
... | Redraw axis labels, typically after draw or resize events. | [
"Redraw",
"axis",
"labels",
"typically",
"after",
"draw",
"or",
"resize",
"events",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L374-L395 | train | 200,079 |
marcharper/python-ternary | ternary/ternary_axes_subplot.py | TernaryAxesSubplot.convert_coordinates | def convert_coordinates(self, points, axisorder='blr'):
"""
Convert data coordinates to simplex coordinates for plotting
in the case that axis limits have been applied.
"""
return convert_coordinates_sequence(points,self._boundary_scale,
self._axis_limits, axisorder) | python | def convert_coordinates(self, points, axisorder='blr'):
"""
Convert data coordinates to simplex coordinates for plotting
in the case that axis limits have been applied.
"""
return convert_coordinates_sequence(points,self._boundary_scale,
self._axis_limits, axisorder) | [
"def",
"convert_coordinates",
"(",
"self",
",",
"points",
",",
"axisorder",
"=",
"'blr'",
")",
":",
"return",
"convert_coordinates_sequence",
"(",
"points",
",",
"self",
".",
"_boundary_scale",
",",
"self",
".",
"_axis_limits",
",",
"axisorder",
")"
] | Convert data coordinates to simplex coordinates for plotting
in the case that axis limits have been applied. | [
"Convert",
"data",
"coordinates",
"to",
"simplex",
"coordinates",
"for",
"plotting",
"in",
"the",
"case",
"that",
"axis",
"limits",
"have",
"been",
"applied",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/ternary_axes_subplot.py#L397-L403 | train | 200,080 |
marcharper/python-ternary | ternary/colormapping.py | get_cmap | def get_cmap(cmap=None):
"""
Loads a matplotlib colormap if specified or supplies the default.
Parameters
----------
cmap: string or matplotlib.colors.Colormap instance
The name of the Matplotlib colormap to look up.
Returns
-------
The desired Matplotlib colormap
Raises
------
ValueError if colormap name is not recognized by Matplotlib
"""
if isinstance(cmap, matplotlib.colors.Colormap):
return cmap
if isinstance(cmap, str):
cmap_name = cmap
else:
cmap_name = DEFAULT_COLOR_MAP_NAME
return plt.get_cmap(cmap_name) | python | def get_cmap(cmap=None):
"""
Loads a matplotlib colormap if specified or supplies the default.
Parameters
----------
cmap: string or matplotlib.colors.Colormap instance
The name of the Matplotlib colormap to look up.
Returns
-------
The desired Matplotlib colormap
Raises
------
ValueError if colormap name is not recognized by Matplotlib
"""
if isinstance(cmap, matplotlib.colors.Colormap):
return cmap
if isinstance(cmap, str):
cmap_name = cmap
else:
cmap_name = DEFAULT_COLOR_MAP_NAME
return plt.get_cmap(cmap_name) | [
"def",
"get_cmap",
"(",
"cmap",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"cmap",
",",
"matplotlib",
".",
"colors",
".",
"Colormap",
")",
":",
"return",
"cmap",
"if",
"isinstance",
"(",
"cmap",
",",
"str",
")",
":",
"cmap_name",
"=",
"cmap",
"e... | Loads a matplotlib colormap if specified or supplies the default.
Parameters
----------
cmap: string or matplotlib.colors.Colormap instance
The name of the Matplotlib colormap to look up.
Returns
-------
The desired Matplotlib colormap
Raises
------
ValueError if colormap name is not recognized by Matplotlib | [
"Loads",
"a",
"matplotlib",
"colormap",
"if",
"specified",
"or",
"supplies",
"the",
"default",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/colormapping.py#L15-L39 | train | 200,081 |
marcharper/python-ternary | ternary/heatmapping.py | blend_value | def blend_value(data, i, j, k, keys=None):
"""Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the lower
horizontal."""
key_size = len(list(data.keys())[0])
if not keys:
keys = triangle_coordinates(i, j, k)
# Reduce key from (i, j, k) to (i, j) if necessary
keys = [tuple(key[:key_size]) for key in keys]
# Sum over the values of the points to blend
try:
s = sum(data[key] for key in keys)
value = s / 3.
except KeyError:
value = None
return value | python | def blend_value(data, i, j, k, keys=None):
"""Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the lower
horizontal."""
key_size = len(list(data.keys())[0])
if not keys:
keys = triangle_coordinates(i, j, k)
# Reduce key from (i, j, k) to (i, j) if necessary
keys = [tuple(key[:key_size]) for key in keys]
# Sum over the values of the points to blend
try:
s = sum(data[key] for key in keys)
value = s / 3.
except KeyError:
value = None
return value | [
"def",
"blend_value",
"(",
"data",
",",
"i",
",",
"j",
",",
"k",
",",
"keys",
"=",
"None",
")",
":",
"key_size",
"=",
"len",
"(",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
")",
"if",
"not",
"keys",
":",
"keys",
"=",
"t... | Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the lower
horizontal. | [
"Computes",
"the",
"average",
"value",
"of",
"the",
"three",
"vertices",
"of",
"a",
"triangle",
"in",
"the",
"simplex",
"triangulation",
"where",
"two",
"of",
"the",
"vertices",
"are",
"on",
"the",
"lower",
"horizontal",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L17-L34 | train | 200,082 |
marcharper/python-ternary | ternary/heatmapping.py | alt_blend_value | def alt_blend_value(data, i, j, k):
"""Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the upper
horizontal."""
keys = alt_triangle_coordinates(i, j, k)
return blend_value(data, i, j, k, keys=keys) | python | def alt_blend_value(data, i, j, k):
"""Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the upper
horizontal."""
keys = alt_triangle_coordinates(i, j, k)
return blend_value(data, i, j, k, keys=keys) | [
"def",
"alt_blend_value",
"(",
"data",
",",
"i",
",",
"j",
",",
"k",
")",
":",
"keys",
"=",
"alt_triangle_coordinates",
"(",
"i",
",",
"j",
",",
"k",
")",
"return",
"blend_value",
"(",
"data",
",",
"i",
",",
"j",
",",
"k",
",",
"keys",
"=",
"keys... | Computes the average value of the three vertices of a triangle in the
simplex triangulation, where two of the vertices are on the upper
horizontal. | [
"Computes",
"the",
"average",
"value",
"of",
"the",
"three",
"vertices",
"of",
"a",
"triangle",
"in",
"the",
"simplex",
"triangulation",
"where",
"two",
"of",
"the",
"vertices",
"are",
"on",
"the",
"upper",
"horizontal",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L37-L43 | train | 200,083 |
marcharper/python-ternary | ternary/heatmapping.py | triangle_coordinates | def triangle_coordinates(i, j, k):
"""
Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the lower side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
return [(i, j, k), (i + 1, j, k - 1), (i, j + 1, k - 1)] | python | def triangle_coordinates(i, j, k):
"""
Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the lower side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
return [(i, j, k), (i + 1, j, k - 1), (i, j + 1, k - 1)] | [
"def",
"triangle_coordinates",
"(",
"i",
",",
"j",
",",
"k",
")",
":",
"return",
"[",
"(",
"i",
",",
"j",
",",
"k",
")",
",",
"(",
"i",
"+",
"1",
",",
"j",
",",
"k",
"-",
"1",
")",
",",
"(",
"i",
",",
"j",
"+",
"1",
",",
"k",
"-",
"1"... | Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the lower side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected) | [
"Computes",
"coordinates",
"of",
"the",
"constituent",
"triangles",
"of",
"a",
"triangulation",
"for",
"the",
"simplex",
".",
"These",
"triangules",
"are",
"parallel",
"to",
"the",
"lower",
"axis",
"on",
"the",
"lower",
"side",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L46-L60 | train | 200,084 |
marcharper/python-ternary | ternary/heatmapping.py | alt_triangle_coordinates | def alt_triangle_coordinates(i, j, k):
"""
Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the upper side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
return [(i, j + 1, k - 1), (i + 1, j, k - 1), (i + 1, j + 1, k - 2)] | python | def alt_triangle_coordinates(i, j, k):
"""
Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the upper side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
return [(i, j + 1, k - 1), (i + 1, j, k - 1), (i + 1, j + 1, k - 2)] | [
"def",
"alt_triangle_coordinates",
"(",
"i",
",",
"j",
",",
"k",
")",
":",
"return",
"[",
"(",
"i",
",",
"j",
"+",
"1",
",",
"k",
"-",
"1",
")",
",",
"(",
"i",
"+",
"1",
",",
"j",
",",
"k",
"-",
"1",
")",
",",
"(",
"i",
"+",
"1",
",",
... | Computes coordinates of the constituent triangles of a triangulation for the
simplex. These triangules are parallel to the lower axis on the upper side.
Parameters
----------
i,j,k: enumeration of the desired triangle
Returns
-------
A numpy array of coordinates of the hexagon (unprojected) | [
"Computes",
"coordinates",
"of",
"the",
"constituent",
"triangles",
"of",
"a",
"triangulation",
"for",
"the",
"simplex",
".",
"These",
"triangules",
"are",
"parallel",
"to",
"the",
"lower",
"axis",
"on",
"the",
"upper",
"side",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L63-L77 | train | 200,085 |
marcharper/python-ternary | ternary/heatmapping.py | generate_hexagon_deltas | def generate_hexagon_deltas():
"""
Generates a dictionary of the necessary additive vectors to generate the
hexagon points for the hexagonal heatmap.
"""
zero = numpy.array([0, 0, 0])
alpha = numpy.array([-1./3, 2./3, 0])
deltaup = numpy.array([1./3, 1./3, 0])
deltadown = numpy.array([2./3, -1./3, 0])
i_vec = numpy.array([0, 1./2, -1./2])
i_vec_down = numpy.array([1./2, -1./2, 0])
deltaX_vec = numpy.array([1./2, 0, -1./2])
d = dict()
# Corner Points
d["100"] = [zero, -deltaX_vec, -deltadown, -i_vec_down]
d["010"] = [zero, i_vec_down, -alpha, -i_vec]
d["001"] = [zero, i_vec, deltaup, deltaX_vec]
# On the Edges
d["011"] = [i_vec, deltaup, deltadown, -alpha, -i_vec]
d["101"] = [-deltaX_vec, -deltadown, alpha, deltaup, deltaX_vec]
d["110"] = [i_vec_down, -alpha, -deltaup, -deltadown, -i_vec_down]
# Interior point
d["111"] = [alpha, deltaup, deltadown, -alpha, -deltaup, -deltadown]
return d | python | def generate_hexagon_deltas():
"""
Generates a dictionary of the necessary additive vectors to generate the
hexagon points for the hexagonal heatmap.
"""
zero = numpy.array([0, 0, 0])
alpha = numpy.array([-1./3, 2./3, 0])
deltaup = numpy.array([1./3, 1./3, 0])
deltadown = numpy.array([2./3, -1./3, 0])
i_vec = numpy.array([0, 1./2, -1./2])
i_vec_down = numpy.array([1./2, -1./2, 0])
deltaX_vec = numpy.array([1./2, 0, -1./2])
d = dict()
# Corner Points
d["100"] = [zero, -deltaX_vec, -deltadown, -i_vec_down]
d["010"] = [zero, i_vec_down, -alpha, -i_vec]
d["001"] = [zero, i_vec, deltaup, deltaX_vec]
# On the Edges
d["011"] = [i_vec, deltaup, deltadown, -alpha, -i_vec]
d["101"] = [-deltaX_vec, -deltadown, alpha, deltaup, deltaX_vec]
d["110"] = [i_vec_down, -alpha, -deltaup, -deltadown, -i_vec_down]
# Interior point
d["111"] = [alpha, deltaup, deltadown, -alpha, -deltaup, -deltadown]
return d | [
"def",
"generate_hexagon_deltas",
"(",
")",
":",
"zero",
"=",
"numpy",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"0",
"]",
")",
"alpha",
"=",
"numpy",
".",
"array",
"(",
"[",
"-",
"1.",
"/",
"3",
",",
"2.",
"/",
"3",
",",
"0",
"]",
")",
"... | Generates a dictionary of the necessary additive vectors to generate the
hexagon points for the hexagonal heatmap. | [
"Generates",
"a",
"dictionary",
"of",
"the",
"necessary",
"additive",
"vectors",
"to",
"generate",
"the",
"hexagon",
"points",
"for",
"the",
"hexagonal",
"heatmap",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L82-L108 | train | 200,086 |
marcharper/python-ternary | ternary/heatmapping.py | hexagon_coordinates | def hexagon_coordinates(i, j, k):
"""
Computes coordinates of the constituent hexagons of a hexagonal heatmap.
Parameters
----------
i, j, k: enumeration of the desired hexagon
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
signature = ""
for x in [i, j, k]:
if x == 0:
signature += "0"
else:
signature += "1"
deltas = hexagon_deltas[signature]
center = numpy.array([i, j, k])
return numpy.array([center + x for x in deltas]) | python | def hexagon_coordinates(i, j, k):
"""
Computes coordinates of the constituent hexagons of a hexagonal heatmap.
Parameters
----------
i, j, k: enumeration of the desired hexagon
Returns
-------
A numpy array of coordinates of the hexagon (unprojected)
"""
signature = ""
for x in [i, j, k]:
if x == 0:
signature += "0"
else:
signature += "1"
deltas = hexagon_deltas[signature]
center = numpy.array([i, j, k])
return numpy.array([center + x for x in deltas]) | [
"def",
"hexagon_coordinates",
"(",
"i",
",",
"j",
",",
"k",
")",
":",
"signature",
"=",
"\"\"",
"for",
"x",
"in",
"[",
"i",
",",
"j",
",",
"k",
"]",
":",
"if",
"x",
"==",
"0",
":",
"signature",
"+=",
"\"0\"",
"else",
":",
"signature",
"+=",
"\"... | Computes coordinates of the constituent hexagons of a hexagonal heatmap.
Parameters
----------
i, j, k: enumeration of the desired hexagon
Returns
-------
A numpy array of coordinates of the hexagon (unprojected) | [
"Computes",
"coordinates",
"of",
"the",
"constituent",
"hexagons",
"of",
"a",
"hexagonal",
"heatmap",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L114-L135 | train | 200,087 |
marcharper/python-ternary | ternary/heatmapping.py | polygon_generator | def polygon_generator(data, scale, style, permutation=None):
"""Generator for the vertices of the polygon to be colored and its color,
depending on style. Called by heatmap."""
# We'll project the coordinates inside this function to prevent
# passing around permutation more than necessary
project = functools.partial(project_point, permutation=permutation)
if isinstance(data, dict):
data_gen = data.items()
else:
# Only works with style == 'h'
data_gen = data
for key, value in data_gen:
if value is None:
continue
i = key[0]
j = key[1]
k = scale - i - j
if style == 'h':
vertices = hexagon_coordinates(i, j, k)
yield (map(project, vertices), value)
elif style == 'd':
# Upright triangles
if (i <= scale) and (j <= scale) and (k >= 0):
vertices = triangle_coordinates(i, j, k)
yield (map(project, vertices), value)
# Upside-down triangles
if (i < scale) and (j < scale) and (k >= 1):
vertices = alt_triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
elif style == 't':
# Upright triangles
if (i < scale) and (j < scale) and (k > 0):
vertices = triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
# If not on the boundary add the upside-down triangle
if (i < scale) and (j < scale) and (k > 1):
vertices = alt_triangle_coordinates(i, j, k)
value = alt_blend_value(data, i, j, k)
yield (map(project, vertices), value) | python | def polygon_generator(data, scale, style, permutation=None):
"""Generator for the vertices of the polygon to be colored and its color,
depending on style. Called by heatmap."""
# We'll project the coordinates inside this function to prevent
# passing around permutation more than necessary
project = functools.partial(project_point, permutation=permutation)
if isinstance(data, dict):
data_gen = data.items()
else:
# Only works with style == 'h'
data_gen = data
for key, value in data_gen:
if value is None:
continue
i = key[0]
j = key[1]
k = scale - i - j
if style == 'h':
vertices = hexagon_coordinates(i, j, k)
yield (map(project, vertices), value)
elif style == 'd':
# Upright triangles
if (i <= scale) and (j <= scale) and (k >= 0):
vertices = triangle_coordinates(i, j, k)
yield (map(project, vertices), value)
# Upside-down triangles
if (i < scale) and (j < scale) and (k >= 1):
vertices = alt_triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
elif style == 't':
# Upright triangles
if (i < scale) and (j < scale) and (k > 0):
vertices = triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
# If not on the boundary add the upside-down triangle
if (i < scale) and (j < scale) and (k > 1):
vertices = alt_triangle_coordinates(i, j, k)
value = alt_blend_value(data, i, j, k)
yield (map(project, vertices), value) | [
"def",
"polygon_generator",
"(",
"data",
",",
"scale",
",",
"style",
",",
"permutation",
"=",
"None",
")",
":",
"# We'll project the coordinates inside this function to prevent",
"# passing around permutation more than necessary",
"project",
"=",
"functools",
".",
"partial",
... | Generator for the vertices of the polygon to be colored and its color,
depending on style. Called by heatmap. | [
"Generator",
"for",
"the",
"vertices",
"of",
"the",
"polygon",
"to",
"be",
"colored",
"and",
"its",
"color",
"depending",
"on",
"style",
".",
"Called",
"by",
"heatmap",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L140-L183 | train | 200,088 |
marcharper/python-ternary | ternary/heatmapping.py | heatmap | def heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None,
scientific=False, style='triangular', colorbar=True,
permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None):
"""
Plots heatmap of given color values.
Parameters
----------
data: dictionary
A dictionary mapping the i, j polygon to the heatmap color, where
i + j + k = scale.
scale: Integer
The scale used to partition the simplex.
vmin: float, None
The minimum color value, used to normalize colors. Computed if absent.
vmax: float, None
The maximum color value, used to normalize colors. Computed if absent.
cmap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scientific: Bool, False
Whether to use scientific notation for colorbar numbers.
style: String, "triangular"
The style of the heatmap, "triangular", "dual-triangular" or "hexagonal"
colorbar: bool, True
Show colorbar.
permutation: string, None
A permutation of the coordinates
use_rgba: bool, False
Use rgba color values
cbarlabel: string, None
Text label for the colorbar
cb_kwargs: dict
dict of kwargs to pass to colorbar
Returns
-------
ax: The matplotlib axis
"""
if not ax:
fig, ax = pyplot.subplots()
# If use_rgba, make the RGBA values numpy arrays so that they can
# be averaged.
if use_rgba:
for k, v in data.items():
data[k] = numpy.array(v)
else:
cmap = get_cmap(cmap)
if vmin is None:
vmin = min(data.values())
if vmax is None:
vmax = max(data.values())
style = style.lower()[0]
if style not in ["t", "h", 'd']:
raise ValueError("Heatmap style must be 'triangular', 'dual-triangular', or 'hexagonal'")
vertices_values = polygon_generator(data, scale, style,
permutation=permutation)
# Draw the polygons and color them
for vertices, value in vertices_values:
if value is None:
continue
if not use_rgba:
color = colormapper(value, vmin, vmax, cmap=cmap)
else:
color = value # rgba tuple (r,g,b,a) all in [0,1]
# Matplotlib wants a list of xs and a list of ys
xs, ys = unzip(vertices)
ax.fill(xs, ys, facecolor=color, edgecolor=color)
if not cb_kwargs:
cb_kwargs = dict()
if colorbar:
colorbar_hack(ax, vmin, vmax, cmap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
return ax | python | def heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None,
scientific=False, style='triangular', colorbar=True,
permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None):
"""
Plots heatmap of given color values.
Parameters
----------
data: dictionary
A dictionary mapping the i, j polygon to the heatmap color, where
i + j + k = scale.
scale: Integer
The scale used to partition the simplex.
vmin: float, None
The minimum color value, used to normalize colors. Computed if absent.
vmax: float, None
The maximum color value, used to normalize colors. Computed if absent.
cmap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scientific: Bool, False
Whether to use scientific notation for colorbar numbers.
style: String, "triangular"
The style of the heatmap, "triangular", "dual-triangular" or "hexagonal"
colorbar: bool, True
Show colorbar.
permutation: string, None
A permutation of the coordinates
use_rgba: bool, False
Use rgba color values
cbarlabel: string, None
Text label for the colorbar
cb_kwargs: dict
dict of kwargs to pass to colorbar
Returns
-------
ax: The matplotlib axis
"""
if not ax:
fig, ax = pyplot.subplots()
# If use_rgba, make the RGBA values numpy arrays so that they can
# be averaged.
if use_rgba:
for k, v in data.items():
data[k] = numpy.array(v)
else:
cmap = get_cmap(cmap)
if vmin is None:
vmin = min(data.values())
if vmax is None:
vmax = max(data.values())
style = style.lower()[0]
if style not in ["t", "h", 'd']:
raise ValueError("Heatmap style must be 'triangular', 'dual-triangular', or 'hexagonal'")
vertices_values = polygon_generator(data, scale, style,
permutation=permutation)
# Draw the polygons and color them
for vertices, value in vertices_values:
if value is None:
continue
if not use_rgba:
color = colormapper(value, vmin, vmax, cmap=cmap)
else:
color = value # rgba tuple (r,g,b,a) all in [0,1]
# Matplotlib wants a list of xs and a list of ys
xs, ys = unzip(vertices)
ax.fill(xs, ys, facecolor=color, edgecolor=color)
if not cb_kwargs:
cb_kwargs = dict()
if colorbar:
colorbar_hack(ax, vmin, vmax, cmap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
return ax | [
"def",
"heatmap",
"(",
"data",
",",
"scale",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"scientific",
"=",
"False",
",",
"style",
"=",
"'triangular'",
",",
"colorbar",
"=",
"True",
","... | Plots heatmap of given color values.
Parameters
----------
data: dictionary
A dictionary mapping the i, j polygon to the heatmap color, where
i + j + k = scale.
scale: Integer
The scale used to partition the simplex.
vmin: float, None
The minimum color value, used to normalize colors. Computed if absent.
vmax: float, None
The maximum color value, used to normalize colors. Computed if absent.
cmap: String or matplotlib.colors.Colormap, None
The name of the Matplotlib colormap to use.
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scientific: Bool, False
Whether to use scientific notation for colorbar numbers.
style: String, "triangular"
The style of the heatmap, "triangular", "dual-triangular" or "hexagonal"
colorbar: bool, True
Show colorbar.
permutation: string, None
A permutation of the coordinates
use_rgba: bool, False
Use rgba color values
cbarlabel: string, None
Text label for the colorbar
cb_kwargs: dict
dict of kwargs to pass to colorbar
Returns
-------
ax: The matplotlib axis | [
"Plots",
"heatmap",
"of",
"given",
"color",
"values",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L186-L264 | train | 200,089 |
marcharper/python-ternary | ternary/heatmapping.py | svg_polygon | def svg_polygon(coordinates, color):
"""
Create an svg triangle for the stationary heatmap.
Parameters
----------
coordinates: list
The coordinates defining the polygon
color: string
RGB color value e.g. #26ffd1
Returns
-------
string, the svg string for the polygon
"""
coord_str = []
for c in coordinates:
coord_str.append(",".join(map(str, c)))
coord_str = " ".join(coord_str)
polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color)
return polygon | python | def svg_polygon(coordinates, color):
"""
Create an svg triangle for the stationary heatmap.
Parameters
----------
coordinates: list
The coordinates defining the polygon
color: string
RGB color value e.g. #26ffd1
Returns
-------
string, the svg string for the polygon
"""
coord_str = []
for c in coordinates:
coord_str.append(",".join(map(str, c)))
coord_str = " ".join(coord_str)
polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color)
return polygon | [
"def",
"svg_polygon",
"(",
"coordinates",
",",
"color",
")",
":",
"coord_str",
"=",
"[",
"]",
"for",
"c",
"in",
"coordinates",
":",
"coord_str",
".",
"append",
"(",
"\",\"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"c",
")",
")",
")",
"coord_str",
... | Create an svg triangle for the stationary heatmap.
Parameters
----------
coordinates: list
The coordinates defining the polygon
color: string
RGB color value e.g. #26ffd1
Returns
-------
string, the svg string for the polygon | [
"Create",
"an",
"svg",
"triangle",
"for",
"the",
"stationary",
"heatmap",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/heatmapping.py#L323-L344 | train | 200,090 |
marcharper/python-ternary | ternary/lines.py | line | def line(ax, p1, p2, permutation=None, **kwargs):
"""
Draws a line on `ax` from p1 to p2.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
p1: 2-tuple
The (x,y) starting coordinates
p2: 2-tuple
The (x,y) ending coordinates
kwargs:
Any kwargs to pass through to Matplotlib.
"""
pp1 = project_point(p1, permutation=permutation)
pp2 = project_point(p2, permutation=permutation)
ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **kwargs)) | python | def line(ax, p1, p2, permutation=None, **kwargs):
"""
Draws a line on `ax` from p1 to p2.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
p1: 2-tuple
The (x,y) starting coordinates
p2: 2-tuple
The (x,y) ending coordinates
kwargs:
Any kwargs to pass through to Matplotlib.
"""
pp1 = project_point(p1, permutation=permutation)
pp2 = project_point(p2, permutation=permutation)
ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **kwargs)) | [
"def",
"line",
"(",
"ax",
",",
"p1",
",",
"p2",
",",
"permutation",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pp1",
"=",
"project_point",
"(",
"p1",
",",
"permutation",
"=",
"permutation",
")",
"pp2",
"=",
"project_point",
"(",
"p2",
",",
"p... | Draws a line on `ax` from p1 to p2.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
p1: 2-tuple
The (x,y) starting coordinates
p2: 2-tuple
The (x,y) ending coordinates
kwargs:
Any kwargs to pass through to Matplotlib. | [
"Draws",
"a",
"line",
"on",
"ax",
"from",
"p1",
"to",
"p2",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L13-L31 | train | 200,091 |
marcharper/python-ternary | ternary/lines.py | horizontal_line | def horizontal_line(ax, scale, i, **kwargs):
"""
Draws the i-th horizontal line parallel to the lower axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float, 1.0
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (0, i, scale - i)
p2 = (scale - i, i, 0)
line(ax, p1, p2, **kwargs) | python | def horizontal_line(ax, scale, i, **kwargs):
"""
Draws the i-th horizontal line parallel to the lower axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float, 1.0
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (0, i, scale - i)
p2 = (scale - i, i, 0)
line(ax, p1, p2, **kwargs) | [
"def",
"horizontal_line",
"(",
"ax",
",",
"scale",
",",
"i",
",",
"*",
"*",
"kwargs",
")",
":",
"p1",
"=",
"(",
"0",
",",
"i",
",",
"scale",
"-",
"i",
")",
"p2",
"=",
"(",
"scale",
"-",
"i",
",",
"i",
",",
"0",
")",
"line",
"(",
"ax",
","... | Draws the i-th horizontal line parallel to the lower axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float, 1.0
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib. | [
"Draws",
"the",
"i",
"-",
"th",
"horizontal",
"line",
"parallel",
"to",
"the",
"lower",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L34-L52 | train | 200,092 |
marcharper/python-ternary | ternary/lines.py | left_parallel_line | def left_parallel_line(ax, scale, i, **kwargs):
"""
Draws the i-th line parallel to the left axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (i, scale - i, 0)
p2 = (i, 0, scale - i)
line(ax, p1, p2, **kwargs) | python | def left_parallel_line(ax, scale, i, **kwargs):
"""
Draws the i-th line parallel to the left axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (i, scale - i, 0)
p2 = (i, 0, scale - i)
line(ax, p1, p2, **kwargs) | [
"def",
"left_parallel_line",
"(",
"ax",
",",
"scale",
",",
"i",
",",
"*",
"*",
"kwargs",
")",
":",
"p1",
"=",
"(",
"i",
",",
"scale",
"-",
"i",
",",
"0",
")",
"p2",
"=",
"(",
"i",
",",
"0",
",",
"scale",
"-",
"i",
")",
"line",
"(",
"ax",
... | Draws the i-th line parallel to the left axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib. | [
"Draws",
"the",
"i",
"-",
"th",
"line",
"parallel",
"to",
"the",
"left",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L55-L73 | train | 200,093 |
marcharper/python-ternary | ternary/lines.py | right_parallel_line | def right_parallel_line(ax, scale, i, **kwargs):
"""
Draws the i-th line parallel to the right axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (0, scale - i, i)
p2 = (scale - i, 0, i)
line(ax, p1, p2, **kwargs) | python | def right_parallel_line(ax, scale, i, **kwargs):
"""
Draws the i-th line parallel to the right axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib.
"""
p1 = (0, scale - i, i)
p2 = (scale - i, 0, i)
line(ax, p1, p2, **kwargs) | [
"def",
"right_parallel_line",
"(",
"ax",
",",
"scale",
",",
"i",
",",
"*",
"*",
"kwargs",
")",
":",
"p1",
"=",
"(",
"0",
",",
"scale",
"-",
"i",
",",
"i",
")",
"p2",
"=",
"(",
"scale",
"-",
"i",
",",
"0",
",",
"i",
")",
"line",
"(",
"ax",
... | Draws the i-th line parallel to the right axis.
Parameters
----------
ax: Matplotlib AxesSubplot
The subplot to draw on.
scale: float
Simplex scale size.
i: float
The index of the line to draw
kwargs: Dictionary
Any kwargs to pass through to Matplotlib. | [
"Draws",
"the",
"i",
"-",
"th",
"line",
"parallel",
"to",
"the",
"right",
"axis",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L76-L94 | train | 200,094 |
marcharper/python-ternary | ternary/lines.py | boundary | def boundary(ax, scale, axes_colors=None, **kwargs):
"""
Plots the boundary of the simplex. Creates and returns matplotlib axis if
none given.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
kwargs:
Any kwargs to pass through to matplotlib.
axes_colors: dict
Option for coloring boundaries different colors.
e.g. {'l': 'g'} for coloring the left axis boundary green
"""
# Set default color as black.
if axes_colors is None:
axes_colors = dict()
for _axis in ['l', 'r', 'b']:
if _axis not in axes_colors.keys():
axes_colors[_axis] = 'black'
horizontal_line(ax, scale, 0, color=axes_colors['b'], **kwargs)
left_parallel_line(ax, scale, 0, color=axes_colors['l'], **kwargs)
right_parallel_line(ax, scale, 0, color=axes_colors['r'], **kwargs)
return ax | python | def boundary(ax, scale, axes_colors=None, **kwargs):
"""
Plots the boundary of the simplex. Creates and returns matplotlib axis if
none given.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
kwargs:
Any kwargs to pass through to matplotlib.
axes_colors: dict
Option for coloring boundaries different colors.
e.g. {'l': 'g'} for coloring the left axis boundary green
"""
# Set default color as black.
if axes_colors is None:
axes_colors = dict()
for _axis in ['l', 'r', 'b']:
if _axis not in axes_colors.keys():
axes_colors[_axis] = 'black'
horizontal_line(ax, scale, 0, color=axes_colors['b'], **kwargs)
left_parallel_line(ax, scale, 0, color=axes_colors['l'], **kwargs)
right_parallel_line(ax, scale, 0, color=axes_colors['r'], **kwargs)
return ax | [
"def",
"boundary",
"(",
"ax",
",",
"scale",
",",
"axes_colors",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set default color as black.",
"if",
"axes_colors",
"is",
"None",
":",
"axes_colors",
"=",
"dict",
"(",
")",
"for",
"_axis",
"in",
"[",
"'l'... | Plots the boundary of the simplex. Creates and returns matplotlib axis if
none given.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
kwargs:
Any kwargs to pass through to matplotlib.
axes_colors: dict
Option for coloring boundaries different colors.
e.g. {'l': 'g'} for coloring the left axis boundary green | [
"Plots",
"the",
"boundary",
"of",
"the",
"simplex",
".",
"Creates",
"and",
"returns",
"matplotlib",
"axis",
"if",
"none",
"given",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L99-L127 | train | 200,095 |
marcharper/python-ternary | ternary/lines.py | gridlines | def gridlines(ax, scale, multiple=None, horizontal_kwargs=None,
left_kwargs=None, right_kwargs=None, **kwargs):
"""
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
multiple: float, None
Specifies which inner gridelines to draw. For example, if scale=30 and
multiple=6, only 5 inner gridlines will be drawn.
horizontal_kwargs: dict, None
Any kwargs to pass through to matplotlib for horizontal gridlines
left_kwargs: dict, None
Any kwargs to pass through to matplotlib for left parallel gridlines
right_kwargs: dict, None
Any kwargs to pass through to matplotlib for right parallel gridlines
kwargs:
Any kwargs to pass through to matplotlib, if not using
horizontal_kwargs, left_kwargs, or right_kwargs
"""
if 'linewidth' not in kwargs:
kwargs["linewidth"] = 0.5
if 'linestyle' not in kwargs:
kwargs["linestyle"] = ':'
horizontal_kwargs = merge_dicts(kwargs, horizontal_kwargs)
left_kwargs = merge_dicts(kwargs, left_kwargs)
right_kwargs = merge_dicts(kwargs, right_kwargs)
if not multiple:
multiple = 1.
## Draw grid-lines
# Parallel to horizontal axis
for i in arange(0, scale, multiple):
horizontal_line(ax, scale, i, **horizontal_kwargs)
# Parallel to left and right axes
for i in arange(0, scale + multiple, multiple):
left_parallel_line(ax, scale, i, **left_kwargs)
right_parallel_line(ax, scale, i, **right_kwargs)
return ax | python | def gridlines(ax, scale, multiple=None, horizontal_kwargs=None,
left_kwargs=None, right_kwargs=None, **kwargs):
"""
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
multiple: float, None
Specifies which inner gridelines to draw. For example, if scale=30 and
multiple=6, only 5 inner gridlines will be drawn.
horizontal_kwargs: dict, None
Any kwargs to pass through to matplotlib for horizontal gridlines
left_kwargs: dict, None
Any kwargs to pass through to matplotlib for left parallel gridlines
right_kwargs: dict, None
Any kwargs to pass through to matplotlib for right parallel gridlines
kwargs:
Any kwargs to pass through to matplotlib, if not using
horizontal_kwargs, left_kwargs, or right_kwargs
"""
if 'linewidth' not in kwargs:
kwargs["linewidth"] = 0.5
if 'linestyle' not in kwargs:
kwargs["linestyle"] = ':'
horizontal_kwargs = merge_dicts(kwargs, horizontal_kwargs)
left_kwargs = merge_dicts(kwargs, left_kwargs)
right_kwargs = merge_dicts(kwargs, right_kwargs)
if not multiple:
multiple = 1.
## Draw grid-lines
# Parallel to horizontal axis
for i in arange(0, scale, multiple):
horizontal_line(ax, scale, i, **horizontal_kwargs)
# Parallel to left and right axes
for i in arange(0, scale + multiple, multiple):
left_parallel_line(ax, scale, i, **left_kwargs)
right_parallel_line(ax, scale, i, **right_kwargs)
return ax | [
"def",
"gridlines",
"(",
"ax",
",",
"scale",
",",
"multiple",
"=",
"None",
",",
"horizontal_kwargs",
"=",
"None",
",",
"left_kwargs",
"=",
"None",
",",
"right_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'linewidth'",
"not",
"in",
"k... | Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
multiple: float, None
Specifies which inner gridelines to draw. For example, if scale=30 and
multiple=6, only 5 inner gridlines will be drawn.
horizontal_kwargs: dict, None
Any kwargs to pass through to matplotlib for horizontal gridlines
left_kwargs: dict, None
Any kwargs to pass through to matplotlib for left parallel gridlines
right_kwargs: dict, None
Any kwargs to pass through to matplotlib for right parallel gridlines
kwargs:
Any kwargs to pass through to matplotlib, if not using
horizontal_kwargs, left_kwargs, or right_kwargs | [
"Plots",
"grid",
"lines",
"excluding",
"boundary",
"."
] | a4bef393ec9df130d4b55707293c750498a01843 | https://github.com/marcharper/python-ternary/blob/a4bef393ec9df130d4b55707293c750498a01843/ternary/lines.py#L150-L192 | train | 200,096 |
ymoch/apyori | apyori.py | create_next_candidates | def create_next_candidates(prev_candidates, length):
"""
Returns the apriori candidates as a list.
Arguments:
prev_candidates -- Previous candidates as a list.
length -- The lengths of the next candidates.
"""
# Solve the items.
item_set = set()
for candidate in prev_candidates:
for item in candidate:
item_set.add(item)
items = sorted(item_set)
# Create the temporary candidates. These will be filtered below.
tmp_next_candidates = (frozenset(x) for x in combinations(items, length))
# Return all the candidates if the length of the next candidates is 2
# because their subsets are the same as items.
if length < 3:
return list(tmp_next_candidates)
# Filter candidates that all of their subsets are
# in the previous candidates.
next_candidates = [
candidate for candidate in tmp_next_candidates
if all(
True if frozenset(x) in prev_candidates else False
for x in combinations(candidate, length - 1))
]
return next_candidates | python | def create_next_candidates(prev_candidates, length):
"""
Returns the apriori candidates as a list.
Arguments:
prev_candidates -- Previous candidates as a list.
length -- The lengths of the next candidates.
"""
# Solve the items.
item_set = set()
for candidate in prev_candidates:
for item in candidate:
item_set.add(item)
items = sorted(item_set)
# Create the temporary candidates. These will be filtered below.
tmp_next_candidates = (frozenset(x) for x in combinations(items, length))
# Return all the candidates if the length of the next candidates is 2
# because their subsets are the same as items.
if length < 3:
return list(tmp_next_candidates)
# Filter candidates that all of their subsets are
# in the previous candidates.
next_candidates = [
candidate for candidate in tmp_next_candidates
if all(
True if frozenset(x) in prev_candidates else False
for x in combinations(candidate, length - 1))
]
return next_candidates | [
"def",
"create_next_candidates",
"(",
"prev_candidates",
",",
"length",
")",
":",
"# Solve the items.",
"item_set",
"=",
"set",
"(",
")",
"for",
"candidate",
"in",
"prev_candidates",
":",
"for",
"item",
"in",
"candidate",
":",
"item_set",
".",
"add",
"(",
"ite... | Returns the apriori candidates as a list.
Arguments:
prev_candidates -- Previous candidates as a list.
length -- The lengths of the next candidates. | [
"Returns",
"the",
"apriori",
"candidates",
"as",
"a",
"list",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L136-L167 | train | 200,097 |
ymoch/apyori | apyori.py | gen_support_records | def gen_support_records(transaction_manager, min_support, **kwargs):
"""
Returns a generator of support records with given transactions.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
min_support -- A minimum support (float).
Keyword arguments:
max_length -- The maximum length of relations (integer).
"""
# Parse arguments.
max_length = kwargs.get('max_length')
# For testing.
_create_next_candidates = kwargs.get(
'_create_next_candidates', create_next_candidates)
# Process.
candidates = transaction_manager.initial_candidates()
length = 1
while candidates:
relations = set()
for relation_candidate in candidates:
support = transaction_manager.calc_support(relation_candidate)
if support < min_support:
continue
candidate_set = frozenset(relation_candidate)
relations.add(candidate_set)
yield SupportRecord(candidate_set, support)
length += 1
if max_length and length > max_length:
break
candidates = _create_next_candidates(relations, length) | python | def gen_support_records(transaction_manager, min_support, **kwargs):
"""
Returns a generator of support records with given transactions.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
min_support -- A minimum support (float).
Keyword arguments:
max_length -- The maximum length of relations (integer).
"""
# Parse arguments.
max_length = kwargs.get('max_length')
# For testing.
_create_next_candidates = kwargs.get(
'_create_next_candidates', create_next_candidates)
# Process.
candidates = transaction_manager.initial_candidates()
length = 1
while candidates:
relations = set()
for relation_candidate in candidates:
support = transaction_manager.calc_support(relation_candidate)
if support < min_support:
continue
candidate_set = frozenset(relation_candidate)
relations.add(candidate_set)
yield SupportRecord(candidate_set, support)
length += 1
if max_length and length > max_length:
break
candidates = _create_next_candidates(relations, length) | [
"def",
"gen_support_records",
"(",
"transaction_manager",
",",
"min_support",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse arguments.",
"max_length",
"=",
"kwargs",
".",
"get",
"(",
"'max_length'",
")",
"# For testing.",
"_create_next_candidates",
"=",
"kwargs",
".",... | Returns a generator of support records with given transactions.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
min_support -- A minimum support (float).
Keyword arguments:
max_length -- The maximum length of relations (integer). | [
"Returns",
"a",
"generator",
"of",
"support",
"records",
"with",
"given",
"transactions",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L170-L203 | train | 200,098 |
ymoch/apyori | apyori.py | gen_ordered_statistics | def gen_ordered_statistics(transaction_manager, record):
"""
Returns a generator of ordered statistics as OrderedStatistic instances.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
record -- A support record as a SupportRecord instance.
"""
items = record.items
for combination_set in combinations(sorted(items), len(items) - 1):
items_base = frozenset(combination_set)
items_add = frozenset(items.difference(items_base))
confidence = (
record.support / transaction_manager.calc_support(items_base))
lift = confidence / transaction_manager.calc_support(items_add)
yield OrderedStatistic(
frozenset(items_base), frozenset(items_add), confidence, lift) | python | def gen_ordered_statistics(transaction_manager, record):
"""
Returns a generator of ordered statistics as OrderedStatistic instances.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
record -- A support record as a SupportRecord instance.
"""
items = record.items
for combination_set in combinations(sorted(items), len(items) - 1):
items_base = frozenset(combination_set)
items_add = frozenset(items.difference(items_base))
confidence = (
record.support / transaction_manager.calc_support(items_base))
lift = confidence / transaction_manager.calc_support(items_add)
yield OrderedStatistic(
frozenset(items_base), frozenset(items_add), confidence, lift) | [
"def",
"gen_ordered_statistics",
"(",
"transaction_manager",
",",
"record",
")",
":",
"items",
"=",
"record",
".",
"items",
"for",
"combination_set",
"in",
"combinations",
"(",
"sorted",
"(",
"items",
")",
",",
"len",
"(",
"items",
")",
"-",
"1",
")",
":",... | Returns a generator of ordered statistics as OrderedStatistic instances.
Arguments:
transaction_manager -- Transactions as a TransactionManager instance.
record -- A support record as a SupportRecord instance. | [
"Returns",
"a",
"generator",
"of",
"ordered",
"statistics",
"as",
"OrderedStatistic",
"instances",
"."
] | 8cc20a19d01b18b83e18e54aabb416c8dedabfde | https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L206-L222 | train | 200,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.