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
dhermes/bezier
src/bezier/_geometric_intersection.py
prune_candidates
def prune_candidates(candidates): """Reduce number of candidate intersection pairs. .. note:: This is a helper for :func:`_all_intersections`. Uses more strict bounding box intersection predicate by forming the actual convex hull of each candidate curve segment and then checking if those convex hulls collide. Args: candidates (List): An iterable of pairs of curves (or linearized curves). Returns: List: A pruned list of curve pairs. """ pruned = [] # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. for first, second in candidates: if first.__class__ is Linearization: nodes1 = first.curve.nodes else: nodes1 = first.nodes if second.__class__ is Linearization: nodes2 = second.curve.nodes else: nodes2 = second.nodes if convex_hull_collide(nodes1, nodes2): pruned.append((first, second)) return pruned
python
def prune_candidates(candidates): """Reduce number of candidate intersection pairs. .. note:: This is a helper for :func:`_all_intersections`. Uses more strict bounding box intersection predicate by forming the actual convex hull of each candidate curve segment and then checking if those convex hulls collide. Args: candidates (List): An iterable of pairs of curves (or linearized curves). Returns: List: A pruned list of curve pairs. """ pruned = [] # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. for first, second in candidates: if first.__class__ is Linearization: nodes1 = first.curve.nodes else: nodes1 = first.nodes if second.__class__ is Linearization: nodes2 = second.curve.nodes else: nodes2 = second.nodes if convex_hull_collide(nodes1, nodes2): pruned.append((first, second)) return pruned
[ "def", "prune_candidates", "(", "candidates", ")", ":", "pruned", "=", "[", "]", "# NOTE: In the below we replace ``isinstance(a, B)`` with", "# ``a.__class__ is B``, which is a 3-3.5x speedup.", "for", "first", ",", "second", "in", "candidates", ":", "if", "first", "...
Reduce number of candidate intersection pairs. .. note:: This is a helper for :func:`_all_intersections`. Uses more strict bounding box intersection predicate by forming the actual convex hull of each candidate curve segment and then checking if those convex hulls collide. Args: candidates (List): An iterable of pairs of curves (or linearized curves). Returns: List: A pruned list of curve pairs.
[ "Reduce", "number", "of", "candidate", "intersection", "pairs", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1145-L1177
train
54,200
dhermes/bezier
src/bezier/_geometric_intersection.py
make_same_degree
def make_same_degree(nodes1, nodes2): """Degree-elevate a curve so two curves have matching degree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The potentially degree-elevated nodes passed in. """ _, num_nodes1 = nodes1.shape _, num_nodes2 = nodes2.shape for _ in six.moves.xrange(num_nodes2 - num_nodes1): nodes1 = _curve_helpers.elevate_nodes(nodes1) for _ in six.moves.xrange(num_nodes1 - num_nodes2): nodes2 = _curve_helpers.elevate_nodes(nodes2) return nodes1, nodes2
python
def make_same_degree(nodes1, nodes2): """Degree-elevate a curve so two curves have matching degree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The potentially degree-elevated nodes passed in. """ _, num_nodes1 = nodes1.shape _, num_nodes2 = nodes2.shape for _ in six.moves.xrange(num_nodes2 - num_nodes1): nodes1 = _curve_helpers.elevate_nodes(nodes1) for _ in six.moves.xrange(num_nodes1 - num_nodes2): nodes2 = _curve_helpers.elevate_nodes(nodes2) return nodes1, nodes2
[ "def", "make_same_degree", "(", "nodes1", ",", "nodes2", ")", ":", "_", ",", "num_nodes1", "=", "nodes1", ".", "shape", "_", ",", "num_nodes2", "=", "nodes2", ".", "shape", "for", "_", "in", "six", ".", "moves", ".", "xrange", "(", "num_nodes2", "-", ...
Degree-elevate a curve so two curves have matching degree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The potentially degree-elevated nodes passed in.
[ "Degree", "-", "elevate", "a", "curve", "so", "two", "curves", "have", "matching", "degree", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1180-L1199
train
54,201
dhermes/bezier
src/bezier/_geometric_intersection.py
coincident_parameters
def coincident_parameters(nodes1, nodes2): r"""Check if two B |eacute| zier curves are coincident. Does so by projecting each segment endpoint onto the other curve .. math:: B_1(s_0) = B_2(0) B_1(s_m) = B_2(1) B_1(0) = B_2(t_0) B_1(1) = B_2(t_n) and then finding the "shared interval" where both curves are defined. If such an interval can't be found (e.g. if one of the endpoints can't be located on the other curve), returns :data:`None`. If such a "shared interval" does exist, then this will specialize each curve onto that shared interval and check if the new control points agree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Optional[Tuple[Tuple[float, float], ...]]: A ``2 x 2`` array of parameters where the two coincident curves meet. If they are not coincident, returns :data:`None`. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-return-statements,too-many-branches nodes1, nodes2 = make_same_degree(nodes1, nodes2) s_initial = _curve_helpers.locate_point( nodes1, nodes2[:, 0].reshape((2, 1), order="F") ) s_final = _curve_helpers.locate_point( nodes1, nodes2[:, -1].reshape((2, 1), order="F") ) if s_initial is not None and s_final is not None: # In this case, if the curves were coincident, then ``curve2`` # would be "fully" contained in ``curve1``, so we specialize # ``curve1`` down to that interval to check. specialized1 = _curve_helpers.specialize_curve( nodes1, s_initial, s_final ) if _helpers.vector_close( specialized1.ravel(order="F"), nodes2.ravel(order="F") ): return ((s_initial, 0.0), (s_final, 1.0)) else: return None t_initial = _curve_helpers.locate_point( nodes2, nodes1[:, 0].reshape((2, 1), order="F") ) t_final = _curve_helpers.locate_point( nodes2, nodes1[:, -1].reshape((2, 1), order="F") ) if t_initial is None and t_final is None: # An overlap must have two endpoints and since at most one of the # endpoints of ``curve2`` lies on ``curve1`` (as indicated by at # least one of the ``s``-parameters being ``None``), we need (at least) # one endpoint of ``curve1`` on ``curve2``. return None if t_initial is not None and t_final is not None: # In this case, if the curves were coincident, then ``curve1`` # would be "fully" contained in ``curve2``, so we specialize # ``curve2`` down to that interval to check. specialized2 = _curve_helpers.specialize_curve( nodes2, t_initial, t_final ) if _helpers.vector_close( nodes1.ravel(order="F"), specialized2.ravel(order="F") ): return ((0.0, t_initial), (1.0, t_final)) else: return None if s_initial is None and s_final is None: # An overlap must have two endpoints and since exactly one of the # endpoints of ``curve1`` lies on ``curve2`` (as indicated by exactly # one of the ``t``-parameters being ``None``), we need (at least) # one endpoint of ``curve1`` on ``curve2``. return None # At this point, we know exactly one of the ``s``-parameters and exactly # one of the ``t``-parameters is not ``None``. if s_initial is None: if t_initial is None: # B1(s_final) = B2(1) AND B1(1) = B2(t_final) start_s = s_final end_s = 1.0 start_t = 1.0 end_t = t_final else: # B1(0) = B2(t_initial) AND B1(s_final) = B2(1) start_s = 0.0 end_s = s_final start_t = t_initial end_t = 1.0 else: if t_initial is None: # B1(s_initial) = B2(0) AND B1(1 ) = B2(t_final) start_s = s_initial end_s = 1.0 start_t = 0.0 end_t = t_final else: # B1(0) = B2(t_initial) AND B1(s_initial) = B2(0) start_s = 0.0 end_s = s_initial start_t = t_initial end_t = 0.0 width_s = abs(start_s - end_s) width_t = abs(start_t - end_t) if width_s < _MIN_INTERVAL_WIDTH and width_t < _MIN_INTERVAL_WIDTH: return None specialized1 = _curve_helpers.specialize_curve(nodes1, start_s, end_s) specialized2 = _curve_helpers.specialize_curve(nodes2, start_t, end_t) if _helpers.vector_close( specialized1.ravel(order="F"), specialized2.ravel(order="F") ): return ((start_s, start_t), (end_s, end_t)) else: return None
python
def coincident_parameters(nodes1, nodes2): r"""Check if two B |eacute| zier curves are coincident. Does so by projecting each segment endpoint onto the other curve .. math:: B_1(s_0) = B_2(0) B_1(s_m) = B_2(1) B_1(0) = B_2(t_0) B_1(1) = B_2(t_n) and then finding the "shared interval" where both curves are defined. If such an interval can't be found (e.g. if one of the endpoints can't be located on the other curve), returns :data:`None`. If such a "shared interval" does exist, then this will specialize each curve onto that shared interval and check if the new control points agree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Optional[Tuple[Tuple[float, float], ...]]: A ``2 x 2`` array of parameters where the two coincident curves meet. If they are not coincident, returns :data:`None`. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-return-statements,too-many-branches nodes1, nodes2 = make_same_degree(nodes1, nodes2) s_initial = _curve_helpers.locate_point( nodes1, nodes2[:, 0].reshape((2, 1), order="F") ) s_final = _curve_helpers.locate_point( nodes1, nodes2[:, -1].reshape((2, 1), order="F") ) if s_initial is not None and s_final is not None: # In this case, if the curves were coincident, then ``curve2`` # would be "fully" contained in ``curve1``, so we specialize # ``curve1`` down to that interval to check. specialized1 = _curve_helpers.specialize_curve( nodes1, s_initial, s_final ) if _helpers.vector_close( specialized1.ravel(order="F"), nodes2.ravel(order="F") ): return ((s_initial, 0.0), (s_final, 1.0)) else: return None t_initial = _curve_helpers.locate_point( nodes2, nodes1[:, 0].reshape((2, 1), order="F") ) t_final = _curve_helpers.locate_point( nodes2, nodes1[:, -1].reshape((2, 1), order="F") ) if t_initial is None and t_final is None: # An overlap must have two endpoints and since at most one of the # endpoints of ``curve2`` lies on ``curve1`` (as indicated by at # least one of the ``s``-parameters being ``None``), we need (at least) # one endpoint of ``curve1`` on ``curve2``. return None if t_initial is not None and t_final is not None: # In this case, if the curves were coincident, then ``curve1`` # would be "fully" contained in ``curve2``, so we specialize # ``curve2`` down to that interval to check. specialized2 = _curve_helpers.specialize_curve( nodes2, t_initial, t_final ) if _helpers.vector_close( nodes1.ravel(order="F"), specialized2.ravel(order="F") ): return ((0.0, t_initial), (1.0, t_final)) else: return None if s_initial is None and s_final is None: # An overlap must have two endpoints and since exactly one of the # endpoints of ``curve1`` lies on ``curve2`` (as indicated by exactly # one of the ``t``-parameters being ``None``), we need (at least) # one endpoint of ``curve1`` on ``curve2``. return None # At this point, we know exactly one of the ``s``-parameters and exactly # one of the ``t``-parameters is not ``None``. if s_initial is None: if t_initial is None: # B1(s_final) = B2(1) AND B1(1) = B2(t_final) start_s = s_final end_s = 1.0 start_t = 1.0 end_t = t_final else: # B1(0) = B2(t_initial) AND B1(s_final) = B2(1) start_s = 0.0 end_s = s_final start_t = t_initial end_t = 1.0 else: if t_initial is None: # B1(s_initial) = B2(0) AND B1(1 ) = B2(t_final) start_s = s_initial end_s = 1.0 start_t = 0.0 end_t = t_final else: # B1(0) = B2(t_initial) AND B1(s_initial) = B2(0) start_s = 0.0 end_s = s_initial start_t = t_initial end_t = 0.0 width_s = abs(start_s - end_s) width_t = abs(start_t - end_t) if width_s < _MIN_INTERVAL_WIDTH and width_t < _MIN_INTERVAL_WIDTH: return None specialized1 = _curve_helpers.specialize_curve(nodes1, start_s, end_s) specialized2 = _curve_helpers.specialize_curve(nodes2, start_t, end_t) if _helpers.vector_close( specialized1.ravel(order="F"), specialized2.ravel(order="F") ): return ((start_s, start_t), (end_s, end_t)) else: return None
[ "def", "coincident_parameters", "(", "nodes1", ",", "nodes2", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-return-statements,too-many-branches", "nodes1", ",", "nodes2", "=", "make_...
r"""Check if two B |eacute| zier curves are coincident. Does so by projecting each segment endpoint onto the other curve .. math:: B_1(s_0) = B_2(0) B_1(s_m) = B_2(1) B_1(0) = B_2(t_0) B_1(1) = B_2(t_n) and then finding the "shared interval" where both curves are defined. If such an interval can't be found (e.g. if one of the endpoints can't be located on the other curve), returns :data:`None`. If such a "shared interval" does exist, then this will specialize each curve onto that shared interval and check if the new control points agree. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier curve. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier curve. Returns: Optional[Tuple[Tuple[float, float], ...]]: A ``2 x 2`` array of parameters where the two coincident curves meet. If they are not coincident, returns :data:`None`.
[ "r", "Check", "if", "two", "B", "|eacute|", "zier", "curves", "are", "coincident", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1202-L1334
train
54,202
dhermes/bezier
src/bezier/_geometric_intersection.py
check_lines
def check_lines(first, second): """Checks if two curves are lines and tries to intersect them. .. note:: This is a helper for :func:`._all_intersections`. If they are not lines / not linearized, immediately returns :data:`False` with no "return value". If they are lines, attempts to intersect them (even if they are parallel and share a coincident segment). Args: first (Union[SubdividedCurve, Linearization]): First curve being intersected. second (Union[SubdividedCurve, Linearization]): Second curve being intersected. Returns: Tuple[bool, Optional[Tuple[numpy.ndarray, bool]]]: A pair of * Flag indicating if both candidates in the pair are lines. * Optional "result" populated only if both candidates are lines. When this result is populated, it will be a pair of * array of parameters of intersection * flag indicating if the two candidates share a coincident segment """ # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. if not ( first.__class__ is Linearization and second.__class__ is Linearization and first.error == 0.0 and second.error == 0.0 ): return False, None s, t, success = segment_intersection( first.start_node, first.end_node, second.start_node, second.end_node ) if success: if _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval( t, 0.0, 1.0 ): intersections = np.asfortranarray([[s], [t]]) result = intersections, False else: result = np.empty((2, 0), order="F"), False else: disjoint, params = parallel_lines_parameters( first.start_node, first.end_node, second.start_node, second.end_node, ) if disjoint: result = np.empty((2, 0), order="F"), False else: result = params, True return True, result
python
def check_lines(first, second): """Checks if two curves are lines and tries to intersect them. .. note:: This is a helper for :func:`._all_intersections`. If they are not lines / not linearized, immediately returns :data:`False` with no "return value". If they are lines, attempts to intersect them (even if they are parallel and share a coincident segment). Args: first (Union[SubdividedCurve, Linearization]): First curve being intersected. second (Union[SubdividedCurve, Linearization]): Second curve being intersected. Returns: Tuple[bool, Optional[Tuple[numpy.ndarray, bool]]]: A pair of * Flag indicating if both candidates in the pair are lines. * Optional "result" populated only if both candidates are lines. When this result is populated, it will be a pair of * array of parameters of intersection * flag indicating if the two candidates share a coincident segment """ # NOTE: In the below we replace ``isinstance(a, B)`` with # ``a.__class__ is B``, which is a 3-3.5x speedup. if not ( first.__class__ is Linearization and second.__class__ is Linearization and first.error == 0.0 and second.error == 0.0 ): return False, None s, t, success = segment_intersection( first.start_node, first.end_node, second.start_node, second.end_node ) if success: if _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval( t, 0.0, 1.0 ): intersections = np.asfortranarray([[s], [t]]) result = intersections, False else: result = np.empty((2, 0), order="F"), False else: disjoint, params = parallel_lines_parameters( first.start_node, first.end_node, second.start_node, second.end_node, ) if disjoint: result = np.empty((2, 0), order="F"), False else: result = params, True return True, result
[ "def", "check_lines", "(", "first", ",", "second", ")", ":", "# NOTE: In the below we replace ``isinstance(a, B)`` with", "# ``a.__class__ is B``, which is a 3-3.5x speedup.", "if", "not", "(", "first", ".", "__class__", "is", "Linearization", "and", "second", ".", "_...
Checks if two curves are lines and tries to intersect them. .. note:: This is a helper for :func:`._all_intersections`. If they are not lines / not linearized, immediately returns :data:`False` with no "return value". If they are lines, attempts to intersect them (even if they are parallel and share a coincident segment). Args: first (Union[SubdividedCurve, Linearization]): First curve being intersected. second (Union[SubdividedCurve, Linearization]): Second curve being intersected. Returns: Tuple[bool, Optional[Tuple[numpy.ndarray, bool]]]: A pair of * Flag indicating if both candidates in the pair are lines. * Optional "result" populated only if both candidates are lines. When this result is populated, it will be a pair of * array of parameters of intersection * flag indicating if the two candidates share a coincident segment
[ "Checks", "if", "two", "curves", "are", "lines", "and", "tries", "to", "intersect", "them", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1337-L1398
train
54,203
dhermes/bezier
src/bezier/_geometric_intersection.py
SubdividedCurve.subdivide
def subdivide(self): """Split the curve into a left and right half. See :meth:`.Curve.subdivide` for more information. Returns: Tuple[SubdividedCurve, SubdividedCurve]: The left and right sub-curves. """ left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self.nodes) midpoint = 0.5 * (self.start + self.end) left = SubdividedCurve( left_nodes, self.original_nodes, start=self.start, end=midpoint ) right = SubdividedCurve( right_nodes, self.original_nodes, start=midpoint, end=self.end ) return left, right
python
def subdivide(self): """Split the curve into a left and right half. See :meth:`.Curve.subdivide` for more information. Returns: Tuple[SubdividedCurve, SubdividedCurve]: The left and right sub-curves. """ left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self.nodes) midpoint = 0.5 * (self.start + self.end) left = SubdividedCurve( left_nodes, self.original_nodes, start=self.start, end=midpoint ) right = SubdividedCurve( right_nodes, self.original_nodes, start=midpoint, end=self.end ) return left, right
[ "def", "subdivide", "(", "self", ")", ":", "left_nodes", ",", "right_nodes", "=", "_curve_helpers", ".", "subdivide_nodes", "(", "self", ".", "nodes", ")", "midpoint", "=", "0.5", "*", "(", "self", ".", "start", "+", "self", ".", "end", ")", "left", "=...
Split the curve into a left and right half. See :meth:`.Curve.subdivide` for more information. Returns: Tuple[SubdividedCurve, SubdividedCurve]: The left and right sub-curves.
[ "Split", "the", "curve", "into", "a", "left", "and", "right", "half", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1543-L1560
train
54,204
dhermes/bezier
src/bezier/curve.py
Curve.plot
def plot(self, num_pts, color=None, alpha=None, ax=None): """Plot the current curve. Args: num_pts (int): Number of points to plot. color (Optional[Tuple[float, float, float]]): Color as RGB profile. alpha (Optional[float]): The alpha channel for the color. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the curve's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) s_vals = np.linspace(0.0, 1.0, num_pts) points = self.evaluate_multi(s_vals) if ax is None: ax = _plot_helpers.new_axis() ax.plot(points[0, :], points[1, :], color=color, alpha=alpha) return ax
python
def plot(self, num_pts, color=None, alpha=None, ax=None): """Plot the current curve. Args: num_pts (int): Number of points to plot. color (Optional[Tuple[float, float, float]]): Color as RGB profile. alpha (Optional[float]): The alpha channel for the color. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the curve's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) s_vals = np.linspace(0.0, 1.0, num_pts) points = self.evaluate_multi(s_vals) if ax is None: ax = _plot_helpers.new_axis() ax.plot(points[0, :], points[1, :], color=color, alpha=alpha) return ax
[ "def", "plot", "(", "self", ",", "num_pts", ",", "color", "=", "None", ",", "alpha", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"2D is the only supported dimension\...
Plot the current curve. Args: num_pts (int): Number of points to plot. color (Optional[Tuple[float, float, float]]): Color as RGB profile. alpha (Optional[float]): The alpha channel for the color. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the curve's dimension is not ``2``.
[ "Plot", "the", "current", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L245-L274
train
54,205
dhermes/bezier
src/bezier/curve.py
Curve.intersect
def intersect( self, other, strategy=IntersectionStrategy.GEOMETRIC, _verify=True ): """Find the points of intersection with another curve. See :doc:`../../algorithms/curve-curve-intersection` for more details. .. image:: ../../images/curve_intersect.png :align: center .. doctest:: curve-intersect :options: +NORMALIZE_WHITESPACE >>> nodes1 = np.asfortranarray([ ... [0.0, 0.375, 0.75 ], ... [0.0, 0.75 , 0.375], ... ]) >>> curve1 = bezier.Curve(nodes1, degree=2) >>> nodes2 = np.asfortranarray([ ... [0.5, 0.5 ], ... [0.0, 0.75], ... ]) >>> curve2 = bezier.Curve(nodes2, degree=1) >>> intersections = curve1.intersect(curve2) >>> 3.0 * intersections array([[2.], [2.]]) >>> s_vals = intersections[0, :] >>> curve1.evaluate_multi(s_vals) array([[0.5], [0.5]]) .. testcleanup:: curve-intersect import make_images make_images.curve_intersect(curve1, curve2, s_vals) Args: other (Curve): Other curve to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the input and current curve. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: numpy.ndarray: ``2 x N`` array of ``s``- and ``t``-parameters where intersections occur (possibly empty). Raises: TypeError: If ``other`` is not a curve (and ``_verify=True``). NotImplementedError: If at least one of the curves isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Curve): raise TypeError( "Can only intersect with another curve", "Received", other ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == IntersectionStrategy.GEOMETRIC: all_intersections = _geometric_intersection.all_intersections elif strategy == IntersectionStrategy.ALGEBRAIC: all_intersections = _algebraic_intersection.all_intersections else: raise ValueError("Unexpected strategy.", strategy) st_vals, _ = all_intersections(self._nodes, other._nodes) return st_vals
python
def intersect( self, other, strategy=IntersectionStrategy.GEOMETRIC, _verify=True ): """Find the points of intersection with another curve. See :doc:`../../algorithms/curve-curve-intersection` for more details. .. image:: ../../images/curve_intersect.png :align: center .. doctest:: curve-intersect :options: +NORMALIZE_WHITESPACE >>> nodes1 = np.asfortranarray([ ... [0.0, 0.375, 0.75 ], ... [0.0, 0.75 , 0.375], ... ]) >>> curve1 = bezier.Curve(nodes1, degree=2) >>> nodes2 = np.asfortranarray([ ... [0.5, 0.5 ], ... [0.0, 0.75], ... ]) >>> curve2 = bezier.Curve(nodes2, degree=1) >>> intersections = curve1.intersect(curve2) >>> 3.0 * intersections array([[2.], [2.]]) >>> s_vals = intersections[0, :] >>> curve1.evaluate_multi(s_vals) array([[0.5], [0.5]]) .. testcleanup:: curve-intersect import make_images make_images.curve_intersect(curve1, curve2, s_vals) Args: other (Curve): Other curve to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the input and current curve. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: numpy.ndarray: ``2 x N`` array of ``s``- and ``t``-parameters where intersections occur (possibly empty). Raises: TypeError: If ``other`` is not a curve (and ``_verify=True``). NotImplementedError: If at least one of the curves isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Curve): raise TypeError( "Can only intersect with another curve", "Received", other ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == IntersectionStrategy.GEOMETRIC: all_intersections = _geometric_intersection.all_intersections elif strategy == IntersectionStrategy.ALGEBRAIC: all_intersections = _algebraic_intersection.all_intersections else: raise ValueError("Unexpected strategy.", strategy) st_vals, _ = all_intersections(self._nodes, other._nodes) return st_vals
[ "def", "intersect", "(", "self", ",", "other", ",", "strategy", "=", "IntersectionStrategy", ".", "GEOMETRIC", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "not", "isinstance", "(", "other", ",", "Curve", ")", ":", "raise", "TypeErr...
Find the points of intersection with another curve. See :doc:`../../algorithms/curve-curve-intersection` for more details. .. image:: ../../images/curve_intersect.png :align: center .. doctest:: curve-intersect :options: +NORMALIZE_WHITESPACE >>> nodes1 = np.asfortranarray([ ... [0.0, 0.375, 0.75 ], ... [0.0, 0.75 , 0.375], ... ]) >>> curve1 = bezier.Curve(nodes1, degree=2) >>> nodes2 = np.asfortranarray([ ... [0.5, 0.5 ], ... [0.0, 0.75], ... ]) >>> curve2 = bezier.Curve(nodes2, degree=1) >>> intersections = curve1.intersect(curve2) >>> 3.0 * intersections array([[2.], [2.]]) >>> s_vals = intersections[0, :] >>> curve1.evaluate_multi(s_vals) array([[0.5], [0.5]]) .. testcleanup:: curve-intersect import make_images make_images.curve_intersect(curve1, curve2, s_vals) Args: other (Curve): Other curve to intersect with. strategy (Optional[~bezier.curve.IntersectionStrategy]): The intersection algorithm to use. Defaults to geometric. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the input and current curve. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: numpy.ndarray: ``2 x N`` array of ``s``- and ``t``-parameters where intersections occur (possibly empty). Raises: TypeError: If ``other`` is not a curve (and ``_verify=True``). NotImplementedError: If at least one of the curves isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`.
[ "Find", "the", "points", "of", "intersection", "with", "another", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L317-L393
train
54,206
dhermes/bezier
src/bezier/curve.py
Curve.elevate
def elevate(self): r"""Return a degree-elevated version of the current curve. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. image:: ../../images/curve_elevate.png :align: center .. testsetup:: curve-elevate import numpy as np import bezier .. doctest:: curve-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0], ... [0.0, 1.5, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> elevated = curve.elevate() >>> elevated <Curve (degree=3, dimension=2)> >>> elevated.nodes array([[0., 1., 2., 3.], [0., 1., 1., 0.]]) .. testcleanup:: curve-elevate import make_images make_images.curve_elevate(curve, elevated) Returns: Curve: The degree-elevated curve. """ new_nodes = _curve_helpers.elevate_nodes(self._nodes) return Curve(new_nodes, self._degree + 1, _copy=False)
python
def elevate(self): r"""Return a degree-elevated version of the current curve. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. image:: ../../images/curve_elevate.png :align: center .. testsetup:: curve-elevate import numpy as np import bezier .. doctest:: curve-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0], ... [0.0, 1.5, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> elevated = curve.elevate() >>> elevated <Curve (degree=3, dimension=2)> >>> elevated.nodes array([[0., 1., 2., 3.], [0., 1., 1., 0.]]) .. testcleanup:: curve-elevate import make_images make_images.curve_elevate(curve, elevated) Returns: Curve: The degree-elevated curve. """ new_nodes = _curve_helpers.elevate_nodes(self._nodes) return Curve(new_nodes, self._degree + 1, _copy=False)
[ "def", "elevate", "(", "self", ")", ":", "new_nodes", "=", "_curve_helpers", ".", "elevate_nodes", "(", "self", ".", "_nodes", ")", "return", "Curve", "(", "new_nodes", ",", "self", ".", "_degree", "+", "1", ",", "_copy", "=", "False", ")" ]
r"""Return a degree-elevated version of the current curve. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. image:: ../../images/curve_elevate.png :align: center .. testsetup:: curve-elevate import numpy as np import bezier .. doctest:: curve-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0], ... [0.0, 1.5, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> elevated = curve.elevate() >>> elevated <Curve (degree=3, dimension=2)> >>> elevated.nodes array([[0., 1., 2., 3.], [0., 1., 1., 0.]]) .. testcleanup:: curve-elevate import make_images make_images.curve_elevate(curve, elevated) Returns: Curve: The degree-elevated curve.
[ "r", "Return", "a", "degree", "-", "elevated", "version", "of", "the", "current", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L395-L441
train
54,207
dhermes/bezier
src/bezier/curve.py
Curve.reduce_
def reduce_(self): r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to reversing the :meth:`elevate` process. This uses the `pseudo-inverse`_ of the elevation matrix. For example when elevating from degree 2 to 3, the matrix :math:`E_2` is given by .. math:: \mathbf{v} = \left[\begin{array}{c c c} v_0 & v_1 & v_2 \end{array}\right] \longmapsto \left[\begin{array}{c c c c} v_0 & \frac{v_0 + 2 v_1}{3} & \frac{2 v_1 + v_2}{3} & v_2 \end{array}\right] = \frac{1}{3} \mathbf{v} \left[\begin{array}{c c c c} 3 & 1 & 0 & 0 \\ 0 & 2 & 2 & 0 \\ 0 & 0 & 1 & 3 \end{array}\right] and the (right) pseudo-inverse is given by .. math:: R_2 = E_2^T \left(E_2 E_2^T\right)^{-1} = \frac{1}{20} \left[\begin{array}{c c c} 19 & -5 & 1 \\ 3 & 15 & -3 \\ -3 & 15 & 3 \\ 1 & -5 & 19 \end{array}\right]. .. warning:: Though degree-elevation preserves the start and end nodes, degree reduction has no such guarantee. Rather, the nodes produced are "best" in the least squares sense (when solving the normal equations). .. image:: ../../images/curve_reduce.png :align: center .. testsetup:: curve-reduce, curve-reduce-approx import numpy as np import bezier .. doctest:: curve-reduce :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-3.0, 0.0, 1.0, 0.0], ... [ 3.0, 2.0, 3.0, 6.0], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-3. , 1.5, 0. ], [ 3. , 1.5, 6. ]]) .. testcleanup:: curve-reduce import make_images make_images.curve_reduce(curve, reduced) In the case that the current curve **is not** degree-elevated. .. image:: ../../images/curve_reduce_approx.png :align: center .. doctest:: curve-reduce-approx :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.25, 3.75, 5.0], ... [2.5, 5.0 , 7.5 , 2.5], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-0.125, 2.5 , 5.125], [ 2.125, 8.125, 2.875]]) .. testcleanup:: curve-reduce-approx import make_images make_images.curve_reduce_approx(curve, reduced) Returns: Curve: The degree-reduced curve. """ new_nodes = _curve_helpers.reduce_pseudo_inverse(self._nodes) return Curve(new_nodes, self._degree - 1, _copy=False)
python
def reduce_(self): r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to reversing the :meth:`elevate` process. This uses the `pseudo-inverse`_ of the elevation matrix. For example when elevating from degree 2 to 3, the matrix :math:`E_2` is given by .. math:: \mathbf{v} = \left[\begin{array}{c c c} v_0 & v_1 & v_2 \end{array}\right] \longmapsto \left[\begin{array}{c c c c} v_0 & \frac{v_0 + 2 v_1}{3} & \frac{2 v_1 + v_2}{3} & v_2 \end{array}\right] = \frac{1}{3} \mathbf{v} \left[\begin{array}{c c c c} 3 & 1 & 0 & 0 \\ 0 & 2 & 2 & 0 \\ 0 & 0 & 1 & 3 \end{array}\right] and the (right) pseudo-inverse is given by .. math:: R_2 = E_2^T \left(E_2 E_2^T\right)^{-1} = \frac{1}{20} \left[\begin{array}{c c c} 19 & -5 & 1 \\ 3 & 15 & -3 \\ -3 & 15 & 3 \\ 1 & -5 & 19 \end{array}\right]. .. warning:: Though degree-elevation preserves the start and end nodes, degree reduction has no such guarantee. Rather, the nodes produced are "best" in the least squares sense (when solving the normal equations). .. image:: ../../images/curve_reduce.png :align: center .. testsetup:: curve-reduce, curve-reduce-approx import numpy as np import bezier .. doctest:: curve-reduce :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-3.0, 0.0, 1.0, 0.0], ... [ 3.0, 2.0, 3.0, 6.0], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-3. , 1.5, 0. ], [ 3. , 1.5, 6. ]]) .. testcleanup:: curve-reduce import make_images make_images.curve_reduce(curve, reduced) In the case that the current curve **is not** degree-elevated. .. image:: ../../images/curve_reduce_approx.png :align: center .. doctest:: curve-reduce-approx :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.25, 3.75, 5.0], ... [2.5, 5.0 , 7.5 , 2.5], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-0.125, 2.5 , 5.125], [ 2.125, 8.125, 2.875]]) .. testcleanup:: curve-reduce-approx import make_images make_images.curve_reduce_approx(curve, reduced) Returns: Curve: The degree-reduced curve. """ new_nodes = _curve_helpers.reduce_pseudo_inverse(self._nodes) return Curve(new_nodes, self._degree - 1, _copy=False)
[ "def", "reduce_", "(", "self", ")", ":", "new_nodes", "=", "_curve_helpers", ".", "reduce_pseudo_inverse", "(", "self", ".", "_nodes", ")", "return", "Curve", "(", "new_nodes", ",", "self", ".", "_degree", "-", "1", ",", "_copy", "=", "False", ")" ]
r"""Return a degree-reduced version of the current curve. .. _pseudo-inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to reversing the :meth:`elevate` process. This uses the `pseudo-inverse`_ of the elevation matrix. For example when elevating from degree 2 to 3, the matrix :math:`E_2` is given by .. math:: \mathbf{v} = \left[\begin{array}{c c c} v_0 & v_1 & v_2 \end{array}\right] \longmapsto \left[\begin{array}{c c c c} v_0 & \frac{v_0 + 2 v_1}{3} & \frac{2 v_1 + v_2}{3} & v_2 \end{array}\right] = \frac{1}{3} \mathbf{v} \left[\begin{array}{c c c c} 3 & 1 & 0 & 0 \\ 0 & 2 & 2 & 0 \\ 0 & 0 & 1 & 3 \end{array}\right] and the (right) pseudo-inverse is given by .. math:: R_2 = E_2^T \left(E_2 E_2^T\right)^{-1} = \frac{1}{20} \left[\begin{array}{c c c} 19 & -5 & 1 \\ 3 & 15 & -3 \\ -3 & 15 & 3 \\ 1 & -5 & 19 \end{array}\right]. .. warning:: Though degree-elevation preserves the start and end nodes, degree reduction has no such guarantee. Rather, the nodes produced are "best" in the least squares sense (when solving the normal equations). .. image:: ../../images/curve_reduce.png :align: center .. testsetup:: curve-reduce, curve-reduce-approx import numpy as np import bezier .. doctest:: curve-reduce :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-3.0, 0.0, 1.0, 0.0], ... [ 3.0, 2.0, 3.0, 6.0], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-3. , 1.5, 0. ], [ 3. , 1.5, 6. ]]) .. testcleanup:: curve-reduce import make_images make_images.curve_reduce(curve, reduced) In the case that the current curve **is not** degree-elevated. .. image:: ../../images/curve_reduce_approx.png :align: center .. doctest:: curve-reduce-approx :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.25, 3.75, 5.0], ... [2.5, 5.0 , 7.5 , 2.5], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> reduced = curve.reduce_() >>> reduced <Curve (degree=2, dimension=2)> >>> reduced.nodes array([[-0.125, 2.5 , 5.125], [ 2.125, 8.125, 2.875]]) .. testcleanup:: curve-reduce-approx import make_images make_images.curve_reduce_approx(curve, reduced) Returns: Curve: The degree-reduced curve.
[ "r", "Return", "a", "degree", "-", "reduced", "version", "of", "the", "current", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L443-L538
train
54,208
dhermes/bezier
src/bezier/curve.py
Curve.specialize
def specialize(self, start, end): """Specialize the curve to a given sub-interval. .. image:: ../../images/curve_specialize.png :align: center .. doctest:: curve-specialize >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> new_curve = curve.specialize(-0.25, 0.75) >>> new_curve.nodes array([[-0.25 , 0.25 , 0.75 ], [-0.625, 0.875, 0.375]]) .. testcleanup:: curve-specialize import make_images make_images.curve_specialize(curve, new_curve) This is generalized version of :meth:`subdivide`, and can even match the output of that method: .. testsetup:: curve-specialize2 import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) curve = bezier.Curve(nodes, degree=2) .. doctest:: curve-specialize2 >>> left, right = curve.subdivide() >>> also_left = curve.specialize(0.0, 0.5) >>> np.all(also_left.nodes == left.nodes) True >>> also_right = curve.specialize(0.5, 1.0) >>> np.all(also_right.nodes == right.nodes) True Args: start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: Curve: The newly-specialized curve. """ new_nodes = _curve_helpers.specialize_curve(self._nodes, start, end) return Curve(new_nodes, self._degree, _copy=False)
python
def specialize(self, start, end): """Specialize the curve to a given sub-interval. .. image:: ../../images/curve_specialize.png :align: center .. doctest:: curve-specialize >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> new_curve = curve.specialize(-0.25, 0.75) >>> new_curve.nodes array([[-0.25 , 0.25 , 0.75 ], [-0.625, 0.875, 0.375]]) .. testcleanup:: curve-specialize import make_images make_images.curve_specialize(curve, new_curve) This is generalized version of :meth:`subdivide`, and can even match the output of that method: .. testsetup:: curve-specialize2 import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) curve = bezier.Curve(nodes, degree=2) .. doctest:: curve-specialize2 >>> left, right = curve.subdivide() >>> also_left = curve.specialize(0.0, 0.5) >>> np.all(also_left.nodes == left.nodes) True >>> also_right = curve.specialize(0.5, 1.0) >>> np.all(also_right.nodes == right.nodes) True Args: start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: Curve: The newly-specialized curve. """ new_nodes = _curve_helpers.specialize_curve(self._nodes, start, end) return Curve(new_nodes, self._degree, _copy=False)
[ "def", "specialize", "(", "self", ",", "start", ",", "end", ")", ":", "new_nodes", "=", "_curve_helpers", ".", "specialize_curve", "(", "self", ".", "_nodes", ",", "start", ",", "end", ")", "return", "Curve", "(", "new_nodes", ",", "self", ".", "_degree"...
Specialize the curve to a given sub-interval. .. image:: ../../images/curve_specialize.png :align: center .. doctest:: curve-specialize >>> nodes = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> curve = bezier.Curve(nodes, degree=2) >>> new_curve = curve.specialize(-0.25, 0.75) >>> new_curve.nodes array([[-0.25 , 0.25 , 0.75 ], [-0.625, 0.875, 0.375]]) .. testcleanup:: curve-specialize import make_images make_images.curve_specialize(curve, new_curve) This is generalized version of :meth:`subdivide`, and can even match the output of that method: .. testsetup:: curve-specialize2 import numpy as np import bezier nodes = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) curve = bezier.Curve(nodes, degree=2) .. doctest:: curve-specialize2 >>> left, right = curve.subdivide() >>> also_left = curve.specialize(0.0, 0.5) >>> np.all(also_left.nodes == left.nodes) True >>> also_right = curve.specialize(0.5, 1.0) >>> np.all(also_right.nodes == right.nodes) True Args: start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: Curve: The newly-specialized curve.
[ "Specialize", "the", "curve", "to", "a", "given", "sub", "-", "interval", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L540-L597
train
54,209
dhermes/bezier
src/bezier/curve.py
Curve.locate
def locate(self, point): r"""Find a point on the current curve. Solves for :math:`s` in :math:`B(s) = p`. This method acts as a (partial) inverse to :meth:`evaluate`. .. note:: A unique solution is only guaranteed if the current curve has no self-intersections. This code assumes, but doesn't check, that this is true. .. image:: ../../images/curve_locate.png :align: center .. doctest:: curve-locate >>> nodes = np.asfortranarray([ ... [0.0, -1.0, 1.0, -0.75 ], ... [2.0, 0.0, 1.0, 1.625], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> point1 = np.asfortranarray([ ... [-0.09375 ], ... [ 0.828125], ... ]) >>> curve.locate(point1) 0.5 >>> point2 = np.asfortranarray([ ... [0.0], ... [1.5], ... ]) >>> curve.locate(point2) is None True >>> point3 = np.asfortranarray([ ... [-0.25 ], ... [ 1.375], ... ]) >>> curve.locate(point3) is None Traceback (most recent call last): ... ValueError: Parameters not close enough to one another .. testcleanup:: curve-locate import make_images make_images.curve_locate(curve, point1, point2, point3) Args: point (numpy.ndarray): A (``D x 1``) point on the curve, where :math:`D` is the dimension of the curve. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the dimension of the ``point`` doesn't match the dimension of the current curve. """ if point.shape != (self._dimension, 1): point_dimensions = " x ".join( str(dimension) for dimension in point.shape ) msg = _LOCATE_ERROR_TEMPLATE.format( self._dimension, self._dimension, point, point_dimensions ) raise ValueError(msg) return _curve_helpers.locate_point(self._nodes, point)
python
def locate(self, point): r"""Find a point on the current curve. Solves for :math:`s` in :math:`B(s) = p`. This method acts as a (partial) inverse to :meth:`evaluate`. .. note:: A unique solution is only guaranteed if the current curve has no self-intersections. This code assumes, but doesn't check, that this is true. .. image:: ../../images/curve_locate.png :align: center .. doctest:: curve-locate >>> nodes = np.asfortranarray([ ... [0.0, -1.0, 1.0, -0.75 ], ... [2.0, 0.0, 1.0, 1.625], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> point1 = np.asfortranarray([ ... [-0.09375 ], ... [ 0.828125], ... ]) >>> curve.locate(point1) 0.5 >>> point2 = np.asfortranarray([ ... [0.0], ... [1.5], ... ]) >>> curve.locate(point2) is None True >>> point3 = np.asfortranarray([ ... [-0.25 ], ... [ 1.375], ... ]) >>> curve.locate(point3) is None Traceback (most recent call last): ... ValueError: Parameters not close enough to one another .. testcleanup:: curve-locate import make_images make_images.curve_locate(curve, point1, point2, point3) Args: point (numpy.ndarray): A (``D x 1``) point on the curve, where :math:`D` is the dimension of the curve. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the dimension of the ``point`` doesn't match the dimension of the current curve. """ if point.shape != (self._dimension, 1): point_dimensions = " x ".join( str(dimension) for dimension in point.shape ) msg = _LOCATE_ERROR_TEMPLATE.format( self._dimension, self._dimension, point, point_dimensions ) raise ValueError(msg) return _curve_helpers.locate_point(self._nodes, point)
[ "def", "locate", "(", "self", ",", "point", ")", ":", "if", "point", ".", "shape", "!=", "(", "self", ".", "_dimension", ",", "1", ")", ":", "point_dimensions", "=", "\" x \"", ".", "join", "(", "str", "(", "dimension", ")", "for", "dimension", "in",...
r"""Find a point on the current curve. Solves for :math:`s` in :math:`B(s) = p`. This method acts as a (partial) inverse to :meth:`evaluate`. .. note:: A unique solution is only guaranteed if the current curve has no self-intersections. This code assumes, but doesn't check, that this is true. .. image:: ../../images/curve_locate.png :align: center .. doctest:: curve-locate >>> nodes = np.asfortranarray([ ... [0.0, -1.0, 1.0, -0.75 ], ... [2.0, 0.0, 1.0, 1.625], ... ]) >>> curve = bezier.Curve(nodes, degree=3) >>> point1 = np.asfortranarray([ ... [-0.09375 ], ... [ 0.828125], ... ]) >>> curve.locate(point1) 0.5 >>> point2 = np.asfortranarray([ ... [0.0], ... [1.5], ... ]) >>> curve.locate(point2) is None True >>> point3 = np.asfortranarray([ ... [-0.25 ], ... [ 1.375], ... ]) >>> curve.locate(point3) is None Traceback (most recent call last): ... ValueError: Parameters not close enough to one another .. testcleanup:: curve-locate import make_images make_images.curve_locate(curve, point1, point2, point3) Args: point (numpy.ndarray): A (``D x 1``) point on the curve, where :math:`D` is the dimension of the curve. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the dimension of the ``point`` doesn't match the dimension of the current curve.
[ "r", "Find", "a", "point", "on", "the", "current", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curve.py#L599-L670
train
54,210
dhermes/bezier
scripts/clean_cython.py
clean_file
def clean_file(c_source, virtualenv_dirname): """Strip trailing whitespace and clean up "local" names in C source. These source files are autogenerated from the ``cython`` CLI. Args: c_source (str): Path to a ``.c`` source file. virtualenv_dirname (str): The name of the ``virtualenv`` directory where Cython is installed (this is part of a relative path ``.nox/{NAME}/lib/...``). """ with open(c_source, "r") as file_obj: contents = file_obj.read().rstrip() # Replace the path to the Cython include files. py_version = "python{}.{}".format(*sys.version_info[:2]) lib_path = os.path.join( ".nox", virtualenv_dirname, "lib", py_version, "site-packages", "" ) contents = contents.replace(lib_path, "") # Write the files back, but strip all trailing whitespace. lines = contents.split("\n") with open(c_source, "w") as file_obj: for line in lines: file_obj.write(line.rstrip() + "\n")
python
def clean_file(c_source, virtualenv_dirname): """Strip trailing whitespace and clean up "local" names in C source. These source files are autogenerated from the ``cython`` CLI. Args: c_source (str): Path to a ``.c`` source file. virtualenv_dirname (str): The name of the ``virtualenv`` directory where Cython is installed (this is part of a relative path ``.nox/{NAME}/lib/...``). """ with open(c_source, "r") as file_obj: contents = file_obj.read().rstrip() # Replace the path to the Cython include files. py_version = "python{}.{}".format(*sys.version_info[:2]) lib_path = os.path.join( ".nox", virtualenv_dirname, "lib", py_version, "site-packages", "" ) contents = contents.replace(lib_path, "") # Write the files back, but strip all trailing whitespace. lines = contents.split("\n") with open(c_source, "w") as file_obj: for line in lines: file_obj.write(line.rstrip() + "\n")
[ "def", "clean_file", "(", "c_source", ",", "virtualenv_dirname", ")", ":", "with", "open", "(", "c_source", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", ".", "rstrip", "(", ")", "# Replace the path to the Cyth...
Strip trailing whitespace and clean up "local" names in C source. These source files are autogenerated from the ``cython`` CLI. Args: c_source (str): Path to a ``.c`` source file. virtualenv_dirname (str): The name of the ``virtualenv`` directory where Cython is installed (this is part of a relative path ``.nox/{NAME}/lib/...``).
[ "Strip", "trailing", "whitespace", "and", "clean", "up", "local", "names", "in", "C", "source", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/clean_cython.py#L17-L40
train
54,211
dhermes/bezier
scripts/doc_template_release.py
get_version
def get_version(): """Get the current version from ``setup.py``. Assumes that importing ``setup.py`` will have no side-effects (i.e. assumes the behavior is guarded by ``if __name__ == "__main__"``). Returns: str: The current version in ``setup.py``. """ # "Spoof" the ``setup.py`` helper modules. sys.modules["setup_helpers"] = object() sys.modules["setup_helpers_macos"] = object() sys.modules["setup_helpers_windows"] = object() filename = os.path.join(_ROOT_DIR, "setup.py") loader = importlib.machinery.SourceFileLoader("setup", filename) setup_mod = loader.load_module() return setup_mod.VERSION
python
def get_version(): """Get the current version from ``setup.py``. Assumes that importing ``setup.py`` will have no side-effects (i.e. assumes the behavior is guarded by ``if __name__ == "__main__"``). Returns: str: The current version in ``setup.py``. """ # "Spoof" the ``setup.py`` helper modules. sys.modules["setup_helpers"] = object() sys.modules["setup_helpers_macos"] = object() sys.modules["setup_helpers_windows"] = object() filename = os.path.join(_ROOT_DIR, "setup.py") loader = importlib.machinery.SourceFileLoader("setup", filename) setup_mod = loader.load_module() return setup_mod.VERSION
[ "def", "get_version", "(", ")", ":", "# \"Spoof\" the ``setup.py`` helper modules.", "sys", ".", "modules", "[", "\"setup_helpers\"", "]", "=", "object", "(", ")", "sys", ".", "modules", "[", "\"setup_helpers_macos\"", "]", "=", "object", "(", ")", "sys", ".", ...
Get the current version from ``setup.py``. Assumes that importing ``setup.py`` will have no side-effects (i.e. assumes the behavior is guarded by ``if __name__ == "__main__"``). Returns: str: The current version in ``setup.py``.
[ "Get", "the", "current", "version", "from", "setup", ".", "py", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/doc_template_release.py#L54-L70
train
54,212
dhermes/bezier
scripts/doc_template_release.py
populate_readme
def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): """Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleCI build ID corresponding to the release. appveyor_build (str): The AppVeyor build ID corresponding to the release. coveralls_build (Union[str, int]): The Coveralls.io build ID corresponding to the release. travis_build (int): The Travis CI build ID corresponding to the release. """ with open(RELEASE_README_FILE, "r") as file_obj: template = file_obj.read() contents = template.format( version=version, circleci_build=circleci_build, appveyor_build=appveyor_build, coveralls_build=coveralls_build, travis_build=travis_build, ) with open(README_FILE, "w") as file_obj: file_obj.write(contents)
python
def populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ): """Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleCI build ID corresponding to the release. appveyor_build (str): The AppVeyor build ID corresponding to the release. coveralls_build (Union[str, int]): The Coveralls.io build ID corresponding to the release. travis_build (int): The Travis CI build ID corresponding to the release. """ with open(RELEASE_README_FILE, "r") as file_obj: template = file_obj.read() contents = template.format( version=version, circleci_build=circleci_build, appveyor_build=appveyor_build, coveralls_build=coveralls_build, travis_build=travis_build, ) with open(README_FILE, "w") as file_obj: file_obj.write(contents)
[ "def", "populate_readme", "(", "version", ",", "circleci_build", ",", "appveyor_build", ",", "coveralls_build", ",", "travis_build", ")", ":", "with", "open", "(", "RELEASE_README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".",...
Populates ``README.rst`` with release-specific data. This is because ``README.rst`` is used on PyPI. Args: version (str): The current version. circleci_build (Union[str, int]): The CircleCI build ID corresponding to the release. appveyor_build (str): The AppVeyor build ID corresponding to the release. coveralls_build (Union[str, int]): The Coveralls.io build ID corresponding to the release. travis_build (int): The Travis CI build ID corresponding to the release.
[ "Populates", "README", ".", "rst", "with", "release", "-", "specific", "data", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/doc_template_release.py#L73-L101
train
54,213
dhermes/bezier
scripts/doc_template_release.py
populate_native_libraries
def populate_native_libraries(version): """Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version) with open(BINARY_EXT_FILE, "w") as file_obj: file_obj.write(contents)
python
def populate_native_libraries(version): """Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version) with open(BINARY_EXT_FILE, "w") as file_obj: file_obj.write(contents)
[ "def", "populate_native_libraries", "(", "version", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "contents", "=", "template", ".", "format", "(", "revision...
Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version.
[ "Populates", "binary", "-", "extension", ".", "rst", "with", "release", "-", "specific", "data", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/doc_template_release.py#L133-L143
train
54,214
dhermes/bezier
scripts/doc_template_release.py
populate_development
def populate_development(version): """Populates ``DEVELOPMENT.rst`` with release-specific data. This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation. Args: version (str): The current version. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version, rtd_version=version) with open(DEVELOPMENT_FILE, "w") as file_obj: file_obj.write(contents)
python
def populate_development(version): """Populates ``DEVELOPMENT.rst`` with release-specific data. This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation. Args: version (str): The current version. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() contents = template.format(revision=version, rtd_version=version) with open(DEVELOPMENT_FILE, "w") as file_obj: file_obj.write(contents)
[ "def", "populate_development", "(", "version", ")", ":", "with", "open", "(", "DEVELOPMENT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "contents", "=", "template", ".", "format", "(", "revision", ...
Populates ``DEVELOPMENT.rst`` with release-specific data. This is because ``DEVELOPMENT.rst`` is used in the Sphinx documentation. Args: version (str): The current version.
[ "Populates", "DEVELOPMENT", ".", "rst", "with", "release", "-", "specific", "data", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/doc_template_release.py#L146-L158
train
54,215
dhermes/bezier
scripts/doc_template_release.py
main
def main(): """Populate the templates with release-specific fields. Requires user input for the CircleCI, AppVeyor, Coveralls.io and Travis build IDs. """ version = get_version() circleci_build = six.moves.input("CircleCI Build ID: ") appveyor_build = six.moves.input("AppVeyor Build ID: ") coveralls_build = six.moves.input("Coveralls Build ID: ") travis_build = six.moves.input("Travis Build ID: ") populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ) populate_index( version, circleci_build, appveyor_build, coveralls_build, travis_build ) populate_native_libraries(version) populate_development(version)
python
def main(): """Populate the templates with release-specific fields. Requires user input for the CircleCI, AppVeyor, Coveralls.io and Travis build IDs. """ version = get_version() circleci_build = six.moves.input("CircleCI Build ID: ") appveyor_build = six.moves.input("AppVeyor Build ID: ") coveralls_build = six.moves.input("Coveralls Build ID: ") travis_build = six.moves.input("Travis Build ID: ") populate_readme( version, circleci_build, appveyor_build, coveralls_build, travis_build ) populate_index( version, circleci_build, appveyor_build, coveralls_build, travis_build ) populate_native_libraries(version) populate_development(version)
[ "def", "main", "(", ")", ":", "version", "=", "get_version", "(", ")", "circleci_build", "=", "six", ".", "moves", ".", "input", "(", "\"CircleCI Build ID: \"", ")", "appveyor_build", "=", "six", ".", "moves", ".", "input", "(", "\"AppVeyor Build ID: \"", ")...
Populate the templates with release-specific fields. Requires user input for the CircleCI, AppVeyor, Coveralls.io and Travis build IDs.
[ "Populate", "the", "templates", "with", "release", "-", "specific", "fields", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/doc_template_release.py#L161-L179
train
54,216
dhermes/bezier
src/bezier/_curve_helpers.py
make_subdivision_matrices
def make_subdivision_matrices(degree): """Make the matrix used to subdivide a curve. .. note:: This is a helper for :func:`_subdivide_nodes`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. Args: degree (int): The degree of the curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The matrices used to convert the nodes into left and right nodes, respectively. """ left = np.zeros((degree + 1, degree + 1), order="F") right = np.zeros((degree + 1, degree + 1), order="F") left[0, 0] = 1.0 right[-1, -1] = 1.0 for col in six.moves.xrange(1, degree + 1): half_prev = 0.5 * left[:col, col - 1] left[:col, col] = half_prev left[1 : col + 1, col] += half_prev # noqa: E203 # Populate the complement col (in right) as well. complement = degree - col # NOTE: We "should" reverse the results when using # the complement, but they are symmetric so # that would be a waste. right[-(col + 1) :, complement] = left[: col + 1, col] # noqa: E203 return left, right
python
def make_subdivision_matrices(degree): """Make the matrix used to subdivide a curve. .. note:: This is a helper for :func:`_subdivide_nodes`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. Args: degree (int): The degree of the curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The matrices used to convert the nodes into left and right nodes, respectively. """ left = np.zeros((degree + 1, degree + 1), order="F") right = np.zeros((degree + 1, degree + 1), order="F") left[0, 0] = 1.0 right[-1, -1] = 1.0 for col in six.moves.xrange(1, degree + 1): half_prev = 0.5 * left[:col, col - 1] left[:col, col] = half_prev left[1 : col + 1, col] += half_prev # noqa: E203 # Populate the complement col (in right) as well. complement = degree - col # NOTE: We "should" reverse the results when using # the complement, but they are symmetric so # that would be a waste. right[-(col + 1) :, complement] = left[: col + 1, col] # noqa: E203 return left, right
[ "def", "make_subdivision_matrices", "(", "degree", ")", ":", "left", "=", "np", ".", "zeros", "(", "(", "degree", "+", "1", ",", "degree", "+", "1", ")", ",", "order", "=", "\"F\"", ")", "right", "=", "np", ".", "zeros", "(", "(", "degree", "+", ...
Make the matrix used to subdivide a curve. .. note:: This is a helper for :func:`_subdivide_nodes`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. Args: degree (int): The degree of the curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The matrices used to convert the nodes into left and right nodes, respectively.
[ "Make", "the", "matrix", "used", "to", "subdivide", "a", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L128-L158
train
54,217
dhermes/bezier
src/bezier/_curve_helpers.py
_subdivide_nodes
def _subdivide_nodes(nodes): """Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The nodes for the two sub-curves. """ _, num_nodes = np.shape(nodes) if num_nodes == 2: left_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_RIGHT) elif num_nodes == 3: left_nodes = _helpers.matrix_product(nodes, _QUADRATIC_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product( nodes, _QUADRATIC_SUBDIVIDE_RIGHT ) elif num_nodes == 4: left_nodes = _helpers.matrix_product(nodes, _CUBIC_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product(nodes, _CUBIC_SUBDIVIDE_RIGHT) else: left_mat, right_mat = make_subdivision_matrices(num_nodes - 1) left_nodes = _helpers.matrix_product(nodes, left_mat) right_nodes = _helpers.matrix_product(nodes, right_mat) return left_nodes, right_nodes
python
def _subdivide_nodes(nodes): """Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The nodes for the two sub-curves. """ _, num_nodes = np.shape(nodes) if num_nodes == 2: left_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product(nodes, _LINEAR_SUBDIVIDE_RIGHT) elif num_nodes == 3: left_nodes = _helpers.matrix_product(nodes, _QUADRATIC_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product( nodes, _QUADRATIC_SUBDIVIDE_RIGHT ) elif num_nodes == 4: left_nodes = _helpers.matrix_product(nodes, _CUBIC_SUBDIVIDE_LEFT) right_nodes = _helpers.matrix_product(nodes, _CUBIC_SUBDIVIDE_RIGHT) else: left_mat, right_mat = make_subdivision_matrices(num_nodes - 1) left_nodes = _helpers.matrix_product(nodes, left_mat) right_nodes = _helpers.matrix_product(nodes, right_mat) return left_nodes, right_nodes
[ "def", "_subdivide_nodes", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "np", ".", "shape", "(", "nodes", ")", "if", "num_nodes", "==", "2", ":", "left_nodes", "=", "_helpers", ".", "matrix_product", "(", "nodes", ",", "_LINEAR_SUBDIVIDE_LEFT", ")",...
Subdivide a curve into two sub-curves. Does so by taking the unit interval (i.e. the domain of the surface) and splitting it into two sub-intervals by splitting down the middle. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. Returns: Tuple[numpy.ndarray, numpy.ndarray]: The nodes for the two sub-curves.
[ "Subdivide", "a", "curve", "into", "two", "sub", "-", "curves", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L161-L194
train
54,218
dhermes/bezier
src/bezier/_curve_helpers.py
_evaluate_multi_barycentric
def _evaluate_multi_barycentric(nodes, lambda1, lambda2): r"""Evaluates a B |eacute| zier type-function. Of the form .. math:: B(\lambda_1, \lambda_2) = \sum_j \binom{n}{j} \lambda_1^{n - j} \lambda_2^j \cdot v_j for some set of vectors :math:`v_j` given by ``nodes``. Does so via a modified Horner's method for each pair of values in ``lambda1`` and ``lambda2``, rather than using the de Casteljau algorithm. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. lambda1 (numpy.ndarray): Parameters along the curve (as a 1D array). lambda2 (numpy.ndarray): Parameters along the curve (as a 1D array). Typically we have ``lambda1 + lambda2 == 1``. Returns: numpy.ndarray: The evaluated points as a two dimensional NumPy array, with the columns corresponding to each pair of parameter values and the rows to the dimension. """ # NOTE: We assume but don't check that lambda2 has the same shape. num_vals, = lambda1.shape dimension, num_nodes = nodes.shape degree = num_nodes - 1 # Resize as row vectors for broadcast multiplying with # columns of ``nodes``. lambda1 = lambda1[np.newaxis, :] lambda2 = lambda2[np.newaxis, :] result = np.zeros((dimension, num_vals), order="F") result += lambda1 * nodes[:, [0]] binom_val = 1.0 lambda2_pow = np.ones((1, num_vals), order="F") for index in six.moves.xrange(1, degree): lambda2_pow *= lambda2 binom_val = (binom_val * (degree - index + 1)) / index result += binom_val * lambda2_pow * nodes[:, [index]] result *= lambda1 result += lambda2 * lambda2_pow * nodes[:, [degree]] return result
python
def _evaluate_multi_barycentric(nodes, lambda1, lambda2): r"""Evaluates a B |eacute| zier type-function. Of the form .. math:: B(\lambda_1, \lambda_2) = \sum_j \binom{n}{j} \lambda_1^{n - j} \lambda_2^j \cdot v_j for some set of vectors :math:`v_j` given by ``nodes``. Does so via a modified Horner's method for each pair of values in ``lambda1`` and ``lambda2``, rather than using the de Casteljau algorithm. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. lambda1 (numpy.ndarray): Parameters along the curve (as a 1D array). lambda2 (numpy.ndarray): Parameters along the curve (as a 1D array). Typically we have ``lambda1 + lambda2 == 1``. Returns: numpy.ndarray: The evaluated points as a two dimensional NumPy array, with the columns corresponding to each pair of parameter values and the rows to the dimension. """ # NOTE: We assume but don't check that lambda2 has the same shape. num_vals, = lambda1.shape dimension, num_nodes = nodes.shape degree = num_nodes - 1 # Resize as row vectors for broadcast multiplying with # columns of ``nodes``. lambda1 = lambda1[np.newaxis, :] lambda2 = lambda2[np.newaxis, :] result = np.zeros((dimension, num_vals), order="F") result += lambda1 * nodes[:, [0]] binom_val = 1.0 lambda2_pow = np.ones((1, num_vals), order="F") for index in six.moves.xrange(1, degree): lambda2_pow *= lambda2 binom_val = (binom_val * (degree - index + 1)) / index result += binom_val * lambda2_pow * nodes[:, [index]] result *= lambda1 result += lambda2 * lambda2_pow * nodes[:, [degree]] return result
[ "def", "_evaluate_multi_barycentric", "(", "nodes", ",", "lambda1", ",", "lambda2", ")", ":", "# NOTE: We assume but don't check that lambda2 has the same shape.", "num_vals", ",", "=", "lambda1", ".", "shape", "dimension", ",", "num_nodes", "=", "nodes", ".", "shape", ...
r"""Evaluates a B |eacute| zier type-function. Of the form .. math:: B(\lambda_1, \lambda_2) = \sum_j \binom{n}{j} \lambda_1^{n - j} \lambda_2^j \cdot v_j for some set of vectors :math:`v_j` given by ``nodes``. Does so via a modified Horner's method for each pair of values in ``lambda1`` and ``lambda2``, rather than using the de Casteljau algorithm. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. lambda1 (numpy.ndarray): Parameters along the curve (as a 1D array). lambda2 (numpy.ndarray): Parameters along the curve (as a 1D array). Typically we have ``lambda1 + lambda2 == 1``. Returns: numpy.ndarray: The evaluated points as a two dimensional NumPy array, with the columns corresponding to each pair of parameter values and the rows to the dimension.
[ "r", "Evaluates", "a", "B", "|eacute|", "zier", "type", "-", "function", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L222-L273
train
54,219
dhermes/bezier
src/bezier/_curve_helpers.py
_compute_length
def _compute_length(nodes): r"""Approximately compute the length of a curve. .. _QUADPACK: https://en.wikipedia.org/wiki/QUADPACK If ``degree`` is :math:`n`, then the Hodograph curve :math:`B'(s)` is degree :math:`d = n - 1`. Using this curve, we approximate the integral: .. math:: \int_{B\left(\left[0, 1\right]\right)} 1 \, d\mathbf{x} = \int_0^1 \left\lVert B'(s) \right\rVert_2 \, ds using `QUADPACK`_ (via SciPy). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: float: The length of the curve. Raises: OSError: If SciPy is not installed. """ _, num_nodes = np.shape(nodes) # NOTE: We somewhat replicate code in ``evaluate_hodograph()`` # here. This is so we don't re-compute the nodes for the first # derivative every time it is evaluated. first_deriv = (num_nodes - 1) * (nodes[:, 1:] - nodes[:, :-1]) if num_nodes == 2: # NOTE: We convert to 1D to make sure NumPy uses vector norm. return np.linalg.norm(first_deriv[:, 0], ord=2) if _scipy_int is None: raise OSError("This function requires SciPy for quadrature.") size_func = functools.partial(vec_size, first_deriv) length, _ = _scipy_int.quad(size_func, 0.0, 1.0) return length
python
def _compute_length(nodes): r"""Approximately compute the length of a curve. .. _QUADPACK: https://en.wikipedia.org/wiki/QUADPACK If ``degree`` is :math:`n`, then the Hodograph curve :math:`B'(s)` is degree :math:`d = n - 1`. Using this curve, we approximate the integral: .. math:: \int_{B\left(\left[0, 1\right]\right)} 1 \, d\mathbf{x} = \int_0^1 \left\lVert B'(s) \right\rVert_2 \, ds using `QUADPACK`_ (via SciPy). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: float: The length of the curve. Raises: OSError: If SciPy is not installed. """ _, num_nodes = np.shape(nodes) # NOTE: We somewhat replicate code in ``evaluate_hodograph()`` # here. This is so we don't re-compute the nodes for the first # derivative every time it is evaluated. first_deriv = (num_nodes - 1) * (nodes[:, 1:] - nodes[:, :-1]) if num_nodes == 2: # NOTE: We convert to 1D to make sure NumPy uses vector norm. return np.linalg.norm(first_deriv[:, 0], ord=2) if _scipy_int is None: raise OSError("This function requires SciPy for quadrature.") size_func = functools.partial(vec_size, first_deriv) length, _ = _scipy_int.quad(size_func, 0.0, 1.0) return length
[ "def", "_compute_length", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "np", ".", "shape", "(", "nodes", ")", "# NOTE: We somewhat replicate code in ``evaluate_hodograph()``", "# here. This is so we don't re-compute the nodes for the first", "# derivative every...
r"""Approximately compute the length of a curve. .. _QUADPACK: https://en.wikipedia.org/wiki/QUADPACK If ``degree`` is :math:`n`, then the Hodograph curve :math:`B'(s)` is degree :math:`d = n - 1`. Using this curve, we approximate the integral: .. math:: \int_{B\left(\left[0, 1\right]\right)} 1 \, d\mathbf{x} = \int_0^1 \left\lVert B'(s) \right\rVert_2 \, ds using `QUADPACK`_ (via SciPy). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: float: The length of the curve. Raises: OSError: If SciPy is not installed.
[ "r", "Approximately", "compute", "the", "length", "of", "a", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L299-L343
train
54,220
dhermes/bezier
src/bezier/_curve_helpers.py
_elevate_nodes
def _elevate_nodes(nodes): r"""Degree-elevate a B |eacute| zier curves. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: numpy.ndarray: The nodes of the degree-elevated curve. """ dimension, num_nodes = np.shape(nodes) new_nodes = np.empty((dimension, num_nodes + 1), order="F") multipliers = np.arange(1, num_nodes, dtype=_FLOAT64)[np.newaxis, :] denominator = float(num_nodes) new_nodes[:, 1:-1] = ( multipliers * nodes[:, :-1] + (denominator - multipliers) * nodes[:, 1:] ) # Hold off on division until the end, to (attempt to) avoid round-off. new_nodes /= denominator # After setting the internal nodes (which require division), set the # boundary nodes. new_nodes[:, 0] = nodes[:, 0] new_nodes[:, -1] = nodes[:, -1] return new_nodes
python
def _elevate_nodes(nodes): r"""Degree-elevate a B |eacute| zier curves. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: numpy.ndarray: The nodes of the degree-elevated curve. """ dimension, num_nodes = np.shape(nodes) new_nodes = np.empty((dimension, num_nodes + 1), order="F") multipliers = np.arange(1, num_nodes, dtype=_FLOAT64)[np.newaxis, :] denominator = float(num_nodes) new_nodes[:, 1:-1] = ( multipliers * nodes[:, :-1] + (denominator - multipliers) * nodes[:, 1:] ) # Hold off on division until the end, to (attempt to) avoid round-off. new_nodes /= denominator # After setting the internal nodes (which require division), set the # boundary nodes. new_nodes[:, 0] = nodes[:, 0] new_nodes[:, -1] = nodes[:, -1] return new_nodes
[ "def", "_elevate_nodes", "(", "nodes", ")", ":", "dimension", ",", "num_nodes", "=", "np", ".", "shape", "(", "nodes", ")", "new_nodes", "=", "np", ".", "empty", "(", "(", "dimension", ",", "num_nodes", "+", "1", ")", ",", "order", "=", "\"F\"", ")",...
r"""Degree-elevate a B |eacute| zier curves. Does this by converting the current nodes :math:`v_0, \ldots, v_n` to new nodes :math:`w_0, \ldots, w_{n + 1}` where .. math:: \begin{align*} w_0 &= v_0 \\ w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + 1 - j}{n + 1} v_j \\ w_{n + 1} &= v_n \end{align*} .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a curve. Returns: numpy.ndarray: The nodes of the degree-elevated curve.
[ "r", "Degree", "-", "elevate", "a", "B", "|eacute|", "zier", "curves", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L346-L385
train
54,221
dhermes/bezier
src/bezier/_curve_helpers.py
de_casteljau_one_round
def de_casteljau_one_round(nodes, lambda1, lambda2): """Perform one round of de Casteljau's algorithm. .. note:: This is a helper for :func:`_specialize_curve`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. The weights are assumed to sum to one. Args: nodes (numpy.ndarray): Control points for a curve. lambda1 (float): First barycentric weight on interval. lambda2 (float): Second barycentric weight on interval. Returns: numpy.ndarray: The nodes for a "blended" curve one degree lower. """ return np.asfortranarray(lambda1 * nodes[:, :-1] + lambda2 * nodes[:, 1:])
python
def de_casteljau_one_round(nodes, lambda1, lambda2): """Perform one round of de Casteljau's algorithm. .. note:: This is a helper for :func:`_specialize_curve`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. The weights are assumed to sum to one. Args: nodes (numpy.ndarray): Control points for a curve. lambda1 (float): First barycentric weight on interval. lambda2 (float): Second barycentric weight on interval. Returns: numpy.ndarray: The nodes for a "blended" curve one degree lower. """ return np.asfortranarray(lambda1 * nodes[:, :-1] + lambda2 * nodes[:, 1:])
[ "def", "de_casteljau_one_round", "(", "nodes", ",", "lambda1", ",", "lambda2", ")", ":", "return", "np", ".", "asfortranarray", "(", "lambda1", "*", "nodes", "[", ":", ",", ":", "-", "1", "]", "+", "lambda2", "*", "nodes", "[", ":", ",", "1", ":", ...
Perform one round of de Casteljau's algorithm. .. note:: This is a helper for :func:`_specialize_curve`. It does not have a Fortran speedup because it is **only** used by a function which has a Fortran speedup. The weights are assumed to sum to one. Args: nodes (numpy.ndarray): Control points for a curve. lambda1 (float): First barycentric weight on interval. lambda2 (float): Second barycentric weight on interval. Returns: numpy.ndarray: The nodes for a "blended" curve one degree lower.
[ "Perform", "one", "round", "of", "de", "Casteljau", "s", "algorithm", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L388-L408
train
54,222
dhermes/bezier
src/bezier/_curve_helpers.py
_specialize_curve
def _specialize_curve(nodes, start, end): """Specialize a curve to a re-parameterization .. note:: This assumes the curve is degree 1 or greater but doesn't check. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control points for a curve. start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: numpy.ndarray: The control points for the specialized curve. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals _, num_nodes = np.shape(nodes) # Uses start-->0, end-->1 to represent the specialization used. weights = ((1.0 - start, start), (1.0 - end, end)) partial_vals = { (0,): de_casteljau_one_round(nodes, *weights[0]), (1,): de_casteljau_one_round(nodes, *weights[1]), } for _ in six.moves.xrange(num_nodes - 2, 0, -1): new_partial = {} for key, sub_nodes in six.iteritems(partial_vals): # Our keys are ascending so we increment from the last value. for next_id in six.moves.xrange(key[-1], 1 + 1): new_key = key + (next_id,) new_partial[new_key] = de_casteljau_one_round( sub_nodes, *weights[next_id] ) partial_vals = new_partial result = np.empty(nodes.shape, order="F") for index in six.moves.xrange(num_nodes): key = (0,) * (num_nodes - index - 1) + (1,) * index result[:, [index]] = partial_vals[key] return result
python
def _specialize_curve(nodes, start, end): """Specialize a curve to a re-parameterization .. note:: This assumes the curve is degree 1 or greater but doesn't check. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control points for a curve. start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: numpy.ndarray: The control points for the specialized curve. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals _, num_nodes = np.shape(nodes) # Uses start-->0, end-->1 to represent the specialization used. weights = ((1.0 - start, start), (1.0 - end, end)) partial_vals = { (0,): de_casteljau_one_round(nodes, *weights[0]), (1,): de_casteljau_one_round(nodes, *weights[1]), } for _ in six.moves.xrange(num_nodes - 2, 0, -1): new_partial = {} for key, sub_nodes in six.iteritems(partial_vals): # Our keys are ascending so we increment from the last value. for next_id in six.moves.xrange(key[-1], 1 + 1): new_key = key + (next_id,) new_partial[new_key] = de_casteljau_one_round( sub_nodes, *weights[next_id] ) partial_vals = new_partial result = np.empty(nodes.shape, order="F") for index in six.moves.xrange(num_nodes): key = (0,) * (num_nodes - index - 1) + (1,) * index result[:, [index]] = partial_vals[key] return result
[ "def", "_specialize_curve", "(", "nodes", ",", "start", ",", "end", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "_", ",", "num_nodes", "=", "np", ".", "shape", "...
Specialize a curve to a re-parameterization .. note:: This assumes the curve is degree 1 or greater but doesn't check. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control points for a curve. start (float): The start point of the interval we are specializing to. end (float): The end point of the interval we are specializing to. Returns: numpy.ndarray: The control points for the specialized curve.
[ "Specialize", "a", "curve", "to", "a", "re", "-", "parameterization" ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L411-L455
train
54,223
dhermes/bezier
src/bezier/_curve_helpers.py
_locate_point
def _locate_point(nodes, point): r"""Locate a point on a curve. Does so by recursively subdividing the curve and rejecting sub-curves with bounding boxes that don't contain the point. After the sub-curves are sufficiently small, uses Newton's method to zoom in on the parameter value. .. note:: This assumes, but does not check, that ``point`` is ``D x 1``, where ``D`` is the dimension that ``curve`` is in. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. point (numpy.ndarray): The point to locate. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the standard deviation of the remaining start / end parameters among the subdivided intervals exceeds a given threshold (e.g. :math:`2^{-20}`). """ candidates = [(0.0, 1.0, nodes)] for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for start, end, candidate in candidates: if _helpers.contains_nd(candidate, point.ravel(order="F")): midpoint = 0.5 * (start + end) left, right = subdivide_nodes(candidate) next_candidates.extend( ((start, midpoint, left), (midpoint, end, right)) ) candidates = next_candidates if not candidates: return None params = [(start, end) for start, end, _ in candidates] if np.std(params) > _LOCATE_STD_CAP: raise ValueError("Parameters not close enough to one another", params) s_approx = np.mean(params) s_approx = newton_refine(nodes, point, s_approx) # NOTE: Since ``np.mean(params)`` must be in ``[0, 1]`` it's # "safe" to push the Newton-refined value back into the unit # interval. if s_approx < 0.0: return 0.0 elif s_approx > 1.0: return 1.0 else: return s_approx
python
def _locate_point(nodes, point): r"""Locate a point on a curve. Does so by recursively subdividing the curve and rejecting sub-curves with bounding boxes that don't contain the point. After the sub-curves are sufficiently small, uses Newton's method to zoom in on the parameter value. .. note:: This assumes, but does not check, that ``point`` is ``D x 1``, where ``D`` is the dimension that ``curve`` is in. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. point (numpy.ndarray): The point to locate. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the standard deviation of the remaining start / end parameters among the subdivided intervals exceeds a given threshold (e.g. :math:`2^{-20}`). """ candidates = [(0.0, 1.0, nodes)] for _ in six.moves.xrange(_MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for start, end, candidate in candidates: if _helpers.contains_nd(candidate, point.ravel(order="F")): midpoint = 0.5 * (start + end) left, right = subdivide_nodes(candidate) next_candidates.extend( ((start, midpoint, left), (midpoint, end, right)) ) candidates = next_candidates if not candidates: return None params = [(start, end) for start, end, _ in candidates] if np.std(params) > _LOCATE_STD_CAP: raise ValueError("Parameters not close enough to one another", params) s_approx = np.mean(params) s_approx = newton_refine(nodes, point, s_approx) # NOTE: Since ``np.mean(params)`` must be in ``[0, 1]`` it's # "safe" to push the Newton-refined value back into the unit # interval. if s_approx < 0.0: return 0.0 elif s_approx > 1.0: return 1.0 else: return s_approx
[ "def", "_locate_point", "(", "nodes", ",", "point", ")", ":", "candidates", "=", "[", "(", "0.0", ",", "1.0", ",", "nodes", ")", "]", "for", "_", "in", "six", ".", "moves", ".", "xrange", "(", "_MAX_LOCATE_SUBDIVISIONS", "+", "1", ")", ":", "next_can...
r"""Locate a point on a curve. Does so by recursively subdividing the curve and rejecting sub-curves with bounding boxes that don't contain the point. After the sub-curves are sufficiently small, uses Newton's method to zoom in on the parameter value. .. note:: This assumes, but does not check, that ``point`` is ``D x 1``, where ``D`` is the dimension that ``curve`` is in. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. point (numpy.ndarray): The point to locate. Returns: Optional[float]: The parameter value (:math:`s`) corresponding to ``point`` or :data:`None` if the point is not on the ``curve``. Raises: ValueError: If the standard deviation of the remaining start / end parameters among the subdivided intervals exceeds a given threshold (e.g. :math:`2^{-20}`).
[ "r", "Locate", "a", "point", "on", "a", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L740-L801
train
54,224
dhermes/bezier
src/bezier/_curve_helpers.py
_reduce_pseudo_inverse
def _reduce_pseudo_inverse(nodes): """Performs degree-reduction for a B |eacute| zier curve. Does so by using the pseudo-inverse of the degree elevation operator (which is overdetermined). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The reduced nodes. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4. """ _, num_nodes = np.shape(nodes) if num_nodes == 2: reduction = _REDUCTION0 denom = _REDUCTION_DENOM0 elif num_nodes == 3: reduction = _REDUCTION1 denom = _REDUCTION_DENOM1 elif num_nodes == 4: reduction = _REDUCTION2 denom = _REDUCTION_DENOM2 elif num_nodes == 5: reduction = _REDUCTION3 denom = _REDUCTION_DENOM3 else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3, 4)) result = _helpers.matrix_product(nodes, reduction) result /= denom return result
python
def _reduce_pseudo_inverse(nodes): """Performs degree-reduction for a B |eacute| zier curve. Does so by using the pseudo-inverse of the degree elevation operator (which is overdetermined). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The reduced nodes. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4. """ _, num_nodes = np.shape(nodes) if num_nodes == 2: reduction = _REDUCTION0 denom = _REDUCTION_DENOM0 elif num_nodes == 3: reduction = _REDUCTION1 denom = _REDUCTION_DENOM1 elif num_nodes == 4: reduction = _REDUCTION2 denom = _REDUCTION_DENOM2 elif num_nodes == 5: reduction = _REDUCTION3 denom = _REDUCTION_DENOM3 else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3, 4)) result = _helpers.matrix_product(nodes, reduction) result /= denom return result
[ "def", "_reduce_pseudo_inverse", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "np", ".", "shape", "(", "nodes", ")", "if", "num_nodes", "==", "2", ":", "reduction", "=", "_REDUCTION0", "denom", "=", "_REDUCTION_DENOM0", "elif", "num_nodes", "==", "3...
Performs degree-reduction for a B |eacute| zier curve. Does so by using the pseudo-inverse of the degree elevation operator (which is overdetermined). .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The reduced nodes. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4.
[ "Performs", "degree", "-", "reduction", "for", "a", "B", "|eacute|", "zier", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L804-L842
train
54,225
dhermes/bezier
src/bezier/_curve_helpers.py
projection_error
def projection_error(nodes, projected): """Compute the error between ``nodes`` and the projected nodes. .. note:: This is a helper for :func:`maybe_reduce`, which is in turn a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. For now, just compute the relative error in the Frobenius norm. But, we may wish to consider the error per row / point instead. Args: nodes (numpy.ndarray): Nodes in a curve. projected (numpy.ndarray): The ``nodes`` projected into the space of degree-elevated nodes. Returns: float: The relative error. """ relative_err = np.linalg.norm(nodes - projected, ord="fro") if relative_err != 0.0: relative_err /= np.linalg.norm(nodes, ord="fro") return relative_err
python
def projection_error(nodes, projected): """Compute the error between ``nodes`` and the projected nodes. .. note:: This is a helper for :func:`maybe_reduce`, which is in turn a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. For now, just compute the relative error in the Frobenius norm. But, we may wish to consider the error per row / point instead. Args: nodes (numpy.ndarray): Nodes in a curve. projected (numpy.ndarray): The ``nodes`` projected into the space of degree-elevated nodes. Returns: float: The relative error. """ relative_err = np.linalg.norm(nodes - projected, ord="fro") if relative_err != 0.0: relative_err /= np.linalg.norm(nodes, ord="fro") return relative_err
[ "def", "projection_error", "(", "nodes", ",", "projected", ")", ":", "relative_err", "=", "np", ".", "linalg", ".", "norm", "(", "nodes", "-", "projected", ",", "ord", "=", "\"fro\"", ")", "if", "relative_err", "!=", "0.0", ":", "relative_err", "/=", "np...
Compute the error between ``nodes`` and the projected nodes. .. note:: This is a helper for :func:`maybe_reduce`, which is in turn a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. For now, just compute the relative error in the Frobenius norm. But, we may wish to consider the error per row / point instead. Args: nodes (numpy.ndarray): Nodes in a curve. projected (numpy.ndarray): The ``nodes`` projected into the space of degree-elevated nodes. Returns: float: The relative error.
[ "Compute", "the", "error", "between", "nodes", "and", "the", "projected", "nodes", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L845-L868
train
54,226
dhermes/bezier
src/bezier/_curve_helpers.py
maybe_reduce
def maybe_reduce(nodes): r"""Reduce nodes in a curve if they are degree-elevated. .. note:: This is a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. We check if the nodes are degree-elevated by projecting onto the space of degree-elevated curves of the same degree, then comparing to the projection. We form the projection by taking the corresponding (right) elevation matrix :math:`E` (from one degree lower) and forming :math:`E^T \left(E E^T\right)^{-1} E`. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: Tuple[bool, numpy.ndarray]: Pair of values. The first indicates if the ``nodes`` were reduced. The second is the resulting nodes, either the reduced ones or the original passed in. Raises: .UnsupportedDegree: If the curve is degree 5 or higher. """ _, num_nodes = nodes.shape if num_nodes < 2: return False, nodes elif num_nodes == 2: projection = _PROJECTION0 denom = _PROJ_DENOM0 elif num_nodes == 3: projection = _PROJECTION1 denom = _PROJ_DENOM1 elif num_nodes == 4: projection = _PROJECTION2 denom = _PROJ_DENOM2 elif num_nodes == 5: projection = _PROJECTION3 denom = _PROJ_DENOM3 else: raise _helpers.UnsupportedDegree( num_nodes - 1, supported=(0, 1, 2, 3, 4) ) projected = _helpers.matrix_product(nodes, projection) / denom relative_err = projection_error(nodes, projected) if relative_err < _REDUCE_THRESHOLD: return True, reduce_pseudo_inverse(nodes) else: return False, nodes
python
def maybe_reduce(nodes): r"""Reduce nodes in a curve if they are degree-elevated. .. note:: This is a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. We check if the nodes are degree-elevated by projecting onto the space of degree-elevated curves of the same degree, then comparing to the projection. We form the projection by taking the corresponding (right) elevation matrix :math:`E` (from one degree lower) and forming :math:`E^T \left(E E^T\right)^{-1} E`. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: Tuple[bool, numpy.ndarray]: Pair of values. The first indicates if the ``nodes`` were reduced. The second is the resulting nodes, either the reduced ones or the original passed in. Raises: .UnsupportedDegree: If the curve is degree 5 or higher. """ _, num_nodes = nodes.shape if num_nodes < 2: return False, nodes elif num_nodes == 2: projection = _PROJECTION0 denom = _PROJ_DENOM0 elif num_nodes == 3: projection = _PROJECTION1 denom = _PROJ_DENOM1 elif num_nodes == 4: projection = _PROJECTION2 denom = _PROJ_DENOM2 elif num_nodes == 5: projection = _PROJECTION3 denom = _PROJ_DENOM3 else: raise _helpers.UnsupportedDegree( num_nodes - 1, supported=(0, 1, 2, 3, 4) ) projected = _helpers.matrix_product(nodes, projection) / denom relative_err = projection_error(nodes, projected) if relative_err < _REDUCE_THRESHOLD: return True, reduce_pseudo_inverse(nodes) else: return False, nodes
[ "def", "maybe_reduce", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "if", "num_nodes", "<", "2", ":", "return", "False", ",", "nodes", "elif", "num_nodes", "==", "2", ":", "projection", "=", "_PROJECTION0", "denom", "=", "...
r"""Reduce nodes in a curve if they are degree-elevated. .. note:: This is a helper for :func:`_full_reduce`. Hence there is no corresponding Fortran speedup. We check if the nodes are degree-elevated by projecting onto the space of degree-elevated curves of the same degree, then comparing to the projection. We form the projection by taking the corresponding (right) elevation matrix :math:`E` (from one degree lower) and forming :math:`E^T \left(E E^T\right)^{-1} E`. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: Tuple[bool, numpy.ndarray]: Pair of values. The first indicates if the ``nodes`` were reduced. The second is the resulting nodes, either the reduced ones or the original passed in. Raises: .UnsupportedDegree: If the curve is degree 5 or higher.
[ "r", "Reduce", "nodes", "in", "a", "curve", "if", "they", "are", "degree", "-", "elevated", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L871-L923
train
54,227
dhermes/bezier
src/bezier/_curve_helpers.py
_full_reduce
def _full_reduce(nodes): """Apply degree reduction to ``nodes`` until it can no longer be reduced. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The fully degree-reduced nodes. """ was_reduced, nodes = maybe_reduce(nodes) while was_reduced: was_reduced, nodes = maybe_reduce(nodes) return nodes
python
def _full_reduce(nodes): """Apply degree reduction to ``nodes`` until it can no longer be reduced. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The fully degree-reduced nodes. """ was_reduced, nodes = maybe_reduce(nodes) while was_reduced: was_reduced, nodes = maybe_reduce(nodes) return nodes
[ "def", "_full_reduce", "(", "nodes", ")", ":", "was_reduced", ",", "nodes", "=", "maybe_reduce", "(", "nodes", ")", "while", "was_reduced", ":", "was_reduced", ",", "nodes", "=", "maybe_reduce", "(", "nodes", ")", "return", "nodes" ]
Apply degree reduction to ``nodes`` until it can no longer be reduced. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): The nodes in the curve. Returns: numpy.ndarray: The fully degree-reduced nodes.
[ "Apply", "degree", "reduction", "to", "nodes", "until", "it", "can", "no", "longer", "be", "reduced", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_curve_helpers.py#L926-L943
train
54,228
dhermes/bezier
scripts/rewrite_package_rst.py
get_desired
def get_desired(): """Populate ``DESIRED_TEMPLATE`` with public members. If there are no members, does nothing. Returns: str: The "desired" contents of ``bezier.rst``. """ public_members = get_public_members() if public_members: members = "\n :members: {}".format(", ".join(public_members)) else: members = "" return DESIRED_TEMPLATE.format(members=members)
python
def get_desired(): """Populate ``DESIRED_TEMPLATE`` with public members. If there are no members, does nothing. Returns: str: The "desired" contents of ``bezier.rst``. """ public_members = get_public_members() if public_members: members = "\n :members: {}".format(", ".join(public_members)) else: members = "" return DESIRED_TEMPLATE.format(members=members)
[ "def", "get_desired", "(", ")", ":", "public_members", "=", "get_public_members", "(", ")", "if", "public_members", ":", "members", "=", "\"\\n :members: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "public_members", ")", ")", "else", ":", "member...
Populate ``DESIRED_TEMPLATE`` with public members. If there are no members, does nothing. Returns: str: The "desired" contents of ``bezier.rst``.
[ "Populate", "DESIRED_TEMPLATE", "with", "public", "members", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/rewrite_package_rst.py#L123-L136
train
54,229
dhermes/bezier
scripts/rewrite_package_rst.py
main
def main(): """Main entry point to replace autogenerated contents. Raises: ValueError: If the file doesn't contain the expected or desired contents. """ with open(FILENAME, "r") as file_obj: contents = file_obj.read() desired = get_desired() if contents == EXPECTED: with open(FILENAME, "w") as file_obj: file_obj.write(desired) elif contents != desired: raise ValueError("Unexpected contents", contents, "Expected", EXPECTED)
python
def main(): """Main entry point to replace autogenerated contents. Raises: ValueError: If the file doesn't contain the expected or desired contents. """ with open(FILENAME, "r") as file_obj: contents = file_obj.read() desired = get_desired() if contents == EXPECTED: with open(FILENAME, "w") as file_obj: file_obj.write(desired) elif contents != desired: raise ValueError("Unexpected contents", contents, "Expected", EXPECTED)
[ "def", "main", "(", ")", ":", "with", "open", "(", "FILENAME", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "desired", "=", "get_desired", "(", ")", "if", "contents", "==", "EXPECTED", ":", "with", "op...
Main entry point to replace autogenerated contents. Raises: ValueError: If the file doesn't contain the expected or desired contents.
[ "Main", "entry", "point", "to", "replace", "autogenerated", "contents", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/rewrite_package_rst.py#L139-L153
train
54,230
dhermes/bezier
setup_helpers_windows.py
run_cleanup
def run_cleanup(build_ext_cmd): """Cleanup after ``BuildFortranThenExt.run``. For in-place builds, moves the built shared library into the source directory. """ if not build_ext_cmd.inplace: return bezier_dir = os.path.join("src", "bezier") shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir) shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir)
python
def run_cleanup(build_ext_cmd): """Cleanup after ``BuildFortranThenExt.run``. For in-place builds, moves the built shared library into the source directory. """ if not build_ext_cmd.inplace: return bezier_dir = os.path.join("src", "bezier") shutil.move(os.path.join(build_ext_cmd.build_lib, LIB_DIR), bezier_dir) shutil.move(os.path.join(build_ext_cmd.build_lib, DLL_DIR), bezier_dir)
[ "def", "run_cleanup", "(", "build_ext_cmd", ")", ":", "if", "not", "build_ext_cmd", ".", "inplace", ":", "return", "bezier_dir", "=", "os", ".", "path", ".", "join", "(", "\"src\"", ",", "\"bezier\"", ")", "shutil", ".", "move", "(", "os", ".", "path", ...
Cleanup after ``BuildFortranThenExt.run``. For in-place builds, moves the built shared library into the source directory.
[ "Cleanup", "after", "BuildFortranThenExt", ".", "run", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers_windows.py#L77-L88
train
54,231
dhermes/bezier
noxfile.py
clean
def clean(session): """Clean up build files. Cleans up all artifacts that might get created during other ``nox`` sessions. There is no need for the session to create a ``virtualenv`` here (we are just pretending to be ``make``). """ clean_dirs = ( get_path(".cache"), get_path(".coverage"), get_path(".pytest_cache"), get_path("__pycache__"), get_path("build"), get_path("dist"), get_path("docs", "__pycache__"), get_path("docs", "build"), get_path("scripts", "macos", "__pycache__"), get_path("scripts", "macos", "dist_wheels"), get_path("scripts", "macos", "fixed_wheels"), get_path("src", "bezier.egg-info"), get_path("src", "bezier", "__pycache__"), get_path("src", "bezier", "extra-dll"), get_path("src", "bezier", "lib"), get_path("tests", "__pycache__"), get_path("tests", "functional", "__pycache__"), get_path("tests", "unit", "__pycache__"), get_path("wheelhouse"), ) clean_globs = ( get_path(".coverage"), get_path("*.mod"), get_path("*.pyc"), get_path("src", "bezier", "*.pyc"), get_path("src", "bezier", "*.pyd"), get_path("src", "bezier", "*.so"), get_path("src", "bezier", "quadpack", "*.o"), get_path("src", "bezier", "*.o"), get_path("tests", "*.pyc"), get_path("tests", "functional", "*.pyc"), get_path("tests", "unit", "*.pyc"), ) for dir_path in clean_dirs: session.run(shutil.rmtree, dir_path, ignore_errors=True) for glob_path in clean_globs: for filename in glob.glob(glob_path): session.run(os.remove, filename)
python
def clean(session): """Clean up build files. Cleans up all artifacts that might get created during other ``nox`` sessions. There is no need for the session to create a ``virtualenv`` here (we are just pretending to be ``make``). """ clean_dirs = ( get_path(".cache"), get_path(".coverage"), get_path(".pytest_cache"), get_path("__pycache__"), get_path("build"), get_path("dist"), get_path("docs", "__pycache__"), get_path("docs", "build"), get_path("scripts", "macos", "__pycache__"), get_path("scripts", "macos", "dist_wheels"), get_path("scripts", "macos", "fixed_wheels"), get_path("src", "bezier.egg-info"), get_path("src", "bezier", "__pycache__"), get_path("src", "bezier", "extra-dll"), get_path("src", "bezier", "lib"), get_path("tests", "__pycache__"), get_path("tests", "functional", "__pycache__"), get_path("tests", "unit", "__pycache__"), get_path("wheelhouse"), ) clean_globs = ( get_path(".coverage"), get_path("*.mod"), get_path("*.pyc"), get_path("src", "bezier", "*.pyc"), get_path("src", "bezier", "*.pyd"), get_path("src", "bezier", "*.so"), get_path("src", "bezier", "quadpack", "*.o"), get_path("src", "bezier", "*.o"), get_path("tests", "*.pyc"), get_path("tests", "functional", "*.pyc"), get_path("tests", "unit", "*.pyc"), ) for dir_path in clean_dirs: session.run(shutil.rmtree, dir_path, ignore_errors=True) for glob_path in clean_globs: for filename in glob.glob(glob_path): session.run(os.remove, filename)
[ "def", "clean", "(", "session", ")", ":", "clean_dirs", "=", "(", "get_path", "(", "\".cache\"", ")", ",", "get_path", "(", "\".coverage\"", ")", ",", "get_path", "(", "\".pytest_cache\"", ")", ",", "get_path", "(", "\"__pycache__\"", ")", ",", "get_path", ...
Clean up build files. Cleans up all artifacts that might get created during other ``nox`` sessions. There is no need for the session to create a ``virtualenv`` here (we are just pretending to be ``make``).
[ "Clean", "up", "build", "files", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/noxfile.py#L373-L420
train
54,232
allianceauth/allianceauth
allianceauth/hooks.py
register
def register(name, fn=None): """ Decorator to register a function as a hook Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) :param name: str Name of the hook/callback to register it as :param fn: function to register in the hook/callback :return: function Decorator if applied as a decorator """ def _hook_add(func): if name not in _hooks: logger.debug("Creating new hook %s" % name) _hooks[name] = [] logger.debug('Registering hook %s for function %s' % (name, fn)) _hooks[name].append(func) if fn is None: # Behave like a decorator def decorator(func): _hook_add(func) return func return decorator else: # Behave like a function, just register hook _hook_add(fn)
python
def register(name, fn=None): """ Decorator to register a function as a hook Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) :param name: str Name of the hook/callback to register it as :param fn: function to register in the hook/callback :return: function Decorator if applied as a decorator """ def _hook_add(func): if name not in _hooks: logger.debug("Creating new hook %s" % name) _hooks[name] = [] logger.debug('Registering hook %s for function %s' % (name, fn)) _hooks[name].append(func) if fn is None: # Behave like a decorator def decorator(func): _hook_add(func) return func return decorator else: # Behave like a function, just register hook _hook_add(fn)
[ "def", "register", "(", "name", ",", "fn", "=", "None", ")", ":", "def", "_hook_add", "(", "func", ")", ":", "if", "name", "not", "in", "_hooks", ":", "logger", ".", "debug", "(", "\"Creating new hook %s\"", "%", "name", ")", "_hooks", "[", "name", "...
Decorator to register a function as a hook Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): pass or as a function call:: def my_hook(...): pass register('hook_name', my_hook) :param name: str Name of the hook/callback to register it as :param fn: function to register in the hook/callback :return: function Decorator if applied as a decorator
[ "Decorator", "to", "register", "a", "function", "as", "a", "hook" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/hooks.py#L47-L81
train
54,233
allianceauth/allianceauth
allianceauth/services/modules/seat/manager.py
SeatManager.exec_request
def exec_request(endpoint, func, raise_for_status=False, **kwargs): """ Send an https api request """ try: endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint) headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'} logger.debug(headers) logger.debug(endpoint) ret = getattr(requests, func)(endpoint, headers=headers, data=kwargs) ret.raise_for_status() return ret.json() except requests.HTTPError as e: if raise_for_status: raise e logger.exception("Error encountered while performing API request to SeAT with url {}".format(endpoint)) return {}
python
def exec_request(endpoint, func, raise_for_status=False, **kwargs): """ Send an https api request """ try: endpoint = '{0}/api/v1/{1}'.format(settings.SEAT_URL, endpoint) headers = {'X-Token': settings.SEAT_XTOKEN, 'Accept': 'application/json'} logger.debug(headers) logger.debug(endpoint) ret = getattr(requests, func)(endpoint, headers=headers, data=kwargs) ret.raise_for_status() return ret.json() except requests.HTTPError as e: if raise_for_status: raise e logger.exception("Error encountered while performing API request to SeAT with url {}".format(endpoint)) return {}
[ "def", "exec_request", "(", "endpoint", ",", "func", ",", "raise_for_status", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "endpoint", "=", "'{0}/api/v1/{1}'", ".", "format", "(", "settings", ".", "SEAT_URL", ",", "endpoint", ")", "headers"...
Send an https api request
[ "Send", "an", "https", "api", "request" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/seat/manager.py#L32-L46
train
54,234
allianceauth/allianceauth
allianceauth/services/modules/seat/manager.py
SeatManager.add_user
def add_user(cls, username, email): """ Add user to service """ sanitized = str(cls.__sanitize_username(username)) logger.debug("Adding user to SeAT with username %s" % sanitized) password = cls.__generate_random_pass() ret = cls.exec_request('user', 'post', username=sanitized, email=str(email), password=password) logger.debug(ret) if cls._response_ok(ret): logger.info("Added SeAT user with username %s" % sanitized) return sanitized, password logger.info("Failed to add SeAT user with username %s" % sanitized) return None, None
python
def add_user(cls, username, email): """ Add user to service """ sanitized = str(cls.__sanitize_username(username)) logger.debug("Adding user to SeAT with username %s" % sanitized) password = cls.__generate_random_pass() ret = cls.exec_request('user', 'post', username=sanitized, email=str(email), password=password) logger.debug(ret) if cls._response_ok(ret): logger.info("Added SeAT user with username %s" % sanitized) return sanitized, password logger.info("Failed to add SeAT user with username %s" % sanitized) return None, None
[ "def", "add_user", "(", "cls", ",", "username", ",", "email", ")", ":", "sanitized", "=", "str", "(", "cls", ".", "__sanitize_username", "(", "username", ")", ")", "logger", ".", "debug", "(", "\"Adding user to SeAT with username %s\"", "%", "sanitized", ")", ...
Add user to service
[ "Add", "user", "to", "service" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/seat/manager.py#L49-L60
train
54,235
allianceauth/allianceauth
allianceauth/services/modules/seat/manager.py
SeatManager._check_email_changed
def _check_email_changed(cls, username, email): """Compares email to one set on SeAT""" ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True) return ret['email'] != email
python
def _check_email_changed(cls, username, email): """Compares email to one set on SeAT""" ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True) return ret['email'] != email
[ "def", "_check_email_changed", "(", "cls", ",", "username", ",", "email", ")", ":", "ret", "=", "cls", ".", "exec_request", "(", "'user/{}'", ".", "format", "(", "username", ")", ",", "'get'", ",", "raise_for_status", "=", "True", ")", "return", "ret", "...
Compares email to one set on SeAT
[ "Compares", "email", "to", "one", "set", "on", "SeAT" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/seat/manager.py#L96-L99
train
54,236
allianceauth/allianceauth
allianceauth/services/modules/seat/manager.py
SeatManager.update_user
def update_user(cls, username, email, password): """ Edit user info """ if cls._check_email_changed(username, email): # if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error logger.debug("Updating SeAT username %s with email %s and password" % (username, email)) ret = cls.exec_request('user/{}'.format(username), 'put', email=email) logger.debug(ret) if not cls._response_ok(ret): logger.warn("Failed to update email for username {}".format(username)) ret = cls.exec_request('user/{}'.format(username), 'put', password=password) logger.debug(ret) if not cls._response_ok(ret): logger.warn("Failed to update password for username {}".format(username)) return None logger.info("Updated SeAT user with username %s" % username) return username
python
def update_user(cls, username, email, password): """ Edit user info """ if cls._check_email_changed(username, email): # if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error logger.debug("Updating SeAT username %s with email %s and password" % (username, email)) ret = cls.exec_request('user/{}'.format(username), 'put', email=email) logger.debug(ret) if not cls._response_ok(ret): logger.warn("Failed to update email for username {}".format(username)) ret = cls.exec_request('user/{}'.format(username), 'put', password=password) logger.debug(ret) if not cls._response_ok(ret): logger.warn("Failed to update password for username {}".format(username)) return None logger.info("Updated SeAT user with username %s" % username) return username
[ "def", "update_user", "(", "cls", ",", "username", ",", "email", ",", "password", ")", ":", "if", "cls", ".", "_check_email_changed", "(", "username", ",", "email", ")", ":", "# if we try to set the email to whatever it is already on SeAT, we get a HTTP422 error", "logg...
Edit user info
[ "Edit", "user", "info" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/seat/manager.py#L102-L117
train
54,237
allianceauth/allianceauth
allianceauth/timerboard/views.py
AddUpdateMixin.get_form_kwargs
def get_form_kwargs(self): """ Inject the request user into the kwargs passed to the form """ kwargs = super(AddUpdateMixin, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs
python
def get_form_kwargs(self): """ Inject the request user into the kwargs passed to the form """ kwargs = super(AddUpdateMixin, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs
[ "def", "get_form_kwargs", "(", "self", ")", ":", "kwargs", "=", "super", "(", "AddUpdateMixin", ",", "self", ")", ".", "get_form_kwargs", "(", ")", "kwargs", ".", "update", "(", "{", "'user'", ":", "self", ".", "request", ".", "user", "}", ")", "return...
Inject the request user into the kwargs passed to the form
[ "Inject", "the", "request", "user", "into", "the", "kwargs", "passed", "to", "the", "form" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/timerboard/views.py#L58-L64
train
54,238
allianceauth/allianceauth
allianceauth/groupmanagement/models.py
create_auth_group
def create_auth_group(sender, instance, created, **kwargs): """ Creates the AuthGroup model when a group is created """ if created: AuthGroup.objects.create(group=instance)
python
def create_auth_group(sender, instance, created, **kwargs): """ Creates the AuthGroup model when a group is created """ if created: AuthGroup.objects.create(group=instance)
[ "def", "create_auth_group", "(", "sender", ",", "instance", ",", "created", ",", "*", "*", "kwargs", ")", ":", "if", "created", ":", "AuthGroup", ".", "objects", ".", "create", "(", "group", "=", "instance", ")" ]
Creates the AuthGroup model when a group is created
[ "Creates", "the", "AuthGroup", "model", "when", "a", "group", "is", "created" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/groupmanagement/models.py#L81-L86
train
54,239
allianceauth/allianceauth
allianceauth/services/modules/teamspeak3/util/ts3.py
TS3Proto.construct_command
def construct_command(self, command, keys=None, opts=None): """ Constructs a TS3 formatted command string Keys can have a single nested list to construct a nested parameter @param command: Command list @type command: string @param keys: Key/Value pairs @type keys: dict @param opts: Options @type opts: list """ cstr = [command] # Add the keys and values, escape as needed if keys: for key in keys: if isinstance(keys[key], list): ncstr = [] for nest in keys[key]: ncstr.append("%s=%s" % (key, self._escape_str(nest))) cstr.append("|".join(ncstr)) else: cstr.append("%s=%s" % (key, self._escape_str(keys[key]))) # Add in options if opts: for opt in opts: cstr.append("-%s" % opt) return " ".join(cstr)
python
def construct_command(self, command, keys=None, opts=None): """ Constructs a TS3 formatted command string Keys can have a single nested list to construct a nested parameter @param command: Command list @type command: string @param keys: Key/Value pairs @type keys: dict @param opts: Options @type opts: list """ cstr = [command] # Add the keys and values, escape as needed if keys: for key in keys: if isinstance(keys[key], list): ncstr = [] for nest in keys[key]: ncstr.append("%s=%s" % (key, self._escape_str(nest))) cstr.append("|".join(ncstr)) else: cstr.append("%s=%s" % (key, self._escape_str(keys[key]))) # Add in options if opts: for opt in opts: cstr.append("-%s" % opt) return " ".join(cstr)
[ "def", "construct_command", "(", "self", ",", "command", ",", "keys", "=", "None", ",", "opts", "=", "None", ")", ":", "cstr", "=", "[", "command", "]", "# Add the keys and values, escape as needed", "if", "keys", ":", "for", "key", "in", "keys", ":", "if"...
Constructs a TS3 formatted command string Keys can have a single nested list to construct a nested parameter @param command: Command list @type command: string @param keys: Key/Value pairs @type keys: dict @param opts: Options @type opts: list
[ "Constructs", "a", "TS3", "formatted", "command", "string", "Keys", "can", "have", "a", "single", "nested", "list", "to", "construct", "a", "nested", "parameter" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/teamspeak3/util/ts3.py#L103-L133
train
54,240
allianceauth/allianceauth
allianceauth/services/modules/teamspeak3/util/ts3.py
TS3Proto._escape_str
def _escape_str(value): """ Escape a value into a TS3 compatible string @param value: Value @type value: string/int """ if isinstance(value, int): return "%d" % value value = value.replace("\\", r'\\') for i, j in ts3_escape.items(): value = value.replace(i, j) return value
python
def _escape_str(value): """ Escape a value into a TS3 compatible string @param value: Value @type value: string/int """ if isinstance(value, int): return "%d" % value value = value.replace("\\", r'\\') for i, j in ts3_escape.items(): value = value.replace(i, j) return value
[ "def", "_escape_str", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "\"%d\"", "%", "value", "value", "=", "value", ".", "replace", "(", "\"\\\\\"", ",", "r'\\\\'", ")", "for", "i", ",", "j", "in", "ts3_esca...
Escape a value into a TS3 compatible string @param value: Value @type value: string/int
[ "Escape", "a", "value", "into", "a", "TS3", "compatible", "string" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/teamspeak3/util/ts3.py#L175-L187
train
54,241
allianceauth/allianceauth
allianceauth/services/modules/teamspeak3/util/ts3.py
TS3Proto._unescape_str
def _unescape_str(value): """ Unescape a TS3 compatible string into a normal string @param value: Value @type value: string/int """ if isinstance(value, int): return "%d" % value value = value.replace(r"\\", "\\") for i, j in ts3_escape.items(): value = value.replace(j, i) return value
python
def _unescape_str(value): """ Unescape a TS3 compatible string into a normal string @param value: Value @type value: string/int """ if isinstance(value, int): return "%d" % value value = value.replace(r"\\", "\\") for i, j in ts3_escape.items(): value = value.replace(j, i) return value
[ "def", "_unescape_str", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "\"%d\"", "%", "value", "value", "=", "value", ".", "replace", "(", "r\"\\\\\"", ",", "\"\\\\\"", ")", "for", "i", ",", "j", "in", "ts3_...
Unescape a TS3 compatible string into a normal string @param value: Value @type value: string/int
[ "Unescape", "a", "TS3", "compatible", "string", "into", "a", "normal", "string" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/teamspeak3/util/ts3.py#L190-L202
train
54,242
allianceauth/allianceauth
allianceauth/services/modules/teamspeak3/util/ts3.py
TS3Server.login
def login(self, username, password): """ Login to the TS3 Server @param username: Username @type username: str @param password: Password @type password: str """ d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': password}) if d == 0: self._log.info('Login Successful') return True return False
python
def login(self, username, password): """ Login to the TS3 Server @param username: Username @type username: str @param password: Password @type password: str """ d = self.send_command('login', keys={'client_login_name': username, 'client_login_password': password}) if d == 0: self._log.info('Login Successful') return True return False
[ "def", "login", "(", "self", ",", "username", ",", "password", ")", ":", "d", "=", "self", ".", "send_command", "(", "'login'", ",", "keys", "=", "{", "'client_login_name'", ":", "username", ",", "'client_login_password'", ":", "password", "}", ")", "if", ...
Login to the TS3 Server @param username: Username @type username: str @param password: Password @type password: str
[ "Login", "to", "the", "TS3", "Server" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/teamspeak3/util/ts3.py#L223-L235
train
54,243
allianceauth/allianceauth
allianceauth/services/modules/teamspeak3/util/ts3.py
TS3Server.use
def use(self, id): """ Use a particular Virtual Server instance @param id: Virtual Server ID @type id: int """ if self._connected and id > 0: self.send_command('use', keys={'sid': id})
python
def use(self, id): """ Use a particular Virtual Server instance @param id: Virtual Server ID @type id: int """ if self._connected and id > 0: self.send_command('use', keys={'sid': id})
[ "def", "use", "(", "self", ",", "id", ")", ":", "if", "self", ".", "_connected", "and", "id", ">", "0", ":", "self", ".", "send_command", "(", "'use'", ",", "keys", "=", "{", "'sid'", ":", "id", "}", ")" ]
Use a particular Virtual Server instance @param id: Virtual Server ID @type id: int
[ "Use", "a", "particular", "Virtual", "Server", "instance" ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/services/modules/teamspeak3/util/ts3.py#L253-L260
train
54,244
allianceauth/allianceauth
allianceauth/eveonline/autogroups/signals.py
pre_save_config
def pre_save_config(sender, instance, *args, **kwargs): """ Checks if enable was toggled on group config and deletes groups if necessary. """ logger.debug("Received pre_save from {}".format(instance)) if not instance.pk: # new model being created return try: old_instance = AutogroupsConfig.objects.get(pk=instance.pk) # Check if enable was toggled, delete groups? if old_instance.alliance_groups is True and instance.alliance_groups is False: instance.delete_alliance_managed_groups() if old_instance.corp_groups is True and instance.corp_groups is False: instance.delete_corp_managed_groups() except AutogroupsConfig.DoesNotExist: pass
python
def pre_save_config(sender, instance, *args, **kwargs): """ Checks if enable was toggled on group config and deletes groups if necessary. """ logger.debug("Received pre_save from {}".format(instance)) if not instance.pk: # new model being created return try: old_instance = AutogroupsConfig.objects.get(pk=instance.pk) # Check if enable was toggled, delete groups? if old_instance.alliance_groups is True and instance.alliance_groups is False: instance.delete_alliance_managed_groups() if old_instance.corp_groups is True and instance.corp_groups is False: instance.delete_corp_managed_groups() except AutogroupsConfig.DoesNotExist: pass
[ "def", "pre_save_config", "(", "sender", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Received pre_save from {}\"", ".", "format", "(", "instance", ")", ")", "if", "not", "instance", ".", "pk", ":"...
Checks if enable was toggled on group config and deletes groups if necessary.
[ "Checks", "if", "enable", "was", "toggled", "on", "group", "config", "and", "deletes", "groups", "if", "necessary", "." ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/eveonline/autogroups/signals.py#L13-L32
train
54,245
allianceauth/allianceauth
allianceauth/eveonline/autogroups/signals.py
check_groups_on_profile_update
def check_groups_on_profile_update(sender, instance, created, *args, **kwargs): """ Trigger check when main character or state changes. """ AutogroupsConfig.objects.update_groups_for_user(instance.user)
python
def check_groups_on_profile_update(sender, instance, created, *args, **kwargs): """ Trigger check when main character or state changes. """ AutogroupsConfig.objects.update_groups_for_user(instance.user)
[ "def", "check_groups_on_profile_update", "(", "sender", ",", "instance", ",", "created", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "AutogroupsConfig", ".", "objects", ".", "update_groups_for_user", "(", "instance", ".", "user", ")" ]
Trigger check when main character or state changes.
[ "Trigger", "check", "when", "main", "character", "or", "state", "changes", "." ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/eveonline/autogroups/signals.py#L45-L49
train
54,246
allianceauth/allianceauth
allianceauth/eveonline/autogroups/signals.py
autogroups_states_changed
def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs): """ Trigger group membership update when a state is added or removed from an autogroup config. """ if action.startswith('post_'): for pk in pk_set: try: state = State.objects.get(pk=pk) instance.update_group_membership_for_state(state) except State.DoesNotExist: # Deleted States handled by the profile state change pass
python
def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs): """ Trigger group membership update when a state is added or removed from an autogroup config. """ if action.startswith('post_'): for pk in pk_set: try: state = State.objects.get(pk=pk) instance.update_group_membership_for_state(state) except State.DoesNotExist: # Deleted States handled by the profile state change pass
[ "def", "autogroups_states_changed", "(", "sender", ",", "instance", ",", "action", ",", "reverse", ",", "model", ",", "pk_set", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "action", ".", "startswith", "(", "'post_'", ")", ":", "for", "pk...
Trigger group membership update when a state is added or removed from an autogroup config.
[ "Trigger", "group", "membership", "update", "when", "a", "state", "is", "added", "or", "removed", "from", "an", "autogroup", "config", "." ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/eveonline/autogroups/signals.py#L53-L65
train
54,247
allianceauth/allianceauth
allianceauth/srp/views.py
random_string
def random_string(string_length=10): """Returns a random string of length string_length.""" random = str(uuid.uuid4()) # Convert UUID format to a Python string. random = random.upper() # Make all characters uppercase. random = random.replace("-", "") # Remove the UUID '-'. return random[0:string_length]
python
def random_string(string_length=10): """Returns a random string of length string_length.""" random = str(uuid.uuid4()) # Convert UUID format to a Python string. random = random.upper() # Make all characters uppercase. random = random.replace("-", "") # Remove the UUID '-'. return random[0:string_length]
[ "def", "random_string", "(", "string_length", "=", "10", ")", ":", "random", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "# Convert UUID format to a Python string.", "random", "=", "random", ".", "upper", "(", ")", "# Make all characters uppercase.", "...
Returns a random string of length string_length.
[ "Returns", "a", "random", "string", "of", "length", "string_length", "." ]
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/srp/views.py#L25-L30
train
54,248
tariqdaouda/pyGeno
pyGeno/Genome.py
getGenomeList
def getGenomeList() : """Return the names of all imported genomes""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(Genome_Raba) names = [] for g in f.iterRun() : names.append(g.name) return names
python
def getGenomeList() : """Return the names of all imported genomes""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(Genome_Raba) names = [] for g in f.iterRun() : names.append(g.name) return names
[ "def", "getGenomeList", "(", ")", ":", "import", "rabaDB", ".", "filters", "as", "rfilt", "f", "=", "rfilt", ".", "RabaQuery", "(", "Genome_Raba", ")", "names", "=", "[", "]", "for", "g", "in", "f", ".", "iterRun", "(", ")", ":", "names", ".", "app...
Return the names of all imported genomes
[ "Return", "the", "names", "of", "all", "imported", "genomes" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/Genome.py#L16-L23
train
54,249
tariqdaouda/pyGeno
pyGeno/Transcript.py
Transcript.iterCodons
def iterCodons(self) : """iterates through the codons""" for i in range(len(self.cDNA)/3) : yield self.getCodon(i)
python
def iterCodons(self) : """iterates through the codons""" for i in range(len(self.cDNA)/3) : yield self.getCodon(i)
[ "def", "iterCodons", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "cDNA", ")", "/", "3", ")", ":", "yield", "self", ".", "getCodon", "(", "i", ")" ]
iterates through the codons
[ "iterates", "through", "the", "codons" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/Transcript.py#L165-L168
train
54,250
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
removeDuplicates
def removeDuplicates(inFileName, outFileName) : """removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName'""" f = open(inFileName) legend = f.readline() data = '' h = {} h[legend] = 0 lines = f.readlines() for l in lines : if not h.has_key(l) : h[l] = 0 data += l f.flush() f.close() f = open(outFileName, 'w') f.write(legend+data) f.flush() f.close()
python
def removeDuplicates(inFileName, outFileName) : """removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName'""" f = open(inFileName) legend = f.readline() data = '' h = {} h[legend] = 0 lines = f.readlines() for l in lines : if not h.has_key(l) : h[l] = 0 data += l f.flush() f.close() f = open(outFileName, 'w') f.write(legend+data) f.flush() f.close()
[ "def", "removeDuplicates", "(", "inFileName", ",", "outFileName", ")", ":", "f", "=", "open", "(", "inFileName", ")", "legend", "=", "f", ".", "readline", "(", ")", "data", "=", "''", "h", "=", "{", "}", "h", "[", "legend", "]", "=", "0", "lines", ...
removes duplicated lines from a 'inFileName' CSV file, the results are witten in 'outFileName
[ "removes", "duplicated", "lines", "from", "a", "inFileName", "CSV", "file", "the", "results", "are", "witten", "in", "outFileName" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L14-L34
train
54,251
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
catCSVs
def catCSVs(folder, ouputFileName, removeDups = False) : """Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems""" strCmd = r"""cat %s/*.csv > %s""" %(folder, ouputFileName) os.system(strCmd) if removeDups : removeDuplicates(ouputFileName, ouputFileName)
python
def catCSVs(folder, ouputFileName, removeDups = False) : """Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems""" strCmd = r"""cat %s/*.csv > %s""" %(folder, ouputFileName) os.system(strCmd) if removeDups : removeDuplicates(ouputFileName, ouputFileName)
[ "def", "catCSVs", "(", "folder", ",", "ouputFileName", ",", "removeDups", "=", "False", ")", ":", "strCmd", "=", "r\"\"\"cat %s/*.csv > %s\"\"\"", "%", "(", "folder", ",", "ouputFileName", ")", "os", ".", "system", "(", "strCmd", ")", "if", "removeDups", ":"...
Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems
[ "Concatenates", "all", "csv", "in", "folder", "and", "wites", "the", "results", "in", "ouputFileName", ".", "My", "not", "work", "on", "non", "Unix", "systems" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L36-L42
train
54,252
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
joinCSVs
def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') : """csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName' """ res = '' legend = [] csvs = [] for f in csvFilePaths : c = CSVFile() c.parse(f) csvs.append(c) legend.append(separator.join(c.legend.keys())) legend = separator.join(legend) lines = [] for i in range(len(csvs[0])) : val = csvs[0].get(i, column) line = separator.join(csvs[0][i]) for c in csvs[1:] : for j in range(len(c)) : if val == c.get(j, column) : line += separator + separator.join(c[j]) lines.append( line ) res = legend + '\n' + '\n'.join(lines) f = open(ouputFileName, 'w') f.write(res) f.flush() f.close() return res
python
def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') : """csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName' """ res = '' legend = [] csvs = [] for f in csvFilePaths : c = CSVFile() c.parse(f) csvs.append(c) legend.append(separator.join(c.legend.keys())) legend = separator.join(legend) lines = [] for i in range(len(csvs[0])) : val = csvs[0].get(i, column) line = separator.join(csvs[0][i]) for c in csvs[1:] : for j in range(len(c)) : if val == c.get(j, column) : line += separator + separator.join(c[j]) lines.append( line ) res = legend + '\n' + '\n'.join(lines) f = open(ouputFileName, 'w') f.write(res) f.flush() f.close() return res
[ "def", "joinCSVs", "(", "csvFilePaths", ",", "column", ",", "ouputFileName", ",", "separator", "=", "','", ")", ":", "res", "=", "''", "legend", "=", "[", "]", "csvs", "=", "[", "]", "for", "f", "in", "csvFilePaths", ":", "c", "=", "CSVFile", "(", ...
csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName'
[ "csvFilePaths", "should", "be", "an", "iterable", ".", "Joins", "all", "CSVs", "according", "to", "the", "values", "in", "the", "column", "column", ".", "Write", "the", "results", "in", "a", "new", "file", "ouputFileName" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L44-L76
train
54,253
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.addField
def addField(self, field) : """add a filed to the legend""" if field.lower() in self.legend : raise ValueError("%s is already in the legend" % field.lower()) self.legend[field.lower()] = len(self.legend) if len(self.strLegend) > 0 : self.strLegend += self.separator + field else : self.strLegend += field
python
def addField(self, field) : """add a filed to the legend""" if field.lower() in self.legend : raise ValueError("%s is already in the legend" % field.lower()) self.legend[field.lower()] = len(self.legend) if len(self.strLegend) > 0 : self.strLegend += self.separator + field else : self.strLegend += field
[ "def", "addField", "(", "self", ",", "field", ")", ":", "if", "field", ".", "lower", "(", ")", "in", "self", ".", "legend", ":", "raise", "ValueError", "(", "\"%s is already in the legend\"", "%", "field", ".", "lower", "(", ")", ")", "self", ".", "leg...
add a filed to the legend
[ "add", "a", "filed", "to", "the", "legend" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L221-L229
train
54,254
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.parse
def parse(self, filePath, skipLines=0, separator = ',', stringSeparator = '"', lineSeparator = '\n') : """Loads a CSV file""" self.filename = filePath f = open(filePath) if lineSeparator == '\n' : lines = f.readlines() else : lines = f.read().split(lineSeparator) f.flush() f.close() lines = lines[skipLines:] self.lines = [] self.comments = [] for l in lines : # print l if len(l) != 0 and l[0] != "#" : self.lines.append(l) elif l[0] == "#" : self.comments.append(l) self.separator = separator self.lineSeparator = lineSeparator self.stringSeparator = stringSeparator self.legend = collections.OrderedDict() i = 0 for c in self.lines[0].lower().replace(stringSeparator, '').split(separator) : legendElement = c.strip() if legendElement not in self.legend : self.legend[legendElement] = i i+=1 self.strLegend = self.lines[0].replace('\r', '\n').replace('\n', '') self.lines = self.lines[1:]
python
def parse(self, filePath, skipLines=0, separator = ',', stringSeparator = '"', lineSeparator = '\n') : """Loads a CSV file""" self.filename = filePath f = open(filePath) if lineSeparator == '\n' : lines = f.readlines() else : lines = f.read().split(lineSeparator) f.flush() f.close() lines = lines[skipLines:] self.lines = [] self.comments = [] for l in lines : # print l if len(l) != 0 and l[0] != "#" : self.lines.append(l) elif l[0] == "#" : self.comments.append(l) self.separator = separator self.lineSeparator = lineSeparator self.stringSeparator = stringSeparator self.legend = collections.OrderedDict() i = 0 for c in self.lines[0].lower().replace(stringSeparator, '').split(separator) : legendElement = c.strip() if legendElement not in self.legend : self.legend[legendElement] = i i+=1 self.strLegend = self.lines[0].replace('\r', '\n').replace('\n', '') self.lines = self.lines[1:]
[ "def", "parse", "(", "self", ",", "filePath", ",", "skipLines", "=", "0", ",", "separator", "=", "','", ",", "stringSeparator", "=", "'\"'", ",", "lineSeparator", "=", "'\\n'", ")", ":", "self", ".", "filename", "=", "filePath", "f", "=", "open", "(", ...
Loads a CSV file
[ "Loads", "a", "CSV", "file" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L231-L266
train
54,255
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.commitLine
def commitLine(self, line) : """Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is only for when you are streaming to a file") self.streamBuffer.append(line) if len(self.streamBuffer) % self.writeRate == 0 : for i in xrange(len(self.streamBuffer)) : self.streamBuffer[i] = str(self.streamBuffer[i]) self.streamFile.write("%s\n" % ('\n'.join(self.streamBuffer))) self.streamFile.flush() self.streamBuffer = []
python
def commitLine(self, line) : """Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is only for when you are streaming to a file") self.streamBuffer.append(line) if len(self.streamBuffer) % self.writeRate == 0 : for i in xrange(len(self.streamBuffer)) : self.streamBuffer[i] = str(self.streamBuffer[i]) self.streamFile.write("%s\n" % ('\n'.join(self.streamBuffer))) self.streamFile.flush() self.streamBuffer = []
[ "def", "commitLine", "(", "self", ",", "line", ")", ":", "if", "self", ".", "streamBuffer", "is", "None", ":", "raise", "ValueError", "(", "\"Commit lines is only for when you are streaming to a file\"", ")", "self", ".", "streamBuffer", ".", "append", "(", "line"...
Commits a line making it ready to be streamed to a file and saves the current buffer if needed. If no stream is active, raises a ValueError
[ "Commits", "a", "line", "making", "it", "ready", "to", "be", "streamed", "to", "a", "file", "and", "saves", "the", "current", "buffer", "if", "needed", ".", "If", "no", "stream", "is", "active", "raises", "a", "ValueError" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L299-L310
train
54,256
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.closeStreamToFile
def closeStreamToFile(self) : """Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is only for when you are streaming to a file") for i in xrange(len(self.streamBuffer)) : self.streamBuffer[i] = str(self.streamBuffer[i]) self.streamFile.write('\n'.join(self.streamBuffer)) self.streamFile.close() self.streamFile = None self.writeRate = None self.streamBuffer = None self.keepInMemory = True
python
def closeStreamToFile(self) : """Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError""" if self.streamBuffer is None : raise ValueError("Commit lines is only for when you are streaming to a file") for i in xrange(len(self.streamBuffer)) : self.streamBuffer[i] = str(self.streamBuffer[i]) self.streamFile.write('\n'.join(self.streamBuffer)) self.streamFile.close() self.streamFile = None self.writeRate = None self.streamBuffer = None self.keepInMemory = True
[ "def", "closeStreamToFile", "(", "self", ")", ":", "if", "self", ".", "streamBuffer", "is", "None", ":", "raise", "ValueError", "(", "\"Commit lines is only for when you are streaming to a file\"", ")", "for", "i", "in", "xrange", "(", "len", "(", "self", ".", "...
Appends the remaining commited lines and closes the stream. If no stream is active, raises a ValueError
[ "Appends", "the", "remaining", "commited", "lines", "and", "closes", "the", "stream", ".", "If", "no", "stream", "is", "active", "raises", "a", "ValueError" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L312-L325
train
54,257
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.newLine
def newLine(self) : """Appends an empty line at the end of the CSV and returns it""" l = CSVEntry(self) if self.keepInMemory : self.lines.append(l) return l
python
def newLine(self) : """Appends an empty line at the end of the CSV and returns it""" l = CSVEntry(self) if self.keepInMemory : self.lines.append(l) return l
[ "def", "newLine", "(", "self", ")", ":", "l", "=", "CSVEntry", "(", "self", ")", "if", "self", ".", "keepInMemory", ":", "self", ".", "lines", ".", "append", "(", "l", ")", "return", "l" ]
Appends an empty line at the end of the CSV and returns it
[ "Appends", "an", "empty", "line", "at", "the", "end", "of", "the", "CSV", "and", "returns", "it" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L350-L355
train
54,258
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.insertLine
def insertLine(self, i) : """Inserts an empty line at position i and returns it""" self.data.insert(i, CSVEntry(self)) return self.lines[i]
python
def insertLine(self, i) : """Inserts an empty line at position i and returns it""" self.data.insert(i, CSVEntry(self)) return self.lines[i]
[ "def", "insertLine", "(", "self", ",", "i", ")", ":", "self", ".", "data", ".", "insert", "(", "i", ",", "CSVEntry", "(", "self", ")", ")", "return", "self", ".", "lines", "[", "i", "]" ]
Inserts an empty line at position i and returns it
[ "Inserts", "an", "empty", "line", "at", "position", "i", "and", "returns", "it" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L357-L360
train
54,259
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.save
def save(self, filePath) : """save the CSV to a file""" self.filename = filePath f = open(filePath, 'w') f.write(self.toStr()) f.flush() f.close()
python
def save(self, filePath) : """save the CSV to a file""" self.filename = filePath f = open(filePath, 'w') f.write(self.toStr()) f.flush() f.close()
[ "def", "save", "(", "self", ",", "filePath", ")", ":", "self", ".", "filename", "=", "filePath", "f", "=", "open", "(", "filePath", ",", "'w'", ")", "f", ".", "write", "(", "self", ".", "toStr", "(", ")", ")", "f", ".", "flush", "(", ")", "f", ...
save the CSV to a file
[ "save", "the", "CSV", "to", "a", "file" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L362-L368
train
54,260
tariqdaouda/pyGeno
pyGeno/tools/parsers/CSVTools.py
CSVFile.toStr
def toStr(self) : """returns a string version of the CSV""" s = [self.strLegend] for l in self.lines : s.append(l.toStr()) return self.lineSeparator.join(s)
python
def toStr(self) : """returns a string version of the CSV""" s = [self.strLegend] for l in self.lines : s.append(l.toStr()) return self.lineSeparator.join(s)
[ "def", "toStr", "(", "self", ")", ":", "s", "=", "[", "self", ".", "strLegend", "]", "for", "l", "in", "self", ".", "lines", ":", "s", ".", "append", "(", "l", ".", "toStr", "(", ")", ")", "return", "self", ".", "lineSeparator", ".", "join", "(...
returns a string version of the CSV
[ "returns", "a", "string", "version", "of", "the", "CSV" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/CSVTools.py#L370-L375
train
54,261
tariqdaouda/pyGeno
pyGeno/pyGenoObjectBases.py
pyGenoRabaObjectWrapper.count
def count(self, objectType, *args, **coolArgs) : """Returns the number of elements satisfying the query""" return self._makeLoadQuery(objectType, *args, **coolArgs).count()
python
def count(self, objectType, *args, **coolArgs) : """Returns the number of elements satisfying the query""" return self._makeLoadQuery(objectType, *args, **coolArgs).count()
[ "def", "count", "(", "self", ",", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ":", "return", "self", ".", "_makeLoadQuery", "(", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ".", "count", "(", ")" ]
Returns the number of elements satisfying the query
[ "Returns", "the", "number", "of", "elements", "satisfying", "the", "query" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/pyGenoObjectBases.py#L112-L114
train
54,262
tariqdaouda/pyGeno
pyGeno/pyGenoObjectBases.py
pyGenoRabaObjectWrapper.iterGet
def iterGet(self, objectType, *args, **coolArgs) : """Same as get. But retuns the elements one by one, much more efficient for large outputs""" for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() : if issubclass(objectType, pyGenoRabaObjectWrapper) : yield objectType(wrapped_object_and_bag = (e, self.bagKey)) else : yield e
python
def iterGet(self, objectType, *args, **coolArgs) : """Same as get. But retuns the elements one by one, much more efficient for large outputs""" for e in self._makeLoadQuery(objectType, *args, **coolArgs).iterRun() : if issubclass(objectType, pyGenoRabaObjectWrapper) : yield objectType(wrapped_object_and_bag = (e, self.bagKey)) else : yield e
[ "def", "iterGet", "(", "self", ",", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ":", "for", "e", "in", "self", ".", "_makeLoadQuery", "(", "objectType", ",", "*", "args", ",", "*", "*", "coolArgs", ")", ".", "iterRun", "(", ")",...
Same as get. But retuns the elements one by one, much more efficient for large outputs
[ "Same", "as", "get", ".", "But", "retuns", "the", "elements", "one", "by", "one", "much", "more", "efficient", "for", "large", "outputs" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/pyGenoObjectBases.py#L137-L144
train
54,263
tariqdaouda/pyGeno
pyGeno/importation/SNPs.py
deleteSNPs
def deleteSNPs(setName) : """deletes a set of polymorphisms""" con = conf.db try : SMaster = SNPMaster(setName = setName) con.beginTransaction() SNPType = SMaster.SNPType con.delete(SNPType, 'setName = ?', (setName,)) SMaster.delete() con.endTransaction() except KeyError : raise KeyError("Can't delete the setName %s because i can't find it in SNPMaster, maybe there's not set by that name" % setName) #~ printf("can't delete the setName %s because i can't find it in SNPMaster, maybe there's no set by that name" % setName) return False return True
python
def deleteSNPs(setName) : """deletes a set of polymorphisms""" con = conf.db try : SMaster = SNPMaster(setName = setName) con.beginTransaction() SNPType = SMaster.SNPType con.delete(SNPType, 'setName = ?', (setName,)) SMaster.delete() con.endTransaction() except KeyError : raise KeyError("Can't delete the setName %s because i can't find it in SNPMaster, maybe there's not set by that name" % setName) #~ printf("can't delete the setName %s because i can't find it in SNPMaster, maybe there's no set by that name" % setName) return False return True
[ "def", "deleteSNPs", "(", "setName", ")", ":", "con", "=", "conf", ".", "db", "try", ":", "SMaster", "=", "SNPMaster", "(", "setName", "=", "setName", ")", "con", ".", "beginTransaction", "(", ")", "SNPType", "=", "SMaster", ".", "SNPType", "con", ".",...
deletes a set of polymorphisms
[ "deletes", "a", "set", "of", "polymorphisms" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/importation/SNPs.py#L86-L100
train
54,264
tariqdaouda/pyGeno
pyGeno/SNP.py
getSNPSetsList
def getSNPSetsList() : """Return the names of all imported snp sets""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(SNPMaster) names = [] for g in f.iterRun() : names.append(g.setName) return names
python
def getSNPSetsList() : """Return the names of all imported snp sets""" import rabaDB.filters as rfilt f = rfilt.RabaQuery(SNPMaster) names = [] for g in f.iterRun() : names.append(g.setName) return names
[ "def", "getSNPSetsList", "(", ")", ":", "import", "rabaDB", ".", "filters", "as", "rfilt", "f", "=", "rfilt", ".", "RabaQuery", "(", "SNPMaster", ")", "names", "=", "[", "]", "for", "g", "in", "f", ".", "iterRun", "(", ")", ":", "names", ".", "appe...
Return the names of all imported snp sets
[ "Return", "the", "names", "of", "all", "imported", "snp", "sets" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/SNP.py#L18-L25
train
54,265
tariqdaouda/pyGeno
pyGeno/tools/parsers/FastaTools.py
FastaFile.parseFile
def parseFile(self, fil) : """Opens a file and parses it""" f = open(fil) self.parseStr(f.read()) f.close()
python
def parseFile(self, fil) : """Opens a file and parses it""" f = open(fil) self.parseStr(f.read()) f.close()
[ "def", "parseFile", "(", "self", ",", "fil", ")", ":", "f", "=", "open", "(", "fil", ")", "self", ".", "parseStr", "(", "f", ".", "read", "(", ")", ")", "f", ".", "close", "(", ")" ]
Opens a file and parses it
[ "Opens", "a", "file", "and", "parses", "it" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/FastaTools.py#L32-L36
train
54,266
tariqdaouda/pyGeno
pyGeno/tools/parsers/FastaTools.py
FastaFile.add
def add(self, header, data) : """appends a new entry to the file""" if header[0] != '>' : self.data.append(('>'+header, data)) else : self.data.append((header, data))
python
def add(self, header, data) : """appends a new entry to the file""" if header[0] != '>' : self.data.append(('>'+header, data)) else : self.data.append((header, data))
[ "def", "add", "(", "self", ",", "header", ",", "data", ")", ":", "if", "header", "[", "0", "]", "!=", "'>'", ":", "self", ".", "data", ".", "append", "(", "(", "'>'", "+", "header", ",", "data", ")", ")", "else", ":", "self", ".", "data", "."...
appends a new entry to the file
[ "appends", "a", "new", "entry", "to", "the", "file" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/FastaTools.py#L52-L57
train
54,267
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
findAll
def findAll(haystack, needle) : """returns a list of all occurances of needle in haystack""" h = haystack res = [] f = haystack.find(needle) offset = 0 while (f >= 0) : #print h, needle, f, offset res.append(f+offset) offset += f+len(needle) h = h[f+len(needle):] f = h.find(needle) return res
python
def findAll(haystack, needle) : """returns a list of all occurances of needle in haystack""" h = haystack res = [] f = haystack.find(needle) offset = 0 while (f >= 0) : #print h, needle, f, offset res.append(f+offset) offset += f+len(needle) h = h[f+len(needle):] f = h.find(needle) return res
[ "def", "findAll", "(", "haystack", ",", "needle", ")", ":", "h", "=", "haystack", "res", "=", "[", "]", "f", "=", "haystack", ".", "find", "(", "needle", ")", "offset", "=", "0", "while", "(", "f", ">=", "0", ")", ":", "#print h, needle, f, offset", ...
returns a list of all occurances of needle in haystack
[ "returns", "a", "list", "of", "all", "occurances", "of", "needle", "in", "haystack" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L136-L150
train
54,268
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
complementTab
def complementTab(seq=[]): """returns a list of complementary sequence without inversing it""" complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M', 'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't', 'c': 'g', 'g': 'c', 't': 'a', 'r': 'y', 'y': 'r', 'm': 'k', 'k': 'm', 'w': 'w', 's': 's', 'b': 'v', 'd': 'h', 'h': 'd', 'v': 'b', 'n': 'n'} seq_tmp = [] for bps in seq: if len(bps) == 0: #Need manage '' for deletion seq_tmp.append('') elif len(bps) == 1: seq_tmp.append(complement[bps]) else: #Need manage 'ACT' for insertion #The insertion need to be reverse complement (like seq) seq_tmp.append(reverseComplement(bps)) #Doesn't work in the second for when bps=='' #seq = [complement[bp] if bp != '' else '' for bps in seq for bp in bps] return seq_tmp
python
def complementTab(seq=[]): """returns a list of complementary sequence without inversing it""" complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'R': 'Y', 'Y': 'R', 'M': 'K', 'K': 'M', 'W': 'W', 'S': 'S', 'B': 'V', 'D': 'H', 'H': 'D', 'V': 'B', 'N': 'N', 'a': 't', 'c': 'g', 'g': 'c', 't': 'a', 'r': 'y', 'y': 'r', 'm': 'k', 'k': 'm', 'w': 'w', 's': 's', 'b': 'v', 'd': 'h', 'h': 'd', 'v': 'b', 'n': 'n'} seq_tmp = [] for bps in seq: if len(bps) == 0: #Need manage '' for deletion seq_tmp.append('') elif len(bps) == 1: seq_tmp.append(complement[bps]) else: #Need manage 'ACT' for insertion #The insertion need to be reverse complement (like seq) seq_tmp.append(reverseComplement(bps)) #Doesn't work in the second for when bps=='' #seq = [complement[bp] if bp != '' else '' for bps in seq for bp in bps] return seq_tmp
[ "def", "complementTab", "(", "seq", "=", "[", "]", ")", ":", "complement", "=", "{", "'A'", ":", "'T'", ",", "'C'", ":", "'G'", ",", "'G'", ":", "'C'", ",", "'T'", ":", "'A'", ",", "'R'", ":", "'Y'", ",", "'Y'", ":", "'R'", ",", "'M'", ":", ...
returns a list of complementary sequence without inversing it
[ "returns", "a", "list", "of", "complementary", "sequence", "without", "inversing", "it" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L153-L174
train
54,269
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
translateDNA_6Frames
def translateDNA_6Frames(sequence) : """returns 6 translation of sequence. One for each reading frame""" trans = ( translateDNA(sequence, 'f1'), translateDNA(sequence, 'f2'), translateDNA(sequence, 'f3'), translateDNA(sequence, 'r1'), translateDNA(sequence, 'r2'), translateDNA(sequence, 'r3'), ) return trans
python
def translateDNA_6Frames(sequence) : """returns 6 translation of sequence. One for each reading frame""" trans = ( translateDNA(sequence, 'f1'), translateDNA(sequence, 'f2'), translateDNA(sequence, 'f3'), translateDNA(sequence, 'r1'), translateDNA(sequence, 'r2'), translateDNA(sequence, 'r3'), ) return trans
[ "def", "translateDNA_6Frames", "(", "sequence", ")", ":", "trans", "=", "(", "translateDNA", "(", "sequence", ",", "'f1'", ")", ",", "translateDNA", "(", "sequence", ",", "'f2'", ")", ",", "translateDNA", "(", "sequence", ",", "'f3'", ")", ",", "translateD...
returns 6 translation of sequence. One for each reading frame
[ "returns", "6", "translation", "of", "sequence", ".", "One", "for", "each", "reading", "frame" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L196-L208
train
54,270
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
getSequenceCombinaisons
def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) : """Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield""" if type(polymorphipolymorphicDnaSeqSeq) is not types.ListType : seq = list(polymorphipolymorphicDnaSeqSeq) else : seq = polymorphipolymorphicDnaSeqSeq if pos >= len(seq) : return [''.join(seq)] variants = [] if seq[pos] in polymorphicNucleotides : chars = decodePolymorphicNucleotide(seq[pos]) else : chars = seq[pos]#.split('/') for c in chars : rseq = copy.copy(seq) rseq[pos] = c variants.extend(getSequenceCombinaisons(rseq, pos + 1)) return variants
python
def getSequenceCombinaisons(polymorphipolymorphicDnaSeqSeq, pos = 0) : """Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield""" if type(polymorphipolymorphicDnaSeqSeq) is not types.ListType : seq = list(polymorphipolymorphicDnaSeqSeq) else : seq = polymorphipolymorphicDnaSeqSeq if pos >= len(seq) : return [''.join(seq)] variants = [] if seq[pos] in polymorphicNucleotides : chars = decodePolymorphicNucleotide(seq[pos]) else : chars = seq[pos]#.split('/') for c in chars : rseq = copy.copy(seq) rseq[pos] = c variants.extend(getSequenceCombinaisons(rseq, pos + 1)) return variants
[ "def", "getSequenceCombinaisons", "(", "polymorphipolymorphicDnaSeqSeq", ",", "pos", "=", "0", ")", ":", "if", "type", "(", "polymorphipolymorphicDnaSeqSeq", ")", "is", "not", "types", ".", "ListType", ":", "seq", "=", "list", "(", "polymorphipolymorphicDnaSeqSeq", ...
Takes a dna sequence with polymorphismes and returns all the possible sequences that it can yield
[ "Takes", "a", "dna", "sequence", "with", "polymorphismes", "and", "returns", "all", "the", "possible", "sequences", "that", "it", "can", "yield" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L252-L274
train
54,271
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
getNucleotideCodon
def getNucleotideCodon(sequence, x1) : """Returns the entire codon of the nucleotide at pos x1 in sequence, and the position of that nocleotide in the codon in a tuple""" if x1 < 0 or x1 >= len(sequence) : return None p = x1%3 if p == 0 : return (sequence[x1: x1+3], 0) elif p ==1 : return (sequence[x1-1: x1+2], 1) elif p == 2 : return (sequence[x1-2: x1+1], 2)
python
def getNucleotideCodon(sequence, x1) : """Returns the entire codon of the nucleotide at pos x1 in sequence, and the position of that nocleotide in the codon in a tuple""" if x1 < 0 or x1 >= len(sequence) : return None p = x1%3 if p == 0 : return (sequence[x1: x1+3], 0) elif p ==1 : return (sequence[x1-1: x1+2], 1) elif p == 2 : return (sequence[x1-2: x1+1], 2)
[ "def", "getNucleotideCodon", "(", "sequence", ",", "x1", ")", ":", "if", "x1", "<", "0", "or", "x1", ">=", "len", "(", "sequence", ")", ":", "return", "None", "p", "=", "x1", "%", "3", "if", "p", "==", "0", ":", "return", "(", "sequence", "[", ...
Returns the entire codon of the nucleotide at pos x1 in sequence, and the position of that nocleotide in the codon in a tuple
[ "Returns", "the", "entire", "codon", "of", "the", "nucleotide", "at", "pos", "x1", "in", "sequence", "and", "the", "position", "of", "that", "nocleotide", "in", "the", "codon", "in", "a", "tuple" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L348-L361
train
54,272
tariqdaouda/pyGeno
pyGeno/tools/UsefulFunctions.py
highlightSubsequence
def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') : """returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop'""" seq = list(sequence) print x1, x2-1, len(seq) seq[x1] = start + seq[x1] seq[x2-1] = seq[x2-1] + stop return ''.join(seq)
python
def highlightSubsequence(sequence, x1, x2, start=' [', stop = '] ') : """returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop'""" seq = list(sequence) print x1, x2-1, len(seq) seq[x1] = start + seq[x1] seq[x2-1] = seq[x2-1] + stop return ''.join(seq)
[ "def", "highlightSubsequence", "(", "sequence", ",", "x1", ",", "x2", ",", "start", "=", "' ['", ",", "stop", "=", "'] '", ")", ":", "seq", "=", "list", "(", "sequence", ")", "print", "x1", ",", "x2", "-", "1", ",", "len", "(", "seq", ")", "seq",...
returns a sequence where the subsequence in [x1, x2[ is placed in bewteen 'start' and 'stop
[ "returns", "a", "sequence", "where", "the", "subsequence", "in", "[", "x1", "x2", "[", "is", "placed", "in", "bewteen", "start", "and", "stop" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/UsefulFunctions.py#L392-L400
train
54,273
tariqdaouda/pyGeno
pyGeno/importation/Genomes.py
deleteGenome
def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = True try : genome = Genome_Raba(name = name, species = species.lower()) objs.append(genome) pBar = ProgressBar(label = 'preparing') for typ in (Chromosome_Raba, Gene_Raba, Transcript_Raba, Exon_Raba, Protein_Raba) : pBar.update() f = RabaQuery(typ, namespace = genome._raba_namespace) f.addFilter({'genome' : genome}) for e in f.iterRun() : objs.append(e) pBar.close() pBar = ProgressBar(nbEpochs = len(objs), label = 'deleting objects') for e in objs : pBar.update() e.delete() pBar.close() except KeyError as e : #~ printf("\tWARNING, couldn't remove genome form db, maybe it's not there: ", e) raise KeyError("\tWARNING, couldn't remove genome form db, maybe it's not there: ", e) allGood = False printf('\tdeleting folder') try : shutil.rmtree(conf.getGenomeSequencePath(species, name)) except OSError as e: #~ printf('\tWARNING, Unable to delete folder: ', e) OSError('\tWARNING, Unable to delete folder: ', e) allGood = False conf.db.endTransaction() return allGood
python
def deleteGenome(species, name) : """Removes a genome from the database""" printf('deleting genome (%s, %s)...' % (species, name)) conf.db.beginTransaction() objs = [] allGood = True try : genome = Genome_Raba(name = name, species = species.lower()) objs.append(genome) pBar = ProgressBar(label = 'preparing') for typ in (Chromosome_Raba, Gene_Raba, Transcript_Raba, Exon_Raba, Protein_Raba) : pBar.update() f = RabaQuery(typ, namespace = genome._raba_namespace) f.addFilter({'genome' : genome}) for e in f.iterRun() : objs.append(e) pBar.close() pBar = ProgressBar(nbEpochs = len(objs), label = 'deleting objects') for e in objs : pBar.update() e.delete() pBar.close() except KeyError as e : #~ printf("\tWARNING, couldn't remove genome form db, maybe it's not there: ", e) raise KeyError("\tWARNING, couldn't remove genome form db, maybe it's not there: ", e) allGood = False printf('\tdeleting folder') try : shutil.rmtree(conf.getGenomeSequencePath(species, name)) except OSError as e: #~ printf('\tWARNING, Unable to delete folder: ', e) OSError('\tWARNING, Unable to delete folder: ', e) allGood = False conf.db.endTransaction() return allGood
[ "def", "deleteGenome", "(", "species", ",", "name", ")", ":", "printf", "(", "'deleting genome (%s, %s)...'", "%", "(", "species", ",", "name", ")", ")", "conf", ".", "db", ".", "beginTransaction", "(", ")", "objs", "=", "[", "]", "allGood", "=", "True",...
Removes a genome from the database
[ "Removes", "a", "genome", "from", "the", "database" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/importation/Genomes.py#L58-L97
train
54,274
tariqdaouda/pyGeno
pyGeno/importation/Genomes.py
_importSequence
def _importSequence(chromosome, fastaFile, targetDir) : "Serializes fastas into .dat files" f = gzip.open(fastaFile) header = f.readline() strRes = f.read().upper().replace('\n', '').replace('\r', '') f.close() fn = '%s/chromosome%s.dat' % (targetDir, chromosome.number) f = open(fn, 'w') f.write(strRes) f.close() chromosome.dataFile = fn chromosome.header = header return len(strRes)
python
def _importSequence(chromosome, fastaFile, targetDir) : "Serializes fastas into .dat files" f = gzip.open(fastaFile) header = f.readline() strRes = f.read().upper().replace('\n', '').replace('\r', '') f.close() fn = '%s/chromosome%s.dat' % (targetDir, chromosome.number) f = open(fn, 'w') f.write(strRes) f.close() chromosome.dataFile = fn chromosome.header = header return len(strRes)
[ "def", "_importSequence", "(", "chromosome", ",", "fastaFile", ",", "targetDir", ")", ":", "f", "=", "gzip", ".", "open", "(", "fastaFile", ")", "header", "=", "f", ".", "readline", "(", ")", "strRes", "=", "f", ".", "read", "(", ")", ".", "upper", ...
Serializes fastas into .dat files
[ "Serializes", "fastas", "into", ".", "dat", "files" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/importation/Genomes.py#L445-L459
train
54,275
tariqdaouda/pyGeno
pyGeno/configuration.py
createDefaultConfigFile
def createDefaultConfigFile() : """Creates a default configuration file""" s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION) f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w') f.write(s) f.close()
python
def createDefaultConfigFile() : """Creates a default configuration file""" s = "[pyGeno_config]\nsettings_dir=%s\nremote_location=%s" % (pyGeno_SETTINGS_DIR, pyGeno_REMOTE_LOCATION) f = open('%s/config.ini' % pyGeno_SETTINGS_DIR, 'w') f.write(s) f.close()
[ "def", "createDefaultConfigFile", "(", ")", ":", "s", "=", "\"[pyGeno_config]\\nsettings_dir=%s\\nremote_location=%s\"", "%", "(", "pyGeno_SETTINGS_DIR", ",", "pyGeno_REMOTE_LOCATION", ")", "f", "=", "open", "(", "'%s/config.ini'", "%", "pyGeno_SETTINGS_DIR", ",", "'w'", ...
Creates a default configuration file
[ "Creates", "a", "default", "configuration", "file" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/configuration.py#L46-L51
train
54,276
tariqdaouda/pyGeno
pyGeno/configuration.py
getSettingsPath
def getSettingsPath() : """Returns the path where the settings are stored""" parser = SafeConfigParser() try : parser.read(os.path.normpath(pyGeno_SETTINGS_DIR+'/config.ini')) return parser.get('pyGeno_config', 'settings_dir') except : createDefaultConfigFile() return getSettingsPath()
python
def getSettingsPath() : """Returns the path where the settings are stored""" parser = SafeConfigParser() try : parser.read(os.path.normpath(pyGeno_SETTINGS_DIR+'/config.ini')) return parser.get('pyGeno_config', 'settings_dir') except : createDefaultConfigFile() return getSettingsPath()
[ "def", "getSettingsPath", "(", ")", ":", "parser", "=", "SafeConfigParser", "(", ")", "try", ":", "parser", ".", "read", "(", "os", ".", "path", ".", "normpath", "(", "pyGeno_SETTINGS_DIR", "+", "'/config.ini'", ")", ")", "return", "parser", ".", "get", ...
Returns the path where the settings are stored
[ "Returns", "the", "path", "where", "the", "settings", "are", "stored" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/configuration.py#L53-L61
train
54,277
tariqdaouda/pyGeno
pyGeno/configuration.py
pyGeno_init
def pyGeno_init() : """This function is automatically called at launch""" global db, dbConf global pyGeno_SETTINGS_PATH global pyGeno_RABA_DBFILE global pyGeno_DATA_PATH if not checkPythonVersion() : raise PythonVersionError("==> FATAL: pyGeno only works with python 2.7 and above, please upgrade your python version") if not os.path.exists(pyGeno_SETTINGS_DIR) : os.makedirs(pyGeno_SETTINGS_DIR) pyGeno_SETTINGS_PATH = getSettingsPath() pyGeno_RABA_DBFILE = os.path.normpath( os.path.join(pyGeno_SETTINGS_PATH, "pyGenoRaba.db") ) pyGeno_DATA_PATH = os.path.normpath( os.path.join(pyGeno_SETTINGS_PATH, "data") ) if not os.path.exists(pyGeno_SETTINGS_PATH) : os.makedirs(pyGeno_SETTINGS_PATH) if not os.path.exists(pyGeno_DATA_PATH) : os.makedirs(pyGeno_DATA_PATH) #launching the db rabaDB.rabaSetup.RabaConfiguration(pyGeno_RABA_NAMESPACE, pyGeno_RABA_DBFILE) db = rabaDB.rabaSetup.RabaConnection(pyGeno_RABA_NAMESPACE) dbConf = rabaDB.rabaSetup.RabaConfiguration(pyGeno_RABA_NAMESPACE)
python
def pyGeno_init() : """This function is automatically called at launch""" global db, dbConf global pyGeno_SETTINGS_PATH global pyGeno_RABA_DBFILE global pyGeno_DATA_PATH if not checkPythonVersion() : raise PythonVersionError("==> FATAL: pyGeno only works with python 2.7 and above, please upgrade your python version") if not os.path.exists(pyGeno_SETTINGS_DIR) : os.makedirs(pyGeno_SETTINGS_DIR) pyGeno_SETTINGS_PATH = getSettingsPath() pyGeno_RABA_DBFILE = os.path.normpath( os.path.join(pyGeno_SETTINGS_PATH, "pyGenoRaba.db") ) pyGeno_DATA_PATH = os.path.normpath( os.path.join(pyGeno_SETTINGS_PATH, "data") ) if not os.path.exists(pyGeno_SETTINGS_PATH) : os.makedirs(pyGeno_SETTINGS_PATH) if not os.path.exists(pyGeno_DATA_PATH) : os.makedirs(pyGeno_DATA_PATH) #launching the db rabaDB.rabaSetup.RabaConfiguration(pyGeno_RABA_NAMESPACE, pyGeno_RABA_DBFILE) db = rabaDB.rabaSetup.RabaConnection(pyGeno_RABA_NAMESPACE) dbConf = rabaDB.rabaSetup.RabaConfiguration(pyGeno_RABA_NAMESPACE)
[ "def", "pyGeno_init", "(", ")", ":", "global", "db", ",", "dbConf", "global", "pyGeno_SETTINGS_PATH", "global", "pyGeno_RABA_DBFILE", "global", "pyGeno_DATA_PATH", "if", "not", "checkPythonVersion", "(", ")", ":", "raise", "PythonVersionError", "(", "\"==> FATAL: pyGe...
This function is automatically called at launch
[ "This", "function", "is", "automatically", "called", "at", "launch" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/configuration.py#L76-L104
train
54,278
tariqdaouda/pyGeno
pyGeno/Exon.py
Exon.previousExon
def previousExon(self) : """Returns the previous exon of the transcript, or None if there is none""" if self.number == 0 : return None try : return self.transcript.exons[self.number-1] except IndexError : return None
python
def previousExon(self) : """Returns the previous exon of the transcript, or None if there is none""" if self.number == 0 : return None try : return self.transcript.exons[self.number-1] except IndexError : return None
[ "def", "previousExon", "(", "self", ")", ":", "if", "self", ".", "number", "==", "0", ":", "return", "None", "try", ":", "return", "self", ".", "transcript", ".", "exons", "[", "self", ".", "number", "-", "1", "]", "except", "IndexError", ":", "retur...
Returns the previous exon of the transcript, or None if there is none
[ "Returns", "the", "previous", "exon", "of", "the", "transcript", "or", "None", "if", "there", "is", "none" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/Exon.py#L152-L161
train
54,279
tariqdaouda/pyGeno
pyGeno/tools/parsers/FastqTools.py
FastqFile.parseStr
def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
python
def parseStr(self, st) : """Parses a string""" self.data = st.replace('\r', '\n') self.data = self.data.replace('\n\n', '\n') self.data = self.data.split('\n')
[ "def", "parseStr", "(", "self", ",", "st", ")", ":", "self", ".", "data", "=", "st", ".", "replace", "(", "'\\r'", ",", "'\\n'", ")", "self", ".", "data", "=", "self", ".", "data", ".", "replace", "(", "'\\n\\n'", ",", "'\\n'", ")", "self", ".", ...
Parses a string
[ "Parses", "a", "string" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/FastqTools.py#L51-L55
train
54,280
tariqdaouda/pyGeno
pyGeno/tools/parsers/FastqTools.py
FastqFile.get
def get(self, li) : """returns the ith entry""" i = li*4 self.__splitEntry(i) return self.data[i]
python
def get(self, li) : """returns the ith entry""" i = li*4 self.__splitEntry(i) return self.data[i]
[ "def", "get", "(", "self", ",", "li", ")", ":", "i", "=", "li", "*", "4", "self", ".", "__splitEntry", "(", "i", ")", "return", "self", ".", "data", "[", "i", "]" ]
returns the ith entry
[ "returns", "the", "ith", "entry" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/FastqTools.py#L70-L74
train
54,281
tariqdaouda/pyGeno
pyGeno/tools/parsers/FastqTools.py
FastqFile.newEntry
def newEntry(self, ident = "", seq = "", plus = "", qual = "") : """Appends an empty entry at the end of the CSV and returns it""" e = FastqEntry() self.data.append(e) return e
python
def newEntry(self, ident = "", seq = "", plus = "", qual = "") : """Appends an empty entry at the end of the CSV and returns it""" e = FastqEntry() self.data.append(e) return e
[ "def", "newEntry", "(", "self", ",", "ident", "=", "\"\"", ",", "seq", "=", "\"\"", ",", "plus", "=", "\"\"", ",", "qual", "=", "\"\"", ")", ":", "e", "=", "FastqEntry", "(", ")", "self", ".", "data", ".", "append", "(", "e", ")", "return", "e"...
Appends an empty entry at the end of the CSV and returns it
[ "Appends", "an", "empty", "entry", "at", "the", "end", "of", "the", "CSV", "and", "returns", "it" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/parsers/FastqTools.py#L76-L80
train
54,282
tariqdaouda/pyGeno
pyGeno/bootstrap.py
listRemoteDatawraps
def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """Lists all the datawraps availabe from a remote a remote location.""" loc = location + "/datawraps.json" response = urllib2.urlopen(loc) js = json.loads(response.read()) return js
python
def listRemoteDatawraps(location = conf.pyGeno_REMOTE_LOCATION) : """Lists all the datawraps availabe from a remote a remote location.""" loc = location + "/datawraps.json" response = urllib2.urlopen(loc) js = json.loads(response.read()) return js
[ "def", "listRemoteDatawraps", "(", "location", "=", "conf", ".", "pyGeno_REMOTE_LOCATION", ")", ":", "loc", "=", "location", "+", "\"/datawraps.json\"", "response", "=", "urllib2", ".", "urlopen", "(", "loc", ")", "js", "=", "json", ".", "loads", "(", "respo...
Lists all the datawraps availabe from a remote a remote location.
[ "Lists", "all", "the", "datawraps", "availabe", "from", "a", "remote", "a", "remote", "location", "." ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L11-L17
train
54,283
tariqdaouda/pyGeno
pyGeno/bootstrap.py
listDatawraps
def listDatawraps() : """Lists all the datawraps pyGeno comes with""" l = {"Genomes" : [], "SNPs" : []} for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) : if f.find(".tar.gz") > -1 : l["Genomes"].append(f) for f in os.listdir(os.path.join(this_dir, "bootstrap_data/SNPs")) : if f.find(".tar.gz") > -1 : l["SNPs"].append(f) return l
python
def listDatawraps() : """Lists all the datawraps pyGeno comes with""" l = {"Genomes" : [], "SNPs" : []} for f in os.listdir(os.path.join(this_dir, "bootstrap_data/genomes")) : if f.find(".tar.gz") > -1 : l["Genomes"].append(f) for f in os.listdir(os.path.join(this_dir, "bootstrap_data/SNPs")) : if f.find(".tar.gz") > -1 : l["SNPs"].append(f) return l
[ "def", "listDatawraps", "(", ")", ":", "l", "=", "{", "\"Genomes\"", ":", "[", "]", ",", "\"SNPs\"", ":", "[", "]", "}", "for", "f", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"bootstrap_data/genomes\"", ...
Lists all the datawraps pyGeno comes with
[ "Lists", "all", "the", "datawraps", "pyGeno", "comes", "with" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L78-L89
train
54,284
tariqdaouda/pyGeno
pyGeno/bootstrap.py
printDatawraps
def printDatawraps() : """print all available datawraps for bootstraping""" l = listDatawraps() printf("Available datawraps for boostraping\n") for k, v in l.iteritems() : printf(k) printf("~"*len(k) + "|") for vv in v : printf(" "*len(k) + "|" + "~~~:> " + vv) printf('\n')
python
def printDatawraps() : """print all available datawraps for bootstraping""" l = listDatawraps() printf("Available datawraps for boostraping\n") for k, v in l.iteritems() : printf(k) printf("~"*len(k) + "|") for vv in v : printf(" "*len(k) + "|" + "~~~:> " + vv) printf('\n')
[ "def", "printDatawraps", "(", ")", ":", "l", "=", "listDatawraps", "(", ")", "printf", "(", "\"Available datawraps for boostraping\\n\"", ")", "for", "k", ",", "v", "in", "l", ".", "iteritems", "(", ")", ":", "printf", "(", "k", ")", "printf", "(", "\"~\...
print all available datawraps for bootstraping
[ "print", "all", "available", "datawraps", "for", "bootstraping" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L91-L100
train
54,285
tariqdaouda/pyGeno
pyGeno/bootstrap.py
importGenome
def importGenome(name, batchSize = 100) : """Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "genomes/" + name) PG.importGenome(path, batchSize)
python
def importGenome(name, batchSize = 100) : """Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "genomes/" + name) PG.importGenome(path, batchSize)
[ "def", "importGenome", "(", "name", ",", "batchSize", "=", "100", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"bootstrap_data\"", ",", "\"genomes/\"", "+", "name", ")", "PG", ".", "importGenome", "(", "path", ",", "ba...
Import a genome shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.
[ "Import", "a", "genome", "shipped", "with", "pyGeno", ".", "Most", "of", "the", "datawraps", "only", "contain", "URLs", "towards", "data", "provided", "by", "third", "parties", "." ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L102-L105
train
54,286
tariqdaouda/pyGeno
pyGeno/bootstrap.py
importSNPs
def importSNPs(name) : """Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name) PS.importSNPs(path)
python
def importSNPs(name) : """Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name) PS.importSNPs(path)
[ "def", "importSNPs", "(", "name", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"bootstrap_data\"", ",", "\"SNPs/\"", "+", "name", ")", "PS", ".", "importSNPs", "(", "path", ")" ]
Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.
[ "Import", "a", "SNP", "set", "shipped", "with", "pyGeno", ".", "Most", "of", "the", "datawraps", "only", "contain", "URLs", "towards", "data", "provided", "by", "third", "parties", "." ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/bootstrap.py#L107-L110
train
54,287
tariqdaouda/pyGeno
pyGeno/tools/ProgressBar.py
ProgressBar.log
def log(self) : """logs stats about the progression, without printing anything on screen""" self.logs['epochDuration'].append(self.lastEpochDuration) self.logs['avg'].append(self.avg) self.logs['runtime'].append(self.runtime) self.logs['remtime'].append(self.remtime)
python
def log(self) : """logs stats about the progression, without printing anything on screen""" self.logs['epochDuration'].append(self.lastEpochDuration) self.logs['avg'].append(self.avg) self.logs['runtime'].append(self.runtime) self.logs['remtime'].append(self.remtime)
[ "def", "log", "(", "self", ")", ":", "self", ".", "logs", "[", "'epochDuration'", "]", ".", "append", "(", "self", ".", "lastEpochDuration", ")", "self", ".", "logs", "[", "'avg'", "]", ".", "append", "(", "self", ".", "avg", ")", "self", ".", "log...
logs stats about the progression, without printing anything on screen
[ "logs", "stats", "about", "the", "progression", "without", "printing", "anything", "on", "screen" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/ProgressBar.py#L60-L66
train
54,288
tariqdaouda/pyGeno
pyGeno/tools/ProgressBar.py
ProgressBar.saveLogs
def saveLogs(self, filename) : """dumps logs into a nice pickle""" f = open(filename, 'wb') cPickle.dump(self.logs, f) f.close()
python
def saveLogs(self, filename) : """dumps logs into a nice pickle""" f = open(filename, 'wb') cPickle.dump(self.logs, f) f.close()
[ "def", "saveLogs", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'wb'", ")", "cPickle", ".", "dump", "(", "self", ".", "logs", ",", "f", ")", "f", ".", "close", "(", ")" ]
dumps logs into a nice pickle
[ "dumps", "logs", "into", "a", "nice", "pickle" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/ProgressBar.py#L68-L72
train
54,289
tariqdaouda/pyGeno
pyGeno/SNPFiltering.py
DefaultSNPFilter.filter
def filter(self, chromosome, **kwargs) : """The default filter mixes applied all SNPs and ignores Insertions and Deletions.""" def appendAllele(alleles, sources, snp) : pos = snp.start if snp.alt[0] == '-' : pass # print warn % ('DELETION', snpSet, snp.start, snp.chromosomeNumber) elif snp.ref[0] == '-' : pass # print warn % ('INSERTION', snpSet, snp.start, snp.chromosomeNumber) else : sources[snpSet] = snp alleles.append(snp.alt) #if not an indel append the polymorphism refAllele = chromosome.refSequence[pos] alleles.append(refAllele) sources['ref'] = refAllele return alleles, sources warn = 'Warning: the default snp filter ignores indels. IGNORED %s of SNP set: %s at pos: %s of chromosome: %s' sources = {} alleles = [] for snpSet, data in kwargs.iteritems() : if type(data) is list : for snp in data : alleles, sources = appendAllele(alleles, sources, snp) else : allels, sources = appendAllele(alleles, sources, data) #appends the refence allele to the lot #optional we keep a record of the polymorphisms that were used during the process return SequenceSNP(alleles, sources = sources)
python
def filter(self, chromosome, **kwargs) : """The default filter mixes applied all SNPs and ignores Insertions and Deletions.""" def appendAllele(alleles, sources, snp) : pos = snp.start if snp.alt[0] == '-' : pass # print warn % ('DELETION', snpSet, snp.start, snp.chromosomeNumber) elif snp.ref[0] == '-' : pass # print warn % ('INSERTION', snpSet, snp.start, snp.chromosomeNumber) else : sources[snpSet] = snp alleles.append(snp.alt) #if not an indel append the polymorphism refAllele = chromosome.refSequence[pos] alleles.append(refAllele) sources['ref'] = refAllele return alleles, sources warn = 'Warning: the default snp filter ignores indels. IGNORED %s of SNP set: %s at pos: %s of chromosome: %s' sources = {} alleles = [] for snpSet, data in kwargs.iteritems() : if type(data) is list : for snp in data : alleles, sources = appendAllele(alleles, sources, snp) else : allels, sources = appendAllele(alleles, sources, data) #appends the refence allele to the lot #optional we keep a record of the polymorphisms that were used during the process return SequenceSNP(alleles, sources = sources)
[ "def", "filter", "(", "self", ",", "chromosome", ",", "*", "*", "kwargs", ")", ":", "def", "appendAllele", "(", "alleles", ",", "sources", ",", "snp", ")", ":", "pos", "=", "snp", ".", "start", "if", "snp", ".", "alt", "[", "0", "]", "==", "'-'",...
The default filter mixes applied all SNPs and ignores Insertions and Deletions.
[ "The", "default", "filter", "mixes", "applied", "all", "SNPs", "and", "ignores", "Insertions", "and", "Deletions", "." ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/SNPFiltering.py#L105-L137
train
54,290
tariqdaouda/pyGeno
pyGeno/tools/SegmentTree.py
SegmentTree.insert
def insert(self, x1, x2, name = '', referedObject = []) : """Insert the segment in it's right place and returns it. If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the referedObject will be appended to the already existing list""" if x1 > x2 : xx1, xx2 = x2, x1 else : xx1, xx2 = x1, x2 rt = None insertId = None childrenToRemove = [] for i in range(len(self.children)) : if self.children[i].x1 == xx1 and xx2 == self.children[i].x2 : self.children[i].name = self.children[i].name + ' U ' + name self.children[i].referedObject.append(referedObject) return self.children[i] if self.children[i].x1 <= xx1 and xx2 <= self.children[i].x2 : return self.children[i].insert(x1, x2, name, referedObject) elif xx1 <= self.children[i].x1 and self.children[i].x2 <= xx2 : if rt == None : if type(referedObject) is types.ListType : rt = SegmentTree(xx1, xx2, name, referedObject, self, self.level+1) else : rt = SegmentTree(xx1, xx2, name, [referedObject], self, self.level+1) insertId = i rt.__addChild(self.children[i]) self.children[i].father = rt childrenToRemove.append(self.children[i]) elif xx1 <= self.children[i].x1 and xx2 <= self.children[i].x2 : insertId = i break if rt != None : self.__addChild(rt, insertId) for c in childrenToRemove : self.children.remove(c) else : if type(referedObject) is types.ListType : rt = SegmentTree(xx1, xx2, name, referedObject, self, self.level+1) else : rt = SegmentTree(xx1, xx2, name, [referedObject], self, self.level+1) if insertId != None : self.__addChild(rt, insertId) else : self.__addChild(rt) return rt
python
def insert(self, x1, x2, name = '', referedObject = []) : """Insert the segment in it's right place and returns it. If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the referedObject will be appended to the already existing list""" if x1 > x2 : xx1, xx2 = x2, x1 else : xx1, xx2 = x1, x2 rt = None insertId = None childrenToRemove = [] for i in range(len(self.children)) : if self.children[i].x1 == xx1 and xx2 == self.children[i].x2 : self.children[i].name = self.children[i].name + ' U ' + name self.children[i].referedObject.append(referedObject) return self.children[i] if self.children[i].x1 <= xx1 and xx2 <= self.children[i].x2 : return self.children[i].insert(x1, x2, name, referedObject) elif xx1 <= self.children[i].x1 and self.children[i].x2 <= xx2 : if rt == None : if type(referedObject) is types.ListType : rt = SegmentTree(xx1, xx2, name, referedObject, self, self.level+1) else : rt = SegmentTree(xx1, xx2, name, [referedObject], self, self.level+1) insertId = i rt.__addChild(self.children[i]) self.children[i].father = rt childrenToRemove.append(self.children[i]) elif xx1 <= self.children[i].x1 and xx2 <= self.children[i].x2 : insertId = i break if rt != None : self.__addChild(rt, insertId) for c in childrenToRemove : self.children.remove(c) else : if type(referedObject) is types.ListType : rt = SegmentTree(xx1, xx2, name, referedObject, self, self.level+1) else : rt = SegmentTree(xx1, xx2, name, [referedObject], self, self.level+1) if insertId != None : self.__addChild(rt, insertId) else : self.__addChild(rt) return rt
[ "def", "insert", "(", "self", ",", "x1", ",", "x2", ",", "name", "=", "''", ",", "referedObject", "=", "[", "]", ")", ":", "if", "x1", ">", "x2", ":", "xx1", ",", "xx2", "=", "x2", ",", "x1", "else", ":", "xx1", ",", "xx2", "=", "x1", ",", ...
Insert the segment in it's right place and returns it. If there's already a segment S as S.x1 == x1 and S.x2 == x2. S.name will be changed to 'S.name U name' and the referedObject will be appended to the already existing list
[ "Insert", "the", "segment", "in", "it", "s", "right", "place", "and", "returns", "it", ".", "If", "there", "s", "already", "a", "segment", "S", "as", "S", ".", "x1", "==", "x1", "and", "S", ".", "x2", "==", "x2", ".", "S", ".", "name", "will", ...
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/SegmentTree.py#L77-L131
train
54,291
tariqdaouda/pyGeno
pyGeno/tools/SegmentTree.py
SegmentTree.removeGaps
def removeGaps(self) : """Remove all gaps between regions""" for i in range(1, len(self.children)) : if self.children[i].x1 > self.children[i-1].x2: aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i])
python
def removeGaps(self) : """Remove all gaps between regions""" for i in range(1, len(self.children)) : if self.children[i].x1 > self.children[i-1].x2: aux_moveTree(self.children[i-1].x2-self.children[i].x1, self.children[i])
[ "def", "removeGaps", "(", "self", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "children", ")", ")", ":", "if", "self", ".", "children", "[", "i", "]", ".", "x1", ">", "self", ".", "children", "[", "i", "-", "1...
Remove all gaps between regions
[ "Remove", "all", "gaps", "between", "regions" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/SegmentTree.py#L224-L229
train
54,292
tariqdaouda/pyGeno
pyGeno/tools/SegmentTree.py
SegmentTree.getIndexedLength
def getIndexedLength(self) : """Returns the total length of indexed regions""" if self.x1 != None and self.x2 != None: return self.x2 - self.x1 else : if len(self.children) == 0 : return 0 else : l = self.children[0].x2 - self.children[0].x1 for i in range(1, len(self.children)) : l += self.children[i].x2 - self.children[i].x1 - max(0, self.children[i-1].x2 - self.children[i].x1) return l
python
def getIndexedLength(self) : """Returns the total length of indexed regions""" if self.x1 != None and self.x2 != None: return self.x2 - self.x1 else : if len(self.children) == 0 : return 0 else : l = self.children[0].x2 - self.children[0].x1 for i in range(1, len(self.children)) : l += self.children[i].x2 - self.children[i].x1 - max(0, self.children[i-1].x2 - self.children[i].x1) return l
[ "def", "getIndexedLength", "(", "self", ")", ":", "if", "self", ".", "x1", "!=", "None", "and", "self", ".", "x2", "!=", "None", ":", "return", "self", ".", "x2", "-", "self", ".", "x1", "else", ":", "if", "len", "(", "self", ".", "children", ")"...
Returns the total length of indexed regions
[ "Returns", "the", "total", "length", "of", "indexed", "regions" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/SegmentTree.py#L243-L254
train
54,293
tariqdaouda/pyGeno
pyGeno/tools/SegmentTree.py
SegmentTree.flatten
def flatten(self) : """Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together""" if len(self.children) > 1 : children = self.children self.emptyChildren() children[0].emptyChildren() x1 = children[0].x1 x2 = children[0].x2 refObjs = [children[0].referedObject] name = children[0].name for i in range(1, len(children)) : children[i].emptyChildren() if children[i-1] >= children[i] : x2 = children[i].x2 refObjs.append(children[i].referedObject) name += " U " + children[i].name else : if len(refObjs) == 1 : refObjs = refObjs[0] self.insert(x1, x2, name, refObjs) x1 = children[i].x1 x2 = children[i].x2 refObjs = [children[i].referedObject] name = children[i].name if len(refObjs) == 1 : refObjs = refObjs[0] self.insert(x1, x2, name, refObjs)
python
def flatten(self) : """Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together""" if len(self.children) > 1 : children = self.children self.emptyChildren() children[0].emptyChildren() x1 = children[0].x1 x2 = children[0].x2 refObjs = [children[0].referedObject] name = children[0].name for i in range(1, len(children)) : children[i].emptyChildren() if children[i-1] >= children[i] : x2 = children[i].x2 refObjs.append(children[i].referedObject) name += " U " + children[i].name else : if len(refObjs) == 1 : refObjs = refObjs[0] self.insert(x1, x2, name, refObjs) x1 = children[i].x1 x2 = children[i].x2 refObjs = [children[i].referedObject] name = children[i].name if len(refObjs) == 1 : refObjs = refObjs[0] self.insert(x1, x2, name, refObjs)
[ "def", "flatten", "(", "self", ")", ":", "if", "len", "(", "self", ".", "children", ")", ">", "1", ":", "children", "=", "self", ".", "children", "self", ".", "emptyChildren", "(", ")", "children", "[", "0", "]", ".", "emptyChildren", "(", ")", "x1...
Flattens the tree. The tree become a tree of depth 1 where overlapping regions have been merged together
[ "Flattens", "the", "tree", ".", "The", "tree", "become", "a", "tree", "of", "depth", "1", "where", "overlapping", "regions", "have", "been", "merged", "together" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/SegmentTree.py#L269-L300
train
54,294
tariqdaouda/pyGeno
pyGeno/tools/SegmentTree.py
SegmentTree.move
def move(self, newX1) : """Moves tree to a new starting position, updates x1s of children""" if self.x1 != None and self.x2 != None : offset = newX1-self.x1 aux_moveTree(offset, self) elif len(self.children) > 0 : offset = newX1-self.children[0].x1 aux_moveTree(offset, self)
python
def move(self, newX1) : """Moves tree to a new starting position, updates x1s of children""" if self.x1 != None and self.x2 != None : offset = newX1-self.x1 aux_moveTree(offset, self) elif len(self.children) > 0 : offset = newX1-self.children[0].x1 aux_moveTree(offset, self)
[ "def", "move", "(", "self", ",", "newX1", ")", ":", "if", "self", ".", "x1", "!=", "None", "and", "self", ".", "x2", "!=", "None", ":", "offset", "=", "newX1", "-", "self", ".", "x1", "aux_moveTree", "(", "offset", ",", "self", ")", "elif", "len"...
Moves tree to a new starting position, updates x1s of children
[ "Moves", "tree", "to", "a", "new", "starting", "position", "updates", "x1s", "of", "children" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/SegmentTree.py#L302-L309
train
54,295
tariqdaouda/pyGeno
pyGeno/tools/BinarySequence.py
BinarySequence.__getSequenceVariants
def __getSequenceVariants(self, x1, polyStart, polyStop, listSequence) : """polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops""" if polyStart < len(self.polymorphisms) and polyStart < polyStop: sequence = copy.copy(listSequence) ret = [] pk = self.polymorphisms[polyStart] posInSequence = pk[0]-x1 if posInSequence < len(listSequence) : for allele in pk[1] : sequence[posInSequence] = allele ret.extend(self.__getSequenceVariants(x1, polyStart+1, polyStop, sequence)) return ret else : return [''.join(listSequence)]
python
def __getSequenceVariants(self, x1, polyStart, polyStop, listSequence) : """polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops""" if polyStart < len(self.polymorphisms) and polyStart < polyStop: sequence = copy.copy(listSequence) ret = [] pk = self.polymorphisms[polyStart] posInSequence = pk[0]-x1 if posInSequence < len(listSequence) : for allele in pk[1] : sequence[posInSequence] = allele ret.extend(self.__getSequenceVariants(x1, polyStart+1, polyStop, sequence)) return ret else : return [''.join(listSequence)]
[ "def", "__getSequenceVariants", "(", "self", ",", "x1", ",", "polyStart", ",", "polyStop", ",", "listSequence", ")", ":", "if", "polyStart", "<", "len", "(", "self", ".", "polymorphisms", ")", "and", "polyStart", "<", "polyStop", ":", "sequence", "=", "cop...
polyStop, is the polymorphisme at wixh number where the calcul of combinaisons stops
[ "polyStop", "is", "the", "polymorphisme", "at", "wixh", "number", "where", "the", "calcul", "of", "combinaisons", "stops" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/BinarySequence.py#L104-L119
train
54,296
tariqdaouda/pyGeno
pyGeno/tools/BinarySequence.py
BinarySequence.getNbVariants
def getNbVariants(self, x1, x2 = -1) : """returns the nb of variants of sequences between x1 and x2""" if x2 == -1 : xx2 = len(self.defaultSequence) else : xx2 = x2 nbP = 1 for p in self.polymorphisms: if x1 <= p[0] and p[0] <= xx2 : nbP *= len(p[1]) return nbP
python
def getNbVariants(self, x1, x2 = -1) : """returns the nb of variants of sequences between x1 and x2""" if x2 == -1 : xx2 = len(self.defaultSequence) else : xx2 = x2 nbP = 1 for p in self.polymorphisms: if x1 <= p[0] and p[0] <= xx2 : nbP *= len(p[1]) return nbP
[ "def", "getNbVariants", "(", "self", ",", "x1", ",", "x2", "=", "-", "1", ")", ":", "if", "x2", "==", "-", "1", ":", "xx2", "=", "len", "(", "self", ".", "defaultSequence", ")", "else", ":", "xx2", "=", "x2", "nbP", "=", "1", "for", "p", "in"...
returns the nb of variants of sequences between x1 and x2
[ "returns", "the", "nb", "of", "variants", "of", "sequences", "between", "x1", "and", "x2" ]
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/BinarySequence.py#L152-L164
train
54,297
tariqdaouda/pyGeno
pyGeno/tools/BinarySequence.py
BinarySequence._kmp_construct_next
def _kmp_construct_next(self, pattern): """the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern.""" next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP] next[pattern[0]][0] = 1 restart_state = 0 for state in range(1, len(pattern)): for input_token in self.ALPHABETA_KMP: next[input_token][state] = next[input_token][restart_state] next[pattern[state]][state] = state + 1 restart_state = next[pattern[state]][restart_state] return next
python
def _kmp_construct_next(self, pattern): """the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern.""" next = [[0 for state in pattern] for input_token in self.ALPHABETA_KMP] next[pattern[0]][0] = 1 restart_state = 0 for state in range(1, len(pattern)): for input_token in self.ALPHABETA_KMP: next[input_token][state] = next[input_token][restart_state] next[pattern[state]][state] = state + 1 restart_state = next[pattern[state]][restart_state] return next
[ "def", "_kmp_construct_next", "(", "self", ",", "pattern", ")", ":", "next", "=", "[", "[", "0", "for", "state", "in", "pattern", "]", "for", "input_token", "in", "self", ".", "ALPHABETA_KMP", "]", "next", "[", "pattern", "[", "0", "]", "]", "[", "0"...
the helper function for KMP-string-searching is to construct the DFA. pattern should be an integer array. return a 2D array representing the DFA for moving the pattern.
[ "the", "helper", "function", "for", "KMP", "-", "string", "-", "searching", "is", "to", "construct", "the", "DFA", ".", "pattern", "should", "be", "an", "integer", "array", ".", "return", "a", "2D", "array", "representing", "the", "DFA", "for", "moving", ...
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/BinarySequence.py#L197-L207
train
54,298
tariqdaouda/pyGeno
pyGeno/tools/BinarySequence.py
BinarySequence._kmp_search_first
def _kmp_search_first(self, pInput_sequence, pPattern): """use KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the occurence if found; otherwise, -1.""" input_sequence, pattern = pInput_sequence, [len(bin(e)) for e in pPattern] n, m = len(input_sequence), len(pattern) d = p = 0 next = self._kmp_construct_next(pattern) while d < n and p < m: p = next[len(bin(input_sequence[d]))][p] d += 1 if p == m: return d - p else: return -1
python
def _kmp_search_first(self, pInput_sequence, pPattern): """use KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the occurence if found; otherwise, -1.""" input_sequence, pattern = pInput_sequence, [len(bin(e)) for e in pPattern] n, m = len(input_sequence), len(pattern) d = p = 0 next = self._kmp_construct_next(pattern) while d < n and p < m: p = next[len(bin(input_sequence[d]))][p] d += 1 if p == m: return d - p else: return -1
[ "def", "_kmp_search_first", "(", "self", ",", "pInput_sequence", ",", "pPattern", ")", ":", "input_sequence", ",", "pattern", "=", "pInput_sequence", ",", "[", "len", "(", "bin", "(", "e", ")", ")", "for", "e", "in", "pPattern", "]", "n", ",", "m", "="...
use KMP algorithm to search the first occurrence in the input_sequence of the pattern. both arguments are integer arrays. return the position of the occurence if found; otherwise, -1.
[ "use", "KMP", "algorithm", "to", "search", "the", "first", "occurrence", "in", "the", "input_sequence", "of", "the", "pattern", ".", "both", "arguments", "are", "integer", "arrays", ".", "return", "the", "position", "of", "the", "occurence", "if", "found", "...
474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14
https://github.com/tariqdaouda/pyGeno/blob/474b1250bf78ce5c7e7c3bbbfdbad9635d5a7d14/pyGeno/tools/BinarySequence.py#L209-L219
train
54,299