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/_surface_helpers.py
ends_to_curve
def ends_to_curve(start_node, end_node): """Convert a "pair" of intersection nodes to a curve segment. .. note:: This is a helper used only by :func:`basic_interior_combine`, which in turn is only used by :func:`combine_intersections`. .. note:: This function could specialize to the first or second segment attached to ``start_node`` and ``end_node``. We determine first / second based on the classification of ``start_node``, but the callers of this function could provide that information / isolate the base curve and the two parameters for us. .. note:: This only checks the classification of the ``start_node``. Args: start_node (.Intersection): The beginning of a segment. end_node (.Intersection): The end of (the same) segment. Returns: Tuple[int, float, float]: The 3-tuple of: * The edge index along the first surface (if in ``{0, 1, 2}``) or the edge index along the second surface shifted to the right by 3 (if in ``{3, 4, 5}``) * The start parameter along the edge * The end parameter along the edge Raises: ValueError: If the ``start_node`` and ``end_node`` disagree on the first curve when classified as "FIRST". ValueError: If the ``start_node`` and ``end_node`` disagree on the second curve when classified as "SECOND". ValueError: If the ``start_node`` and ``end_node`` disagree on the both curves when classified as "COINCIDENT". ValueError: If the ``start_node`` is not classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.SECOND`, :attr:`~.IntersectionClassification.TANGENT_SECOND` or :attr:`~.IntersectionClassification.COINCIDENT`. """ if is_first(start_node.interior_curve): if end_node.index_first != start_node.index_first: raise ValueError(_WRONG_CURVE) return start_node.index_first, start_node.s, end_node.s elif is_second(start_node.interior_curve): if end_node.index_second != start_node.index_second: raise ValueError(_WRONG_CURVE) return start_node.index_second + 3, start_node.t, end_node.t elif start_node.interior_curve == CLASSIFICATION_T.COINCIDENT: if end_node.index_first == start_node.index_first: return start_node.index_first, start_node.s, end_node.s elif end_node.index_second == start_node.index_second: return start_node.index_second + 3, start_node.t, end_node.t else: raise ValueError(_WRONG_CURVE) else: raise ValueError( 'Segment start must be classified as "FIRST", "TANGENT_FIRST", ' '"SECOND", "TANGENT_SECOND" or "COINCIDENT".' )
python
def ends_to_curve(start_node, end_node): """Convert a "pair" of intersection nodes to a curve segment. .. note:: This is a helper used only by :func:`basic_interior_combine`, which in turn is only used by :func:`combine_intersections`. .. note:: This function could specialize to the first or second segment attached to ``start_node`` and ``end_node``. We determine first / second based on the classification of ``start_node``, but the callers of this function could provide that information / isolate the base curve and the two parameters for us. .. note:: This only checks the classification of the ``start_node``. Args: start_node (.Intersection): The beginning of a segment. end_node (.Intersection): The end of (the same) segment. Returns: Tuple[int, float, float]: The 3-tuple of: * The edge index along the first surface (if in ``{0, 1, 2}``) or the edge index along the second surface shifted to the right by 3 (if in ``{3, 4, 5}``) * The start parameter along the edge * The end parameter along the edge Raises: ValueError: If the ``start_node`` and ``end_node`` disagree on the first curve when classified as "FIRST". ValueError: If the ``start_node`` and ``end_node`` disagree on the second curve when classified as "SECOND". ValueError: If the ``start_node`` and ``end_node`` disagree on the both curves when classified as "COINCIDENT". ValueError: If the ``start_node`` is not classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.SECOND`, :attr:`~.IntersectionClassification.TANGENT_SECOND` or :attr:`~.IntersectionClassification.COINCIDENT`. """ if is_first(start_node.interior_curve): if end_node.index_first != start_node.index_first: raise ValueError(_WRONG_CURVE) return start_node.index_first, start_node.s, end_node.s elif is_second(start_node.interior_curve): if end_node.index_second != start_node.index_second: raise ValueError(_WRONG_CURVE) return start_node.index_second + 3, start_node.t, end_node.t elif start_node.interior_curve == CLASSIFICATION_T.COINCIDENT: if end_node.index_first == start_node.index_first: return start_node.index_first, start_node.s, end_node.s elif end_node.index_second == start_node.index_second: return start_node.index_second + 3, start_node.t, end_node.t else: raise ValueError(_WRONG_CURVE) else: raise ValueError( 'Segment start must be classified as "FIRST", "TANGENT_FIRST", ' '"SECOND", "TANGENT_SECOND" or "COINCIDENT".' )
[ "def", "ends_to_curve", "(", "start_node", ",", "end_node", ")", ":", "if", "is_first", "(", "start_node", ".", "interior_curve", ")", ":", "if", "end_node", ".", "index_first", "!=", "start_node", ".", "index_first", ":", "raise", "ValueError", "(", "_WRONG_C...
Convert a "pair" of intersection nodes to a curve segment. .. note:: This is a helper used only by :func:`basic_interior_combine`, which in turn is only used by :func:`combine_intersections`. .. note:: This function could specialize to the first or second segment attached to ``start_node`` and ``end_node``. We determine first / second based on the classification of ``start_node``, but the callers of this function could provide that information / isolate the base curve and the two parameters for us. .. note:: This only checks the classification of the ``start_node``. Args: start_node (.Intersection): The beginning of a segment. end_node (.Intersection): The end of (the same) segment. Returns: Tuple[int, float, float]: The 3-tuple of: * The edge index along the first surface (if in ``{0, 1, 2}``) or the edge index along the second surface shifted to the right by 3 (if in ``{3, 4, 5}``) * The start parameter along the edge * The end parameter along the edge Raises: ValueError: If the ``start_node`` and ``end_node`` disagree on the first curve when classified as "FIRST". ValueError: If the ``start_node`` and ``end_node`` disagree on the second curve when classified as "SECOND". ValueError: If the ``start_node`` and ``end_node`` disagree on the both curves when classified as "COINCIDENT". ValueError: If the ``start_node`` is not classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.SECOND`, :attr:`~.IntersectionClassification.TANGENT_SECOND` or :attr:`~.IntersectionClassification.COINCIDENT`.
[ "Convert", "a", "pair", "of", "intersection", "nodes", "to", "a", "curve", "segment", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2475-L2548
train
54,100
dhermes/bezier
src/bezier/_surface_helpers.py
no_intersections
def no_intersections(nodes1, degree1, nodes2, degree2): r"""Determine if one surface is in the other. Helper for :func:`combine_intersections` that handles the case of no points of intersection. In this case, either the surfaces are disjoint or one is fully contained in the other. To check containment, it's enough to check if one of the corners is contained in the other surface. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. """ # NOTE: This is a circular import. from bezier import _surface_intersection located = _surface_intersection.locate_point( nodes2, degree2, nodes1[0, 0], nodes1[1, 0] ) if located is not None: return None, True located = _surface_intersection.locate_point( nodes1, degree1, nodes2[0, 0], nodes2[1, 0] ) if located is not None: return None, False return [], None
python
def no_intersections(nodes1, degree1, nodes2, degree2): r"""Determine if one surface is in the other. Helper for :func:`combine_intersections` that handles the case of no points of intersection. In this case, either the surfaces are disjoint or one is fully contained in the other. To check containment, it's enough to check if one of the corners is contained in the other surface. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. """ # NOTE: This is a circular import. from bezier import _surface_intersection located = _surface_intersection.locate_point( nodes2, degree2, nodes1[0, 0], nodes1[1, 0] ) if located is not None: return None, True located = _surface_intersection.locate_point( nodes1, degree1, nodes2[0, 0], nodes2[1, 0] ) if located is not None: return None, False return [], None
[ "def", "no_intersections", "(", "nodes1", ",", "degree1", ",", "nodes2", ",", "degree2", ")", ":", "# NOTE: This is a circular import.", "from", "bezier", "import", "_surface_intersection", "located", "=", "_surface_intersection", ".", "locate_point", "(", "nodes2", "...
r"""Determine if one surface is in the other. Helper for :func:`combine_intersections` that handles the case of no points of intersection. In this case, either the surfaces are disjoint or one is fully contained in the other. To check containment, it's enough to check if one of the corners is contained in the other surface. Args: nodes1 (numpy.ndarray): The nodes defining the first surface in the intersection (assumed in :math:\mathbf{R}^2`). degree1 (int): The degree of the surface given by ``nodes1``. nodes2 (numpy.ndarray): The nodes defining the second surface in the intersection (assumed in :math:\mathbf{R}^2`). degree2 (int): The degree of the surface given by ``nodes2``. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other.
[ "r", "Determine", "if", "one", "surface", "is", "in", "the", "other", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2551-L2591
train
54,101
dhermes/bezier
src/bezier/_surface_helpers.py
tangent_only_intersections
def tangent_only_intersections(all_types): """Determine intersection in the case of only-tangent intersections. If the only intersections are tangencies, then either the surfaces are tangent but don't meet ("kissing" edges) or one surface is internally tangent to the other. Thus we expect every intersection to be classified as :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. What's more, we expect all intersections to be classified the same for a given pairing. Args: all_types (Set[.IntersectionClassification]): The set of all intersection classifications encountered among the intersections for the given surface-surface pair. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: ValueError: If there are intersections of more than one type among :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. ValueError: If there is a unique classification, but it isn't one of the tangent types. """ if len(all_types) != 1: raise ValueError("Unexpected value, types should all match", all_types) point_type = all_types.pop() if point_type == CLASSIFICATION_T.OPPOSED: return [], None elif point_type == CLASSIFICATION_T.IGNORED_CORNER: return [], None elif point_type == CLASSIFICATION_T.TANGENT_FIRST: return None, True elif point_type == CLASSIFICATION_T.TANGENT_SECOND: return None, False elif point_type == CLASSIFICATION_T.COINCIDENT_UNUSED: return [], None else: raise ValueError("Point type not for tangency", point_type)
python
def tangent_only_intersections(all_types): """Determine intersection in the case of only-tangent intersections. If the only intersections are tangencies, then either the surfaces are tangent but don't meet ("kissing" edges) or one surface is internally tangent to the other. Thus we expect every intersection to be classified as :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. What's more, we expect all intersections to be classified the same for a given pairing. Args: all_types (Set[.IntersectionClassification]): The set of all intersection classifications encountered among the intersections for the given surface-surface pair. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: ValueError: If there are intersections of more than one type among :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. ValueError: If there is a unique classification, but it isn't one of the tangent types. """ if len(all_types) != 1: raise ValueError("Unexpected value, types should all match", all_types) point_type = all_types.pop() if point_type == CLASSIFICATION_T.OPPOSED: return [], None elif point_type == CLASSIFICATION_T.IGNORED_CORNER: return [], None elif point_type == CLASSIFICATION_T.TANGENT_FIRST: return None, True elif point_type == CLASSIFICATION_T.TANGENT_SECOND: return None, False elif point_type == CLASSIFICATION_T.COINCIDENT_UNUSED: return [], None else: raise ValueError("Point type not for tangency", point_type)
[ "def", "tangent_only_intersections", "(", "all_types", ")", ":", "if", "len", "(", "all_types", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Unexpected value, types should all match\"", ",", "all_types", ")", "point_type", "=", "all_types", ".", "pop", "(",...
Determine intersection in the case of only-tangent intersections. If the only intersections are tangencies, then either the surfaces are tangent but don't meet ("kissing" edges) or one surface is internally tangent to the other. Thus we expect every intersection to be classified as :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. What's more, we expect all intersections to be classified the same for a given pairing. Args: all_types (Set[.IntersectionClassification]): The set of all intersection classifications encountered among the intersections for the given surface-surface pair. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * Edges info list; will be empty or :data:`None` * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: ValueError: If there are intersections of more than one type among :attr:`~.IntersectionClassification.TANGENT_FIRST`, :attr:`~.IntersectionClassification.TANGENT_SECOND`, :attr:`~.IntersectionClassification.OPPOSED`, :attr:`~.IntersectionClassification.IGNORED_CORNER` or :attr:`~.IntersectionClassification.COINCIDENT_UNUSED`. ValueError: If there is a unique classification, but it isn't one of the tangent types.
[ "Determine", "intersection", "in", "the", "case", "of", "only", "-", "tangent", "intersections", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2594-L2653
train
54,102
dhermes/bezier
src/bezier/_surface_helpers.py
basic_interior_combine
def basic_interior_combine(intersections, max_edges=10): """Combine intersections that don't involve tangencies. .. note:: This is a helper used only by :func:`combine_intersections`. .. note:: This helper assumes ``intersections`` isn't empty, but doesn't enforce it. Args: intersections (List[.Intersection]): Intersections from each of the 9 edge-edge pairs from a surface-surface pairing. max_edges (Optional[int]): The maximum number of allowed / expected edges per intersection. This is to avoid infinite loops. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: RuntimeError: If the number of edges in a curved polygon exceeds ``max_edges``. This is interpreted as a sign that the algorithm failed. """ unused = intersections[:] result = [] while unused: start = unused.pop() curr_node = start next_node = get_next(curr_node, intersections, unused) edge_ends = [(curr_node, next_node)] while next_node is not start: curr_node = to_front(next_node, intersections, unused) # NOTE: We also check to break when moving a corner node # to the front. This is because ``intersections`` # de-duplicates corners by selecting the one # (of 2 or 4 choices) at the front of segment(s). if curr_node is start: break next_node = get_next(curr_node, intersections, unused) edge_ends.append((curr_node, next_node)) if len(edge_ends) > max_edges: raise RuntimeError( "Unexpected number of edges", len(edge_ends) ) edge_info = tuple( ends_to_curve(start_node, end_node) for start_node, end_node in edge_ends ) result.append(edge_info) if len(result) == 1: if result[0] in FIRST_SURFACE_INFO: return None, True elif result[0] in SECOND_SURFACE_INFO: return None, False return result, None
python
def basic_interior_combine(intersections, max_edges=10): """Combine intersections that don't involve tangencies. .. note:: This is a helper used only by :func:`combine_intersections`. .. note:: This helper assumes ``intersections`` isn't empty, but doesn't enforce it. Args: intersections (List[.Intersection]): Intersections from each of the 9 edge-edge pairs from a surface-surface pairing. max_edges (Optional[int]): The maximum number of allowed / expected edges per intersection. This is to avoid infinite loops. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: RuntimeError: If the number of edges in a curved polygon exceeds ``max_edges``. This is interpreted as a sign that the algorithm failed. """ unused = intersections[:] result = [] while unused: start = unused.pop() curr_node = start next_node = get_next(curr_node, intersections, unused) edge_ends = [(curr_node, next_node)] while next_node is not start: curr_node = to_front(next_node, intersections, unused) # NOTE: We also check to break when moving a corner node # to the front. This is because ``intersections`` # de-duplicates corners by selecting the one # (of 2 or 4 choices) at the front of segment(s). if curr_node is start: break next_node = get_next(curr_node, intersections, unused) edge_ends.append((curr_node, next_node)) if len(edge_ends) > max_edges: raise RuntimeError( "Unexpected number of edges", len(edge_ends) ) edge_info = tuple( ends_to_curve(start_node, end_node) for start_node, end_node in edge_ends ) result.append(edge_info) if len(result) == 1: if result[0] in FIRST_SURFACE_INFO: return None, True elif result[0] in SECOND_SURFACE_INFO: return None, False return result, None
[ "def", "basic_interior_combine", "(", "intersections", ",", "max_edges", "=", "10", ")", ":", "unused", "=", "intersections", "[", ":", "]", "result", "=", "[", "]", "while", "unused", ":", "start", "=", "unused", ".", "pop", "(", ")", "curr_node", "=", ...
Combine intersections that don't involve tangencies. .. note:: This is a helper used only by :func:`combine_intersections`. .. note:: This helper assumes ``intersections`` isn't empty, but doesn't enforce it. Args: intersections (List[.Intersection]): Intersections from each of the 9 edge-edge pairs from a surface-surface pairing. max_edges (Optional[int]): The maximum number of allowed / expected edges per intersection. This is to avoid infinite loops. Returns: Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of * List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). * "Contained" boolean. If not :data:`None`, indicates that one of the surfaces is contained in the other. Raises: RuntimeError: If the number of edges in a curved polygon exceeds ``max_edges``. This is interpreted as a sign that the algorithm failed.
[ "Combine", "intersections", "that", "don", "t", "involve", "tangencies", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2656-L2723
train
54,103
dhermes/bezier
src/bezier/_surface_helpers.py
_evaluate_barycentric
def _evaluate_barycentric(nodes, degree, lambda1, lambda2, lambda3): r"""Compute a point on a surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)` for a B |eacute| zier surface / triangle defined by ``nodes``. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Returns: numpy.ndarray: The evaluated point as a ``D x 1`` array (where ``D`` is the ambient dimension where ``nodes`` reside). """ dimension, num_nodes = nodes.shape binom_val = 1.0 result = np.zeros((dimension, 1), order="F") index = num_nodes - 1 result[:, 0] += nodes[:, index] # curve evaluate_multi_barycentric() takes arrays. lambda1 = np.asfortranarray([lambda1]) lambda2 = np.asfortranarray([lambda2]) for k in six.moves.xrange(degree - 1, -1, -1): # We want to go from (d C (k + 1)) to (d C k). binom_val = (binom_val * (k + 1)) / (degree - k) index -= 1 # Step to last element in column. # k = d - 1, d - 2, ... # d - k = 1, 2, ... # We know column k has (d - k + 1) elements. new_index = index - degree + k # First element in column. col_nodes = nodes[:, new_index : index + 1] # noqa: E203 col_nodes = np.asfortranarray(col_nodes) col_result = _curve_helpers.evaluate_multi_barycentric( col_nodes, lambda1, lambda2 ) result *= lambda3 result += binom_val * col_result # Update index for next iteration. index = new_index return result
python
def _evaluate_barycentric(nodes, degree, lambda1, lambda2, lambda3): r"""Compute a point on a surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)` for a B |eacute| zier surface / triangle defined by ``nodes``. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Returns: numpy.ndarray: The evaluated point as a ``D x 1`` array (where ``D`` is the ambient dimension where ``nodes`` reside). """ dimension, num_nodes = nodes.shape binom_val = 1.0 result = np.zeros((dimension, 1), order="F") index = num_nodes - 1 result[:, 0] += nodes[:, index] # curve evaluate_multi_barycentric() takes arrays. lambda1 = np.asfortranarray([lambda1]) lambda2 = np.asfortranarray([lambda2]) for k in six.moves.xrange(degree - 1, -1, -1): # We want to go from (d C (k + 1)) to (d C k). binom_val = (binom_val * (k + 1)) / (degree - k) index -= 1 # Step to last element in column. # k = d - 1, d - 2, ... # d - k = 1, 2, ... # We know column k has (d - k + 1) elements. new_index = index - degree + k # First element in column. col_nodes = nodes[:, new_index : index + 1] # noqa: E203 col_nodes = np.asfortranarray(col_nodes) col_result = _curve_helpers.evaluate_multi_barycentric( col_nodes, lambda1, lambda2 ) result *= lambda3 result += binom_val * col_result # Update index for next iteration. index = new_index return result
[ "def", "_evaluate_barycentric", "(", "nodes", ",", "degree", ",", "lambda1", ",", "lambda2", ",", "lambda3", ")", ":", "dimension", ",", "num_nodes", "=", "nodes", ".", "shape", "binom_val", "=", "1.0", "result", "=", "np", ".", "zeros", "(", "(", "dimen...
r"""Compute a point on a surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)` for a B |eacute| zier surface / triangle defined by ``nodes``. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Returns: numpy.ndarray: The evaluated point as a ``D x 1`` array (where ``D`` is the ambient dimension where ``nodes`` reside).
[ "r", "Compute", "a", "point", "on", "a", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2776-L2823
train
54,104
dhermes/bezier
src/bezier/_surface_helpers.py
_compute_edge_nodes
def _compute_edge_nodes(nodes, degree): """Compute the nodes of each edges of a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. Returns: Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]: The nodes in the edges of the surface. """ dimension, _ = np.shape(nodes) nodes1 = np.empty((dimension, degree + 1), order="F") nodes2 = np.empty((dimension, degree + 1), order="F") nodes3 = np.empty((dimension, degree + 1), order="F") curr2 = degree curr3 = -1 for i in six.moves.xrange(degree + 1): nodes1[:, i] = nodes[:, i] nodes2[:, i] = nodes[:, curr2] nodes3[:, i] = nodes[:, curr3] # Update the indices. curr2 += degree - i curr3 -= i + 2 return nodes1, nodes2, nodes3
python
def _compute_edge_nodes(nodes, degree): """Compute the nodes of each edges of a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. Returns: Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]: The nodes in the edges of the surface. """ dimension, _ = np.shape(nodes) nodes1 = np.empty((dimension, degree + 1), order="F") nodes2 = np.empty((dimension, degree + 1), order="F") nodes3 = np.empty((dimension, degree + 1), order="F") curr2 = degree curr3 = -1 for i in six.moves.xrange(degree + 1): nodes1[:, i] = nodes[:, i] nodes2[:, i] = nodes[:, curr2] nodes3[:, i] = nodes[:, curr3] # Update the indices. curr2 += degree - i curr3 -= i + 2 return nodes1, nodes2, nodes3
[ "def", "_compute_edge_nodes", "(", "nodes", ",", "degree", ")", ":", "dimension", ",", "_", "=", "np", ".", "shape", "(", "nodes", ")", "nodes1", "=", "np", ".", "empty", "(", "(", "dimension", ",", "degree", "+", "1", ")", ",", "order", "=", "\"F\...
Compute the nodes of each edges of a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): Control point nodes that define the surface. degree (int): The degree of the surface define by ``nodes``. Returns: Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]: The nodes in the edges of the surface.
[ "Compute", "the", "nodes", "of", "each", "edges", "of", "a", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2884-L2913
train
54,105
dhermes/bezier
src/bezier/_surface_helpers.py
shoelace_for_area
def shoelace_for_area(nodes): r"""Compute an auxiliary "shoelace" sum used to compute area. .. note:: This is a helper for :func:`_compute_area`. Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace term illuminates the name of this helper. On a degree one curve, this function will return .. math:: \frac{1}{2}\left[0, 1\right]. on a degree two curve it will return .. math:: \frac{1}{6}\left(2 \left[0, 1\right] + 2 \left[1, 2\right] + \left[0, 2\right]\right) and so on. For a given :math:`\left[i, j\right]`, the coefficient comes from integrating :math:`b_{i, d}, b_{j, d}` on :math:`\left[0, 1\right]` (where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials). Returns: float: The computed sum of shoelace terms. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4. """ _, num_nodes = nodes.shape if num_nodes == 2: shoelace = SHOELACE_LINEAR scale_factor = 2.0 elif num_nodes == 3: shoelace = SHOELACE_QUADRATIC scale_factor = 6.0 elif num_nodes == 4: shoelace = SHOELACE_CUBIC scale_factor = 20.0 elif num_nodes == 5: shoelace = SHOELACE_QUARTIC scale_factor = 70.0 else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3, 4)) result = 0.0 for multiplier, index1, index2 in shoelace: result += multiplier * ( nodes[0, index1] * nodes[1, index2] - nodes[1, index1] * nodes[0, index2] ) return result / scale_factor
python
def shoelace_for_area(nodes): r"""Compute an auxiliary "shoelace" sum used to compute area. .. note:: This is a helper for :func:`_compute_area`. Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace term illuminates the name of this helper. On a degree one curve, this function will return .. math:: \frac{1}{2}\left[0, 1\right]. on a degree two curve it will return .. math:: \frac{1}{6}\left(2 \left[0, 1\right] + 2 \left[1, 2\right] + \left[0, 2\right]\right) and so on. For a given :math:`\left[i, j\right]`, the coefficient comes from integrating :math:`b_{i, d}, b_{j, d}` on :math:`\left[0, 1\right]` (where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials). Returns: float: The computed sum of shoelace terms. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4. """ _, num_nodes = nodes.shape if num_nodes == 2: shoelace = SHOELACE_LINEAR scale_factor = 2.0 elif num_nodes == 3: shoelace = SHOELACE_QUADRATIC scale_factor = 6.0 elif num_nodes == 4: shoelace = SHOELACE_CUBIC scale_factor = 20.0 elif num_nodes == 5: shoelace = SHOELACE_QUARTIC scale_factor = 70.0 else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3, 4)) result = 0.0 for multiplier, index1, index2 in shoelace: result += multiplier * ( nodes[0, index1] * nodes[1, index2] - nodes[1, index1] * nodes[0, index2] ) return result / scale_factor
[ "def", "shoelace_for_area", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "if", "num_nodes", "==", "2", ":", "shoelace", "=", "SHOELACE_LINEAR", "scale_factor", "=", "2.0", "elif", "num_nodes", "==", "3", ":", "shoelace", "=", ...
r"""Compute an auxiliary "shoelace" sum used to compute area. .. note:: This is a helper for :func:`_compute_area`. Defining :math:`\left[i, j\right] = x_i y_j - y_i x_j` as a shoelace term illuminates the name of this helper. On a degree one curve, this function will return .. math:: \frac{1}{2}\left[0, 1\right]. on a degree two curve it will return .. math:: \frac{1}{6}\left(2 \left[0, 1\right] + 2 \left[1, 2\right] + \left[0, 2\right]\right) and so on. For a given :math:`\left[i, j\right]`, the coefficient comes from integrating :math:`b_{i, d}, b_{j, d}` on :math:`\left[0, 1\right]` (where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials). Returns: float: The computed sum of shoelace terms. Raises: .UnsupportedDegree: If the degree is not 1, 2, 3 or 4.
[ "r", "Compute", "an", "auxiliary", "shoelace", "sum", "used", "to", "compute", "area", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_helpers.py#L2916-L2973
train
54,106
dhermes/bezier
docs/make_images.py
save_image
def save_image(figure, filename): """Save an image to the docs images directory. Args: filename (str): The name of the file (not containing directory info). """ path = os.path.join(IMAGES_DIR, filename) figure.savefig(path, bbox_inches="tight") plt.close(figure)
python
def save_image(figure, filename): """Save an image to the docs images directory. Args: filename (str): The name of the file (not containing directory info). """ path = os.path.join(IMAGES_DIR, filename) figure.savefig(path, bbox_inches="tight") plt.close(figure)
[ "def", "save_image", "(", "figure", ",", "filename", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "IMAGES_DIR", ",", "filename", ")", "figure", ".", "savefig", "(", "path", ",", "bbox_inches", "=", "\"tight\"", ")", "plt", ".", "close", ...
Save an image to the docs images directory. Args: filename (str): The name of the file (not containing directory info).
[ "Save", "an", "image", "to", "the", "docs", "images", "directory", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L48-L57
train
54,107
dhermes/bezier
docs/make_images.py
stack1d
def stack1d(*points): """Fill out the columns of matrix with a series of points. This is because ``np.hstack()`` will just make another 1D vector out of them and ``np.vstack()`` will put them in the rows. Args: points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e. arrays with shape ``(2,)``. Returns: numpy.ndarray: The array with each point in ``points`` as its columns. """ result = np.empty((2, len(points)), order="F") for index, point in enumerate(points): result[:, index] = point return result
python
def stack1d(*points): """Fill out the columns of matrix with a series of points. This is because ``np.hstack()`` will just make another 1D vector out of them and ``np.vstack()`` will put them in the rows. Args: points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e. arrays with shape ``(2,)``. Returns: numpy.ndarray: The array with each point in ``points`` as its columns. """ result = np.empty((2, len(points)), order="F") for index, point in enumerate(points): result[:, index] = point return result
[ "def", "stack1d", "(", "*", "points", ")", ":", "result", "=", "np", ".", "empty", "(", "(", "2", ",", "len", "(", "points", ")", ")", ",", "order", "=", "\"F\"", ")", "for", "index", ",", "point", "in", "enumerate", "(", "points", ")", ":", "r...
Fill out the columns of matrix with a series of points. This is because ``np.hstack()`` will just make another 1D vector out of them and ``np.vstack()`` will put them in the rows. Args: points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e. arrays with shape ``(2,)``. Returns: numpy.ndarray: The array with each point in ``points`` as its columns.
[ "Fill", "out", "the", "columns", "of", "matrix", "with", "a", "series", "of", "points", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L60-L77
train
54,108
dhermes/bezier
docs/make_images.py
_edges_classify_intersection9
def _edges_classify_intersection9(): """The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`. """ edges1 = ( bezier.Curve.from_nodes( np.asfortranarray([[32.0, 30.0], [20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 25.0, 20.0], [25.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 25.0, 30.0], [20.0, 20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 32.0], [15.0, 20.0]]) ), ) edges2 = ( bezier.Curve.from_nodes( np.asfortranarray([[8.0, 10.0], [20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 15.0, 20.0], [15.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 15.0, 10.0], [20.0, 20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 8.0], [25.0, 20.0]]) ), ) return edges1, edges2
python
def _edges_classify_intersection9(): """The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`. """ edges1 = ( bezier.Curve.from_nodes( np.asfortranarray([[32.0, 30.0], [20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 25.0, 20.0], [25.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 25.0, 30.0], [20.0, 20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[30.0, 32.0], [15.0, 20.0]]) ), ) edges2 = ( bezier.Curve.from_nodes( np.asfortranarray([[8.0, 10.0], [20.0, 15.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 15.0, 20.0], [15.0, 20.0, 20.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[20.0, 15.0, 10.0], [20.0, 20.0, 25.0]]) ), bezier.Curve.from_nodes( np.asfortranarray([[10.0, 8.0], [25.0, 20.0]]) ), ) return edges1, edges2
[ "def", "_edges_classify_intersection9", "(", ")", ":", "edges1", "=", "(", "bezier", ".", "Curve", ".", "from_nodes", "(", "np", ".", "asfortranarray", "(", "[", "[", "32.0", ",", "30.0", "]", ",", "[", "20.0", ",", "25.0", "]", "]", ")", ")", ",", ...
The edges for the curved polygon intersection used below. Helper for :func:`classify_intersection9`.
[ "The", "edges", "for", "the", "curved", "polygon", "intersection", "used", "below", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/make_images.py#L1141-L1174
train
54,109
dhermes/bezier
src/bezier/_surface_intersection.py
update_locate_candidates
def update_locate_candidates(candidate, next_candidates, x_val, y_val, degree): """Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface. """ centroid_x, centroid_y, width, candidate_nodes = candidate point = np.asfortranarray([x_val, y_val]) if not _helpers.contains_nd(candidate_nodes, point): return nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( candidate_nodes, degree ) half_width = 0.5 * width next_candidates.extend( ( ( centroid_x - half_width, centroid_y - half_width, half_width, nodes_a, ), (centroid_x, centroid_y, -half_width, nodes_b), (centroid_x + width, centroid_y - half_width, half_width, nodes_c), (centroid_x - half_width, centroid_y + width, half_width, nodes_d), ) )
python
def update_locate_candidates(candidate, next_candidates, x_val, y_val, degree): """Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface. """ centroid_x, centroid_y, width, candidate_nodes = candidate point = np.asfortranarray([x_val, y_val]) if not _helpers.contains_nd(candidate_nodes, point): return nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( candidate_nodes, degree ) half_width = 0.5 * width next_candidates.extend( ( ( centroid_x - half_width, centroid_y - half_width, half_width, nodes_a, ), (centroid_x, centroid_y, -half_width, nodes_b), (centroid_x + width, centroid_y - half_width, half_width, nodes_c), (centroid_x - half_width, centroid_y + width, half_width, nodes_d), ) )
[ "def", "update_locate_candidates", "(", "candidate", ",", "next_candidates", ",", "x_val", ",", "y_val", ",", "degree", ")", ":", "centroid_x", ",", "centroid_y", ",", "width", ",", "candidate_nodes", "=", "candidate", "point", "=", "np", ".", "asfortranarray", ...
Update list of candidate surfaces during geometric search for a point. .. note:: This is used **only** as a helper for :func:`locate_point`. Checks if the point ``(x_val, y_val)`` is contained in the ``candidate`` surface. If not, this function does nothing. If the point is contaned, the four subdivided surfaces from ``candidate`` are added to ``next_candidates``. Args: candidate (Tuple[float, float, float, numpy.ndarray]): A 4-tuple describing a surface and its centroid / width. Contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of parameter space for the surface * Control points for the surface next_candidates (list): List of "candidate" sub-surfaces that may contain the point being located. x_val (float): The ``x``-coordinate being located. y_val (float): The ``y``-coordinate being located. degree (int): The degree of the surface.
[ "Update", "list", "of", "candidate", "surfaces", "during", "geometric", "search", "for", "a", "point", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L231-L278
train
54,110
dhermes/bezier
src/bezier/_surface_intersection.py
mean_centroid
def mean_centroid(candidates): """Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids. """ sum_x = 0.0 sum_y = 0.0 for centroid_x, centroid_y, _, _ in candidates: sum_x += centroid_x sum_y += centroid_y denom = 3.0 * len(candidates) return sum_x / denom, sum_y / denom
python
def mean_centroid(candidates): """Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids. """ sum_x = 0.0 sum_y = 0.0 for centroid_x, centroid_y, _, _ in candidates: sum_x += centroid_x sum_y += centroid_y denom = 3.0 * len(candidates) return sum_x / denom, sum_y / denom
[ "def", "mean_centroid", "(", "candidates", ")", ":", "sum_x", "=", "0.0", "sum_y", "=", "0.0", "for", "centroid_x", ",", "centroid_y", ",", "_", ",", "_", "in", "candidates", ":", "sum_x", "+=", "centroid_x", "sum_y", "+=", "centroid_y", "denom", "=", "3...
Take the mean of all centroids in set of reference triangles. .. note:: This is used **only** as a helper for :func:`locate_point`. Args: candidates (List[Tuple[float, float, float, numpy.ndarray]): List of 4-tuples, each of which has been produced by :func:`locate_point`. Each 4-tuple contains * Three times centroid ``x``-value * Three times centroid ``y``-value * "Width" of a parameter space for a surface * Control points for a surface We only use the first two values, which are triple the desired value so that we can put off division by three until summing in our average. We don't use the other two values, they are just an artifact of the way ``candidates`` is constructed by the caller. Returns: Tuple[float, float]: The mean of all centroids.
[ "Take", "the", "mean", "of", "all", "centroids", "in", "set", "of", "reference", "triangles", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L281-L312
train
54,111
dhermes/bezier
src/bezier/_surface_intersection.py
_locate_point
def _locate_point(nodes, degree, x_val, y_val): r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``. """ # We track the centroid rather than base_x/base_y/width (by storing triple # the centroid -- to avoid division by three until needed). We also need # to track the width (or rather, just the sign of the width). candidates = [(1.0, 1.0, 1.0, nodes)] for _ in six.moves.xrange(MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for candidate in candidates: update_locate_candidates( candidate, next_candidates, x_val, y_val, degree ) candidates = next_candidates if not candidates: return None # We take the average of all centroids from the candidates # that may contain the point. s_approx, t_approx = mean_centroid(candidates) s, t = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx) actual = _surface_helpers.evaluate_barycentric( nodes, degree, 1.0 - s - t, s, t ) expected = np.asfortranarray([x_val, y_val]) if not _helpers.vector_close( actual.ravel(order="F"), expected, eps=LOCATE_EPS ): s, t = newton_refine(nodes, degree, x_val, y_val, s, t) return s, t
python
def _locate_point(nodes, degree, x_val, y_val): r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``. """ # We track the centroid rather than base_x/base_y/width (by storing triple # the centroid -- to avoid division by three until needed). We also need # to track the width (or rather, just the sign of the width). candidates = [(1.0, 1.0, 1.0, nodes)] for _ in six.moves.xrange(MAX_LOCATE_SUBDIVISIONS + 1): next_candidates = [] for candidate in candidates: update_locate_candidates( candidate, next_candidates, x_val, y_val, degree ) candidates = next_candidates if not candidates: return None # We take the average of all centroids from the candidates # that may contain the point. s_approx, t_approx = mean_centroid(candidates) s, t = newton_refine(nodes, degree, x_val, y_val, s_approx, t_approx) actual = _surface_helpers.evaluate_barycentric( nodes, degree, 1.0 - s - t, s, t ) expected = np.asfortranarray([x_val, y_val]) if not _helpers.vector_close( actual.ravel(order="F"), expected, eps=LOCATE_EPS ): s, t = newton_refine(nodes, degree, x_val, y_val, s, t) return s, t
[ "def", "_locate_point", "(", "nodes", ",", "degree", ",", "x_val", ",", "y_val", ")", ":", "# We track the centroid rather than base_x/base_y/width (by storing triple", "# the centroid -- to avoid division by three until needed). We also need", "# to track the width (or rather, just the ...
r"""Locate a point on a surface. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Does so by recursively subdividing the surface and rejecting sub-surfaces with bounding boxes that don't contain the point. After the sub-surfaces are sufficiently small, uses Newton's method to narrow in on the pre-image of the point. Args: nodes (numpy.ndarray): Control points for B |eacute| zier surface (assumed to be two-dimensional). degree (int): The degree of the surface. x_val (float): The :math:`x`-coordinate of a point on the surface. y_val (float): The :math:`y`-coordinate of a point on the surface. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``x_val`` and ``y_val`` or :data:`None` if the point is not on the ``surface``.
[ "r", "Locate", "a", "point", "on", "a", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L315-L368
train
54,112
dhermes/bezier
src/bezier/_surface_intersection.py
same_intersection
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40): """Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision. """ if intersection1.index_first != intersection2.index_first: return False if intersection1.index_second != intersection2.index_second: return False return np.allclose( [intersection1.s, intersection1.t], [intersection2.s, intersection2.t], atol=0.0, rtol=wiggle, )
python
def same_intersection(intersection1, intersection2, wiggle=0.5 ** 40): """Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision. """ if intersection1.index_first != intersection2.index_first: return False if intersection1.index_second != intersection2.index_second: return False return np.allclose( [intersection1.s, intersection1.t], [intersection2.s, intersection2.t], atol=0.0, rtol=wiggle, )
[ "def", "same_intersection", "(", "intersection1", ",", "intersection2", ",", "wiggle", "=", "0.5", "**", "40", ")", ":", "if", "intersection1", ".", "index_first", "!=", "intersection2", ".", "index_first", ":", "return", "False", "if", "intersection1", ".", "...
Check if two intersections are close to machine precision. .. note:: This is a helper used only by :func:`verify_duplicates`, which in turn is only used by :func:`generic_intersect`. Args: intersection1 (.Intersection): The first intersection. intersection2 (.Intersection): The second intersection. wiggle (Optional[float]): The amount of relative error allowed in parameter values. Returns: bool: Indicates if the two intersections are the same to machine precision.
[ "Check", "if", "two", "intersections", "are", "close", "to", "machine", "precision", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L371-L400
train
54,113
dhermes/bezier
src/bezier/_surface_intersection.py
verify_duplicates
def verify_duplicates(duplicates, uniques): """Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times. """ for uniq1, uniq2 in itertools.combinations(uniques, 2): if same_intersection(uniq1, uniq2): raise ValueError("Non-unique intersection") counter = collections.Counter() for dupe in duplicates: matches = [] for index, uniq in enumerate(uniques): if same_intersection(dupe, uniq): matches.append(index) if len(matches) != 1: raise ValueError("Duplicate not among uniques", dupe) matched = matches[0] counter[matched] += 1 for index, count in six.iteritems(counter): uniq = uniques[index] if count == 1: if (uniq.s, uniq.t).count(0.0) != 1: raise ValueError("Count == 1 should be a single corner", uniq) elif count == 3: if (uniq.s, uniq.t) != (0.0, 0.0): raise ValueError("Count == 3 should be a double corner", uniq) else: raise ValueError("Unexpected duplicate count", count)
python
def verify_duplicates(duplicates, uniques): """Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times. """ for uniq1, uniq2 in itertools.combinations(uniques, 2): if same_intersection(uniq1, uniq2): raise ValueError("Non-unique intersection") counter = collections.Counter() for dupe in duplicates: matches = [] for index, uniq in enumerate(uniques): if same_intersection(dupe, uniq): matches.append(index) if len(matches) != 1: raise ValueError("Duplicate not among uniques", dupe) matched = matches[0] counter[matched] += 1 for index, count in six.iteritems(counter): uniq = uniques[index] if count == 1: if (uniq.s, uniq.t).count(0.0) != 1: raise ValueError("Count == 1 should be a single corner", uniq) elif count == 3: if (uniq.s, uniq.t) != (0.0, 0.0): raise ValueError("Count == 3 should be a double corner", uniq) else: raise ValueError("Unexpected duplicate count", count)
[ "def", "verify_duplicates", "(", "duplicates", ",", "uniques", ")", ":", "for", "uniq1", ",", "uniq2", "in", "itertools", ".", "combinations", "(", "uniques", ",", "2", ")", ":", "if", "same_intersection", "(", "uniq1", ",", "uniq2", ")", ":", "raise", "...
Verify that a set of intersections had expected duplicates. .. note:: This is a helper used only by :func:`generic_intersect`. Args: duplicates (List[.Intersection]): List of intersections corresponding to duplicates that were filtered out. uniques (List[.Intersection]): List of "final" intersections with duplicates filtered out. Raises: ValueError: If the ``uniques`` are not actually all unique. ValueError: If one of the ``duplicates`` does not correspond to an intersection in ``uniques``. ValueError: If a duplicate occurs only once but does not have exactly one of ``s`` and ``t`` equal to ``0.0``. ValueError: If a duplicate occurs three times but does not have exactly both ``s == t == 0.0``. ValueError: If a duplicate occurs a number other than one or three times.
[ "Verify", "that", "a", "set", "of", "intersections", "had", "expected", "duplicates", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L403-L453
train
54,114
dhermes/bezier
src/bezier/_surface_intersection.py
verify_edge_segments
def verify_edge_segments(edge_infos): """Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end). """ if edge_infos is None: return for edge_info in edge_infos: num_segments = len(edge_info) for index in six.moves.xrange(-1, num_segments - 1): index1, start1, end1 = edge_info[index] # First, verify the start and end parameters for the current # segment. if not 0.0 <= start1 < end1 <= 1.0: raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index]) # Then, verify that the indices are not the same. index2, _, _ = edge_info[index + 1] if index1 == index2: raise ValueError( SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1] )
python
def verify_edge_segments(edge_infos): """Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end). """ if edge_infos is None: return for edge_info in edge_infos: num_segments = len(edge_info) for index in six.moves.xrange(-1, num_segments - 1): index1, start1, end1 = edge_info[index] # First, verify the start and end parameters for the current # segment. if not 0.0 <= start1 < end1 <= 1.0: raise ValueError(BAD_SEGMENT_PARAMS, edge_info[index]) # Then, verify that the indices are not the same. index2, _, _ = edge_info[index + 1] if index1 == index2: raise ValueError( SEGMENTS_SAME_EDGE, edge_info[index], edge_info[index + 1] )
[ "def", "verify_edge_segments", "(", "edge_infos", ")", ":", "if", "edge_infos", "is", "None", ":", "return", "for", "edge_info", "in", "edge_infos", ":", "num_segments", "=", "len", "(", "edge_info", ")", "for", "index", "in", "six", ".", "moves", ".", "xr...
Verify that the edge segments in an intersection are valid. .. note:: This is a helper used only by :func:`generic_intersect`. Args: edge_infos (Optional[list]): List of "edge info" lists. Each list represents a curved polygon and contains 3-tuples of edge index, start and end (see the output of :func:`ends_to_curve`). Raises: ValueError: If two consecutive edge segments lie on the same edge index. ValueError: If the start and end parameter are "invalid" (they should be between 0 and 1 and start should be strictly less than end).
[ "Verify", "that", "the", "edge", "segments", "in", "an", "intersection", "are", "valid", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L456-L491
train
54,115
dhermes/bezier
src/bezier/_surface_intersection.py
add_edge_end_unused
def add_edge_end_unused(intersection, duplicates, intersections): """Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ found = None for other in intersections: if ( intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: found = other break if intersection.t == 0.0 and other.t == 0.0: found = other break if found is not None: intersections.remove(found) duplicates.append(found) intersections.append(intersection)
python
def add_edge_end_unused(intersection, duplicates, intersections): """Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. """ found = None for other in intersections: if ( intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: found = other break if intersection.t == 0.0 and other.t == 0.0: found = other break if found is not None: intersections.remove(found) duplicates.append(found) intersections.append(intersection)
[ "def", "add_edge_end_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", ":", "found", "=", "None", "for", "other", "in", "intersections", ":", "if", "(", "intersection", ".", "index_first", "==", "other", ".", "index_first", "and", "in...
Add intersection that is ``COINCIDENT_UNUSED`` but on an edge end. This is a helper for :func:`~._surface_intersection.add_intersection`. It assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * A "misclassified" intersection in ``intersections`` that matches ``intersection`` will be the "same" if it matches both ``index_first`` and ``index_second`` and if it matches the start index exactly Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections.
[ "Add", "intersection", "that", "is", "COINCIDENT_UNUSED", "but", "on", "an", "edge", "end", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L494-L528
train
54,116
dhermes/bezier
src/bezier/_surface_intersection.py
check_unused
def check_unused(intersection, duplicates, intersections): """Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate. """ for other in intersections: if ( other.interior_curve == UNUSED_T and intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: duplicates.append(intersection) return True if intersection.t == 0.0 and other.t == 0.0: duplicates.append(intersection) return True return False
python
def check_unused(intersection, duplicates, intersections): """Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate. """ for other in intersections: if ( other.interior_curve == UNUSED_T and intersection.index_first == other.index_first and intersection.index_second == other.index_second ): if intersection.s == 0.0 and other.s == 0.0: duplicates.append(intersection) return True if intersection.t == 0.0 and other.t == 0.0: duplicates.append(intersection) return True return False
[ "def", "check_unused", "(", "intersection", ",", "duplicates", ",", "intersections", ")", ":", "for", "other", "in", "intersections", ":", "if", "(", "other", ".", "interior_curve", "==", "UNUSED_T", "and", "intersection", ".", "index_first", "==", "other", "....
Check if a "valid" ``intersection`` is already in ``intersections``. This assumes that * ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0`` * At least one of the intersections in ``intersections`` is classified as ``COINCIDENT_UNUSED``. Args: intersection (.Intersection): An intersection to be added. duplicates (List[.Intersection]): List of duplicate intersections. intersections (List[.Intersection]): List of "accepted" (i.e. non-duplicate) intersections. Returns: bool: Indicates if the ``intersection`` is a duplicate.
[ "Check", "if", "a", "valid", "intersection", "is", "already", "in", "intersections", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L531-L563
train
54,117
dhermes/bezier
src/bezier/_surface_intersection.py
classify_coincident
def classify_coincident(st_vals, coincident): r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections. """ if not coincident: return None if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]: return UNUSED_T else: return CLASSIFICATION_T.COINCIDENT
python
def classify_coincident(st_vals, coincident): r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections. """ if not coincident: return None if st_vals[0, 0] >= st_vals[0, 1] or st_vals[1, 0] >= st_vals[1, 1]: return UNUSED_T else: return CLASSIFICATION_T.COINCIDENT
[ "def", "classify_coincident", "(", "st_vals", ",", "coincident", ")", ":", "if", "not", "coincident", ":", "return", "None", "if", "st_vals", "[", "0", ",", "0", "]", ">=", "st_vals", "[", "0", ",", "1", "]", "or", "st_vals", "[", "1", ",", "0", "]...
r"""Determine if coincident parameters are "unused". .. note:: This is a helper for :func:`surface_intersections`. In the case that ``coincident`` is :data:`True`, then we'll have two sets of parameters :math:`(s_1, t_1)` and :math:`(s_2, t_2)`. If one of :math:`s1 < s2` or :math:`t1 < t2` is not satisfied, the coincident segments will be moving in opposite directions, hence don't define an interior of an intersection. .. warning:: In the "coincident" case, this assumes, but doesn't check, that ``st_vals`` is ``2 x 2``. Args: st_vals (numpy.ndarray): ``2 X N`` array of intersection parameters. coincident (bool): Flag indicating if the intersections are the endpoints of coincident segments of two curves. Returns: Optional[.IntersectionClassification]: The classification of the intersections.
[ "r", "Determine", "if", "coincident", "parameters", "are", "unused", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L632-L667
train
54,118
dhermes/bezier
src/bezier/_surface_intersection.py
should_use
def should_use(intersection): """Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used. """ if intersection.interior_curve in ACCEPTABLE_CLASSIFICATIONS: return True if intersection.interior_curve in TANGENT_CLASSIFICATIONS: return intersection.s == 0.0 or intersection.t == 0.0 return False
python
def should_use(intersection): """Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used. """ if intersection.interior_curve in ACCEPTABLE_CLASSIFICATIONS: return True if intersection.interior_curve in TANGENT_CLASSIFICATIONS: return intersection.s == 0.0 or intersection.t == 0.0 return False
[ "def", "should_use", "(", "intersection", ")", ":", "if", "intersection", ".", "interior_curve", "in", "ACCEPTABLE_CLASSIFICATIONS", ":", "return", "True", "if", "intersection", ".", "interior_curve", "in", "TANGENT_CLASSIFICATIONS", ":", "return", "intersection", "."...
Check if an intersection can be used as part of a curved polygon. Will return :data:`True` if the intersection is classified as :attr:`~.IntersectionClassification.FIRST`, :attr:`~.IntersectionClassification.SECOND` or :attr:`~.IntersectionClassification.COINCIDENT` or if the intersection is classified is a corner / edge end which is classified as :attr:`~.IntersectionClassification.TANGENT_FIRST` or :attr:`~.IntersectionClassification.TANGENT_SECOND`. Args: intersection (.Intersection): An intersection to be added. Returns: bool: Indicating if the intersection will be used.
[ "Check", "if", "an", "intersection", "can", "be", "used", "as", "part", "of", "a", "curved", "polygon", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L670-L693
train
54,119
dhermes/bezier
src/bezier/_surface_intersection.py
surface_intersections
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections): """Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals intersections = [] duplicates = [] for index1, nodes1 in enumerate(edge_nodes1): for index2, nodes2 in enumerate(edge_nodes2): st_vals, coincident = all_intersections(nodes1, nodes2) interior_curve = classify_coincident(st_vals, coincident) for s, t in st_vals.T: add_intersection( index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ) all_types = set() to_keep = [] unused = [] for intersection in intersections: all_types.add(intersection.interior_curve) # Only keep the intersections which are "acceptable". if should_use(intersection): to_keep.append(intersection) else: unused.append(intersection) return to_keep, duplicates, unused, all_types
python
def surface_intersections(edge_nodes1, edge_nodes2, all_intersections): """Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals intersections = [] duplicates = [] for index1, nodes1 in enumerate(edge_nodes1): for index2, nodes2 in enumerate(edge_nodes2): st_vals, coincident = all_intersections(nodes1, nodes2) interior_curve = classify_coincident(st_vals, coincident) for s, t in st_vals.T: add_intersection( index1, s, index2, t, interior_curve, edge_nodes1, edge_nodes2, duplicates, intersections, ) all_types = set() to_keep = [] unused = [] for intersection in intersections: all_types.add(intersection.interior_curve) # Only keep the intersections which are "acceptable". if should_use(intersection): to_keep.append(intersection) else: unused.append(intersection) return to_keep, duplicates, unused, all_types
[ "def", "surface_intersections", "(", "edge_nodes1", ",", "edge_nodes2", ",", "all_intersections", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "intersections", "=", "[", ...
Find all intersections among edges of two surfaces. This treats intersections which have ``s == 1.0`` or ``t == 1.0`` as duplicates. The duplicates may be checked by the caller, e.g. by :func:`verify_duplicates`. Args: edge_nodes1 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the first surface being intersected. edge_nodes2 (Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]): The nodes of the three edges of the second surface being intersected. all_intersections (Callable): A helper that intersects B |eacute| zier curves. Takes the nodes of each curve as input and returns an array (``2 x N``) of intersections. Returns: Tuple[list, list, list, set]: 4-tuple of * The actual "unique" :class:`Intersection`-s * Duplicate :class:`Intersection`-s encountered (these will be corner intersections) * Intersections that won't be used, such as a tangent intersection along an edge * All the intersection classifications encountered
[ "Find", "all", "intersections", "among", "edges", "of", "two", "surfaces", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_surface_intersection.py#L696-L753
train
54,120
dhermes/bezier
src/bezier/__config__.py
modify_path
def modify_path(): """Modify the module search path.""" # Only modify path on Windows. if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_dir except ImportError: pass
python
def modify_path(): """Modify the module search path.""" # Only modify path on Windows. if os.name != "nt": return path = os.environ.get("PATH") if path is None: return try: extra_dll_dir = pkg_resources.resource_filename("bezier", "extra-dll") if os.path.isdir(extra_dll_dir): os.environ["PATH"] = path + os.pathsep + extra_dll_dir except ImportError: pass
[ "def", "modify_path", "(", ")", ":", "# Only modify path on Windows.", "if", "os", ".", "name", "!=", "\"nt\"", ":", "return", "path", "=", "os", ".", "environ", ".", "get", "(", "\"PATH\"", ")", "if", "path", "is", "None", ":", "return", "try", ":", "...
Modify the module search path.
[ "Modify", "the", "module", "search", "path", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/__config__.py#L30-L45
train
54,121
dhermes/bezier
src/bezier/__config__.py
handle_import_error
def handle_import_error(caught_exc, name): """Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message. """ for template in TEMPLATES: expected_msg = template.format(name) if caught_exc.args == (expected_msg,): return raise caught_exc
python
def handle_import_error(caught_exc, name): """Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message. """ for template in TEMPLATES: expected_msg = template.format(name) if caught_exc.args == (expected_msg,): return raise caught_exc
[ "def", "handle_import_error", "(", "caught_exc", ",", "name", ")", ":", "for", "template", "in", "TEMPLATES", ":", "expected_msg", "=", "template", ".", "format", "(", "name", ")", "if", "caught_exc", ".", "args", "==", "(", "expected_msg", ",", ")", ":", ...
Allow or re-raise an import error. This is to distinguish between expected and unexpected import errors. If the module is not found, it simply means the Cython / Fortran speedups were not built with the package. If the error message is different, e.g. ``... undefined symbol: __curve_intersection_MOD_all_intersections``, then the import error **should** be raised. Args: caught_exc (ImportError): An exception caught when trying to import a Cython module. name (str): The name of the module. For example, for the module ``bezier._curve_speedup``, the name is ``"_curve_speedup"``. Raises: ImportError: If the error message is different than the basic "missing module" error message.
[ "Allow", "or", "re", "-", "raise", "an", "import", "error", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/__config__.py#L48-L72
train
54,122
dhermes/bezier
setup_helpers_macos.py
is_macos_gfortran
def is_macos_gfortran(f90_compiler): """Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure. from numpy.distutils.fcompiler import gnu # Only macOS. if sys.platform != MAC_OS: return False # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False return True
python
def is_macos_gfortran(f90_compiler): """Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure. from numpy.distutils.fcompiler import gnu # Only macOS. if sys.platform != MAC_OS: return False # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False return True
[ "def", "is_macos_gfortran", "(", "f90_compiler", ")", ":", "# NOTE: NumPy may not be installed, but we don't want **this** module to", "# cause an import failure.", "from", "numpy", ".", "distutils", ".", "fcompiler", "import", "gnu", "# Only macOS.", "if", "sys", ".", ...
Checks if the current build is ``gfortran`` on macOS. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. Returns: bool: Only :data:`True` if * Current OS is macOS (checked via ``sys.platform``). * ``f90_compiler`` corresponds to ``gfortran``.
[ "Checks", "if", "the", "current", "build", "is", "gfortran", "on", "macOS", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers_macos.py#L23-L48
train
54,123
dhermes/bezier
src/bezier/surface.py
_make_intersection
def _make_intersection(edge_info, all_edge_nodes): """Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``. """ edges = [] for index, start, end in edge_info: nodes = all_edge_nodes[index] new_nodes = _curve_helpers.specialize_curve(nodes, start, end) degree = new_nodes.shape[1] - 1 edge = _curve_mod.Curve(new_nodes, degree, _copy=False) edges.append(edge) return curved_polygon.CurvedPolygon( *edges, metadata=edge_info, _verify=False )
python
def _make_intersection(edge_info, all_edge_nodes): """Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``. """ edges = [] for index, start, end in edge_info: nodes = all_edge_nodes[index] new_nodes = _curve_helpers.specialize_curve(nodes, start, end) degree = new_nodes.shape[1] - 1 edge = _curve_mod.Curve(new_nodes, degree, _copy=False) edges.append(edge) return curved_polygon.CurvedPolygon( *edges, metadata=edge_info, _verify=False )
[ "def", "_make_intersection", "(", "edge_info", ",", "all_edge_nodes", ")", ":", "edges", "=", "[", "]", "for", "index", ",", "start", ",", "end", "in", "edge_info", ":", "nodes", "=", "all_edge_nodes", "[", "index", "]", "new_nodes", "=", "_curve_helpers", ...
Convert a description of edges into a curved polygon. .. note:: This is a helper used only by :meth:`.Surface.intersect`. Args: edge_info (Tuple[Tuple[int, float, float], ...]): Information describing each edge in the curved polygon by indicating which surface / edge on the surface and then start and end parameters along that edge. (See :func:`.ends_to_curve`.) all_edge_nodes (Tuple[numpy.ndarray, ...]): The nodes of three edges of the first surface being intersected followed by the nodes of the three edges of the second. Returns: .CurvedPolygon: The intersection corresponding to ``edge_info``.
[ "Convert", "a", "description", "of", "edges", "into", "a", "curved", "polygon", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L1100-L1128
train
54,124
dhermes/bezier
src/bezier/surface.py
Surface._get_degree
def _get_degree(num_nodes): """Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number. """ # 8 * num_nodes = 4(d + 1)(d + 2) # = 4d^2 + 12d + 8 # = (2d + 3)^2 - 1 d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0) d_int = int(np.round(d_float)) if (d_int + 1) * (d_int + 2) == 2 * num_nodes: return d_int else: raise ValueError(num_nodes, "not a triangular number")
python
def _get_degree(num_nodes): """Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number. """ # 8 * num_nodes = 4(d + 1)(d + 2) # = 4d^2 + 12d + 8 # = (2d + 3)^2 - 1 d_float = 0.5 * (np.sqrt(8.0 * num_nodes + 1.0) - 3.0) d_int = int(np.round(d_float)) if (d_int + 1) * (d_int + 2) == 2 * num_nodes: return d_int else: raise ValueError(num_nodes, "not a triangular number")
[ "def", "_get_degree", "(", "num_nodes", ")", ":", "# 8 * num_nodes = 4(d + 1)(d + 2)", "# = 4d^2 + 12d + 8", "# = (2d + 3)^2 - 1", "d_float", "=", "0.5", "*", "(", "np", ".", "sqrt", "(", "8.0", "*", "num_nodes", "+", "1.0", ")", "-", "3....
Get the degree of the current surface. Args: num_nodes (int): The number of control points for a B |eacute| zier surface. Returns: int: The degree :math:`d` such that :math:`(d + 1)(d + 2)/2` equals ``num_nodes``. Raises: ValueError: If ``num_nodes`` isn't a triangular number.
[ "Get", "the", "degree", "of", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L214-L237
train
54,125
dhermes/bezier
src/bezier/surface.py
Surface.area
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) edge1, edge2, edge3 = self._get_edges() return _surface_helpers.compute_area( (edge1._nodes, edge2._nodes, edge3._nodes) )
python
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) edge1, edge2, edge3 = self._get_edges() return _surface_helpers.compute_area( (edge1._nodes, edge2._nodes, edge3._nodes) )
[ "def", "area", "(", "self", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"2D is the only supported dimension\"", ",", "\"Current dimension\"", ",", "self", ".", "_dimension", ",", ")", "edge1", ",", "edge2", ...
r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to .. math:: \int_{B\left(\mathcal{U}\right)} 2 \, d\mathbf{x} = \int_{\partial B\left(\mathcal{U}\right)} -y \, dx + x \, dy. This relies on the assumption that the current surface is valid, which implies that the image of the unit triangle under the B |eacute| zier map --- :math:`B\left(\mathcal{U}\right)` --- has the edges of the surface as its boundary. Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current surface. Raises: NotImplementedError: If the current surface isn't in :math:`\mathbf{R}^2`.
[ "r", "The", "area", "of", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L240-L286
train
54,126
dhermes/bezier
src/bezier/surface.py
Surface._compute_edges
def _compute_edges(self): """Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface. """ nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes( self._nodes, self._degree ) edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False) edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False) edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False) return edge1, edge2, edge3
python
def _compute_edges(self): """Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface. """ nodes1, nodes2, nodes3 = _surface_helpers.compute_edge_nodes( self._nodes, self._degree ) edge1 = _curve_mod.Curve(nodes1, self._degree, _copy=False) edge2 = _curve_mod.Curve(nodes2, self._degree, _copy=False) edge3 = _curve_mod.Curve(nodes3, self._degree, _copy=False) return edge1, edge2, edge3
[ "def", "_compute_edges", "(", "self", ")", ":", "nodes1", ",", "nodes2", ",", "nodes3", "=", "_surface_helpers", ".", "compute_edge_nodes", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ")", "edge1", "=", "_curve_mod", ".", "Curve", "(", "nodes1...
Compute the edges of the current surface. Returns: Tuple[~curve.Curve, ~curve.Curve, ~curve.Curve]: The edges of the surface.
[ "Compute", "the", "edges", "of", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L288-L301
train
54,127
dhermes/bezier
src/bezier/surface.py
Surface._get_edges
def _get_edges(self): """Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ if self._edges is None: self._edges = self._compute_edges() return self._edges
python
def _get_edges(self): """Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ if self._edges is None: self._edges = self._compute_edges() return self._edges
[ "def", "_get_edges", "(", "self", ")", ":", "if", "self", ".", "_edges", "is", "None", ":", "self", ".", "_edges", "=", "self", ".", "_compute_edges", "(", ")", "return", "self", ".", "_edges" ]
Get the edges for the current surface. If they haven't been computed yet, first compute and store them. This is provided as a means for internal calls to get the edges without copying (since :attr:`.edges` copies before giving to a user to keep the stored data immutable). Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface.
[ "Get", "the", "edges", "for", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L303-L319
train
54,128
dhermes/bezier
src/bezier/surface.py
Surface.edges
def edges(self): """The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ edge1, edge2, edge3 = self._get_edges() # NOTE: It is crucial that we return copies here. Since the edges # are cached, if they were mutable, callers could # inadvertently mutate the cached value. edge1 = edge1._copy() # pylint: disable=protected-access edge2 = edge2._copy() # pylint: disable=protected-access edge3 = edge3._copy() # pylint: disable=protected-access return edge1, edge2, edge3
python
def edges(self): """The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface. """ edge1, edge2, edge3 = self._get_edges() # NOTE: It is crucial that we return copies here. Since the edges # are cached, if they were mutable, callers could # inadvertently mutate the cached value. edge1 = edge1._copy() # pylint: disable=protected-access edge2 = edge2._copy() # pylint: disable=protected-access edge3 = edge3._copy() # pylint: disable=protected-access return edge1, edge2, edge3
[ "def", "edges", "(", "self", ")", ":", "edge1", ",", "edge2", ",", "edge3", "=", "self", ".", "_get_edges", "(", ")", "# NOTE: It is crucial that we return copies here. Since the edges", "# are cached, if they were mutable, callers could", "# inadvertently mutate th...
The edges of the surface. .. doctest:: surface-edges :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.1875, 0.625, 0.0], ... [0.0, -0.1875, 0.0, 0.5 , 0.625, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> edge1, _, _ = surface.edges >>> edge1 <Curve (degree=2, dimension=2)> >>> edge1.nodes array([[ 0. , 0.5 , 1. ], [ 0. , -0.1875, 0. ]]) Returns: Tuple[~bezier.curve.Curve, ~bezier.curve.Curve, \ ~bezier.curve.Curve]: The edges of the surface.
[ "The", "edges", "of", "the", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L322-L352
train
54,129
dhermes/bezier
src/bezier/surface.py
Surface._verify_barycentric
def _verify_barycentric(lambda1, lambda2, lambda3): """Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative. """ weights_total = lambda1 + lambda2 + lambda3 if not np.allclose(weights_total, 1.0, atol=0.0): raise ValueError( "Weights do not sum to 1", lambda1, lambda2, lambda3 ) if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0: raise ValueError( "Weights must be positive", lambda1, lambda2, lambda3 )
python
def _verify_barycentric(lambda1, lambda2, lambda3): """Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative. """ weights_total = lambda1 + lambda2 + lambda3 if not np.allclose(weights_total, 1.0, atol=0.0): raise ValueError( "Weights do not sum to 1", lambda1, lambda2, lambda3 ) if lambda1 < 0.0 or lambda2 < 0.0 or lambda3 < 0.0: raise ValueError( "Weights must be positive", lambda1, lambda2, lambda3 )
[ "def", "_verify_barycentric", "(", "lambda1", ",", "lambda2", ",", "lambda3", ")", ":", "weights_total", "=", "lambda1", "+", "lambda2", "+", "lambda3", "if", "not", "np", ".", "allclose", "(", "weights_total", ",", "1.0", ",", "atol", "=", "0.0", ")", "...
Verifies that weights are barycentric and on the reference triangle. I.e., checks that they sum to one and are all non-negative. Args: lambda1 (float): Parameter along the reference triangle. lambda2 (float): Parameter along the reference triangle. lambda3 (float): Parameter along the reference triangle. Raises: ValueError: If the weights are not valid barycentric coordinates, i.e. they don't sum to ``1``. ValueError: If some weights are negative.
[ "Verifies", "that", "weights", "are", "barycentric", "and", "on", "the", "reference", "triangle", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L355-L379
train
54,130
dhermes/bezier
src/bezier/surface.py
Surface._verify_cartesian
def _verify_cartesian(s, t): """Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle. """ if s < 0.0 or t < 0.0 or s + t > 1.0: raise ValueError("Point lies outside reference triangle", s, t)
python
def _verify_cartesian(s, t): """Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle. """ if s < 0.0 or t < 0.0 or s + t > 1.0: raise ValueError("Point lies outside reference triangle", s, t)
[ "def", "_verify_cartesian", "(", "s", ",", "t", ")", ":", "if", "s", "<", "0.0", "or", "t", "<", "0.0", "or", "s", "+", "t", ">", "1.0", ":", "raise", "ValueError", "(", "\"Point lies outside reference triangle\"", ",", "s", ",", "t", ")" ]
Verifies that a point is in the reference triangle. I.e., checks that they sum to <= one and are each non-negative. Args: s (float): Parameter along the reference triangle. t (float): Parameter along the reference triangle. Raises: ValueError: If the point lies outside the reference triangle.
[ "Verifies", "that", "a", "point", "is", "in", "the", "reference", "triangle", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L539-L552
train
54,131
dhermes/bezier
src/bezier/surface.py
Surface.plot
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False): """Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges()) if with_nodes: ax.plot( self._nodes[0, :], self._nodes[1, :], color="black", marker="o", linestyle="None", ) return ax
python
def plot(self, pts_per_edge, color=None, ax=None, with_nodes=False): """Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``. """ if self._dimension != 2: raise NotImplementedError( "2D is the only supported dimension", "Current dimension", self._dimension, ) if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._get_edges()) if with_nodes: ax.plot( self._nodes[0, :], self._nodes[1, :], color="black", marker="o", linestyle="None", ) return ax
[ "def", "plot", "(", "self", ",", "pts_per_edge", ",", "color", "=", "None", ",", "ax", "=", "None", ",", "with_nodes", "=", "False", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"2D is the only supported...
Plot the current surface. Args: pts_per_edge (int): Number of points to plot per edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. ax (Optional[matplotlib.artist.Artist]): matplotlib axis object to add plot to. with_nodes (Optional[bool]): Determines if the control points should be added to the plot. Off by default. Returns: matplotlib.artist.Artist: The axis containing the plot. This may be a newly created axis. Raises: NotImplementedError: If the surface's dimension is not ``2``.
[ "Plot", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L660-L696
train
54,132
dhermes/bezier
src/bezier/surface.py
Surface.subdivide
def subdivide(self): r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order). """ nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( self._nodes, self._degree ) return ( Surface(nodes_a, self._degree, _copy=False), Surface(nodes_b, self._degree, _copy=False), Surface(nodes_c, self._degree, _copy=False), Surface(nodes_d, self._degree, _copy=False), )
python
def subdivide(self): r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order). """ nodes_a, nodes_b, nodes_c, nodes_d = _surface_helpers.subdivide_nodes( self._nodes, self._degree ) return ( Surface(nodes_a, self._degree, _copy=False), Surface(nodes_b, self._degree, _copy=False), Surface(nodes_c, self._degree, _copy=False), Surface(nodes_d, self._degree, _copy=False), )
[ "def", "subdivide", "(", "self", ")", ":", "nodes_a", ",", "nodes_b", ",", "nodes_c", ",", "nodes_d", "=", "_surface_helpers", ".", "subdivide_nodes", "(", "self", ".", "_nodes", ",", "self", ".", "_degree", ")", "return", "(", "Surface", "(", "nodes_a", ...
r"""Split the surface into four sub-surfaces. Does so by taking the unit triangle (i.e. the domain of the surface) and splitting it into four sub-triangles .. image:: ../../images/surface_subdivide1.png :align: center Then the surface is re-parameterized via the map to / from the given sub-triangles and the unit triangle. For example, when a degree two surface is subdivided: .. image:: ../../images/surface_subdivide2.png :align: center .. doctest:: surface-subdivide :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [-1.0, 0.5, 2.0, 0.25, 2.0, 0.0], ... [ 0.0, 0.5, 0.0, 1.75, 3.0, 4.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> _, sub_surface_b, _, _ = surface.subdivide() >>> sub_surface_b <Surface (degree=2, dimension=2)> >>> sub_surface_b.nodes array([[ 1.5 , 0.6875, -0.125 , 1.1875, 0.4375, 0.5 ], [ 2.5 , 2.3125, 1.875 , 1.3125, 1.3125, 0.25 ]]) .. testcleanup:: surface-subdivide import make_images make_images.surface_subdivide1() make_images.surface_subdivide2(surface, sub_surface_b) Returns: Tuple[Surface, Surface, Surface, Surface]: The lower left, central, lower right and upper left sub-surfaces (in that order).
[ "r", "Split", "the", "surface", "into", "four", "sub", "-", "surfaces", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L698-L748
train
54,133
dhermes/bezier
src/bezier/surface.py
Surface._compute_valid
def _compute_valid(self): r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ if self._dimension != 2: raise NotImplementedError("Validity check only implemented in R^2") poly_sign = None if self._degree == 1: # In the linear case, we are only invalid if the points # are collinear. first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1] poly_sign = _SIGN(np.linalg.det(first_deriv)) elif self._degree == 2: bernstein = _surface_helpers.quadratic_jacobian_polynomial( self._nodes ) poly_sign = _surface_helpers.polynomial_sign(bernstein, 2) elif self._degree == 3: bernstein = _surface_helpers.cubic_jacobian_polynomial(self._nodes) poly_sign = _surface_helpers.polynomial_sign(bernstein, 4) else: raise _helpers.UnsupportedDegree(self._degree, supported=(1, 2, 3)) return poly_sign == 1
python
def _compute_valid(self): r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ if self._dimension != 2: raise NotImplementedError("Validity check only implemented in R^2") poly_sign = None if self._degree == 1: # In the linear case, we are only invalid if the points # are collinear. first_deriv = self._nodes[:, 1:] - self._nodes[:, :-1] poly_sign = _SIGN(np.linalg.det(first_deriv)) elif self._degree == 2: bernstein = _surface_helpers.quadratic_jacobian_polynomial( self._nodes ) poly_sign = _surface_helpers.polynomial_sign(bernstein, 2) elif self._degree == 3: bernstein = _surface_helpers.cubic_jacobian_polynomial(self._nodes) poly_sign = _surface_helpers.polynomial_sign(bernstein, 4) else: raise _helpers.UnsupportedDegree(self._degree, supported=(1, 2, 3)) return poly_sign == 1
[ "def", "_compute_valid", "(", "self", ")", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Validity check only implemented in R^2\"", ")", "poly_sign", "=", "None", "if", "self", ".", "_degree", "==", "1", ":", "# ...
r"""Determines if the current surface is "valid". Does this by checking if the Jacobian of the map from the reference triangle is everywhere positive. Returns: bool: Flag indicating if the current surface is valid. Raises: NotImplementedError: If the surface is in a dimension other than :math:`\mathbf{R}^2`. .UnsupportedDegree: If the degree is not 1, 2 or 3.
[ "r", "Determines", "if", "the", "current", "surface", "is", "valid", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L750-L784
train
54,134
dhermes/bezier
src/bezier/surface.py
Surface.locate
def locate(self, point, _verify=True): r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface. """ if _verify: if self._dimension != 2: raise NotImplementedError("Only 2D surfaces supported.") 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 _surface_intersection.locate_point( self._nodes, self._degree, point[0, 0], point[1, 0] )
python
def locate(self, point, _verify=True): r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface. """ if _verify: if self._dimension != 2: raise NotImplementedError("Only 2D surfaces supported.") 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 _surface_intersection.locate_point( self._nodes, self._degree, point[0, 0], point[1, 0] )
[ "def", "locate", "(", "self", ",", "point", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "self", ".", "_dimension", "!=", "2", ":", "raise", "NotImplementedError", "(", "\"Only 2D surfaces supported.\"", ")", "if", "point", ".", "shap...
r"""Find a point on the current surface. Solves for :math:`s` and :math:`t` in :math:`B(s, t) = p`. This method acts as a (partial) inverse to :meth:`evaluate_cartesian`. .. warning:: A unique solution is only guaranteed if the current surface is valid. This code assumes a valid surface, but doesn't check. .. image:: ../../images/surface_locate.png :align: center .. doctest:: surface-locate >>> nodes = np.asfortranarray([ ... [0.0, 0.5 , 1.0, 0.25, 0.75, 0.0], ... [0.0, -0.25, 0.0, 0.5 , 0.75, 1.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> point = np.asfortranarray([ ... [0.59375], ... [0.25 ], ... ]) >>> s, t = surface.locate(point) >>> s 0.5 >>> t 0.25 .. testcleanup:: surface-locate import make_images make_images.surface_locate(surface, point) Args: point (numpy.ndarray): A (``D x 1``) point on the surface, where :math:`D` is the dimension of the surface. _verify (Optional[bool]): Indicates if extra caution should be used to verify assumptions about the inputs. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: Optional[Tuple[float, float]]: The :math:`s` and :math:`t` values corresponding to ``point`` or :data:`None` if the point is not on the surface. Raises: NotImplementedError: If the surface isn't in :math:`\mathbf{R}^2`. ValueError: If the dimension of the ``point`` doesn't match the dimension of the current surface.
[ "r", "Find", "a", "point", "on", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L877-L946
train
54,135
dhermes/bezier
src/bezier/surface.py
Surface.intersect
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface 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 algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Surface): raise TypeError( "Can only intersect with another surface", "Received", other, ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == _STRATEGY.GEOMETRIC: do_intersect = _surface_intersection.geometric_intersect elif strategy == _STRATEGY.ALGEBRAIC: do_intersect = _surface_intersection.algebraic_intersect else: raise ValueError("Unexpected strategy.", strategy) edge_infos, contained, all_edge_nodes = do_intersect( self._nodes, self._degree, other._nodes, other._degree, _verify ) if edge_infos is None: if contained: return [self] else: return [other] else: return [ _make_intersection(edge_info, all_edge_nodes) for edge_info in edge_infos ]
python
def intersect(self, other, strategy=_STRATEGY.GEOMETRIC, _verify=True): """Find the common intersection with another surface. Args: other (Surface): Other surface 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 algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`. """ if _verify: if not isinstance(other, Surface): raise TypeError( "Can only intersect with another surface", "Received", other, ) if self._dimension != 2 or other._dimension != 2: raise NotImplementedError( "Intersection only implemented in 2D" ) if strategy == _STRATEGY.GEOMETRIC: do_intersect = _surface_intersection.geometric_intersect elif strategy == _STRATEGY.ALGEBRAIC: do_intersect = _surface_intersection.algebraic_intersect else: raise ValueError("Unexpected strategy.", strategy) edge_infos, contained, all_edge_nodes = do_intersect( self._nodes, self._degree, other._nodes, other._degree, _verify ) if edge_infos is None: if contained: return [self] else: return [other] else: return [ _make_intersection(edge_info, all_edge_nodes) for edge_info in edge_infos ]
[ "def", "intersect", "(", "self", ",", "other", ",", "strategy", "=", "_STRATEGY", ".", "GEOMETRIC", ",", "_verify", "=", "True", ")", ":", "if", "_verify", ":", "if", "not", "isinstance", "(", "other", ",", "Surface", ")", ":", "raise", "TypeError", "(...
Find the common intersection with another surface. Args: other (Surface): Other surface 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 algorithm as it proceeds. Can be disabled to speed up execution time. Defaults to :data:`True`. Returns: List[Union[~bezier.curved_polygon.CurvedPolygon, \ ~bezier.surface.Surface]]: List of intersections (possibly empty). Raises: TypeError: If ``other`` is not a surface (and ``_verify=True``). NotImplementedError: If at least one of the surfaces isn't two-dimensional (and ``_verify=True``). ValueError: If ``strategy`` is not a valid :class:`.IntersectionStrategy`.
[ "Find", "the", "common", "intersection", "with", "another", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L948-L1005
train
54,136
dhermes/bezier
src/bezier/surface.py
Surface.elevate
def elevate(self): r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface. """ _, num_nodes = self._nodes.shape # (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2 num_new = num_nodes + self._degree + 2 new_nodes = np.zeros((self._dimension, num_new), order="F") # NOTE: We start from the index triples (i, j, k) for the current # nodes and map them onto (i + 1, j, k), etc. This index # tracking is also done in :func:`.de_casteljau_one_round`. index = 0 # parent_i1 = index + k # parent_i2 = index + k + 1 # parent_i3 = index + degree + 2 parent_i1 = 0 parent_i2 = 1 parent_i3 = self._degree + 2 for k in six.moves.xrange(self._degree + 1): for j in six.moves.xrange(self._degree + 1 - k): i = self._degree - j - k new_nodes[:, parent_i1] += (i + 1) * self._nodes[:, index] new_nodes[:, parent_i2] += (j + 1) * self._nodes[:, index] new_nodes[:, parent_i3] += (k + 1) * self._nodes[:, index] # Update all the indices. parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 # Update the indices that depend on k. parent_i1 += 1 parent_i2 += 1 # Hold off on division until the end, to (attempt to) avoid round-off. denominator = self._degree + 1.0 new_nodes /= denominator return Surface(new_nodes, self._degree + 1, _copy=False)
python
def elevate(self): r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface. """ _, num_nodes = self._nodes.shape # (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2 num_new = num_nodes + self._degree + 2 new_nodes = np.zeros((self._dimension, num_new), order="F") # NOTE: We start from the index triples (i, j, k) for the current # nodes and map them onto (i + 1, j, k), etc. This index # tracking is also done in :func:`.de_casteljau_one_round`. index = 0 # parent_i1 = index + k # parent_i2 = index + k + 1 # parent_i3 = index + degree + 2 parent_i1 = 0 parent_i2 = 1 parent_i3 = self._degree + 2 for k in six.moves.xrange(self._degree + 1): for j in six.moves.xrange(self._degree + 1 - k): i = self._degree - j - k new_nodes[:, parent_i1] += (i + 1) * self._nodes[:, index] new_nodes[:, parent_i2] += (j + 1) * self._nodes[:, index] new_nodes[:, parent_i3] += (k + 1) * self._nodes[:, index] # Update all the indices. parent_i1 += 1 parent_i2 += 1 parent_i3 += 1 index += 1 # Update the indices that depend on k. parent_i1 += 1 parent_i2 += 1 # Hold off on division until the end, to (attempt to) avoid round-off. denominator = self._degree + 1.0 new_nodes /= denominator return Surface(new_nodes, self._degree + 1, _copy=False)
[ "def", "elevate", "(", "self", ")", ":", "_", ",", "num_nodes", "=", "self", ".", "_nodes", ".", "shape", "# (d + 1)(d + 2)/2 --> (d + 2)(d + 3)/2", "num_new", "=", "num_nodes", "+", "self", ".", "_degree", "+", "2", "new_nodes", "=", "np", ".", "zeros", "...
r"""Return a degree-elevated version of the current surface. Does this by converting the current nodes :math:`\left\{v_{i, j, k}\right\}_{i + j + k = d}` to new nodes :math:`\left\{w_{i, j, k}\right\}_{i + j + k = d + 1}`. Does so by re-writing .. math:: E\left(\lambda_1, \lambda_2, \lambda_3\right) = \left(\lambda_1 + \lambda_2 + \lambda_3\right) B\left(\lambda_1, \lambda_2, \lambda_3\right) = \sum_{i + j + k = d + 1} \binom{d + 1}{i \, j \, k} \lambda_1^i \lambda_2^j \lambda_3^k \cdot w_{i, j, k} In this form, we must have .. math:: \begin{align*} \binom{d + 1}{i \, j \, k} \cdot w_{i, j, k} &= \binom{d}{i - 1 \, j \, k} \cdot v_{i - 1, j, k} + \binom{d}{i \, j - 1 \, k} \cdot v_{i, j - 1, k} + \binom{d}{i \, j \, k - 1} \cdot v_{i, j, k - 1} \\ \Longleftrightarrow (d + 1) \cdot w_{i, j, k} &= i \cdot v_{i - 1, j, k} + j \cdot v_{i, j - 1, k} + k \cdot v_{i, j, k - 1} \end{align*} where we define, for example, :math:`v_{i, j, k - 1} = 0` if :math:`k = 0`. .. image:: ../../images/surface_elevate.png :align: center .. doctest:: surface-elevate :options: +NORMALIZE_WHITESPACE >>> nodes = np.asfortranarray([ ... [0.0, 1.5, 3.0, 0.75, 2.25, 0.0], ... [0.0, 0.0, 0.0, 1.5 , 2.25, 3.0], ... ]) >>> surface = bezier.Surface(nodes, degree=2) >>> elevated = surface.elevate() >>> elevated <Surface (degree=3, dimension=2)> >>> elevated.nodes array([[0. , 1. , 2. , 3. , 0.5 , 1.5 , 2.5 , 0.5 , 1.5 , 0. ], [0. , 0. , 0. , 0. , 1. , 1.25, 1.5 , 2. , 2.5 , 3. ]]) .. testcleanup:: surface-elevate import make_images make_images.surface_elevate(surface, elevated) Returns: Surface: The degree-elevated surface.
[ "r", "Return", "a", "degree", "-", "elevated", "version", "of", "the", "current", "surface", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/surface.py#L1007-L1097
train
54,137
dhermes/bezier
src/bezier/_intersection_helpers.py
_newton_refine
def _newton_refine(s, nodes1, t, nodes2): r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``. """ # NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t). func_val = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) - _curve_helpers.evaluate_multi(nodes1, np.asfortranarray([s])) if np.all(func_val == 0.0): # No refinement is needed. return s, t # NOTE: This assumes the curves are 2D. jac_mat = np.empty((2, 2), order="F") jac_mat[:, :1] = _curve_helpers.evaluate_hodograph(s, nodes1) jac_mat[:, 1:] = -_curve_helpers.evaluate_hodograph(t, nodes2) # Solve the system. singular, delta_s, delta_t = _helpers.solve2x2(jac_mat, func_val[:, 0]) if singular: raise ValueError("Jacobian is singular.") else: return s + delta_s, t + delta_t
python
def _newton_refine(s, nodes1, t, nodes2): r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``. """ # NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t). func_val = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t]) ) - _curve_helpers.evaluate_multi(nodes1, np.asfortranarray([s])) if np.all(func_val == 0.0): # No refinement is needed. return s, t # NOTE: This assumes the curves are 2D. jac_mat = np.empty((2, 2), order="F") jac_mat[:, :1] = _curve_helpers.evaluate_hodograph(s, nodes1) jac_mat[:, 1:] = -_curve_helpers.evaluate_hodograph(t, nodes2) # Solve the system. singular, delta_s, delta_t = _helpers.solve2x2(jac_mat, func_val[:, 0]) if singular: raise ValueError("Jacobian is singular.") else: return s + delta_s, t + delta_t
[ "def", "_newton_refine", "(", "s", ",", "nodes1", ",", "t", ",", "nodes2", ")", ":", "# NOTE: We form -F(s, t) since we want to solve -DF^{-1} F(s, t).", "func_val", "=", "_curve_helpers", ".", "evaluate_multi", "(", "nodes2", ",", "np", ".", "asfortranarray", "(", ...
r"""Apply one step of 2D Newton's method. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. We want to use Newton's method on the function .. math:: F(s, t) = B_1(s) - B_2(t) to refine :math:`\left(s_{\ast}, t_{\ast}\right)`. Using this, and the Jacobian :math:`DF`, we "solve" .. math:: \left[\begin{array}{c} 0 \\ 0 \end{array}\right] \approx F\left(s_{\ast} + \Delta s, t_{\ast} + \Delta t\right) \approx F\left(s_{\ast}, t_{\ast}\right) + \left[\begin{array}{c c} B_1'\left(s_{\ast}\right) & - B_2'\left(t_{\ast}\right) \end{array}\right] \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] and refine with the component updates :math:`\Delta s` and :math:`\Delta t`. .. note:: This implementation assumes the curves live in :math:`\mathbf{R}^2`. For example, the curves .. math:: \begin{align*} B_1(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 2 \\ 4 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 4 \\ 0 \end{array}\right] s^2 \\ B_2(t) &= \left[\begin{array}{c} 2 \\ 0 \end{array}\right] (1 - t) + \left[\begin{array}{c} 0 \\ 3 \end{array}\right] t \end{align*} intersect at the point :math:`B_1\left(\frac{1}{4}\right) = B_2\left(\frac{1}{2}\right) = \frac{1}{2} \left[\begin{array}{c} 2 \\ 3 \end{array}\right]`. However, starting from the wrong point we have .. math:: \begin{align*} F\left(\frac{3}{8}, \frac{1}{4}\right) &= \frac{1}{8} \left[\begin{array}{c} 0 \\ 9 \end{array}\right] \\ DF\left(\frac{3}{8}, \frac{1}{4}\right) &= \left[\begin{array}{c c} 4 & 2 \\ 2 & -3 \end{array}\right] \\ \Longrightarrow \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] &= \frac{9}{64} \left[\begin{array}{c} -1 \\ 2 \end{array}\right]. \end{align*} .. image:: ../images/newton_refine1.png :align: center .. testsetup:: newton-refine1, newton-refine2, newton-refine3 import numpy as np import bezier from bezier._intersection_helpers import newton_refine machine_eps = np.finfo(np.float64).eps def cuberoot(value): return np.cbrt(value) .. doctest:: newton-refine1 >>> nodes1 = np.asfortranarray([ ... [0.0, 2.0, 4.0], ... [0.0, 4.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [2.0, 0.0], ... [0.0, 3.0], ... ]) >>> s, t = 0.375, 0.25 >>> new_s, new_t = newton_refine(s, nodes1, t, nodes2) >>> 64.0 * (new_s - s) -9.0 >>> 64.0 * (new_t - t) 18.0 .. testcleanup:: newton-refine1 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine1(s, new_s, curve1, t, new_t, curve2) For "typical" curves, we converge to a solution quadratically. This means that the number of correct digits doubles every iteration (until machine precision is reached). .. image:: ../images/newton_refine2.png :align: center .. doctest:: newton-refine2 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [0.0, 2.0 , -2.0, 2.0 , 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 0.25, 0.5, 0.75, 1.0], ... [1.0, 0.5 , 0.5, 0.5 , 0.0], ... ]) >>> # The expected intersection is the only real root of >>> # 28 s^3 - 30 s^2 + 9 s - 1. >>> omega = cuberoot(28.0 * np.sqrt(17.0) + 132.0) / 28.0 >>> expected = 5.0 / 14.0 + omega + 1 / (49.0 * omega) >>> s_vals = [0.625, None, None, None, None] >>> t = 0.625 >>> np.log2(abs(expected - s_vals[0])) -4.399... >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -7.901... >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -16.010... >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -32.110... >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.allclose(s_vals[4], expected, rtol=machine_eps, atol=0.0) True .. testcleanup:: newton-refine2 import make_images curve1 = bezier.Curve(nodes1, degree=4) curve2 = bezier.Curve(nodes2, degree=4) make_images.newton_refine2(s_vals, curve1, curve2) However, when the intersection occurs at a point of tangency, the convergence becomes linear. This means that the number of correct digits added each iteration is roughly constant. .. image:: ../images/newton_refine3.png :align: center .. doctest:: newton-refine3 >>> nodes1 = np.asfortranarray([ ... [0.0, 0.5, 1.0], ... [0.0, 1.0, 0.0], ... ]) >>> nodes2 = np.asfortranarray([ ... [0.0, 1.0], ... [0.5, 0.5], ... ]) >>> expected = 0.5 >>> s_vals = [0.375, None, None, None, None, None] >>> t = 0.375 >>> np.log2(abs(expected - s_vals[0])) -3.0 >>> s_vals[1], t = newton_refine(s_vals[0], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[1])) -4.0 >>> s_vals[2], t = newton_refine(s_vals[1], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[2])) -5.0 >>> s_vals[3], t = newton_refine(s_vals[2], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[3])) -6.0 >>> s_vals[4], t = newton_refine(s_vals[3], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[4])) -7.0 >>> s_vals[5], t = newton_refine(s_vals[4], nodes1, t, nodes2) >>> np.log2(abs(expected - s_vals[5])) -8.0 .. testcleanup:: newton-refine3 import make_images curve1 = bezier.Curve(nodes1, degree=2) curve2 = bezier.Curve(nodes2, degree=1) make_images.newton_refine3(s_vals, curve1, curve2) Unfortunately, the process terminates with an error that is not close to machine precision :math:`\varepsilon` when :math:`\Delta s = \Delta t = 0`. .. testsetup:: newton-refine3-continued import numpy as np import bezier from bezier._intersection_helpers import newton_refine nodes1 = np.asfortranarray([ [0.0, 0.5, 1.0], [0.0, 1.0, 0.0], ]) nodes2 = np.asfortranarray([ [0.0, 1.0], [0.5, 0.5], ]) .. doctest:: newton-refine3-continued >>> s1 = t1 = 0.5 - 0.5**27 >>> np.log2(0.5 - s1) -27.0 >>> s2, t2 = newton_refine(s1, nodes1, t1, nodes2) >>> s2 == t2 True >>> np.log2(0.5 - s2) -28.0 >>> s3, t3 = newton_refine(s2, nodes1, t2, nodes2) >>> s3 == t3 == s2 True Due to round-off near the point of tangency, the final error resembles :math:`\sqrt{\varepsilon}` rather than machine precision as expected. .. note:: The following is not implemented in this function. It's just an exploration on how the shortcomings might be addressed. However, this can be overcome. At the point of tangency, we want :math:`B_1'(s) \parallel B_2'(t)`. This can be checked numerically via .. math:: B_1'(s) \times B_2'(t) = 0. For the last example (the one that converges linearly), this is .. math:: 0 = \left[\begin{array}{c} 1 \\ 2 - 4s \end{array}\right] \times \left[\begin{array}{c} 1 \\ 0 \end{array}\right] = 4 s - 2. With this, we can modify Newton's method to find a zero of the over-determined system .. math:: G(s, t) = \left[\begin{array}{c} B_0(s) - B_1(t) \\ B_1'(s) \times B_2'(t) \end{array}\right] = \left[\begin{array}{c} s - t \\ 2 s (1 - s) - \frac{1}{2} \\ 4 s - 2\end{array}\right]. Since :math:`DG` is :math:`3 \times 2`, we can't invert it. However, we can find a least-squares solution: .. math:: \left(DG^T DG\right) \left[\begin{array}{c} \Delta s \\ \Delta t \end{array}\right] = -DG^T G. This only works if :math:`DG` has full rank. In this case, it does since the submatrix containing the first and last rows has rank two: .. math:: DG = \left[\begin{array}{c c} 1 & -1 \\ 2 - 4 s & 0 \\ 4 & 0 \end{array}\right]. Though this avoids a singular system, the normal equations have a condition number that is the square of the condition number of the matrix. Starting from :math:`s = t = \frac{3}{8}` as above: .. testsetup:: newton-refine4 import numpy as np from bezier import _helpers def modified_update(s, t): minus_G = np.asfortranarray([ [t - s], [0.5 - 2.0 * s * (1.0 - s)], [2.0 - 4.0 * s], ]) DG = np.asfortranarray([ [1.0, -1.0], [2.0 - 4.0 * s, 0.0], [4.0, 0.0], ]) DG_t = np.asfortranarray(DG.T) LHS = _helpers.matrix_product(DG_t, DG) RHS = _helpers.matrix_product(DG_t, minus_G) delta_params = np.linalg.solve(LHS, RHS) delta_s, delta_t = delta_params.flatten() return s + delta_s, t + delta_t .. doctest:: newton-refine4 >>> s0, t0 = 0.375, 0.375 >>> np.log2(0.5 - s0) -3.0 >>> s1, t1 = modified_update(s0, t0) >>> s1 == t1 True >>> 1040.0 * s1 519.0 >>> np.log2(0.5 - s1) -10.022... >>> s2, t2 = modified_update(s1, t1) >>> s2 == t2 True >>> np.log2(0.5 - s2) -31.067... >>> s3, t3 = modified_update(s2, t2) >>> s3 == t3 == 0.5 True Args: s (float): Parameter of a near-intersection along the first curve. nodes1 (numpy.ndarray): Nodes of first curve forming intersection. t (float): Parameter of a near-intersection along the second curve. nodes2 (numpy.ndarray): Nodes of second curve forming intersection. Returns: Tuple[float, float]: The refined parameters from a single Newton step. Raises: ValueError: If the Jacobian is singular at ``(s, t)``.
[ "r", "Apply", "one", "step", "of", "2D", "Newton", "s", "method", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L67-L427
train
54,138
dhermes/bezier
src/bezier/_intersection_helpers.py
newton_iterate
def newton_iterate(evaluate_fn, s, t): r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped. """ # Several quantities will be tracked throughout the iteration: # * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}|| # * norm_update : ||p{n+1} - p{n} || = ||dp{n} || # * linear_updates : This is a count on the number of times that # ``dp{n}`` "looks like" ``dp{n-1}`` (i.e. # is within a constant factor of it). norm_update_prev = None norm_update = None linear_updates = 0 # Track the number of "linear" updates. current_s = s current_t = t for index in six.moves.xrange(MAX_NEWTON_ITERATIONS): jacobian, func_val = evaluate_fn(current_s, current_t) if jacobian is None: return True, current_s, current_t singular, delta_s, delta_t = _helpers.solve2x2( jacobian, func_val[:, 0] ) if singular: break norm_update_prev = norm_update norm_update = np.linalg.norm([delta_s, delta_t], ord=2) # If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means # our convergence is acting linear at the current step. if index > 0 and norm_update > 0.25 * norm_update_prev: linear_updates += 1 # If ``>=2/3`` of the updates have been linear, we are near a # non-simple root. (Make sure at least 5 updates have occurred.) if index >= 4 and 3 * linear_updates >= 2 * index: break # Determine the norm of the "old" solution before updating. norm_soln = np.linalg.norm([current_s, current_t], ord=2) current_s -= delta_s current_t -= delta_t if norm_update < NEWTON_ERROR_RATIO * norm_soln: return True, current_s, current_t return False, current_s, current_t
python
def newton_iterate(evaluate_fn, s, t): r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped. """ # Several quantities will be tracked throughout the iteration: # * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}|| # * norm_update : ||p{n+1} - p{n} || = ||dp{n} || # * linear_updates : This is a count on the number of times that # ``dp{n}`` "looks like" ``dp{n-1}`` (i.e. # is within a constant factor of it). norm_update_prev = None norm_update = None linear_updates = 0 # Track the number of "linear" updates. current_s = s current_t = t for index in six.moves.xrange(MAX_NEWTON_ITERATIONS): jacobian, func_val = evaluate_fn(current_s, current_t) if jacobian is None: return True, current_s, current_t singular, delta_s, delta_t = _helpers.solve2x2( jacobian, func_val[:, 0] ) if singular: break norm_update_prev = norm_update norm_update = np.linalg.norm([delta_s, delta_t], ord=2) # If ||p{n} - p{n-1}|| > 0.25 ||p{n-1} - p{n-2}||, then that means # our convergence is acting linear at the current step. if index > 0 and norm_update > 0.25 * norm_update_prev: linear_updates += 1 # If ``>=2/3`` of the updates have been linear, we are near a # non-simple root. (Make sure at least 5 updates have occurred.) if index >= 4 and 3 * linear_updates >= 2 * index: break # Determine the norm of the "old" solution before updating. norm_soln = np.linalg.norm([current_s, current_t], ord=2) current_s -= delta_s current_t -= delta_t if norm_update < NEWTON_ERROR_RATIO * norm_soln: return True, current_s, current_t return False, current_s, current_t
[ "def", "newton_iterate", "(", "evaluate_fn", ",", "s", ",", "t", ")", ":", "# Several quantities will be tracked throughout the iteration:", "# * norm_update_prev: ||p{n} - p{n-1}|| = ||dp{n-1}||", "# * norm_update : ||p{n+1} - p{n} || = ||dp{n} ||", "# * linear_updates : This is ...
r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used below: * :math:`10` (:attr:`MAX_NEWTON_ITERATIONS`) iterations will be done before "giving up". This is based on the assumption that we are already starting near a root, so quadratic convergence should terminate quickly. * :math:`\tau = \frac{1}{4}` is used as the boundary between linear and superlinear convergence. So if the current error :math:`\|p_{n + 1} - p_n\|` is not smaller than :math:`\tau` times the previous error :math:`\|p_n - p_{n - 1}\|`, then convergence is considered to be linear at that point. * :math:`\frac{2}{3}` of all iterations must be converging linearly for convergence to be stopped (and moved to the next regime). This will only be checked after 4 or more updates have occurred. * :math:`\tau = 2^{-42}` (:attr:`NEWTON_ERROR_RATIO`) is used to determine that an update is sufficiently small to stop iterating. So if the error :math:`\|p_{n + 1} - p_n\|` smaller than :math:`\tau` times size of the term being updated :math:`\|p_n\|`, then we exit with the "correct" answer. It is assumed that ``evaluate_fn`` will use a Jacobian return value of :data:`None` to indicate that :math:`F(s, t)` is exactly ``0.0``. We **assume** that if the function evaluates to exactly ``0.0``, then we are at a solution. It is possible however, that badly parameterized curves can evaluate to exactly ``0.0`` for inputs that are relatively far away from a solution (see issue #21). Args: evaluate_fn (Callable[Tuple[float, float], tuple]): A callable which takes :math:`s` and :math:`t` and produces an evaluated function value and the Jacobian matrix. s (float): The (first) parameter where the iteration will start. t (float): The (second) parameter where the iteration will start. Returns: Tuple[bool, float, float]: The triple of * Flag indicating if the iteration converged. * The current :math:`s` value when the iteration stopped. * The current :math:`t` value when the iteration stopped.
[ "r", "Perform", "a", "Newton", "iteration", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_intersection_helpers.py#L645-L732
train
54,139
dhermes/bezier
setup_helpers.py
gfortran_search_path
def gfortran_search_path(library_dirs): """Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``. """ cmd = ("gfortran", "-print-search-dirs") process = subprocess.Popen(cmd, stdout=subprocess.PIPE) return_code = process.wait() # Bail out if the command failed. if return_code != 0: return library_dirs cmd_output = process.stdout.read().decode("utf-8") # Find single line starting with ``libraries: ``. search_lines = cmd_output.strip().split("\n") library_lines = [ line[len(FORTRAN_LIBRARY_PREFIX) :] for line in search_lines if line.startswith(FORTRAN_LIBRARY_PREFIX) ] if len(library_lines) != 1: msg = GFORTRAN_MISSING_LIBS.format(cmd_output) print(msg, file=sys.stderr) return library_dirs # Go through each library in the ``libraries: = ...`` line. library_line = library_lines[0] accepted = set(library_dirs) for part in library_line.split(os.pathsep): full_path = os.path.abspath(part.strip()) if os.path.isdir(full_path): accepted.add(full_path) else: # Ignore anything that isn't a directory. msg = GFORTRAN_BAD_PATH.format(full_path) print(msg, file=sys.stderr) return sorted(accepted)
python
def gfortran_search_path(library_dirs): """Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``. """ cmd = ("gfortran", "-print-search-dirs") process = subprocess.Popen(cmd, stdout=subprocess.PIPE) return_code = process.wait() # Bail out if the command failed. if return_code != 0: return library_dirs cmd_output = process.stdout.read().decode("utf-8") # Find single line starting with ``libraries: ``. search_lines = cmd_output.strip().split("\n") library_lines = [ line[len(FORTRAN_LIBRARY_PREFIX) :] for line in search_lines if line.startswith(FORTRAN_LIBRARY_PREFIX) ] if len(library_lines) != 1: msg = GFORTRAN_MISSING_LIBS.format(cmd_output) print(msg, file=sys.stderr) return library_dirs # Go through each library in the ``libraries: = ...`` line. library_line = library_lines[0] accepted = set(library_dirs) for part in library_line.split(os.pathsep): full_path = os.path.abspath(part.strip()) if os.path.isdir(full_path): accepted.add(full_path) else: # Ignore anything that isn't a directory. msg = GFORTRAN_BAD_PATH.format(full_path) print(msg, file=sys.stderr) return sorted(accepted)
[ "def", "gfortran_search_path", "(", "library_dirs", ")", ":", "cmd", "=", "(", "\"gfortran\"", ",", "\"-print-search-dirs\"", ")", "process", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "return_code", "=", ...
Get the library directory paths for ``gfortran``. Looks for ``libraries: =`` in the output of ``gfortran -print-search-dirs`` and then parses the paths. If this fails for any reason, this method will print an error and return ``library_dirs``. Args: library_dirs (List[str]): Existing library directories. Returns: List[str]: The library directories for ``gfortran``.
[ "Get", "the", "library", "directory", "paths", "for", "gfortran", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L96-L140
train
54,140
dhermes/bezier
setup_helpers.py
_update_flags
def _update_flags(compiler_flags, remove_flags=()): """Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed). """ for flag in GFORTRAN_SHARED_FLAGS: if flag not in compiler_flags: compiler_flags.append(flag) if DEBUG_ENV in os.environ: to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else: to_add = GFORTRAN_OPTIMIZE_FLAGS if os.environ.get(WHEEL_ENV) is None: to_add += (GFORTRAN_NATIVE_FLAG,) to_remove = GFORTRAN_DEBUG_FLAGS for flag in to_add: if flag not in compiler_flags: compiler_flags.append(flag) return [ flag for flag in compiler_flags if not (flag in to_remove or flag in remove_flags) ]
python
def _update_flags(compiler_flags, remove_flags=()): """Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed). """ for flag in GFORTRAN_SHARED_FLAGS: if flag not in compiler_flags: compiler_flags.append(flag) if DEBUG_ENV in os.environ: to_add = GFORTRAN_DEBUG_FLAGS to_remove = GFORTRAN_OPTIMIZE_FLAGS else: to_add = GFORTRAN_OPTIMIZE_FLAGS if os.environ.get(WHEEL_ENV) is None: to_add += (GFORTRAN_NATIVE_FLAG,) to_remove = GFORTRAN_DEBUG_FLAGS for flag in to_add: if flag not in compiler_flags: compiler_flags.append(flag) return [ flag for flag in compiler_flags if not (flag in to_remove or flag in remove_flags) ]
[ "def", "_update_flags", "(", "compiler_flags", ",", "remove_flags", "=", "(", ")", ")", ":", "for", "flag", "in", "GFORTRAN_SHARED_FLAGS", ":", "if", "flag", "not", "in", "compiler_flags", ":", "compiler_flags", ".", "append", "(", "flag", ")", "if", "DEBUG_...
Update a given set of compiler flags. Args: compiler_flags (List[str]): Existing flags associated with a compiler. remove_flags (Optional[Container[str]]): A container of flags to remove that will override any of the defaults. Returns: List[str]: The modified list (i.e. some flags added and some removed).
[ "Update", "a", "given", "set", "of", "compiler", "flags", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L178-L207
train
54,141
dhermes/bezier
setup_helpers.py
patch_f90_compiler
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure in ``setup.py``. from numpy.distutils.fcompiler import gnu # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False f90_compiler.compiler_f77[:] = _update_flags( f90_compiler.compiler_f77, remove_flags=("-Werror",) ) f90_compiler.compiler_f90[:] = _update_flags(f90_compiler.compiler_f90)
python
def patch_f90_compiler(f90_compiler): """Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance. """ # NOTE: NumPy may not be installed, but we don't want **this** module to # cause an import failure in ``setup.py``. from numpy.distutils.fcompiler import gnu # Only ``gfortran``. if not isinstance(f90_compiler, gnu.Gnu95FCompiler): return False f90_compiler.compiler_f77[:] = _update_flags( f90_compiler.compiler_f77, remove_flags=("-Werror",) ) f90_compiler.compiler_f90[:] = _update_flags(f90_compiler.compiler_f90)
[ "def", "patch_f90_compiler", "(", "f90_compiler", ")", ":", "# NOTE: NumPy may not be installed, but we don't want **this** module to", "# cause an import failure in ``setup.py``.", "from", "numpy", ".", "distutils", ".", "fcompiler", "import", "gnu", "# Only ``gfortran``.", ...
Patch up ``f90_compiler``. For now, only updates the flags for ``gfortran``. In this case, it add any of ``GFORTRAN_SHARED_FLAGS`` that are missing. In debug mode, it also adds any flags in ``GFORTRAN_DEBUG_FLAGS`` and makes sure none of the flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present. In standard mode ("OPTIMIZE"), makes sure flags in ``GFORTRAN_OPTIMIZE_FLAGS`` are present and flags in ``GFORTRAN_DEBUG_FLAGS`` are not. Args: f90_compiler (numpy.distutils.fcompiler.FCompiler): A Fortran compiler instance.
[ "Patch", "up", "f90_compiler", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L210-L235
train
54,142
dhermes/bezier
setup_helpers.py
BuildFortranThenExt.start_journaling
def start_journaling(self): """Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute. """ import numpy.distutils.ccompiler if self.journal_file is None: return def journaled_spawn(patched_self, cmd, display=None): self.commands.append(cmd) return numpy.distutils.ccompiler.CCompiler_spawn( patched_self, cmd, display=None ) numpy.distutils.ccompiler.replace_method( distutils.ccompiler.CCompiler, "spawn", journaled_spawn )
python
def start_journaling(self): """Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute. """ import numpy.distutils.ccompiler if self.journal_file is None: return def journaled_spawn(patched_self, cmd, display=None): self.commands.append(cmd) return numpy.distutils.ccompiler.CCompiler_spawn( patched_self, cmd, display=None ) numpy.distutils.ccompiler.replace_method( distutils.ccompiler.CCompiler, "spawn", journaled_spawn )
[ "def", "start_journaling", "(", "self", ")", ":", "import", "numpy", ".", "distutils", ".", "ccompiler", "if", "self", ".", "journal_file", "is", "None", ":", "return", "def", "journaled_spawn", "(", "patched_self", ",", "cmd", ",", "display", "=", "None", ...
Capture calls to the system by compilers. See: https://github.com/numpy/numpy/blob/v1.15.2/\ numpy/distutils/ccompiler.py#L154 Intercepts all calls to ``CCompiler.spawn`` and keeps the arguments around to be stored in the local ``commands`` instance attribute.
[ "Capture", "calls", "to", "the", "system", "by", "compilers", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L321-L344
train
54,143
dhermes/bezier
setup_helpers.py
BuildFortranThenExt.save_journal
def save_journal(self): """Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully. """ if self.journal_file is None: return try: as_text = self._commands_to_text() with open(self.journal_file, "w") as file_obj: file_obj.write(as_text) except Exception as exc: msg = BAD_JOURNAL.format(exc) print(msg, file=sys.stderr)
python
def save_journal(self): """Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully. """ if self.journal_file is None: return try: as_text = self._commands_to_text() with open(self.journal_file, "w") as file_obj: file_obj.write(as_text) except Exception as exc: msg = BAD_JOURNAL.format(exc) print(msg, file=sys.stderr)
[ "def", "save_journal", "(", "self", ")", ":", "if", "self", ".", "journal_file", "is", "None", ":", "return", "try", ":", "as_text", "=", "self", ".", "_commands_to_text", "(", ")", "with", "open", "(", "self", ".", "journal_file", ",", "\"w\"", ")", "...
Save journaled commands to file. If there is no active journal, does nothing. If saving the commands to a file fails, a message will be printed to STDERR but the failure will be swallowed so that the extension can be built successfully.
[ "Save", "journaled", "commands", "to", "file", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/setup_helpers.py#L368-L386
train
54,144
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon._verify_pair
def _verify_pair(prev, curr): """Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if prev._dimension != 2: raise ValueError("Curve not in R^2", prev) end = prev._nodes[:, -1] start = curr._nodes[:, 0] if not _helpers.vector_close(end, start): raise ValueError( "Not sufficiently close", "Consecutive sides do not have common endpoint", prev, curr, )
python
def _verify_pair(prev, curr): """Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if prev._dimension != 2: raise ValueError("Curve not in R^2", prev) end = prev._nodes[:, -1] start = curr._nodes[:, 0] if not _helpers.vector_close(end, start): raise ValueError( "Not sufficiently close", "Consecutive sides do not have common endpoint", prev, curr, )
[ "def", "_verify_pair", "(", "prev", ",", "curr", ")", ":", "if", "prev", ".", "_dimension", "!=", "2", ":", "raise", "ValueError", "(", "\"Curve not in R^2\"", ",", "prev", ")", "end", "=", "prev", ".", "_nodes", "[", ":", ",", "-", "1", "]", "start"...
Verify a pair of sides share an endpoint. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Args: prev (.Curve): "Previous" curve at piecewise junction. curr (.Curve): "Next" curve at piecewise junction. Raises: ValueError: If the previous side is not in 2D. ValueError: If consecutive sides don't share an endpoint.
[ "Verify", "a", "pair", "of", "sides", "share", "an", "endpoint", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L146-L173
train
54,145
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon._verify
def _verify(self): """Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if self._num_sides < 2: raise ValueError("At least two sides required.") for prev, curr in six.moves.zip(self._edges, self._edges[1:]): self._verify_pair(prev, curr) # Now we check that the final edge wraps around. prev = self._edges[-1] curr = self._edges[0] self._verify_pair(prev, curr)
python
def _verify(self): """Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint. """ if self._num_sides < 2: raise ValueError("At least two sides required.") for prev, curr in six.moves.zip(self._edges, self._edges[1:]): self._verify_pair(prev, curr) # Now we check that the final edge wraps around. prev = self._edges[-1] curr = self._edges[0] self._verify_pair(prev, curr)
[ "def", "_verify", "(", "self", ")", ":", "if", "self", ".", "_num_sides", "<", "2", ":", "raise", "ValueError", "(", "\"At least two sides required.\"", ")", "for", "prev", ",", "curr", "in", "six", ".", "moves", ".", "zip", "(", "self", ".", "_edges", ...
Verify that the edges define a curved polygon. This may not be entirely comprehensive, e.g. won't check self-intersection of the defined polygon. .. note:: This currently checks that edge endpoints match **exactly** but allowing some roundoff may be desired. Raises: ValueError: If there are fewer than two sides. ValueError: If one of the sides is not in 2D. ValueError: If consecutive sides don't share an endpoint.
[ "Verify", "that", "the", "edges", "define", "a", "curved", "polygon", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L175-L199
train
54,146
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon.area
def area(self): r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon. """ edges = tuple(edge._nodes for edge in self._edges) return _surface_helpers.compute_area(edges)
python
def area(self): r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon. """ edges = tuple(edge._nodes for edge in self._edges) return _surface_helpers.compute_area(edges)
[ "def", "area", "(", "self", ")", ":", "edges", "=", "tuple", "(", "edge", ".", "_nodes", "for", "edge", "in", "self", ".", "_edges", ")", "return", "_surface_helpers", ".", "compute_area", "(", "edges", ")" ]
r"""The area of the current curved polygon. This assumes, but does not check, that the current curved polygon is valid (i.e. it is bounded by the edges). This computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says .. math:: \int_{\mathcal{P}} 2 \, d\textbf{x} = \int_{\partial \mathcal{P}} -y \, dx + x \, dy (where :math:`\mathcal{P}` is the current curved polygon). Note that for a given edge :math:`C(r)` with control points :math:`x_j, y_j`, the integral can be simplified: .. math:: \int_C -y \, dx + x \, dy = \int_0^1 (x y' - y x') \, dr = \sum_{i < j} (x_i y_j - y_i x_j) \int_0^1 b_{i, d} b'_{j, d} \, dr where :math:`b_{i, d}, b_{j, d}` are Bernstein basis polynomials. Returns: float: The area of the current curved polygon.
[ "r", "The", "area", "of", "the", "current", "curved", "polygon", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L220-L252
train
54,147
dhermes/bezier
src/bezier/curved_polygon.py
CurvedPolygon.plot
def plot(self, pts_per_edge, color=None, ax=None): """Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. 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. """ if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges) return ax
python
def plot(self, pts_per_edge, color=None, ax=None): """Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. 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. """ if ax is None: ax = _plot_helpers.new_axis() _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges) return ax
[ "def", "plot", "(", "self", ",", "pts_per_edge", ",", "color", "=", "None", ",", "ax", "=", "None", ")", ":", "if", "ax", "is", "None", ":", "ax", "=", "_plot_helpers", ".", "new_axis", "(", ")", "_plot_helpers", ".", "add_patch", "(", "ax", ",", "...
Plot the current curved polygon. Args: pts_per_edge (int): Number of points to plot per curved edge. color (Optional[Tuple[float, float, float]]): Color as RGB profile. 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.
[ "Plot", "the", "current", "curved", "polygon", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/curved_polygon.py#L264-L280
train
54,148
dhermes/bezier
src/bezier/_clipping.py
compute_implicit_line
def compute_implicit_line(nodes): """Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` """ delta = nodes[:, -1] - nodes[:, 0] length = np.linalg.norm(delta, ord=2) # Normalize and rotate 90 degrees to the "left". coeff_a = -delta[1] / length coeff_b = delta[0] / length # c = - ax - by = (delta[1] x - delta[0] y) / L # NOTE: We divide by ``length`` at the end to "put off" rounding. coeff_c = (delta[1] * nodes[0, 0] - delta[0] * nodes[1, 0]) / length return coeff_a, coeff_b, coeff_c
python
def compute_implicit_line(nodes): """Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` """ delta = nodes[:, -1] - nodes[:, 0] length = np.linalg.norm(delta, ord=2) # Normalize and rotate 90 degrees to the "left". coeff_a = -delta[1] / length coeff_b = delta[0] / length # c = - ax - by = (delta[1] x - delta[0] y) / L # NOTE: We divide by ``length`` at the end to "put off" rounding. coeff_c = (delta[1] * nodes[0, 0] - delta[0] * nodes[1, 0]) / length return coeff_a, coeff_b, coeff_c
[ "def", "compute_implicit_line", "(", "nodes", ")", ":", "delta", "=", "nodes", "[", ":", ",", "-", "1", "]", "-", "nodes", "[", ":", ",", "0", "]", "length", "=", "np", ".", "linalg", ".", "norm", "(", "delta", ",", "ord", "=", "2", ")", "# Nor...
Compute the implicit form of the line connecting curve endpoints. .. note:: This assumes, but does not check, that the first and last nodes in ``nodes`` are different. Computes :math:`a, b` and :math:`c` in the normalized implicit equation for the line .. math:: ax + by + c = 0 where :math:`a^2 + b^2 = 1` (only unique up to sign). Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. The line will be (directed) from the first to last node in ``nodes``. Returns: Tuple[float, float, float]: The triple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c`
[ "Compute", "the", "implicit", "form", "of", "the", "line", "connecting", "curve", "endpoints", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L41-L78
train
54,149
dhermes/bezier
src/bezier/_clipping.py
compute_fat_line
def compute_fat_line(nodes): """Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points. """ coeff_a, coeff_b, coeff_c = compute_implicit_line(nodes) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes = nodes.shape d_min = 0.0 d_max = 0.0 for index in six.moves.xrange(1, num_nodes - 1): # Only interior nodes. curr_dist = ( coeff_a * nodes[0, index] + coeff_b * nodes[1, index] + coeff_c ) if curr_dist < d_min: d_min = curr_dist elif curr_dist > d_max: d_max = curr_dist return coeff_a, coeff_b, coeff_c, d_min, d_max
python
def compute_fat_line(nodes): """Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points. """ coeff_a, coeff_b, coeff_c = compute_implicit_line(nodes) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes = nodes.shape d_min = 0.0 d_max = 0.0 for index in six.moves.xrange(1, num_nodes - 1): # Only interior nodes. curr_dist = ( coeff_a * nodes[0, index] + coeff_b * nodes[1, index] + coeff_c ) if curr_dist < d_min: d_min = curr_dist elif curr_dist > d_max: d_max = curr_dist return coeff_a, coeff_b, coeff_c, d_min, d_max
[ "def", "compute_fat_line", "(", "nodes", ")", ":", "coeff_a", ",", "coeff_b", ",", "coeff_c", "=", "compute_implicit_line", "(", "nodes", ")", "# NOTE: This assumes, but does not check, that there are two rows.", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "d_m...
Compute the "fat line" around a B |eacute| zier curve. Both computes the implicit (normalized) form .. math:: ax + by + c = 0 for the line connecting the first and last node in ``nodes``. Also computes the maximum and minimum distances to that line from each control point. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. Returns: Tuple[float, float, float, float, float]: The 5-tuple of * The :math:`x` coefficient :math:`a` * The :math:`y` coefficient :math:`b` * The constant :math:`c` * The "minimum" distance to the fat line among the control points. * The "maximum" distance to the fat line among the control points.
[ "Compute", "the", "fat", "line", "around", "a", "B", "|eacute|", "zier", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L81-L119
train
54,150
dhermes/bezier
src/bezier/_clipping.py
_update_parameters
def _update_parameters(s_min, s_max, start0, end0, start1, end1): """Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.) """ s, t, success = _geometric_intersection.segment_intersection( start0, end0, start1, end1 ) if not success: raise NotImplementedError(NO_PARALLEL) if _helpers.in_interval(t, 0.0, 1.0): if _helpers.in_interval(s, 0.0, s_min): return s, s_max elif _helpers.in_interval(s, s_max, 1.0): return s_min, s return s_min, s_max
python
def _update_parameters(s_min, s_max, start0, end0, start1, end1): """Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.) """ s, t, success = _geometric_intersection.segment_intersection( start0, end0, start1, end1 ) if not success: raise NotImplementedError(NO_PARALLEL) if _helpers.in_interval(t, 0.0, 1.0): if _helpers.in_interval(s, 0.0, s_min): return s, s_max elif _helpers.in_interval(s, s_max, 1.0): return s_min, s return s_min, s_max
[ "def", "_update_parameters", "(", "s_min", ",", "s_max", ",", "start0", ",", "end0", ",", "start1", ",", "end1", ")", ":", "s", ",", "t", ",", "success", "=", "_geometric_intersection", ".", "segment_intersection", "(", "start0", ",", "end0", ",", "start1"...
Update clipped parameter range. .. note:: This is a helper for :func:`clip_range`. Does so by intersecting one of the two fat lines with an edge of the convex hull of the distance polynomial of the curve being clipped. If both of ``s_min`` and ``s_max`` are "unset", then any :math:`s` value that is valid for ``s_min`` would also be valid for ``s_max``. Rather than adding a special case to handle this scenario, **only** ``s_min`` will be updated. In cases where a given parameter :math:`s` would be a valid update for both ``s_min`` and ``s_max`` This function **only** updates ``s_min`` Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of one of the two fat lines. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of one of the two fat lines. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector of an edge of the convex hull of the distance polynomial :math:`d(t)` as an explicit B |eacute| zier curve. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. Raises: NotImplementedError: If the two line segments are parallel. (This case will be supported at some point, just not now.)
[ "Update", "clipped", "parameter", "range", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L122-L179
train
54,151
dhermes/bezier
src/bezier/_clipping.py
_check_parameter_range
def _check_parameter_range(s_min, s_max): r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. """ if s_min == DEFAULT_S_MIN: # Based on the way ``_update_parameters`` works, we know # both parameters must be unset if ``s_min``. return 0.0, 1.0 if s_max == DEFAULT_S_MAX: return s_min, s_min return s_min, s_max
python
def _check_parameter_range(s_min, s_max): r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range. """ if s_min == DEFAULT_S_MIN: # Based on the way ``_update_parameters`` works, we know # both parameters must be unset if ``s_min``. return 0.0, 1.0 if s_max == DEFAULT_S_MAX: return s_min, s_min return s_min, s_max
[ "def", "_check_parameter_range", "(", "s_min", ",", "s_max", ")", ":", "if", "s_min", "==", "DEFAULT_S_MIN", ":", "# Based on the way ``_update_parameters`` works, we know", "# both parameters must be unset if ``s_min``.", "return", "0.0", ",", "1.0", "if", "s_max", "==", ...
r"""Performs a final check on a clipped parameter range. .. note:: This is a helper for :func:`clip_range`. If both values are unchanged from the "unset" default, this returns the whole interval :math:`\left[0.0, 1.0\right]`. If only one of the values is set to some parameter :math:`s`, this returns the "degenerate" interval :math:`\left[s, s\right]`. (We rely on the fact that ``s_min`` must be the only set value, based on how :func:`_update_parameters` works.) Otherwise, this simply returns ``[s_min, s_max]``. Args: s_min (float): Current start of clipped interval. If "unset", this value will be ``DEFAULT_S_MIN``. s_max (float): Current end of clipped interval. If "unset", this value will be ``DEFAULT_S_MAX``. Returns: Tuple[float, float]: The (possibly updated) start and end of the clipped parameter range.
[ "r", "Performs", "a", "final", "check", "on", "a", "clipped", "parameter", "range", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L182-L217
train
54,152
dhermes/bezier
src/bezier/_clipping.py
clip_range
def clip_range(nodes1, nodes2): r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals coeff_a, coeff_b, coeff_c, d_min, d_max = compute_fat_line(nodes1) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes2 = nodes2.shape polynomial = np.empty((2, num_nodes2), order="F") denominator = float(num_nodes2 - 1) for index in six.moves.xrange(num_nodes2): polynomial[0, index] = index / denominator polynomial[1, index] = ( coeff_a * nodes2[0, index] + coeff_b * nodes2[1, index] + coeff_c ) # Define segments for the top and the bottom of the region # bounded by the fat line. start_bottom = np.asfortranarray([0.0, d_min]) end_bottom = np.asfortranarray([1.0, d_min]) start_top = np.asfortranarray([0.0, d_max]) end_top = np.asfortranarray([1.0, d_max]) s_min = DEFAULT_S_MIN s_max = DEFAULT_S_MAX # NOTE: We avoid computing the convex hull and just compute where # all segments connecting two control points intersect the # fat lines. for start_index in six.moves.xrange(num_nodes2 - 1): for end_index in six.moves.xrange(start_index + 1, num_nodes2): s_min, s_max = _update_parameters( s_min, s_max, start_bottom, end_bottom, polynomial[:, start_index], polynomial[:, end_index], ) s_min, s_max = _update_parameters( s_min, s_max, start_top, end_top, polynomial[:, start_index], polynomial[:, end_index], ) return _check_parameter_range(s_min, s_max)
python
def clip_range(nodes1, nodes2): r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-locals coeff_a, coeff_b, coeff_c, d_min, d_max = compute_fat_line(nodes1) # NOTE: This assumes, but does not check, that there are two rows. _, num_nodes2 = nodes2.shape polynomial = np.empty((2, num_nodes2), order="F") denominator = float(num_nodes2 - 1) for index in six.moves.xrange(num_nodes2): polynomial[0, index] = index / denominator polynomial[1, index] = ( coeff_a * nodes2[0, index] + coeff_b * nodes2[1, index] + coeff_c ) # Define segments for the top and the bottom of the region # bounded by the fat line. start_bottom = np.asfortranarray([0.0, d_min]) end_bottom = np.asfortranarray([1.0, d_min]) start_top = np.asfortranarray([0.0, d_max]) end_top = np.asfortranarray([1.0, d_max]) s_min = DEFAULT_S_MIN s_max = DEFAULT_S_MAX # NOTE: We avoid computing the convex hull and just compute where # all segments connecting two control points intersect the # fat lines. for start_index in six.moves.xrange(num_nodes2 - 1): for end_index in six.moves.xrange(start_index + 1, num_nodes2): s_min, s_max = _update_parameters( s_min, s_max, start_bottom, end_bottom, polynomial[:, start_index], polynomial[:, end_index], ) s_min, s_max = _update_parameters( s_min, s_max, start_top, end_top, polynomial[:, start_index], polynomial[:, end_index], ) return _check_parameter_range(s_min, s_max)
[ "def", "clip_range", "(", "nodes1", ",", "nodes2", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-locals", "coeff_a", ",", "coeff_b", ",", "coeff_c", ",", "d_min", ",", "d_max...
r"""Reduce the parameter range where two curves can intersect. Does so by using the "fat line" for ``nodes1`` and computing the distance polynomial against ``nodes2``. .. note:: This assumes, but does not check that the curves being considered will only have one intersection in the parameter ranges :math:`s \in \left[0, 1\right]`, :math:`t \in \left[0, 1\right]`. This assumption is based on the fact that B |eacute| zier clipping is meant to be used to find tangent intersections for already subdivided (i.e. sufficiently zoomed in) curve segments. Args: nodes1 (numpy.ndarray): ``2 x N1`` array of nodes in a curve which will define the clipping region. nodes2 (numpy.ndarray): ``2 x N2`` array of nodes in a curve which will be clipped. Returns: Tuple[float, float]: The pair of * The start parameter of the clipped range. * The end parameter of the clipped range.
[ "r", "Reduce", "the", "parameter", "range", "where", "two", "curves", "can", "intersect", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_clipping.py#L220-L289
train
54,153
dhermes/bezier
scripts/post_process_journal.py
post_process_travis_macos
def post_process_travis_macos(journal_filename): """Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file. """ travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "") with open(journal_filename, "r") as file_obj: content = file_obj.read() processed = content.replace(travis_build_dir, "${TRAVIS_BUILD_DIR}") with open(journal_filename, "w") as file_obj: file_obj.write(processed)
python
def post_process_travis_macos(journal_filename): """Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file. """ travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "") with open(journal_filename, "r") as file_obj: content = file_obj.read() processed = content.replace(travis_build_dir, "${TRAVIS_BUILD_DIR}") with open(journal_filename, "w") as file_obj: file_obj.write(processed)
[ "def", "post_process_travis_macos", "(", "journal_filename", ")", ":", "travis_build_dir", "=", "os", ".", "environ", ".", "get", "(", "\"TRAVIS_BUILD_DIR\"", ",", "\"\"", ")", "with", "open", "(", "journal_filename", ",", "\"r\"", ")", "as", "file_obj", ":", ...
Post-process a generated journal file on Travis macOS. Args: journal_filename (str): The name of the journal file.
[ "Post", "-", "process", "a", "generated", "journal", "file", "on", "Travis", "macOS", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/post_process_journal.py#L23-L34
train
54,154
dhermes/bezier
scripts/check_doc_templates.py
get_diff
def get_diff(value1, value2, name1, name2): """Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff. """ lines1 = [line + "\n" for line in value1.splitlines()] lines2 = [line + "\n" for line in value2.splitlines()] diff_lines = difflib.context_diff( lines1, lines2, fromfile=name1, tofile=name2 ) return "".join(diff_lines)
python
def get_diff(value1, value2, name1, name2): """Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff. """ lines1 = [line + "\n" for line in value1.splitlines()] lines2 = [line + "\n" for line in value2.splitlines()] diff_lines = difflib.context_diff( lines1, lines2, fromfile=name1, tofile=name2 ) return "".join(diff_lines)
[ "def", "get_diff", "(", "value1", ",", "value2", ",", "name1", ",", "name2", ")", ":", "lines1", "=", "[", "line", "+", "\"\\n\"", "for", "line", "in", "value1", ".", "splitlines", "(", ")", "]", "lines2", "=", "[", "line", "+", "\"\\n\"", "for", "...
Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff.
[ "Get", "a", "diff", "between", "two", "strings", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L245-L262
train
54,155
dhermes/bezier
scripts/check_doc_templates.py
populate_readme
def populate_readme(revision, rtd_version, **extra_kwargs): """Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected. """ with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() img_prefix = IMG_PREFIX.format(revision=revision) extra_links = EXTRA_LINKS.format( rtd_version=rtd_version, revision=revision ) docs_img = DOCS_IMG.format(rtd_version=rtd_version) bernstein_basis = BERNSTEIN_BASIS_PLAIN.format(img_prefix=img_prefix) bezier_defn = BEZIER_DEFN_PLAIN.format(img_prefix=img_prefix) sum_to_unity = SUM_TO_UNITY_PLAIN.format(img_prefix=img_prefix) template_kwargs = { "code_block1": PLAIN_CODE_BLOCK, "code_block2": PLAIN_CODE_BLOCK, "code_block3": PLAIN_CODE_BLOCK, "testcleanup": "", "toctree": "", "bernstein_basis": bernstein_basis, "bezier_defn": bezier_defn, "sum_to_unity": sum_to_unity, "img_prefix": img_prefix, "extra_links": extra_links, "docs": "|docs| ", "docs_img": docs_img, "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": rtd_version, "revision": revision, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) readme_contents = template.format(**template_kwargs) # Apply regular expressions to convert Sphinx "roles" to plain reST. readme_contents = INLINE_MATH_EXPR.sub(inline_math, readme_contents) sphinx_modules = [] to_replace = functools.partial(mod_replace, sphinx_modules=sphinx_modules) readme_contents = MOD_EXPR.sub(to_replace, readme_contents) if sphinx_modules != ["bezier.curve", "bezier.surface"]: raise ValueError("Unexpected sphinx_modules", sphinx_modules) sphinx_docs = [] to_replace = functools.partial(doc_replace, sphinx_docs=sphinx_docs) readme_contents = DOC_EXPR.sub(to_replace, readme_contents) if sphinx_docs != ["python/reference/bezier", "development"]: raise ValueError("Unexpected sphinx_docs", sphinx_docs) return readme_contents
python
def populate_readme(revision, rtd_version, **extra_kwargs): """Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected. """ with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() img_prefix = IMG_PREFIX.format(revision=revision) extra_links = EXTRA_LINKS.format( rtd_version=rtd_version, revision=revision ) docs_img = DOCS_IMG.format(rtd_version=rtd_version) bernstein_basis = BERNSTEIN_BASIS_PLAIN.format(img_prefix=img_prefix) bezier_defn = BEZIER_DEFN_PLAIN.format(img_prefix=img_prefix) sum_to_unity = SUM_TO_UNITY_PLAIN.format(img_prefix=img_prefix) template_kwargs = { "code_block1": PLAIN_CODE_BLOCK, "code_block2": PLAIN_CODE_BLOCK, "code_block3": PLAIN_CODE_BLOCK, "testcleanup": "", "toctree": "", "bernstein_basis": bernstein_basis, "bezier_defn": bezier_defn, "sum_to_unity": sum_to_unity, "img_prefix": img_prefix, "extra_links": extra_links, "docs": "|docs| ", "docs_img": docs_img, "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": rtd_version, "revision": revision, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) readme_contents = template.format(**template_kwargs) # Apply regular expressions to convert Sphinx "roles" to plain reST. readme_contents = INLINE_MATH_EXPR.sub(inline_math, readme_contents) sphinx_modules = [] to_replace = functools.partial(mod_replace, sphinx_modules=sphinx_modules) readme_contents = MOD_EXPR.sub(to_replace, readme_contents) if sphinx_modules != ["bezier.curve", "bezier.surface"]: raise ValueError("Unexpected sphinx_modules", sphinx_modules) sphinx_docs = [] to_replace = functools.partial(doc_replace, sphinx_docs=sphinx_docs) readme_contents = DOC_EXPR.sub(to_replace, readme_contents) if sphinx_docs != ["python/reference/bezier", "development"]: raise ValueError("Unexpected sphinx_docs", sphinx_docs) return readme_contents
[ "def", "populate_readme", "(", "revision", ",", "rtd_version", ",", "*", "*", "extra_kwargs", ")", ":", "with", "open", "(", "TEMPLATE_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "img_prefix", "=", ...
Populate README template with values. Args: revision (str): The branch, commit, etc. being referred to (e.g. ``master``). rtd_version (str): The version to use for RTD (Read the Docs) links (e.g. ``latest``). extra_kwargs (Dict[str, str]): Over-ride for template arguments. Returns: str: The populated README contents. Raises: ValueError: If the ``sphinx_modules`` encountered are not as expected. ValueError: If the ``sphinx_docs`` encountered are not as expected.
[ "Populate", "README", "template", "with", "values", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L265-L340
train
54,156
dhermes/bezier
scripts/check_doc_templates.py
readme_verify
def readme_verify(): """Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template. """ expected = populate_readme(REVISION, RTD_VERSION) # Actually get the stored contents. with open(README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.actual", "README.rst.expected" ) raise ValueError(err_msg) else: print("README contents are as expected.")
python
def readme_verify(): """Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template. """ expected = populate_readme(REVISION, RTD_VERSION) # Actually get the stored contents. with open(README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.actual", "README.rst.expected" ) raise ValueError(err_msg) else: print("README contents are as expected.")
[ "def", "readme_verify", "(", ")", ":", "expected", "=", "populate_readme", "(", "REVISION", ",", "RTD_VERSION", ")", "# Actually get the stored contents.", "with", "open", "(", "README_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ...
Populate the template and compare to ``README``. Raises: ValueError: If the current README doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "README", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L343-L361
train
54,157
dhermes/bezier
scripts/check_doc_templates.py
release_readme_verify
def release_readme_verify(): """Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template. """ version = "{version}" expected = populate_readme( version, version, pypi="", pypi_img="", versions="\n\n", versions_img="", circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", ) with open(RELEASE_README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.release.actual", "README.rst.release.expected", ) raise ValueError(err_msg) else: print("README.rst.release.template contents are as expected.")
python
def release_readme_verify(): """Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template. """ version = "{version}" expected = populate_readme( version, version, pypi="", pypi_img="", versions="\n\n", versions_img="", circleci_badge=CIRCLECI_BADGE_RELEASE, circleci_path="/{circleci_build}", travis_badge=TRAVIS_BADGE_RELEASE, travis_path="/builds/{travis_build}", appveyor_badge=APPVEYOR_BADGE_RELEASE, appveyor_path="/build/{appveyor_build}", coveralls_badge=COVERALLS_BADGE_RELEASE, coveralls_path="builds/{coveralls_build}", ) with open(RELEASE_README_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "README.rst.release.actual", "README.rst.release.expected", ) raise ValueError(err_msg) else: print("README.rst.release.template contents are as expected.")
[ "def", "release_readme_verify", "(", ")", ":", "version", "=", "\"{version}\"", "expected", "=", "populate_readme", "(", "version", ",", "version", ",", "pypi", "=", "\"\"", ",", "pypi_img", "=", "\"\"", ",", "versions", "=", "\"\\n\\n\"", ",", "versions_img",...
Specialize the template to a PyPI release template. Once populated, compare to ``README.rst.release.template``. Raises: ValueError: If the current template doesn't agree with the expected value specialized from the template.
[ "Specialize", "the", "template", "to", "a", "PyPI", "release", "template", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L364-L402
train
54,158
dhermes/bezier
scripts/check_doc_templates.py
_index_verify
def _index_verify(index_file, **extra_kwargs): """Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template. """ side_effect = extra_kwargs.pop("side_effect", None) with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() template_kwargs = { "code_block1": SPHINX_CODE_BLOCK1, "code_block2": SPHINX_CODE_BLOCK2, "code_block3": SPHINX_CODE_BLOCK3, "testcleanup": TEST_CLEANUP, "toctree": TOCTREE, "bernstein_basis": BERNSTEIN_BASIS_SPHINX, "bezier_defn": BEZIER_DEFN_SPHINX, "sum_to_unity": SUM_TO_UNITY_SPHINX, "img_prefix": "", "extra_links": "", "docs": "", "docs_img": "", "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": RTD_VERSION, "revision": REVISION, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) expected = template.format(**template_kwargs) if side_effect is not None: expected = side_effect(expected) with open(index_file, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, index_file + ".actual", index_file + ".expected", ) raise ValueError(err_msg) else: rel_name = os.path.relpath(index_file, _ROOT_DIR) msg = "{} contents are as expected.".format(rel_name) print(msg)
python
def _index_verify(index_file, **extra_kwargs): """Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template. """ side_effect = extra_kwargs.pop("side_effect", None) with open(TEMPLATE_FILE, "r") as file_obj: template = file_obj.read() template_kwargs = { "code_block1": SPHINX_CODE_BLOCK1, "code_block2": SPHINX_CODE_BLOCK2, "code_block3": SPHINX_CODE_BLOCK3, "testcleanup": TEST_CLEANUP, "toctree": TOCTREE, "bernstein_basis": BERNSTEIN_BASIS_SPHINX, "bezier_defn": BEZIER_DEFN_SPHINX, "sum_to_unity": SUM_TO_UNITY_SPHINX, "img_prefix": "", "extra_links": "", "docs": "", "docs_img": "", "pypi": "\n\n|pypi| ", "pypi_img": PYPI_IMG, "versions": "|versions|\n\n", "versions_img": VERSIONS_IMG, "rtd_version": RTD_VERSION, "revision": REVISION, "circleci_badge": CIRCLECI_BADGE, "circleci_path": "", "travis_badge": TRAVIS_BADGE, "travis_path": "", "appveyor_badge": APPVEYOR_BADGE, "appveyor_path": "", "coveralls_badge": COVERALLS_BADGE, "coveralls_path": COVERALLS_PATH, "zenodo": "|zenodo|", "zenodo_img": ZENODO_IMG, "joss": " |JOSS|", "joss_img": JOSS_IMG, } template_kwargs.update(**extra_kwargs) expected = template.format(**template_kwargs) if side_effect is not None: expected = side_effect(expected) with open(index_file, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, index_file + ".actual", index_file + ".expected", ) raise ValueError(err_msg) else: rel_name = os.path.relpath(index_file, _ROOT_DIR) msg = "{} contents are as expected.".format(rel_name) print(msg)
[ "def", "_index_verify", "(", "index_file", ",", "*", "*", "extra_kwargs", ")", ":", "side_effect", "=", "extra_kwargs", ".", "pop", "(", "\"side_effect\"", ",", "None", ")", "with", "open", "(", "TEMPLATE_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "t...
Populate the template and compare to documentation index file. Used for both ``docs/index.rst`` and ``docs/index.rst.release.template``. Args: index_file (str): Filename to compare against. extra_kwargs (Dict[str, str]): Over-ride for template arguments. One **special** keyword is ``side_effect``, which can be used to update the template output after the fact. Raises: ValueError: If the current ``index.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "documentation", "index", "file", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L405-L473
train
54,159
dhermes/bezier
scripts/check_doc_templates.py
release_docs_side_effect
def release_docs_side_effect(content): """Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces. """ # First replace **all** curly braces. result = content.replace("{", "{{").replace("}", "}}") # Then reset the actual template arguments. result = result.replace("{{version}}", "{version}") result = result.replace("{{circleci_build}}", "{circleci_build}") result = result.replace("{{travis_build}}", "{travis_build}") result = result.replace("{{appveyor_build}}", "{appveyor_build}") result = result.replace("{{coveralls_build}}", "{coveralls_build}") return result
python
def release_docs_side_effect(content): """Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces. """ # First replace **all** curly braces. result = content.replace("{", "{{").replace("}", "}}") # Then reset the actual template arguments. result = result.replace("{{version}}", "{version}") result = result.replace("{{circleci_build}}", "{circleci_build}") result = result.replace("{{travis_build}}", "{travis_build}") result = result.replace("{{appveyor_build}}", "{appveyor_build}") result = result.replace("{{coveralls_build}}", "{coveralls_build}") return result
[ "def", "release_docs_side_effect", "(", "content", ")", ":", "# First replace **all** curly braces.", "result", "=", "content", ".", "replace", "(", "\"{\"", ",", "\"{{\"", ")", ".", "replace", "(", "\"}\"", ",", "\"}}\"", ")", "# Then reset the actual template argume...
Updates the template so that curly braces are escaped correctly. Args: content (str): The template for ``docs/index.rst.release.template``. Returns: str: The updated template with properly escaped curly braces.
[ "Updates", "the", "template", "so", "that", "curly", "braces", "are", "escaped", "correctly", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L486-L503
train
54,160
dhermes/bezier
scripts/check_doc_templates.py
development_verify
def development_verify(): """Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION, rtd_version=RTD_VERSION) with open(DEVELOPMENT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "DEVELOPMENT.rst.actual", "DEVELOPMENT.rst.expected", ) raise ValueError(err_msg) else: print("DEVELOPMENT.rst contents are as expected.")
python
def development_verify(): """Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template. """ with open(DEVELOPMENT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION, rtd_version=RTD_VERSION) with open(DEVELOPMENT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "DEVELOPMENT.rst.actual", "DEVELOPMENT.rst.expected", ) raise ValueError(err_msg) else: print("DEVELOPMENT.rst contents are as expected.")
[ "def", "development_verify", "(", ")", ":", "with", "open", "(", "DEVELOPMENT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISI...
Populate template and compare to ``DEVELOPMENT.rst`` Raises: ValueError: If the current ``DEVELOPMENT.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "template", "and", "compare", "to", "DEVELOPMENT", ".", "rst" ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L534-L556
train
54,161
dhermes/bezier
scripts/check_doc_templates.py
native_libraries_verify
def native_libraries_verify(): """Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION) with open(BINARY_EXT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "docs/python/binary-extension.rst.actual", "docs/python/binary-extension.rst.expected", ) raise ValueError(err_msg) else: print("docs/python/binary-extension.rst contents are as expected.")
python
def native_libraries_verify(): """Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template. """ with open(BINARY_EXT_TEMPLATE, "r") as file_obj: template = file_obj.read() expected = template.format(revision=REVISION) with open(BINARY_EXT_FILE, "r") as file_obj: contents = file_obj.read() if contents != expected: err_msg = "\n" + get_diff( contents, expected, "docs/python/binary-extension.rst.actual", "docs/python/binary-extension.rst.expected", ) raise ValueError(err_msg) else: print("docs/python/binary-extension.rst contents are as expected.")
[ "def", "native_libraries_verify", "(", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "RE...
Populate the template and compare to ``binary-extension.rst``. Raises: ValueError: If the current ``docs/python/binary-extension.rst`` doesn't agree with the expected value computed from the template.
[ "Populate", "the", "template", "and", "compare", "to", "binary", "-", "extension", ".", "rst", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/scripts/check_doc_templates.py#L559-L581
train
54,162
dhermes/bezier
src/bezier/_algebraic_intersection.py
evaluate
def evaluate(nodes, x_val, y_val): r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ _, num_nodes = nodes.shape if num_nodes == 1: raise ValueError("A point cannot be implicitized") elif num_nodes == 2: # x(s) - x = (x0 - x) (1 - s) + (x1 - x) s # y(s) - y = (y0 - y) (1 - s) + (y1 - y) s # Modified Sylvester: [x0 - x, x1 - x] # [y0 - y, y1 - y] return (nodes[0, 0] - x_val) * (nodes[1, 1] - y_val) - ( nodes[0, 1] - x_val ) * (nodes[1, 0] - y_val) elif num_nodes == 3: # x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2 # y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2 # Modified Sylvester: [x0 - x, 2(x1 - x), x2 - x, 0] = A|B|C|0 # [ 0, x0 - x, 2(x1 - x), x2 - x] 0|A|B|C # [y0 - y, 2(y1 - y), y2 - y, 0] D|E|F|0 # [ 0, y0 - y, 2(y1 - y), y2 - y] 0|D|E|F val_a, val_b, val_c = nodes[0, :] - x_val val_b *= 2 val_d, val_e, val_f = nodes[1, :] - y_val val_e *= 2 # [A, B, C] [E, F, 0] # det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD) # [D, E, F] [D, E, F] sub1 = val_b * val_f - val_c * val_e sub2 = val_a * val_f - val_c * val_d sub_det_a = -val_e * sub1 + val_f * sub2 # [B, C, 0] # det [A, B, C] = B (BF - CE) - C (AF - CD) # [D, E, F] sub_det_d = val_b * sub1 - val_c * sub2 return val_a * sub_det_a + val_d * sub_det_d elif num_nodes == 4: return _evaluate3(nodes, x_val, y_val) else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3))
python
def evaluate(nodes, x_val, y_val): r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3. """ _, num_nodes = nodes.shape if num_nodes == 1: raise ValueError("A point cannot be implicitized") elif num_nodes == 2: # x(s) - x = (x0 - x) (1 - s) + (x1 - x) s # y(s) - y = (y0 - y) (1 - s) + (y1 - y) s # Modified Sylvester: [x0 - x, x1 - x] # [y0 - y, y1 - y] return (nodes[0, 0] - x_val) * (nodes[1, 1] - y_val) - ( nodes[0, 1] - x_val ) * (nodes[1, 0] - y_val) elif num_nodes == 3: # x(s) - x = (x0 - x) (1 - s)^2 + 2 (x1 - x) s(1 - s) + (x2 - x) s^2 # y(s) - y = (y0 - y) (1 - s)^2 + 2 (y1 - y) s(1 - s) + (y2 - y) s^2 # Modified Sylvester: [x0 - x, 2(x1 - x), x2 - x, 0] = A|B|C|0 # [ 0, x0 - x, 2(x1 - x), x2 - x] 0|A|B|C # [y0 - y, 2(y1 - y), y2 - y, 0] D|E|F|0 # [ 0, y0 - y, 2(y1 - y), y2 - y] 0|D|E|F val_a, val_b, val_c = nodes[0, :] - x_val val_b *= 2 val_d, val_e, val_f = nodes[1, :] - y_val val_e *= 2 # [A, B, C] [E, F, 0] # det [E, F, 0] = - det [A, B, C] = -E (BF - CE) + F(AF - CD) # [D, E, F] [D, E, F] sub1 = val_b * val_f - val_c * val_e sub2 = val_a * val_f - val_c * val_d sub_det_a = -val_e * sub1 + val_f * sub2 # [B, C, 0] # det [A, B, C] = B (BF - CE) - C (AF - CD) # [D, E, F] sub_det_d = val_b * sub1 - val_c * sub2 return val_a * sub_det_a + val_d * sub_det_d elif num_nodes == 4: return _evaluate3(nodes, x_val, y_val) else: raise _helpers.UnsupportedDegree(num_nodes - 1, supported=(1, 2, 3))
[ "def", "evaluate", "(", "nodes", ",", "x_val", ",", "y_val", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "if", "num_nodes", "==", "1", ":", "raise", "ValueError", "(", "\"A point cannot be implicitized\"", ")", "elif", "num_nodes", "==", "...
r"""Evaluate the implicitized bivariate polynomial containing the curve. Assumes `algebraic curve`_ containing :math:`B(s, t)` is given by :math:`f(x, y) = 0`. This function evaluates :math:`f(x, y)`. .. note:: This assumes, but doesn't check, that ``nodes`` has 2 rows. .. note:: This assumes, but doesn't check, that ``nodes`` is not degree-elevated. If it were degree-elevated, then the Sylvester matrix will always have zero determinant. Args: nodes (numpy.ndarray): ``2 x N`` array of nodes in a curve. x_val (float): ``x``-coordinate for evaluation. y_val (float): ``y``-coordinate for evaluation. Returns: float: The computed value of :math:`f(x, y)`. Raises: ValueError: If the curve is a point. .UnsupportedDegree: If the degree is not 1, 2 or 3.
[ "r", "Evaluate", "the", "implicitized", "bivariate", "polynomial", "containing", "the", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L144-L212
train
54,163
dhermes/bezier
src/bezier/_algebraic_intersection.py
_get_sigma_coeffs
def _get_sigma_coeffs(coeffs): r"""Compute "transformed" form of polynomial in Bernstein form. Makes sure the "transformed" polynomial is monic (i.e. by dividing by the lead coefficient) and just returns the coefficients of the non-lead terms. For example, the polynomial .. math:: f(s) = 4 (1 - s)^2 + 3 \cdot 2 s(1 - s) + 7 s^2 can be transformed into :math:`f(s) = 7 (1 - s)^2 g\left(\sigma\right)` for :math:`\sigma = \frac{s}{1 - s}` and :math:`g(\sigma)` a polynomial in the power basis: .. math:: g(\sigma) = \frac{4}{7} + \frac{6}{7} \sigma + \sigma^2. In cases where terms with "low exponents" of :math:`(1 - s)` have coefficient zero, the degree of :math:`g(\sigma)` may not be the same as the degree of :math:`f(s)`: .. math:: \begin{align*} f(s) &= 5 (1 - s)^4 - 3 \cdot 4 s(1 - s)^3 + 11 \cdot 6 s^2 (1 - s)^2 \\ \Longrightarrow g(\sigma) &= \frac{5}{66} - \frac{2}{11} \sigma + \sigma^2. \end{align*} Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[Optional[numpy.ndarray], int, int]: A triple of * 1D array of the transformed coefficients (will be unset if ``effective_degree == 0``) * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros. """ num_nodes, = coeffs.shape degree = num_nodes - 1 effective_degree = None for index in six.moves.range(degree, -1, -1): if coeffs[index] != 0.0: effective_degree = index break if effective_degree is None: # NOTE: This means ``np.all(coeffs == 0.0)``. return None, 0, 0 if effective_degree == 0: return None, degree, 0 sigma_coeffs = coeffs[:effective_degree] / coeffs[effective_degree] # Now we need to add the binomial coefficients, but we avoid # computing actual binomial coefficients. Starting from the largest # exponent, the first ratio of binomial coefficients is # (d C (e - 1)) / (d C e) # = e / (d - e + 1) binom_numerator = effective_degree binom_denominator = degree - effective_degree + 1 for exponent in six.moves.xrange(effective_degree - 1, -1, -1): sigma_coeffs[exponent] *= binom_numerator sigma_coeffs[exponent] /= binom_denominator # We swap (d C j) with (d C (j - 1)), so `p / q` becomes # (p / q) (d C (j - 1)) / (d C j) # = (p j) / (q (d - j + 1)) binom_numerator *= exponent binom_denominator *= degree - exponent + 1 return sigma_coeffs, degree, effective_degree
python
def _get_sigma_coeffs(coeffs): r"""Compute "transformed" form of polynomial in Bernstein form. Makes sure the "transformed" polynomial is monic (i.e. by dividing by the lead coefficient) and just returns the coefficients of the non-lead terms. For example, the polynomial .. math:: f(s) = 4 (1 - s)^2 + 3 \cdot 2 s(1 - s) + 7 s^2 can be transformed into :math:`f(s) = 7 (1 - s)^2 g\left(\sigma\right)` for :math:`\sigma = \frac{s}{1 - s}` and :math:`g(\sigma)` a polynomial in the power basis: .. math:: g(\sigma) = \frac{4}{7} + \frac{6}{7} \sigma + \sigma^2. In cases where terms with "low exponents" of :math:`(1 - s)` have coefficient zero, the degree of :math:`g(\sigma)` may not be the same as the degree of :math:`f(s)`: .. math:: \begin{align*} f(s) &= 5 (1 - s)^4 - 3 \cdot 4 s(1 - s)^3 + 11 \cdot 6 s^2 (1 - s)^2 \\ \Longrightarrow g(\sigma) &= \frac{5}{66} - \frac{2}{11} \sigma + \sigma^2. \end{align*} Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[Optional[numpy.ndarray], int, int]: A triple of * 1D array of the transformed coefficients (will be unset if ``effective_degree == 0``) * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros. """ num_nodes, = coeffs.shape degree = num_nodes - 1 effective_degree = None for index in six.moves.range(degree, -1, -1): if coeffs[index] != 0.0: effective_degree = index break if effective_degree is None: # NOTE: This means ``np.all(coeffs == 0.0)``. return None, 0, 0 if effective_degree == 0: return None, degree, 0 sigma_coeffs = coeffs[:effective_degree] / coeffs[effective_degree] # Now we need to add the binomial coefficients, but we avoid # computing actual binomial coefficients. Starting from the largest # exponent, the first ratio of binomial coefficients is # (d C (e - 1)) / (d C e) # = e / (d - e + 1) binom_numerator = effective_degree binom_denominator = degree - effective_degree + 1 for exponent in six.moves.xrange(effective_degree - 1, -1, -1): sigma_coeffs[exponent] *= binom_numerator sigma_coeffs[exponent] /= binom_denominator # We swap (d C j) with (d C (j - 1)), so `p / q` becomes # (p / q) (d C (j - 1)) / (d C j) # = (p j) / (q (d - j + 1)) binom_numerator *= exponent binom_denominator *= degree - exponent + 1 return sigma_coeffs, degree, effective_degree
[ "def", "_get_sigma_coeffs", "(", "coeffs", ")", ":", "num_nodes", ",", "=", "coeffs", ".", "shape", "degree", "=", "num_nodes", "-", "1", "effective_degree", "=", "None", "for", "index", "in", "six", ".", "moves", ".", "range", "(", "degree", ",", "-", ...
r"""Compute "transformed" form of polynomial in Bernstein form. Makes sure the "transformed" polynomial is monic (i.e. by dividing by the lead coefficient) and just returns the coefficients of the non-lead terms. For example, the polynomial .. math:: f(s) = 4 (1 - s)^2 + 3 \cdot 2 s(1 - s) + 7 s^2 can be transformed into :math:`f(s) = 7 (1 - s)^2 g\left(\sigma\right)` for :math:`\sigma = \frac{s}{1 - s}` and :math:`g(\sigma)` a polynomial in the power basis: .. math:: g(\sigma) = \frac{4}{7} + \frac{6}{7} \sigma + \sigma^2. In cases where terms with "low exponents" of :math:`(1 - s)` have coefficient zero, the degree of :math:`g(\sigma)` may not be the same as the degree of :math:`f(s)`: .. math:: \begin{align*} f(s) &= 5 (1 - s)^4 - 3 \cdot 4 s(1 - s)^3 + 11 \cdot 6 s^2 (1 - s)^2 \\ \Longrightarrow g(\sigma) &= \frac{5}{66} - \frac{2}{11} \sigma + \sigma^2. \end{align*} Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[Optional[numpy.ndarray], int, int]: A triple of * 1D array of the transformed coefficients (will be unset if ``effective_degree == 0``) * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros.
[ "r", "Compute", "transformed", "form", "of", "polynomial", "in", "Bernstein", "form", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L604-L679
train
54,164
dhermes/bezier
src/bezier/_algebraic_intersection.py
bernstein_companion
def bernstein_companion(coeffs): r"""Compute a companion matrix for a polynomial in Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: f(s) = (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j. This converts the Bernstein coefficients :math:`C_j` into "generalized Bernstein" coefficients :math:`\widetilde{C_j} = \binom{n}{j} C_j`. Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[numpy.ndarray, int, int]: A triple of * 2D NumPy array with the companion matrix. * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros. """ sigma_coeffs, degree, effective_degree = _get_sigma_coeffs(coeffs) if effective_degree == 0: return np.empty((0, 0), order="F"), degree, 0 companion = np.zeros((effective_degree, effective_degree), order="F") companion.flat[ effective_degree :: effective_degree + 1 # noqa: E203 ] = 1.0 companion[0, :] = -sigma_coeffs[::-1] return companion, degree, effective_degree
python
def bernstein_companion(coeffs): r"""Compute a companion matrix for a polynomial in Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: f(s) = (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j. This converts the Bernstein coefficients :math:`C_j` into "generalized Bernstein" coefficients :math:`\widetilde{C_j} = \binom{n}{j} C_j`. Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[numpy.ndarray, int, int]: A triple of * 2D NumPy array with the companion matrix. * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros. """ sigma_coeffs, degree, effective_degree = _get_sigma_coeffs(coeffs) if effective_degree == 0: return np.empty((0, 0), order="F"), degree, 0 companion = np.zeros((effective_degree, effective_degree), order="F") companion.flat[ effective_degree :: effective_degree + 1 # noqa: E203 ] = 1.0 companion[0, :] = -sigma_coeffs[::-1] return companion, degree, effective_degree
[ "def", "bernstein_companion", "(", "coeffs", ")", ":", "sigma_coeffs", ",", "degree", ",", "effective_degree", "=", "_get_sigma_coeffs", "(", "coeffs", ")", "if", "effective_degree", "==", "0", ":", "return", "np", ".", "empty", "(", "(", "0", ",", "0", ")...
r"""Compute a companion matrix for a polynomial in Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: f(s) = (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j. This converts the Bernstein coefficients :math:`C_j` into "generalized Bernstein" coefficients :math:`\widetilde{C_j} = \binom{n}{j} C_j`. Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: Tuple[numpy.ndarray, int, int]: A triple of * 2D NumPy array with the companion matrix. * the "full degree" based on the size of ``coeffs`` * the "effective degree" determined by the number of leading zeros.
[ "r", "Compute", "a", "companion", "matrix", "for", "a", "polynomial", "in", "Bernstein", "basis", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L682-L724
train
54,165
dhermes/bezier
src/bezier/_algebraic_intersection.py
bezier_roots
def bezier_roots(coeffs): r"""Compute polynomial roots from a polynomial in the Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: \begin{align*} f(s) &= (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j \\ &= (1 - s)^n \sum_{j = 0}^n \widetilde{C_j} \sigma^j. \end{align*} Then it uses an eigenvalue solver to find the roots of .. math:: g(\sigma) = \sum_{j = 0}^n \widetilde{C_j} \sigma^j and convert them back into roots of :math:`f(s)` via :math:`s = \frac{\sigma}{1 + \sigma}`. For example, consider .. math:: \begin{align*} f_0(s) &= 2 (2 - s)(3 + s) \\ &= 12(1 - s)^2 + 11 \cdot 2s(1 - s) + 8 s^2 \end{align*} First, we compute the companion matrix for .. math:: g_0(\sigma) = 12 + 22 \sigma + 8 \sigma^2 .. testsetup:: bezier-roots0, bezier-roots1, bezier-roots2 import numpy as np import numpy.linalg from bezier._algebraic_intersection import bernstein_companion from bezier._algebraic_intersection import bezier_roots .. doctest:: bezier-roots0 >>> coeffs0 = np.asfortranarray([12.0, 11.0, 8.0]) >>> companion0, _, _ = bernstein_companion(coeffs0) >>> companion0 array([[-2.75, -1.5 ], [ 1. , 0. ]]) then take the eigenvalues of the companion matrix: .. doctest:: bezier-roots0 >>> sigma_values0 = np.linalg.eigvals(companion0) >>> sigma_values0 array([-2. , -0.75]) after transforming them, we have the roots of :math:`f(s)`: .. doctest:: bezier-roots0 >>> sigma_values0 / (1.0 + sigma_values0) array([ 2., -3.]) >>> bezier_roots(coeffs0) array([ 2., -3.]) In cases where :math:`s = 1` is a root, the lead coefficient of :math:`g` would be :math:`0`, so there is a reduction in the companion matrix. .. math:: \begin{align*} f_1(s) &= 6 (s - 1)^2 (s - 3) (s - 5) \\ &= 90 (1 - s)^4 + 33 \cdot 4s(1 - s)^3 + 8 \cdot 6s^2(1 - s)^2 \end{align*} .. doctest:: bezier-roots1 :options: +NORMALIZE_WHITESPACE >>> coeffs1 = np.asfortranarray([90.0, 33.0, 8.0, 0.0, 0.0]) >>> companion1, degree1, effective_degree1 = bernstein_companion( ... coeffs1) >>> companion1 array([[-2.75 , -1.875], [ 1. , 0. ]]) >>> degree1 4 >>> effective_degree1 2 so the roots are a combination of the roots determined from :math:`s = \frac{\sigma}{1 + \sigma}` and the number of factors of :math:`(1 - s)` (i.e. the difference between the degree and the effective degree): .. doctest:: bezier-roots1 >>> bezier_roots(coeffs1) array([3., 5., 1., 1.]) In some cases, a polynomial is represented with an "elevated" degree: .. math:: \begin{align*} f_2(s) &= 3 (s^2 + 1) \\ &= 3 (1 - s)^3 + 3 \cdot 3s(1 - s)^2 + 4 \cdot 3s^2(1 - s) + 6 s^3 \end{align*} This results in a "point at infinity" :math:`\sigma = -1 \Longleftrightarrow s = \infty`: .. doctest:: bezier-roots2 >>> coeffs2 = np.asfortranarray([3.0, 3.0, 4.0, 6.0]) >>> companion2, _, _ = bernstein_companion(coeffs2) >>> companion2 array([[-2. , -1.5, -0.5], [ 1. , 0. , 0. ], [ 0. , 1. , 0. ]]) >>> sigma_values2 = np.linalg.eigvals(companion2) >>> sigma_values2 array([-1. +0.j , -0.5+0.5j, -0.5-0.5j]) so we drop any values :math:`\sigma` that are sufficiently close to :math:`-1`: .. doctest:: bezier-roots2 >>> expected2 = np.asfortranarray([1.0j, -1.0j]) >>> roots2 = bezier_roots(coeffs2) >>> np.allclose(expected2, roots2, rtol=2e-15, atol=0.0) True Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: A 1D array containing the roots. """ companion, degree, effective_degree = bernstein_companion(coeffs) if effective_degree: sigma_roots = np.linalg.eigvals(companion) # Filter out `sigma = -1`, i.e. "points at infinity". # We want the error ||(sigma - (-1))|| ~= 2^{-52} to_keep = np.abs(sigma_roots + 1.0) > _SIGMA_THRESHOLD sigma_roots = sigma_roots[to_keep] s_vals = sigma_roots / (1.0 + sigma_roots) else: s_vals = np.empty((0,), order="F") if effective_degree != degree: delta = degree - effective_degree s_vals = np.hstack([s_vals, [1] * delta]) return s_vals
python
def bezier_roots(coeffs): r"""Compute polynomial roots from a polynomial in the Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: \begin{align*} f(s) &= (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j \\ &= (1 - s)^n \sum_{j = 0}^n \widetilde{C_j} \sigma^j. \end{align*} Then it uses an eigenvalue solver to find the roots of .. math:: g(\sigma) = \sum_{j = 0}^n \widetilde{C_j} \sigma^j and convert them back into roots of :math:`f(s)` via :math:`s = \frac{\sigma}{1 + \sigma}`. For example, consider .. math:: \begin{align*} f_0(s) &= 2 (2 - s)(3 + s) \\ &= 12(1 - s)^2 + 11 \cdot 2s(1 - s) + 8 s^2 \end{align*} First, we compute the companion matrix for .. math:: g_0(\sigma) = 12 + 22 \sigma + 8 \sigma^2 .. testsetup:: bezier-roots0, bezier-roots1, bezier-roots2 import numpy as np import numpy.linalg from bezier._algebraic_intersection import bernstein_companion from bezier._algebraic_intersection import bezier_roots .. doctest:: bezier-roots0 >>> coeffs0 = np.asfortranarray([12.0, 11.0, 8.0]) >>> companion0, _, _ = bernstein_companion(coeffs0) >>> companion0 array([[-2.75, -1.5 ], [ 1. , 0. ]]) then take the eigenvalues of the companion matrix: .. doctest:: bezier-roots0 >>> sigma_values0 = np.linalg.eigvals(companion0) >>> sigma_values0 array([-2. , -0.75]) after transforming them, we have the roots of :math:`f(s)`: .. doctest:: bezier-roots0 >>> sigma_values0 / (1.0 + sigma_values0) array([ 2., -3.]) >>> bezier_roots(coeffs0) array([ 2., -3.]) In cases where :math:`s = 1` is a root, the lead coefficient of :math:`g` would be :math:`0`, so there is a reduction in the companion matrix. .. math:: \begin{align*} f_1(s) &= 6 (s - 1)^2 (s - 3) (s - 5) \\ &= 90 (1 - s)^4 + 33 \cdot 4s(1 - s)^3 + 8 \cdot 6s^2(1 - s)^2 \end{align*} .. doctest:: bezier-roots1 :options: +NORMALIZE_WHITESPACE >>> coeffs1 = np.asfortranarray([90.0, 33.0, 8.0, 0.0, 0.0]) >>> companion1, degree1, effective_degree1 = bernstein_companion( ... coeffs1) >>> companion1 array([[-2.75 , -1.875], [ 1. , 0. ]]) >>> degree1 4 >>> effective_degree1 2 so the roots are a combination of the roots determined from :math:`s = \frac{\sigma}{1 + \sigma}` and the number of factors of :math:`(1 - s)` (i.e. the difference between the degree and the effective degree): .. doctest:: bezier-roots1 >>> bezier_roots(coeffs1) array([3., 5., 1., 1.]) In some cases, a polynomial is represented with an "elevated" degree: .. math:: \begin{align*} f_2(s) &= 3 (s^2 + 1) \\ &= 3 (1 - s)^3 + 3 \cdot 3s(1 - s)^2 + 4 \cdot 3s^2(1 - s) + 6 s^3 \end{align*} This results in a "point at infinity" :math:`\sigma = -1 \Longleftrightarrow s = \infty`: .. doctest:: bezier-roots2 >>> coeffs2 = np.asfortranarray([3.0, 3.0, 4.0, 6.0]) >>> companion2, _, _ = bernstein_companion(coeffs2) >>> companion2 array([[-2. , -1.5, -0.5], [ 1. , 0. , 0. ], [ 0. , 1. , 0. ]]) >>> sigma_values2 = np.linalg.eigvals(companion2) >>> sigma_values2 array([-1. +0.j , -0.5+0.5j, -0.5-0.5j]) so we drop any values :math:`\sigma` that are sufficiently close to :math:`-1`: .. doctest:: bezier-roots2 >>> expected2 = np.asfortranarray([1.0j, -1.0j]) >>> roots2 = bezier_roots(coeffs2) >>> np.allclose(expected2, roots2, rtol=2e-15, atol=0.0) True Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: A 1D array containing the roots. """ companion, degree, effective_degree = bernstein_companion(coeffs) if effective_degree: sigma_roots = np.linalg.eigvals(companion) # Filter out `sigma = -1`, i.e. "points at infinity". # We want the error ||(sigma - (-1))|| ~= 2^{-52} to_keep = np.abs(sigma_roots + 1.0) > _SIGMA_THRESHOLD sigma_roots = sigma_roots[to_keep] s_vals = sigma_roots / (1.0 + sigma_roots) else: s_vals = np.empty((0,), order="F") if effective_degree != degree: delta = degree - effective_degree s_vals = np.hstack([s_vals, [1] * delta]) return s_vals
[ "def", "bezier_roots", "(", "coeffs", ")", ":", "companion", ",", "degree", ",", "effective_degree", "=", "bernstein_companion", "(", "coeffs", ")", "if", "effective_degree", ":", "sigma_roots", "=", "np", ".", "linalg", ".", "eigvals", "(", "companion", ")", ...
r"""Compute polynomial roots from a polynomial in the Bernstein basis. .. note:: This assumes the caller passes in a 1D array but does not check. This takes the polynomial .. math:: f(s) = \sum_{j = 0}^n b_{j, n} \cdot C_j. and uses the variable :math:`\sigma = \frac{s}{1 - s}` to rewrite as .. math:: \begin{align*} f(s) &= (1 - s)^n \sum_{j = 0}^n \binom{n}{j} C_j \sigma^j \\ &= (1 - s)^n \sum_{j = 0}^n \widetilde{C_j} \sigma^j. \end{align*} Then it uses an eigenvalue solver to find the roots of .. math:: g(\sigma) = \sum_{j = 0}^n \widetilde{C_j} \sigma^j and convert them back into roots of :math:`f(s)` via :math:`s = \frac{\sigma}{1 + \sigma}`. For example, consider .. math:: \begin{align*} f_0(s) &= 2 (2 - s)(3 + s) \\ &= 12(1 - s)^2 + 11 \cdot 2s(1 - s) + 8 s^2 \end{align*} First, we compute the companion matrix for .. math:: g_0(\sigma) = 12 + 22 \sigma + 8 \sigma^2 .. testsetup:: bezier-roots0, bezier-roots1, bezier-roots2 import numpy as np import numpy.linalg from bezier._algebraic_intersection import bernstein_companion from bezier._algebraic_intersection import bezier_roots .. doctest:: bezier-roots0 >>> coeffs0 = np.asfortranarray([12.0, 11.0, 8.0]) >>> companion0, _, _ = bernstein_companion(coeffs0) >>> companion0 array([[-2.75, -1.5 ], [ 1. , 0. ]]) then take the eigenvalues of the companion matrix: .. doctest:: bezier-roots0 >>> sigma_values0 = np.linalg.eigvals(companion0) >>> sigma_values0 array([-2. , -0.75]) after transforming them, we have the roots of :math:`f(s)`: .. doctest:: bezier-roots0 >>> sigma_values0 / (1.0 + sigma_values0) array([ 2., -3.]) >>> bezier_roots(coeffs0) array([ 2., -3.]) In cases where :math:`s = 1` is a root, the lead coefficient of :math:`g` would be :math:`0`, so there is a reduction in the companion matrix. .. math:: \begin{align*} f_1(s) &= 6 (s - 1)^2 (s - 3) (s - 5) \\ &= 90 (1 - s)^4 + 33 \cdot 4s(1 - s)^3 + 8 \cdot 6s^2(1 - s)^2 \end{align*} .. doctest:: bezier-roots1 :options: +NORMALIZE_WHITESPACE >>> coeffs1 = np.asfortranarray([90.0, 33.0, 8.0, 0.0, 0.0]) >>> companion1, degree1, effective_degree1 = bernstein_companion( ... coeffs1) >>> companion1 array([[-2.75 , -1.875], [ 1. , 0. ]]) >>> degree1 4 >>> effective_degree1 2 so the roots are a combination of the roots determined from :math:`s = \frac{\sigma}{1 + \sigma}` and the number of factors of :math:`(1 - s)` (i.e. the difference between the degree and the effective degree): .. doctest:: bezier-roots1 >>> bezier_roots(coeffs1) array([3., 5., 1., 1.]) In some cases, a polynomial is represented with an "elevated" degree: .. math:: \begin{align*} f_2(s) &= 3 (s^2 + 1) \\ &= 3 (1 - s)^3 + 3 \cdot 3s(1 - s)^2 + 4 \cdot 3s^2(1 - s) + 6 s^3 \end{align*} This results in a "point at infinity" :math:`\sigma = -1 \Longleftrightarrow s = \infty`: .. doctest:: bezier-roots2 >>> coeffs2 = np.asfortranarray([3.0, 3.0, 4.0, 6.0]) >>> companion2, _, _ = bernstein_companion(coeffs2) >>> companion2 array([[-2. , -1.5, -0.5], [ 1. , 0. , 0. ], [ 0. , 1. , 0. ]]) >>> sigma_values2 = np.linalg.eigvals(companion2) >>> sigma_values2 array([-1. +0.j , -0.5+0.5j, -0.5-0.5j]) so we drop any values :math:`\sigma` that are sufficiently close to :math:`-1`: .. doctest:: bezier-roots2 >>> expected2 = np.asfortranarray([1.0j, -1.0j]) >>> roots2 = bezier_roots(coeffs2) >>> np.allclose(expected2, roots2, rtol=2e-15, atol=0.0) True Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: A 1D array containing the roots.
[ "r", "Compute", "polynomial", "roots", "from", "a", "polynomial", "in", "the", "Bernstein", "basis", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L727-L896
train
54,166
dhermes/bezier
src/bezier/_algebraic_intersection.py
_reciprocal_condition_number
def _reciprocal_condition_number(lu_mat, one_norm): r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :math:`U` stored in the upper triangle. one_norm (float): The 1-norm of the original matrix :math:`A`. Returns: float: The reciprocal condition number of :math:`A`. Raises: OSError: If SciPy is not installed. RuntimeError: If the reciprocal 1-norm condition number could not be computed. """ if _scipy_lapack is None: raise OSError("This function requires SciPy for calling into LAPACK.") # pylint: disable=no-member rcond, info = _scipy_lapack.dgecon(lu_mat, one_norm) # pylint: enable=no-member if info != 0: raise RuntimeError( "The reciprocal 1-norm condition number could not be computed." ) return rcond
python
def _reciprocal_condition_number(lu_mat, one_norm): r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :math:`U` stored in the upper triangle. one_norm (float): The 1-norm of the original matrix :math:`A`. Returns: float: The reciprocal condition number of :math:`A`. Raises: OSError: If SciPy is not installed. RuntimeError: If the reciprocal 1-norm condition number could not be computed. """ if _scipy_lapack is None: raise OSError("This function requires SciPy for calling into LAPACK.") # pylint: disable=no-member rcond, info = _scipy_lapack.dgecon(lu_mat, one_norm) # pylint: enable=no-member if info != 0: raise RuntimeError( "The reciprocal 1-norm condition number could not be computed." ) return rcond
[ "def", "_reciprocal_condition_number", "(", "lu_mat", ",", "one_norm", ")", ":", "if", "_scipy_lapack", "is", "None", ":", "raise", "OSError", "(", "\"This function requires SciPy for calling into LAPACK.\"", ")", "# pylint: disable=no-member", "rcond", ",", "info", "=", ...
r"""Compute reciprocal condition number of a matrix. Args: lu_mat (numpy.ndarray): A 2D array of a matrix :math:`A` that has been LU-factored, with the non-diagonal part of :math:`L` stored in the strictly lower triangle and :math:`U` stored in the upper triangle. one_norm (float): The 1-norm of the original matrix :math:`A`. Returns: float: The reciprocal condition number of :math:`A`. Raises: OSError: If SciPy is not installed. RuntimeError: If the reciprocal 1-norm condition number could not be computed.
[ "r", "Compute", "reciprocal", "condition", "number", "of", "a", "matrix", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1026-L1054
train
54,167
dhermes/bezier
src/bezier/_algebraic_intersection.py
bezier_value_check
def bezier_value_check(coeffs, s_val, rhs_val=0.0): r"""Check if a polynomial in the Bernstein basis evaluates to a value. This is intended to be used for root checking, i.e. for a polynomial :math:`f(s)` and a particular value :math:`s_{\ast}`: Is it true that :math:`f\left(s_{\ast}\right) = 0`? Does so by re-stating as a matrix rank problem. As in :func:`~bezier._algebraic_intersection.bezier_roots`, we can rewrite .. math:: f(s) = (1 - s)^n g\left(\sigma\right) for :math:`\sigma = \frac{s}{1 - s}` and :math:`g\left(\sigma\right)` written in the power / monomial basis. Now, checking if :math:`g\left(\sigma\right) = 0` is a matter of checking that :math:`\det\left(C_g - \sigma I\right) = 0` (where :math:`C_g` is the companion matrix of :math:`g`). Due to issues of numerical stability, we'd rather ask if :math:`C_g - \sigma I` is singular to numerical precision. A typical approach to this using the singular values (assuming :math:`C_g` is :math:`m \times m`) is that the matrix is singular if .. math:: \sigma_m < m \varepsilon \sigma_1 \Longleftrightarrow \frac{1}{\kappa_2} < m \varepsilon (where :math:`\kappa_2` is the 2-norm condition number of the matrix). Since we also know that :math:`\kappa_2 < \kappa_1`, a stronger requirement would be .. math:: \frac{1}{\kappa_1} < \frac{1}{\kappa_2} < m \varepsilon. This is more useful since it is **much** easier to compute the 1-norm condition number / reciprocal condition number (and methods in LAPACK are provided for doing so). Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis representing a polynomial. s_val (float): The value to check on the polynomial: :math:`f(s) = r`. rhs_val (Optional[float]): The value to check that the polynomial evaluates to. Defaults to ``0.0``. Returns: bool: Indicates if :math:`f\left(s_{\ast}\right) = r` (where :math:`s_{\ast}` is ``s_val`` and :math:`r` is ``rhs_val``). """ if s_val == 1.0: return coeffs[-1] == rhs_val shifted_coeffs = coeffs - rhs_val sigma_coeffs, _, effective_degree = _get_sigma_coeffs(shifted_coeffs) if effective_degree == 0: # This means that all coefficients except the ``(1 - s)^n`` # term are zero, so we have ``f(s) = C (1 - s)^n``. Since we know # ``s != 1``, this can only be zero if ``C == 0``. return shifted_coeffs[0] == 0.0 sigma_val = s_val / (1.0 - s_val) lu_mat, one_norm = lu_companion(-sigma_coeffs[::-1], sigma_val) rcond = _reciprocal_condition_number(lu_mat, one_norm) # "Is a root?" IFF Singular IF ``1/kappa_1 < m epsilon`` return rcond < effective_degree * _SINGULAR_EPS
python
def bezier_value_check(coeffs, s_val, rhs_val=0.0): r"""Check if a polynomial in the Bernstein basis evaluates to a value. This is intended to be used for root checking, i.e. for a polynomial :math:`f(s)` and a particular value :math:`s_{\ast}`: Is it true that :math:`f\left(s_{\ast}\right) = 0`? Does so by re-stating as a matrix rank problem. As in :func:`~bezier._algebraic_intersection.bezier_roots`, we can rewrite .. math:: f(s) = (1 - s)^n g\left(\sigma\right) for :math:`\sigma = \frac{s}{1 - s}` and :math:`g\left(\sigma\right)` written in the power / monomial basis. Now, checking if :math:`g\left(\sigma\right) = 0` is a matter of checking that :math:`\det\left(C_g - \sigma I\right) = 0` (where :math:`C_g` is the companion matrix of :math:`g`). Due to issues of numerical stability, we'd rather ask if :math:`C_g - \sigma I` is singular to numerical precision. A typical approach to this using the singular values (assuming :math:`C_g` is :math:`m \times m`) is that the matrix is singular if .. math:: \sigma_m < m \varepsilon \sigma_1 \Longleftrightarrow \frac{1}{\kappa_2} < m \varepsilon (where :math:`\kappa_2` is the 2-norm condition number of the matrix). Since we also know that :math:`\kappa_2 < \kappa_1`, a stronger requirement would be .. math:: \frac{1}{\kappa_1} < \frac{1}{\kappa_2} < m \varepsilon. This is more useful since it is **much** easier to compute the 1-norm condition number / reciprocal condition number (and methods in LAPACK are provided for doing so). Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis representing a polynomial. s_val (float): The value to check on the polynomial: :math:`f(s) = r`. rhs_val (Optional[float]): The value to check that the polynomial evaluates to. Defaults to ``0.0``. Returns: bool: Indicates if :math:`f\left(s_{\ast}\right) = r` (where :math:`s_{\ast}` is ``s_val`` and :math:`r` is ``rhs_val``). """ if s_val == 1.0: return coeffs[-1] == rhs_val shifted_coeffs = coeffs - rhs_val sigma_coeffs, _, effective_degree = _get_sigma_coeffs(shifted_coeffs) if effective_degree == 0: # This means that all coefficients except the ``(1 - s)^n`` # term are zero, so we have ``f(s) = C (1 - s)^n``. Since we know # ``s != 1``, this can only be zero if ``C == 0``. return shifted_coeffs[0] == 0.0 sigma_val = s_val / (1.0 - s_val) lu_mat, one_norm = lu_companion(-sigma_coeffs[::-1], sigma_val) rcond = _reciprocal_condition_number(lu_mat, one_norm) # "Is a root?" IFF Singular IF ``1/kappa_1 < m epsilon`` return rcond < effective_degree * _SINGULAR_EPS
[ "def", "bezier_value_check", "(", "coeffs", ",", "s_val", ",", "rhs_val", "=", "0.0", ")", ":", "if", "s_val", "==", "1.0", ":", "return", "coeffs", "[", "-", "1", "]", "==", "rhs_val", "shifted_coeffs", "=", "coeffs", "-", "rhs_val", "sigma_coeffs", ","...
r"""Check if a polynomial in the Bernstein basis evaluates to a value. This is intended to be used for root checking, i.e. for a polynomial :math:`f(s)` and a particular value :math:`s_{\ast}`: Is it true that :math:`f\left(s_{\ast}\right) = 0`? Does so by re-stating as a matrix rank problem. As in :func:`~bezier._algebraic_intersection.bezier_roots`, we can rewrite .. math:: f(s) = (1 - s)^n g\left(\sigma\right) for :math:`\sigma = \frac{s}{1 - s}` and :math:`g\left(\sigma\right)` written in the power / monomial basis. Now, checking if :math:`g\left(\sigma\right) = 0` is a matter of checking that :math:`\det\left(C_g - \sigma I\right) = 0` (where :math:`C_g` is the companion matrix of :math:`g`). Due to issues of numerical stability, we'd rather ask if :math:`C_g - \sigma I` is singular to numerical precision. A typical approach to this using the singular values (assuming :math:`C_g` is :math:`m \times m`) is that the matrix is singular if .. math:: \sigma_m < m \varepsilon \sigma_1 \Longleftrightarrow \frac{1}{\kappa_2} < m \varepsilon (where :math:`\kappa_2` is the 2-norm condition number of the matrix). Since we also know that :math:`\kappa_2 < \kappa_1`, a stronger requirement would be .. math:: \frac{1}{\kappa_1} < \frac{1}{\kappa_2} < m \varepsilon. This is more useful since it is **much** easier to compute the 1-norm condition number / reciprocal condition number (and methods in LAPACK are provided for doing so). Args: coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis representing a polynomial. s_val (float): The value to check on the polynomial: :math:`f(s) = r`. rhs_val (Optional[float]): The value to check that the polynomial evaluates to. Defaults to ``0.0``. Returns: bool: Indicates if :math:`f\left(s_{\ast}\right) = r` (where :math:`s_{\ast}` is ``s_val`` and :math:`r` is ``rhs_val``).
[ "r", "Check", "if", "a", "polynomial", "in", "the", "Bernstein", "basis", "evaluates", "to", "a", "value", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1057-L1127
train
54,168
dhermes/bezier
src/bezier/_algebraic_intersection.py
roots_in_unit_interval
def roots_in_unit_interval(coeffs): r"""Compute roots of a polynomial in the unit interval. Args: coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in monomial / power basis. Returns: numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`. """ all_roots = polynomial.polyroots(coeffs) # Only keep roots inside or very near to the unit interval. all_roots = all_roots[ (_UNIT_INTERVAL_WIGGLE_START < all_roots.real) & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END) ] # Only keep roots with very small imaginary part. (Really only # keep the real parts.) real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE return all_roots[real_inds].real
python
def roots_in_unit_interval(coeffs): r"""Compute roots of a polynomial in the unit interval. Args: coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in monomial / power basis. Returns: numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`. """ all_roots = polynomial.polyroots(coeffs) # Only keep roots inside or very near to the unit interval. all_roots = all_roots[ (_UNIT_INTERVAL_WIGGLE_START < all_roots.real) & (all_roots.real < _UNIT_INTERVAL_WIGGLE_END) ] # Only keep roots with very small imaginary part. (Really only # keep the real parts.) real_inds = np.abs(all_roots.imag) < _IMAGINARY_WIGGLE return all_roots[real_inds].real
[ "def", "roots_in_unit_interval", "(", "coeffs", ")", ":", "all_roots", "=", "polynomial", ".", "polyroots", "(", "coeffs", ")", "# Only keep roots inside or very near to the unit interval.", "all_roots", "=", "all_roots", "[", "(", "_UNIT_INTERVAL_WIGGLE_START", "<", "all...
r"""Compute roots of a polynomial in the unit interval. Args: coeffs (numpy.ndarray): A 1D array (size ``d + 1``) of coefficients in monomial / power basis. Returns: numpy.ndarray: ``N``-array of real values in :math:`\left[0, 1\right]`.
[ "r", "Compute", "roots", "of", "a", "polynomial", "in", "the", "unit", "interval", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1130-L1149
train
54,169
dhermes/bezier
src/bezier/_algebraic_intersection.py
_strip_leading_zeros
def _strip_leading_zeros(coeffs, threshold=_COEFFICIENT_THRESHOLD): r"""Strip leading zero coefficients from a polynomial. .. note:: This assumes the polynomial :math:`f` defined by ``coeffs`` has been normalized (via :func:`.normalize_polynomial`). Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. threshold (Optional[float]): The point :math:`\tau` below which a a coefficient will be considered to be numerically zero. Returns: numpy.ndarray: The same coefficients without any unnecessary zero terms. """ while np.abs(coeffs[-1]) < threshold: coeffs = coeffs[:-1] return coeffs
python
def _strip_leading_zeros(coeffs, threshold=_COEFFICIENT_THRESHOLD): r"""Strip leading zero coefficients from a polynomial. .. note:: This assumes the polynomial :math:`f` defined by ``coeffs`` has been normalized (via :func:`.normalize_polynomial`). Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. threshold (Optional[float]): The point :math:`\tau` below which a a coefficient will be considered to be numerically zero. Returns: numpy.ndarray: The same coefficients without any unnecessary zero terms. """ while np.abs(coeffs[-1]) < threshold: coeffs = coeffs[:-1] return coeffs
[ "def", "_strip_leading_zeros", "(", "coeffs", ",", "threshold", "=", "_COEFFICIENT_THRESHOLD", ")", ":", "while", "np", ".", "abs", "(", "coeffs", "[", "-", "1", "]", ")", "<", "threshold", ":", "coeffs", "=", "coeffs", "[", ":", "-", "1", "]", "return...
r"""Strip leading zero coefficients from a polynomial. .. note:: This assumes the polynomial :math:`f` defined by ``coeffs`` has been normalized (via :func:`.normalize_polynomial`). Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. threshold (Optional[float]): The point :math:`\tau` below which a a coefficient will be considered to be numerically zero. Returns: numpy.ndarray: The same coefficients without any unnecessary zero terms.
[ "r", "Strip", "leading", "zero", "coefficients", "from", "a", "polynomial", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1152-L1172
train
54,170
dhermes/bezier
src/bezier/_algebraic_intersection.py
_check_non_simple
def _check_non_simple(coeffs): r"""Checks that a polynomial has no non-simple roots. Does so by computing the companion matrix :math:`A` of :math:`f'` and then evaluating the rank of :math:`B = f(A)`. If :math:`B` is not full rank, then :math:`f` and :math:`f'` have a shared factor. See: https://dx.doi.org/10.1016/0024-3795(70)90023-6 .. note:: This assumes that :math:`f \neq 0`. Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. Raises: NotImplementedError: If the polynomial has non-simple roots. """ coeffs = _strip_leading_zeros(coeffs) num_coeffs, = coeffs.shape if num_coeffs < 3: return deriv_poly = polynomial.polyder(coeffs) companion = polynomial.polycompanion(deriv_poly) # NOTE: ``polycompanion()`` returns a C-contiguous array. companion = companion.T # Use Horner's method to evaluate f(companion) num_companion, _ = companion.shape id_mat = np.eye(num_companion, order="F") evaluated = coeffs[-1] * id_mat for index in six.moves.xrange(num_coeffs - 2, -1, -1): coeff = coeffs[index] evaluated = ( _helpers.matrix_product(evaluated, companion) + coeff * id_mat ) if num_companion == 1: # NOTE: This relies on the fact that coeffs is normalized. if np.abs(evaluated[0, 0]) > _NON_SIMPLE_THRESHOLD: rank = 1 else: rank = 0 else: rank = np.linalg.matrix_rank(evaluated) if rank < num_companion: raise NotImplementedError(_NON_SIMPLE_ERR, coeffs)
python
def _check_non_simple(coeffs): r"""Checks that a polynomial has no non-simple roots. Does so by computing the companion matrix :math:`A` of :math:`f'` and then evaluating the rank of :math:`B = f(A)`. If :math:`B` is not full rank, then :math:`f` and :math:`f'` have a shared factor. See: https://dx.doi.org/10.1016/0024-3795(70)90023-6 .. note:: This assumes that :math:`f \neq 0`. Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. Raises: NotImplementedError: If the polynomial has non-simple roots. """ coeffs = _strip_leading_zeros(coeffs) num_coeffs, = coeffs.shape if num_coeffs < 3: return deriv_poly = polynomial.polyder(coeffs) companion = polynomial.polycompanion(deriv_poly) # NOTE: ``polycompanion()`` returns a C-contiguous array. companion = companion.T # Use Horner's method to evaluate f(companion) num_companion, _ = companion.shape id_mat = np.eye(num_companion, order="F") evaluated = coeffs[-1] * id_mat for index in six.moves.xrange(num_coeffs - 2, -1, -1): coeff = coeffs[index] evaluated = ( _helpers.matrix_product(evaluated, companion) + coeff * id_mat ) if num_companion == 1: # NOTE: This relies on the fact that coeffs is normalized. if np.abs(evaluated[0, 0]) > _NON_SIMPLE_THRESHOLD: rank = 1 else: rank = 0 else: rank = np.linalg.matrix_rank(evaluated) if rank < num_companion: raise NotImplementedError(_NON_SIMPLE_ERR, coeffs)
[ "def", "_check_non_simple", "(", "coeffs", ")", ":", "coeffs", "=", "_strip_leading_zeros", "(", "coeffs", ")", "num_coeffs", ",", "=", "coeffs", ".", "shape", "if", "num_coeffs", "<", "3", ":", "return", "deriv_poly", "=", "polynomial", ".", "polyder", "(",...
r"""Checks that a polynomial has no non-simple roots. Does so by computing the companion matrix :math:`A` of :math:`f'` and then evaluating the rank of :math:`B = f(A)`. If :math:`B` is not full rank, then :math:`f` and :math:`f'` have a shared factor. See: https://dx.doi.org/10.1016/0024-3795(70)90023-6 .. note:: This assumes that :math:`f \neq 0`. Args: coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial / power basis. Raises: NotImplementedError: If the polynomial has non-simple roots.
[ "r", "Checks", "that", "a", "polynomial", "has", "no", "non", "-", "simple", "roots", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1175-L1222
train
54,171
dhermes/bezier
src/bezier/_algebraic_intersection.py
_resolve_and_add
def _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t): """Resolve a computed intersection and add to lists. We perform one Newton step to deal with any residual issues of high-degree polynomial solves (one of which depends on the already approximate ``x_val, y_val``). Args: nodes1 (numpy.ndarray): The nodes in the first curve. s_val (float): The approximate intersection parameter along ``nodes1``. final_s (List[float]): The list of accepted intersection parameters ``s``. nodes2 (numpy.ndarray): The nodes in the second curve. t_val (float): The approximate intersection parameter along ``nodes2``. final_t (List[float]): The list of accepted intersection parameters ``t``. """ s_val, t_val = _intersection_helpers.newton_refine( s_val, nodes1, t_val, nodes2 ) s_val, success_s = _helpers.wiggle_interval(s_val) t_val, success_t = _helpers.wiggle_interval(t_val) if not (success_s and success_t): return final_s.append(s_val) final_t.append(t_val)
python
def _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t): """Resolve a computed intersection and add to lists. We perform one Newton step to deal with any residual issues of high-degree polynomial solves (one of which depends on the already approximate ``x_val, y_val``). Args: nodes1 (numpy.ndarray): The nodes in the first curve. s_val (float): The approximate intersection parameter along ``nodes1``. final_s (List[float]): The list of accepted intersection parameters ``s``. nodes2 (numpy.ndarray): The nodes in the second curve. t_val (float): The approximate intersection parameter along ``nodes2``. final_t (List[float]): The list of accepted intersection parameters ``t``. """ s_val, t_val = _intersection_helpers.newton_refine( s_val, nodes1, t_val, nodes2 ) s_val, success_s = _helpers.wiggle_interval(s_val) t_val, success_t = _helpers.wiggle_interval(t_val) if not (success_s and success_t): return final_s.append(s_val) final_t.append(t_val)
[ "def", "_resolve_and_add", "(", "nodes1", ",", "s_val", ",", "final_s", ",", "nodes2", ",", "t_val", ",", "final_t", ")", ":", "s_val", ",", "t_val", "=", "_intersection_helpers", ".", "newton_refine", "(", "s_val", ",", "nodes1", ",", "t_val", ",", "nodes...
Resolve a computed intersection and add to lists. We perform one Newton step to deal with any residual issues of high-degree polynomial solves (one of which depends on the already approximate ``x_val, y_val``). Args: nodes1 (numpy.ndarray): The nodes in the first curve. s_val (float): The approximate intersection parameter along ``nodes1``. final_s (List[float]): The list of accepted intersection parameters ``s``. nodes2 (numpy.ndarray): The nodes in the second curve. t_val (float): The approximate intersection parameter along ``nodes2``. final_t (List[float]): The list of accepted intersection parameters ``t``.
[ "Resolve", "a", "computed", "intersection", "and", "add", "to", "lists", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1225-L1253
train
54,172
dhermes/bezier
src/bezier/_algebraic_intersection.py
intersect_curves
def intersect_curves(nodes1, nodes2): r"""Intersect two parametric B |eacute| zier curves. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2 x N`` array of intersection parameters. Each row contains a pair of values :math:`s` and :math:`t` (each in :math:`\left[0, 1\right]`) such that the curves intersect: :math:`B_1(s) = B_2(t)`. Raises: NotImplementedError: If the "intersection polynomial" is all zeros -- which indicates coincident curves. """ nodes1 = _curve_helpers.full_reduce(nodes1) nodes2 = _curve_helpers.full_reduce(nodes2) _, num_nodes1 = nodes1.shape _, num_nodes2 = nodes2.shape swapped = False if num_nodes1 > num_nodes2: nodes1, nodes2 = nodes2, nodes1 swapped = True coeffs = normalize_polynomial(to_power_basis(nodes1, nodes2)) if np.all(coeffs == 0.0): raise NotImplementedError(_COINCIDENT_ERR) _check_non_simple(coeffs) t_vals = roots_in_unit_interval(coeffs) final_s = [] final_t = [] for t_val in t_vals: (x_val,), (y_val,) = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t_val]) ) s_val = locate_point(nodes1, x_val, y_val) if s_val is not None: _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t) result = np.zeros((2, len(final_s)), order="F") if swapped: final_s, final_t = final_t, final_s result[0, :] = final_s result[1, :] = final_t return result
python
def intersect_curves(nodes1, nodes2): r"""Intersect two parametric B |eacute| zier curves. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2 x N`` array of intersection parameters. Each row contains a pair of values :math:`s` and :math:`t` (each in :math:`\left[0, 1\right]`) such that the curves intersect: :math:`B_1(s) = B_2(t)`. Raises: NotImplementedError: If the "intersection polynomial" is all zeros -- which indicates coincident curves. """ nodes1 = _curve_helpers.full_reduce(nodes1) nodes2 = _curve_helpers.full_reduce(nodes2) _, num_nodes1 = nodes1.shape _, num_nodes2 = nodes2.shape swapped = False if num_nodes1 > num_nodes2: nodes1, nodes2 = nodes2, nodes1 swapped = True coeffs = normalize_polynomial(to_power_basis(nodes1, nodes2)) if np.all(coeffs == 0.0): raise NotImplementedError(_COINCIDENT_ERR) _check_non_simple(coeffs) t_vals = roots_in_unit_interval(coeffs) final_s = [] final_t = [] for t_val in t_vals: (x_val,), (y_val,) = _curve_helpers.evaluate_multi( nodes2, np.asfortranarray([t_val]) ) s_val = locate_point(nodes1, x_val, y_val) if s_val is not None: _resolve_and_add(nodes1, s_val, final_s, nodes2, t_val, final_t) result = np.zeros((2, len(final_s)), order="F") if swapped: final_s, final_t = final_t, final_s result[0, :] = final_s result[1, :] = final_t return result
[ "def", "intersect_curves", "(", "nodes1", ",", "nodes2", ")", ":", "nodes1", "=", "_curve_helpers", ".", "full_reduce", "(", "nodes1", ")", "nodes2", "=", "_curve_helpers", ".", "full_reduce", "(", "nodes2", ")", "_", ",", "num_nodes1", "=", "nodes1", ".", ...
r"""Intersect two parametric B |eacute| zier curves. Args: nodes1 (numpy.ndarray): The nodes in the first curve. nodes2 (numpy.ndarray): The nodes in the second curve. Returns: numpy.ndarray: ``2 x N`` array of intersection parameters. Each row contains a pair of values :math:`s` and :math:`t` (each in :math:`\left[0, 1\right]`) such that the curves intersect: :math:`B_1(s) = B_2(t)`. Raises: NotImplementedError: If the "intersection polynomial" is all zeros -- which indicates coincident curves.
[ "r", "Intersect", "two", "parametric", "B", "|eacute|", "zier", "curves", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1256-L1301
train
54,173
dhermes/bezier
src/bezier/_algebraic_intersection.py
poly_to_power_basis
def poly_to_power_basis(bezier_coeffs): """Convert a B |eacute| zier curve to polynomial in power basis. .. note:: This assumes, but does not verify, that the "B |eacute| zier degree" matches the true degree of the curve. Callers can guarantee this by calling :func:`.full_reduce`. Args: bezier_coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: 1D array of coefficients in monomial basis. Raises: .UnsupportedDegree: If the degree of the curve is not among 0, 1, 2 or 3. """ num_coeffs, = bezier_coeffs.shape if num_coeffs == 1: return bezier_coeffs elif num_coeffs == 2: # C0 (1 - s) + C1 s = C0 + (C1 - C0) s coeff0, coeff1 = bezier_coeffs return np.asfortranarray([coeff0, coeff1 - coeff0]) elif num_coeffs == 3: # C0 (1 - s)^2 + C1 2 (1 - s) s + C2 s^2 # = C0 + 2(C1 - C0) s + (C2 - 2 C1 + C0) s^2 coeff0, coeff1, coeff2 = bezier_coeffs return np.asfortranarray( [coeff0, 2.0 * (coeff1 - coeff0), coeff2 - 2.0 * coeff1 + coeff0] ) elif num_coeffs == 4: # C0 (1 - s)^3 + C1 3 (1 - s)^2 + C2 3 (1 - s) s^2 + C3 s^3 # = C0 + 3(C1 - C0) s + 3(C2 - 2 C1 + C0) s^2 + # (C3 - 3 C2 + 3 C1 - C0) s^3 coeff0, coeff1, coeff2, coeff3 = bezier_coeffs return np.asfortranarray( [ coeff0, 3.0 * (coeff1 - coeff0), 3.0 * (coeff2 - 2.0 * coeff1 + coeff0), coeff3 - 3.0 * coeff2 + 3.0 * coeff1 - coeff0, ] ) else: raise _helpers.UnsupportedDegree( num_coeffs - 1, supported=(0, 1, 2, 3) )
python
def poly_to_power_basis(bezier_coeffs): """Convert a B |eacute| zier curve to polynomial in power basis. .. note:: This assumes, but does not verify, that the "B |eacute| zier degree" matches the true degree of the curve. Callers can guarantee this by calling :func:`.full_reduce`. Args: bezier_coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: 1D array of coefficients in monomial basis. Raises: .UnsupportedDegree: If the degree of the curve is not among 0, 1, 2 or 3. """ num_coeffs, = bezier_coeffs.shape if num_coeffs == 1: return bezier_coeffs elif num_coeffs == 2: # C0 (1 - s) + C1 s = C0 + (C1 - C0) s coeff0, coeff1 = bezier_coeffs return np.asfortranarray([coeff0, coeff1 - coeff0]) elif num_coeffs == 3: # C0 (1 - s)^2 + C1 2 (1 - s) s + C2 s^2 # = C0 + 2(C1 - C0) s + (C2 - 2 C1 + C0) s^2 coeff0, coeff1, coeff2 = bezier_coeffs return np.asfortranarray( [coeff0, 2.0 * (coeff1 - coeff0), coeff2 - 2.0 * coeff1 + coeff0] ) elif num_coeffs == 4: # C0 (1 - s)^3 + C1 3 (1 - s)^2 + C2 3 (1 - s) s^2 + C3 s^3 # = C0 + 3(C1 - C0) s + 3(C2 - 2 C1 + C0) s^2 + # (C3 - 3 C2 + 3 C1 - C0) s^3 coeff0, coeff1, coeff2, coeff3 = bezier_coeffs return np.asfortranarray( [ coeff0, 3.0 * (coeff1 - coeff0), 3.0 * (coeff2 - 2.0 * coeff1 + coeff0), coeff3 - 3.0 * coeff2 + 3.0 * coeff1 - coeff0, ] ) else: raise _helpers.UnsupportedDegree( num_coeffs - 1, supported=(0, 1, 2, 3) )
[ "def", "poly_to_power_basis", "(", "bezier_coeffs", ")", ":", "num_coeffs", ",", "=", "bezier_coeffs", ".", "shape", "if", "num_coeffs", "==", "1", ":", "return", "bezier_coeffs", "elif", "num_coeffs", "==", "2", ":", "# C0 (1 - s) + C1 s = C0 + (C1 - C0) s", "coeff...
Convert a B |eacute| zier curve to polynomial in power basis. .. note:: This assumes, but does not verify, that the "B |eacute| zier degree" matches the true degree of the curve. Callers can guarantee this by calling :func:`.full_reduce`. Args: bezier_coeffs (numpy.ndarray): A 1D array of coefficients in the Bernstein basis. Returns: numpy.ndarray: 1D array of coefficients in monomial basis. Raises: .UnsupportedDegree: If the degree of the curve is not among 0, 1, 2 or 3.
[ "Convert", "a", "B", "|eacute|", "zier", "curve", "to", "polynomial", "in", "power", "basis", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1304-L1358
train
54,174
dhermes/bezier
src/bezier/_algebraic_intersection.py
locate_point
def locate_point(nodes, x_val, y_val): r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. x_val (float): The :math:`x`-coordinate of the point. y_val (float): The :math:`y`-coordinate of the point. Returns: Optional[float]: The parameter on the curve (if it exists). """ # First, reduce to the true degree of x(s) and y(s). zero1 = _curve_helpers.full_reduce(nodes[[0], :]) - x_val zero2 = _curve_helpers.full_reduce(nodes[[1], :]) - y_val # Make sure we have the lowest degree in front, to make the polynomial # solve have the fewest number of roots. if zero1.shape[1] > zero2.shape[1]: zero1, zero2 = zero2, zero1 # If the "smallest" is a constant, we can't find any roots from it. if zero1.shape[1] == 1: # NOTE: We assume that callers won't pass ``nodes`` that are # degree 0, so if ``zero1`` is a constant, ``zero2`` won't be. zero1, zero2 = zero2, zero1 power_basis1 = poly_to_power_basis(zero1[0, :]) all_roots = roots_in_unit_interval(power_basis1) if all_roots.size == 0: return None # NOTE: We normalize ``power_basis2`` because we want to check for # "zero" values, i.e. f2(s) == 0. power_basis2 = normalize_polynomial(poly_to_power_basis(zero2[0, :])) near_zero = np.abs(polynomial.polyval(all_roots, power_basis2)) index = np.argmin(near_zero) if near_zero[index] < _ZERO_THRESHOLD: return all_roots[index] return None
python
def locate_point(nodes, x_val, y_val): r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. x_val (float): The :math:`x`-coordinate of the point. y_val (float): The :math:`y`-coordinate of the point. Returns: Optional[float]: The parameter on the curve (if it exists). """ # First, reduce to the true degree of x(s) and y(s). zero1 = _curve_helpers.full_reduce(nodes[[0], :]) - x_val zero2 = _curve_helpers.full_reduce(nodes[[1], :]) - y_val # Make sure we have the lowest degree in front, to make the polynomial # solve have the fewest number of roots. if zero1.shape[1] > zero2.shape[1]: zero1, zero2 = zero2, zero1 # If the "smallest" is a constant, we can't find any roots from it. if zero1.shape[1] == 1: # NOTE: We assume that callers won't pass ``nodes`` that are # degree 0, so if ``zero1`` is a constant, ``zero2`` won't be. zero1, zero2 = zero2, zero1 power_basis1 = poly_to_power_basis(zero1[0, :]) all_roots = roots_in_unit_interval(power_basis1) if all_roots.size == 0: return None # NOTE: We normalize ``power_basis2`` because we want to check for # "zero" values, i.e. f2(s) == 0. power_basis2 = normalize_polynomial(poly_to_power_basis(zero2[0, :])) near_zero = np.abs(polynomial.polyval(all_roots, power_basis2)) index = np.argmin(near_zero) if near_zero[index] < _ZERO_THRESHOLD: return all_roots[index] return None
[ "def", "locate_point", "(", "nodes", ",", "x_val", ",", "y_val", ")", ":", "# First, reduce to the true degree of x(s) and y(s).", "zero1", "=", "_curve_helpers", ".", "full_reduce", "(", "nodes", "[", "[", "0", "]", ",", ":", "]", ")", "-", "x_val", "zero2", ...
r"""Find the parameter corresponding to a point on a curve. .. note:: This assumes that the curve :math:`B(s, t)` defined by ``nodes`` lives in :math:`\mathbf{R}^2`. Args: nodes (numpy.ndarray): The nodes defining a B |eacute| zier curve. x_val (float): The :math:`x`-coordinate of the point. y_val (float): The :math:`y`-coordinate of the point. Returns: Optional[float]: The parameter on the curve (if it exists).
[ "r", "Find", "the", "parameter", "corresponding", "to", "a", "point", "on", "a", "curve", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_algebraic_intersection.py#L1361-L1402
train
54,175
dhermes/bezier
src/bezier/_helpers.py
_vector_close
def _vector_close(vec1, vec2, eps=_EPS): r"""Checks that two vectors are equal to some threshold. Does so by computing :math:`s_1 = \|v_1\|_2` and :math:`s_2 = \|v_2\|_2` and then checking if .. math:: \|v_1 - v_2\|_2 \leq \varepsilon \min(s_1, s_2) where :math:`\varepsilon = 2^{-40} \approx 10^{-12}` is a fixed threshold. In the rare case that one of ``vec1`` or ``vec2`` is the zero vector (i.e. when :math:`\min(s_1, s_2) = 0`) instead checks that the other vector is close enough to zero: .. math:: \|v_1\|_2 = 0 \Longrightarrow \|v_2\|_2 \leq \varepsilon .. note:: This function assumes that both vectors have finite values, i.e. that no NaN or infinite numbers occur. NumPy provides :func:`np.allclose` for coverage of **all** cases. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: vec1 (numpy.ndarray): First vector (1D) for comparison. vec2 (numpy.ndarray): Second vector (1D) for comparison. eps (float): Error threshold. Defaults to :math:`2^{-40}`. Returns: bool: Flag indicating if they are close to precision. """ # NOTE: This relies on ``vec1`` and ``vec2`` being one-dimensional # vectors so NumPy doesn't try to use a matrix norm. size1 = np.linalg.norm(vec1, ord=2) size2 = np.linalg.norm(vec2, ord=2) if size1 == 0: return size2 <= eps elif size2 == 0: return size1 <= eps else: upper_bound = eps * min(size1, size2) return np.linalg.norm(vec1 - vec2, ord=2) <= upper_bound
python
def _vector_close(vec1, vec2, eps=_EPS): r"""Checks that two vectors are equal to some threshold. Does so by computing :math:`s_1 = \|v_1\|_2` and :math:`s_2 = \|v_2\|_2` and then checking if .. math:: \|v_1 - v_2\|_2 \leq \varepsilon \min(s_1, s_2) where :math:`\varepsilon = 2^{-40} \approx 10^{-12}` is a fixed threshold. In the rare case that one of ``vec1`` or ``vec2`` is the zero vector (i.e. when :math:`\min(s_1, s_2) = 0`) instead checks that the other vector is close enough to zero: .. math:: \|v_1\|_2 = 0 \Longrightarrow \|v_2\|_2 \leq \varepsilon .. note:: This function assumes that both vectors have finite values, i.e. that no NaN or infinite numbers occur. NumPy provides :func:`np.allclose` for coverage of **all** cases. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: vec1 (numpy.ndarray): First vector (1D) for comparison. vec2 (numpy.ndarray): Second vector (1D) for comparison. eps (float): Error threshold. Defaults to :math:`2^{-40}`. Returns: bool: Flag indicating if they are close to precision. """ # NOTE: This relies on ``vec1`` and ``vec2`` being one-dimensional # vectors so NumPy doesn't try to use a matrix norm. size1 = np.linalg.norm(vec1, ord=2) size2 = np.linalg.norm(vec2, ord=2) if size1 == 0: return size2 <= eps elif size2 == 0: return size1 <= eps else: upper_bound = eps * min(size1, size2) return np.linalg.norm(vec1 - vec2, ord=2) <= upper_bound
[ "def", "_vector_close", "(", "vec1", ",", "vec2", ",", "eps", "=", "_EPS", ")", ":", "# NOTE: This relies on ``vec1`` and ``vec2`` being one-dimensional", "# vectors so NumPy doesn't try to use a matrix norm.", "size1", "=", "np", ".", "linalg", ".", "norm", "(", "v...
r"""Checks that two vectors are equal to some threshold. Does so by computing :math:`s_1 = \|v_1\|_2` and :math:`s_2 = \|v_2\|_2` and then checking if .. math:: \|v_1 - v_2\|_2 \leq \varepsilon \min(s_1, s_2) where :math:`\varepsilon = 2^{-40} \approx 10^{-12}` is a fixed threshold. In the rare case that one of ``vec1`` or ``vec2`` is the zero vector (i.e. when :math:`\min(s_1, s_2) = 0`) instead checks that the other vector is close enough to zero: .. math:: \|v_1\|_2 = 0 \Longrightarrow \|v_2\|_2 \leq \varepsilon .. note:: This function assumes that both vectors have finite values, i.e. that no NaN or infinite numbers occur. NumPy provides :func:`np.allclose` for coverage of **all** cases. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: vec1 (numpy.ndarray): First vector (1D) for comparison. vec2 (numpy.ndarray): Second vector (1D) for comparison. eps (float): Error threshold. Defaults to :math:`2^{-40}`. Returns: bool: Flag indicating if they are close to precision.
[ "r", "Checks", "that", "two", "vectors", "are", "equal", "to", "some", "threshold", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L36-L86
train
54,176
dhermes/bezier
src/bezier/_helpers.py
_bbox
def _bbox(nodes): """Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple[float, float, float, float]: The left, right, bottom and top bounds for the box. """ left, bottom = np.min(nodes, axis=1) right, top = np.max(nodes, axis=1) return left, right, bottom, top
python
def _bbox(nodes): """Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple[float, float, float, float]: The left, right, bottom and top bounds for the box. """ left, bottom = np.min(nodes, axis=1) right, top = np.max(nodes, axis=1) return left, right, bottom, top
[ "def", "_bbox", "(", "nodes", ")", ":", "left", ",", "bottom", "=", "np", ".", "min", "(", "nodes", ",", "axis", "=", "1", ")", "right", ",", "top", "=", "np", ".", "max", "(", "nodes", ",", "axis", "=", "1", ")", "return", "left", ",", "righ...
Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple[float, float, float, float]: The left, right, bottom and top bounds for the box.
[ "Get", "the", "bounding", "box", "for", "set", "of", "points", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L115-L132
train
54,177
dhermes/bezier
src/bezier/_helpers.py
_contains_nd
def _contains_nd(nodes, point): r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point in the same dimension as ``nodes``. Returns: bool: Indicating containment. """ min_vals = np.min(nodes, axis=1) if not np.all(min_vals <= point): return False max_vals = np.max(nodes, axis=1) if not np.all(point <= max_vals): return False return True
python
def _contains_nd(nodes, point): r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point in the same dimension as ``nodes``. Returns: bool: Indicating containment. """ min_vals = np.min(nodes, axis=1) if not np.all(min_vals <= point): return False max_vals = np.max(nodes, axis=1) if not np.all(point <= max_vals): return False return True
[ "def", "_contains_nd", "(", "nodes", ",", "point", ")", ":", "min_vals", "=", "np", ".", "min", "(", "nodes", ",", "axis", "=", "1", ")", "if", "not", "np", ".", "all", "(", "min_vals", "<=", "point", ")", ":", "return", "False", "max_vals", "=", ...
r"""Predicate indicating if a point is within a bounding box. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. point (numpy.ndarray): A 1D NumPy array representing a point in the same dimension as ``nodes``. Returns: bool: Indicating containment.
[ "r", "Predicate", "indicating", "if", "a", "point", "is", "within", "a", "bounding", "box", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L135-L159
train
54,178
dhermes/bezier
src/bezier/_helpers.py
matrix_product
def matrix_product(mat1, mat2): """Compute the product of two Fortran contiguous matrices. This is to avoid the overhead of NumPy converting to C-contiguous before computing a matrix product. Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be C-contiguous without a copy, then the product ``P = B^T A^T`` will be C-contiguous and we can return the view ``P^T`` without a copy. Args: mat1 (numpy.ndarray): The left-hand side matrix. mat2 (numpy.ndarray): The right-hand side matrix. Returns: numpy.ndarray: The product of the two matrices. """ return np.dot(mat2.T, mat1.T).T
python
def matrix_product(mat1, mat2): """Compute the product of two Fortran contiguous matrices. This is to avoid the overhead of NumPy converting to C-contiguous before computing a matrix product. Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be C-contiguous without a copy, then the product ``P = B^T A^T`` will be C-contiguous and we can return the view ``P^T`` without a copy. Args: mat1 (numpy.ndarray): The left-hand side matrix. mat2 (numpy.ndarray): The right-hand side matrix. Returns: numpy.ndarray: The product of the two matrices. """ return np.dot(mat2.T, mat1.T).T
[ "def", "matrix_product", "(", "mat1", ",", "mat2", ")", ":", "return", "np", ".", "dot", "(", "mat2", ".", "T", ",", "mat1", ".", "T", ")", ".", "T" ]
Compute the product of two Fortran contiguous matrices. This is to avoid the overhead of NumPy converting to C-contiguous before computing a matrix product. Does so via ``A B = (B^T A^T)^T`` since ``B^T`` and ``A^T`` will be C-contiguous without a copy, then the product ``P = B^T A^T`` will be C-contiguous and we can return the view ``P^T`` without a copy. Args: mat1 (numpy.ndarray): The left-hand side matrix. mat2 (numpy.ndarray): The right-hand side matrix. Returns: numpy.ndarray: The product of the two matrices.
[ "Compute", "the", "product", "of", "two", "Fortran", "contiguous", "matrices", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L190-L207
train
54,179
dhermes/bezier
src/bezier/_helpers.py
cross_product_compare
def cross_product_compare(start, candidate1, candidate2): """Compare two relative changes by their cross-product. This is meant to be a way to determine which vector is more "inside" relative to ``start``. .. note:: This is a helper for :func:`_simple_convex_hull`. Args: start (numpy.ndarray): The start vector (as 1D NumPy array with 2 elements). candidate1 (numpy.ndarray): The first candidate vector (as 1D NumPy array with 2 elements). candidate2 (numpy.ndarray): The second candidate vector (as 1D NumPy array with 2 elements). Returns: float: The cross product of the two differences. """ delta1 = candidate1 - start delta2 = candidate2 - start return cross_product(delta1, delta2)
python
def cross_product_compare(start, candidate1, candidate2): """Compare two relative changes by their cross-product. This is meant to be a way to determine which vector is more "inside" relative to ``start``. .. note:: This is a helper for :func:`_simple_convex_hull`. Args: start (numpy.ndarray): The start vector (as 1D NumPy array with 2 elements). candidate1 (numpy.ndarray): The first candidate vector (as 1D NumPy array with 2 elements). candidate2 (numpy.ndarray): The second candidate vector (as 1D NumPy array with 2 elements). Returns: float: The cross product of the two differences. """ delta1 = candidate1 - start delta2 = candidate2 - start return cross_product(delta1, delta2)
[ "def", "cross_product_compare", "(", "start", ",", "candidate1", ",", "candidate2", ")", ":", "delta1", "=", "candidate1", "-", "start", "delta2", "=", "candidate2", "-", "start", "return", "cross_product", "(", "delta1", ",", "delta2", ")" ]
Compare two relative changes by their cross-product. This is meant to be a way to determine which vector is more "inside" relative to ``start``. .. note:: This is a helper for :func:`_simple_convex_hull`. Args: start (numpy.ndarray): The start vector (as 1D NumPy array with 2 elements). candidate1 (numpy.ndarray): The first candidate vector (as 1D NumPy array with 2 elements). candidate2 (numpy.ndarray): The second candidate vector (as 1D NumPy array with 2 elements). Returns: float: The cross product of the two differences.
[ "Compare", "two", "relative", "changes", "by", "their", "cross", "-", "product", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L248-L271
train
54,180
dhermes/bezier
src/bezier/_helpers.py
in_sorted
def in_sorted(values, value): """Checks if a value is in a sorted list. Uses the :mod:`bisect` builtin to find the insertion point for ``value``. Args: values (List[int]): Integers sorted in ascending order. value (int): Value to check if contained in ``values``. Returns: bool: Indicating if the value is contained. """ index = bisect.bisect_left(values, value) if index >= len(values): return False return values[index] == value
python
def in_sorted(values, value): """Checks if a value is in a sorted list. Uses the :mod:`bisect` builtin to find the insertion point for ``value``. Args: values (List[int]): Integers sorted in ascending order. value (int): Value to check if contained in ``values``. Returns: bool: Indicating if the value is contained. """ index = bisect.bisect_left(values, value) if index >= len(values): return False return values[index] == value
[ "def", "in_sorted", "(", "values", ",", "value", ")", ":", "index", "=", "bisect", ".", "bisect_left", "(", "values", ",", "value", ")", "if", "index", ">=", "len", "(", "values", ")", ":", "return", "False", "return", "values", "[", "index", "]", "=...
Checks if a value is in a sorted list. Uses the :mod:`bisect` builtin to find the insertion point for ``value``. Args: values (List[int]): Integers sorted in ascending order. value (int): Value to check if contained in ``values``. Returns: bool: Indicating if the value is contained.
[ "Checks", "if", "a", "value", "is", "in", "a", "sorted", "list", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L274-L291
train
54,181
dhermes/bezier
src/bezier/_helpers.py
_simple_convex_hull
def _simple_convex_hull(points): r"""Compute the convex hull for a set of points. .. _wikibooks: https://en.wikibooks.org/wiki/Algorithm_Implementation/\ Geometry/Convex_hull/Monotone_chain This uses Andrew's monotone chain convex hull algorithm and this code used a `wikibooks`_ implementation as motivation. tion. The code there is licensed CC BY-SA 3.0. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Note that ``scipy.spatial.ConvexHull`` can do this as well (via Qhull), but that would require a hard dependency on ``scipy`` and that helper computes much more than we need. .. note:: This computes the convex hull in a "naive" way. It's expected that internal callers of this function will have a small number of points so ``n log n`` vs. ``n^2`` vs. ``n`` aren't that relevant. Args: points (numpy.ndarray): A ``2 x N`` array (``float64``) of points. Returns: numpy.ndarray: The ``2 x N`` array (``float64``) of ordered points in the polygonal convex hull. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-branches if points.size == 0: return points # First, drop duplicates. unique_points = np.unique(points, axis=1) _, num_points = unique_points.shape if num_points < 2: return unique_points # Then sort the data in left-to-right order (and break ties by y-value). points = np.empty((2, num_points), order="F") for index, xy_val in enumerate( sorted(tuple(column) for column in unique_points.T) ): points[:, index] = xy_val # After sorting, if there are only 2 points, return. if num_points < 3: return points # Build lower hull lower = [0, 1] for index in six.moves.xrange(2, num_points): point2 = points[:, index] while len(lower) >= 2: point0 = points[:, lower[-2]] point1 = points[:, lower[-1]] if cross_product_compare(point0, point1, point2) > 0: break else: lower.pop() lower.append(index) # Build upper hull upper = [num_points - 1] for index in six.moves.xrange(num_points - 2, -1, -1): # Don't consider indices from the lower hull (other than the ends). if index > 0 and in_sorted(lower, index): continue point2 = points[:, index] while len(upper) >= 2: point0 = points[:, upper[-2]] point1 = points[:, upper[-1]] if cross_product_compare(point0, point1, point2) > 0: break else: upper.pop() upper.append(index) # **Both** corners are double counted. size_polygon = len(lower) + len(upper) - 2 polygon = np.empty((2, size_polygon), order="F") for index, column in enumerate(lower[:-1]): polygon[:, index] = points[:, column] index_start = len(lower) - 1 for index, column in enumerate(upper[:-1]): polygon[:, index + index_start] = points[:, column] return polygon
python
def _simple_convex_hull(points): r"""Compute the convex hull for a set of points. .. _wikibooks: https://en.wikibooks.org/wiki/Algorithm_Implementation/\ Geometry/Convex_hull/Monotone_chain This uses Andrew's monotone chain convex hull algorithm and this code used a `wikibooks`_ implementation as motivation. tion. The code there is licensed CC BY-SA 3.0. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Note that ``scipy.spatial.ConvexHull`` can do this as well (via Qhull), but that would require a hard dependency on ``scipy`` and that helper computes much more than we need. .. note:: This computes the convex hull in a "naive" way. It's expected that internal callers of this function will have a small number of points so ``n log n`` vs. ``n^2`` vs. ``n`` aren't that relevant. Args: points (numpy.ndarray): A ``2 x N`` array (``float64``) of points. Returns: numpy.ndarray: The ``2 x N`` array (``float64``) of ordered points in the polygonal convex hull. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-branches if points.size == 0: return points # First, drop duplicates. unique_points = np.unique(points, axis=1) _, num_points = unique_points.shape if num_points < 2: return unique_points # Then sort the data in left-to-right order (and break ties by y-value). points = np.empty((2, num_points), order="F") for index, xy_val in enumerate( sorted(tuple(column) for column in unique_points.T) ): points[:, index] = xy_val # After sorting, if there are only 2 points, return. if num_points < 3: return points # Build lower hull lower = [0, 1] for index in six.moves.xrange(2, num_points): point2 = points[:, index] while len(lower) >= 2: point0 = points[:, lower[-2]] point1 = points[:, lower[-1]] if cross_product_compare(point0, point1, point2) > 0: break else: lower.pop() lower.append(index) # Build upper hull upper = [num_points - 1] for index in six.moves.xrange(num_points - 2, -1, -1): # Don't consider indices from the lower hull (other than the ends). if index > 0 and in_sorted(lower, index): continue point2 = points[:, index] while len(upper) >= 2: point0 = points[:, upper[-2]] point1 = points[:, upper[-1]] if cross_product_compare(point0, point1, point2) > 0: break else: upper.pop() upper.append(index) # **Both** corners are double counted. size_polygon = len(lower) + len(upper) - 2 polygon = np.empty((2, size_polygon), order="F") for index, column in enumerate(lower[:-1]): polygon[:, index] = points[:, column] index_start = len(lower) - 1 for index, column in enumerate(upper[:-1]): polygon[:, index + index_start] = points[:, column] return polygon
[ "def", "_simple_convex_hull", "(", "points", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-branches", "if", "points", ".", "size", "==", "0", ":", "return", "points", "# First,...
r"""Compute the convex hull for a set of points. .. _wikibooks: https://en.wikibooks.org/wiki/Algorithm_Implementation/\ Geometry/Convex_hull/Monotone_chain This uses Andrew's monotone chain convex hull algorithm and this code used a `wikibooks`_ implementation as motivation. tion. The code there is licensed CC BY-SA 3.0. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Note that ``scipy.spatial.ConvexHull`` can do this as well (via Qhull), but that would require a hard dependency on ``scipy`` and that helper computes much more than we need. .. note:: This computes the convex hull in a "naive" way. It's expected that internal callers of this function will have a small number of points so ``n log n`` vs. ``n^2`` vs. ``n`` aren't that relevant. Args: points (numpy.ndarray): A ``2 x N`` array (``float64``) of points. Returns: numpy.ndarray: The ``2 x N`` array (``float64``) of ordered points in the polygonal convex hull.
[ "r", "Compute", "the", "convex", "hull", "for", "a", "set", "of", "points", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L294-L384
train
54,182
dhermes/bezier
src/bezier/_helpers.py
is_separating
def is_separating(direction, polygon1, polygon2): """Checks if a given ``direction`` is a separating line for two polygons. .. note:: This is a helper for :func:`_polygon_collide`. Args: direction (numpy.ndarray): A 1D ``2``-array (``float64``) of a potential separating line for the two polygons. polygon1 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. polygon2 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. Returns: bool: Flag indicating if ``direction`` is a separating line. """ # NOTE: We assume throughout that ``norm_squared != 0``. If it **were** # zero that would mean the ``direction`` corresponds to an # invalid edge. norm_squared = direction[0] * direction[0] + direction[1] * direction[1] params = [] vertex = np.empty((2,), order="F") for polygon in (polygon1, polygon2): _, polygon_size = polygon.shape min_param = np.inf max_param = -np.inf for index in six.moves.xrange(polygon_size): vertex[:] = polygon[:, index] param = cross_product(direction, vertex) / norm_squared min_param = min(min_param, param) max_param = max(max_param, param) params.append((min_param, max_param)) # NOTE: The indexing is based on: # params[0] = (min_param1, max_param1) # params[1] = (min_param2, max_param2) return params[0][0] > params[1][1] or params[0][1] < params[1][0]
python
def is_separating(direction, polygon1, polygon2): """Checks if a given ``direction`` is a separating line for two polygons. .. note:: This is a helper for :func:`_polygon_collide`. Args: direction (numpy.ndarray): A 1D ``2``-array (``float64``) of a potential separating line for the two polygons. polygon1 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. polygon2 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. Returns: bool: Flag indicating if ``direction`` is a separating line. """ # NOTE: We assume throughout that ``norm_squared != 0``. If it **were** # zero that would mean the ``direction`` corresponds to an # invalid edge. norm_squared = direction[0] * direction[0] + direction[1] * direction[1] params = [] vertex = np.empty((2,), order="F") for polygon in (polygon1, polygon2): _, polygon_size = polygon.shape min_param = np.inf max_param = -np.inf for index in six.moves.xrange(polygon_size): vertex[:] = polygon[:, index] param = cross_product(direction, vertex) / norm_squared min_param = min(min_param, param) max_param = max(max_param, param) params.append((min_param, max_param)) # NOTE: The indexing is based on: # params[0] = (min_param1, max_param1) # params[1] = (min_param2, max_param2) return params[0][0] > params[1][1] or params[0][1] < params[1][0]
[ "def", "is_separating", "(", "direction", ",", "polygon1", ",", "polygon2", ")", ":", "# NOTE: We assume throughout that ``norm_squared != 0``. If it **were**", "# zero that would mean the ``direction`` corresponds to an", "# invalid edge.", "norm_squared", "=", "direction"...
Checks if a given ``direction`` is a separating line for two polygons. .. note:: This is a helper for :func:`_polygon_collide`. Args: direction (numpy.ndarray): A 1D ``2``-array (``float64``) of a potential separating line for the two polygons. polygon1 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. polygon2 (numpy.ndarray): A ``2 x N`` array (``float64``) of ordered points in a polygon. Returns: bool: Flag indicating if ``direction`` is a separating line.
[ "Checks", "if", "a", "given", "direction", "is", "a", "separating", "line", "for", "two", "polygons", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L387-L424
train
54,183
dhermes/bezier
src/bezier/_helpers.py
solve2x2
def solve2x2(lhs, rhs): """Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func`numpy.linalg.solve` does). * We seek to avoid excessive type- and size-checking, since this special case is already known. Args: lhs (numpy.ndarray) A ``2 x 2`` array of real numbers. rhs (numpy.ndarray) A 1D array of 2 real numbers. Returns: Tuple[bool, float, float]: A triple of * A flag indicating if ``lhs`` is a singular matrix. * The first component of the solution. * The second component of the solution. """ # A <--> lhs[0, 0] # B <--> lhs[0, 1] # C <--> lhs[1, 0] # D <--> lhs[1, 1] # E <--> rhs[0] # F <--> rhs[1] if np.abs(lhs[1, 0]) > np.abs(lhs[0, 0]): # NOTE: We know there is no division by zero here since ``C`` # is **strictly** bigger than **some** value (in magnitude). # [A | B][x] = [E] # [C | D][y] [F] ratio = lhs[0, 0] / lhs[1, 0] # r = A / C # [A - rC | B - rD][x] [E - rF] # [C | D ][y] = [F ] # ==> 0x + (B - rD) y = E - rF denominator = lhs[0, 1] - ratio * lhs[1, 1] if denominator == 0.0: return True, None, None y_val = (rhs[0] - ratio * rhs[1]) / denominator # Cx + Dy = F ==> x = (F - Dy) / C x_val = (rhs[1] - lhs[1, 1] * y_val) / lhs[1, 0] return False, x_val, y_val else: if lhs[0, 0] == 0.0: return True, None, None # [A | B][x] = [E] # [C | D][y] [F] ratio = lhs[1, 0] / lhs[0, 0] # r = C / A # [A | B ][x] = [E ] # [C - rA | D - rB][y] [F - rE] # ==> 0x + (D - rB) y = F - rE denominator = lhs[1, 1] - ratio * lhs[0, 1] if denominator == 0.0: return True, None, None y_val = (rhs[1] - ratio * rhs[0]) / denominator # Ax + By = E ==> x = (E - B y) / A x_val = (rhs[0] - lhs[0, 1] * y_val) / lhs[0, 0] return False, x_val, y_val
python
def solve2x2(lhs, rhs): """Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func`numpy.linalg.solve` does). * We seek to avoid excessive type- and size-checking, since this special case is already known. Args: lhs (numpy.ndarray) A ``2 x 2`` array of real numbers. rhs (numpy.ndarray) A 1D array of 2 real numbers. Returns: Tuple[bool, float, float]: A triple of * A flag indicating if ``lhs`` is a singular matrix. * The first component of the solution. * The second component of the solution. """ # A <--> lhs[0, 0] # B <--> lhs[0, 1] # C <--> lhs[1, 0] # D <--> lhs[1, 1] # E <--> rhs[0] # F <--> rhs[1] if np.abs(lhs[1, 0]) > np.abs(lhs[0, 0]): # NOTE: We know there is no division by zero here since ``C`` # is **strictly** bigger than **some** value (in magnitude). # [A | B][x] = [E] # [C | D][y] [F] ratio = lhs[0, 0] / lhs[1, 0] # r = A / C # [A - rC | B - rD][x] [E - rF] # [C | D ][y] = [F ] # ==> 0x + (B - rD) y = E - rF denominator = lhs[0, 1] - ratio * lhs[1, 1] if denominator == 0.0: return True, None, None y_val = (rhs[0] - ratio * rhs[1]) / denominator # Cx + Dy = F ==> x = (F - Dy) / C x_val = (rhs[1] - lhs[1, 1] * y_val) / lhs[1, 0] return False, x_val, y_val else: if lhs[0, 0] == 0.0: return True, None, None # [A | B][x] = [E] # [C | D][y] [F] ratio = lhs[1, 0] / lhs[0, 0] # r = C / A # [A | B ][x] = [E ] # [C - rA | D - rB][y] [F - rE] # ==> 0x + (D - rB) y = F - rE denominator = lhs[1, 1] - ratio * lhs[0, 1] if denominator == 0.0: return True, None, None y_val = (rhs[1] - ratio * rhs[0]) / denominator # Ax + By = E ==> x = (E - B y) / A x_val = (rhs[0] - lhs[0, 1] * y_val) / lhs[0, 0] return False, x_val, y_val
[ "def", "solve2x2", "(", "lhs", ",", "rhs", ")", ":", "# A <--> lhs[0, 0]", "# B <--> lhs[0, 1]", "# C <--> lhs[1, 0]", "# D <--> lhs[1, 1]", "# E <--> rhs[0]", "# F <--> rhs[1]", "if", "np", ".", "abs", "(", "lhs", "[", "1", ",", "0", "]", ")", ">", "np", ".",...
Solve a square 2 x 2 system via LU factorization. This is meant to be a stand-in for LAPACK's ``dgesv``, which just wraps two calls to ``dgetrf`` and ``dgetrs``. We wrap for two reasons: * We seek to avoid exceptions as part of the control flow (which is what :func`numpy.linalg.solve` does). * We seek to avoid excessive type- and size-checking, since this special case is already known. Args: lhs (numpy.ndarray) A ``2 x 2`` array of real numbers. rhs (numpy.ndarray) A 1D array of 2 real numbers. Returns: Tuple[bool, float, float]: A triple of * A flag indicating if ``lhs`` is a singular matrix. * The first component of the solution. * The second component of the solution.
[ "Solve", "a", "square", "2", "x", "2", "system", "via", "LU", "factorization", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_helpers.py#L463-L528
train
54,184
dhermes/bezier
src/bezier/_plot_helpers.py
add_plot_boundary
def add_plot_boundary(ax, padding=0.125): """Add a buffer of empty space around a plot boundary. .. note:: This only uses ``line`` data from the axis. It **could** use ``patch`` data, but doesn't at this time. Args: ax (matplotlib.artist.Artist): A matplotlib axis. padding (Optional[float]): Amount (as a fraction of width and height) of padding to add around data. Defaults to ``0.125``. """ nodes = np.asfortranarray( np.vstack([line.get_xydata() for line in ax.lines]).T ) left, right, bottom, top = _helpers.bbox(nodes) center_x = 0.5 * (right + left) delta_x = right - left center_y = 0.5 * (top + bottom) delta_y = top - bottom multiplier = (1.0 + padding) * 0.5 ax.set_xlim( center_x - multiplier * delta_x, center_x + multiplier * delta_x ) ax.set_ylim( center_y - multiplier * delta_y, center_y + multiplier * delta_y )
python
def add_plot_boundary(ax, padding=0.125): """Add a buffer of empty space around a plot boundary. .. note:: This only uses ``line`` data from the axis. It **could** use ``patch`` data, but doesn't at this time. Args: ax (matplotlib.artist.Artist): A matplotlib axis. padding (Optional[float]): Amount (as a fraction of width and height) of padding to add around data. Defaults to ``0.125``. """ nodes = np.asfortranarray( np.vstack([line.get_xydata() for line in ax.lines]).T ) left, right, bottom, top = _helpers.bbox(nodes) center_x = 0.5 * (right + left) delta_x = right - left center_y = 0.5 * (top + bottom) delta_y = top - bottom multiplier = (1.0 + padding) * 0.5 ax.set_xlim( center_x - multiplier * delta_x, center_x + multiplier * delta_x ) ax.set_ylim( center_y - multiplier * delta_y, center_y + multiplier * delta_y )
[ "def", "add_plot_boundary", "(", "ax", ",", "padding", "=", "0.125", ")", ":", "nodes", "=", "np", ".", "asfortranarray", "(", "np", ".", "vstack", "(", "[", "line", ".", "get_xydata", "(", ")", "for", "line", "in", "ax", ".", "lines", "]", ")", "....
Add a buffer of empty space around a plot boundary. .. note:: This only uses ``line`` data from the axis. It **could** use ``patch`` data, but doesn't at this time. Args: ax (matplotlib.artist.Artist): A matplotlib axis. padding (Optional[float]): Amount (as a fraction of width and height) of padding to add around data. Defaults to ``0.125``.
[ "Add", "a", "buffer", "of", "empty", "space", "around", "a", "plot", "boundary", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_plot_helpers.py#L34-L61
train
54,185
dhermes/bezier
src/bezier/_plot_helpers.py
add_patch
def add_patch(ax, color, pts_per_edge, *edges): """Add a polygonal surface patch to a plot. Args: ax (matplotlib.artist.Artist): A matplotlib axis. color (Tuple[float, float, float]): Color as RGB profile. pts_per_edge (int): Number of points to use in polygonal approximation of edge. edges (Tuple[~bezier.curve.Curve, ...]): Curved edges defining a boundary. """ from matplotlib import patches from matplotlib import path as _path_mod s_vals = np.linspace(0.0, 1.0, pts_per_edge) # Evaluate points on each edge. all_points = [] for edge in edges: points = edge.evaluate_multi(s_vals) # We assume the edges overlap and leave out the first point # in each. all_points.append(points[:, 1:]) # Add first point as last point (polygon is closed). first_edge = all_points[0] all_points.append(first_edge[:, [0]]) # Add boundary first. polygon = np.asfortranarray(np.hstack(all_points)) line, = ax.plot(polygon[0, :], polygon[1, :], color=color) # Reset ``color`` in case it was ``None`` and set from color wheel. color = line.get_color() # ``polygon`` is stored Fortran-contiguous with ``x-y`` points in each # column but ``Path()`` wants ``x-y`` points in each row. path = _path_mod.Path(polygon.T) patch = patches.PathPatch(path, facecolor=color, alpha=0.625) ax.add_patch(patch)
python
def add_patch(ax, color, pts_per_edge, *edges): """Add a polygonal surface patch to a plot. Args: ax (matplotlib.artist.Artist): A matplotlib axis. color (Tuple[float, float, float]): Color as RGB profile. pts_per_edge (int): Number of points to use in polygonal approximation of edge. edges (Tuple[~bezier.curve.Curve, ...]): Curved edges defining a boundary. """ from matplotlib import patches from matplotlib import path as _path_mod s_vals = np.linspace(0.0, 1.0, pts_per_edge) # Evaluate points on each edge. all_points = [] for edge in edges: points = edge.evaluate_multi(s_vals) # We assume the edges overlap and leave out the first point # in each. all_points.append(points[:, 1:]) # Add first point as last point (polygon is closed). first_edge = all_points[0] all_points.append(first_edge[:, [0]]) # Add boundary first. polygon = np.asfortranarray(np.hstack(all_points)) line, = ax.plot(polygon[0, :], polygon[1, :], color=color) # Reset ``color`` in case it was ``None`` and set from color wheel. color = line.get_color() # ``polygon`` is stored Fortran-contiguous with ``x-y`` points in each # column but ``Path()`` wants ``x-y`` points in each row. path = _path_mod.Path(polygon.T) patch = patches.PathPatch(path, facecolor=color, alpha=0.625) ax.add_patch(patch)
[ "def", "add_patch", "(", "ax", ",", "color", ",", "pts_per_edge", ",", "*", "edges", ")", ":", "from", "matplotlib", "import", "patches", "from", "matplotlib", "import", "path", "as", "_path_mod", "s_vals", "=", "np", ".", "linspace", "(", "0.0", ",", "1...
Add a polygonal surface patch to a plot. Args: ax (matplotlib.artist.Artist): A matplotlib axis. color (Tuple[float, float, float]): Color as RGB profile. pts_per_edge (int): Number of points to use in polygonal approximation of edge. edges (Tuple[~bezier.curve.Curve, ...]): Curved edges defining a boundary.
[ "Add", "a", "polygonal", "surface", "patch", "to", "a", "plot", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_plot_helpers.py#L64-L98
train
54,186
dhermes/bezier
docs/custom_html_writer.py
CustomHTMLWriter.visit_literal_block
def visit_literal_block(self, node): """Visit a ``literal_block`` node. This verifies the state of each literal / code block. """ language = node.attributes.get("language", "") test_type = node.attributes.get("testnodetype", "") if test_type != "doctest": if language.lower() in ("", "python"): msg = _LITERAL_ERR_TEMPLATE.format( node.rawsource, language, test_type ) raise errors.ExtensionError(msg) # The base classes are not new-style, so we can't use super(). return html.HTMLTranslator.visit_literal_block(self, node)
python
def visit_literal_block(self, node): """Visit a ``literal_block`` node. This verifies the state of each literal / code block. """ language = node.attributes.get("language", "") test_type = node.attributes.get("testnodetype", "") if test_type != "doctest": if language.lower() in ("", "python"): msg = _LITERAL_ERR_TEMPLATE.format( node.rawsource, language, test_type ) raise errors.ExtensionError(msg) # The base classes are not new-style, so we can't use super(). return html.HTMLTranslator.visit_literal_block(self, node)
[ "def", "visit_literal_block", "(", "self", ",", "node", ")", ":", "language", "=", "node", ".", "attributes", ".", "get", "(", "\"language\"", ",", "\"\"", ")", "test_type", "=", "node", ".", "attributes", ".", "get", "(", "\"testnodetype\"", ",", "\"\"", ...
Visit a ``literal_block`` node. This verifies the state of each literal / code block.
[ "Visit", "a", "literal_block", "node", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/docs/custom_html_writer.py#L42-L57
train
54,187
dhermes/bezier
src/bezier/_geometric_intersection.py
_bbox_intersect
def _bbox_intersect(nodes1, nodes2): r"""Bounding box intersection predicate. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Determines if the bounding box of two sets of control points intersects in :math:`\mathbf{R}^2` with non-trivial intersection (i.e. tangent bounding boxes are insufficient). .. note:: Though we assume (and the code relies on this fact) that the nodes are two-dimensional, we don't check it. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier shape. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier shape. Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection. """ left1, right1, bottom1, top1 = _helpers.bbox(nodes1) left2, right2, bottom2, top2 = _helpers.bbox(nodes2) if right2 < left1 or right1 < left2 or top2 < bottom1 or top1 < bottom2: return BoxIntersectionType.DISJOINT if ( right2 == left1 or right1 == left2 or top2 == bottom1 or top1 == bottom2 ): return BoxIntersectionType.TANGENT else: return BoxIntersectionType.INTERSECTION
python
def _bbox_intersect(nodes1, nodes2): r"""Bounding box intersection predicate. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Determines if the bounding box of two sets of control points intersects in :math:`\mathbf{R}^2` with non-trivial intersection (i.e. tangent bounding boxes are insufficient). .. note:: Though we assume (and the code relies on this fact) that the nodes are two-dimensional, we don't check it. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier shape. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier shape. Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection. """ left1, right1, bottom1, top1 = _helpers.bbox(nodes1) left2, right2, bottom2, top2 = _helpers.bbox(nodes2) if right2 < left1 or right1 < left2 or top2 < bottom1 or top1 < bottom2: return BoxIntersectionType.DISJOINT if ( right2 == left1 or right1 == left2 or top2 == bottom1 or top1 == bottom2 ): return BoxIntersectionType.TANGENT else: return BoxIntersectionType.INTERSECTION
[ "def", "_bbox_intersect", "(", "nodes1", ",", "nodes2", ")", ":", "left1", ",", "right1", ",", "bottom1", ",", "top1", "=", "_helpers", ".", "bbox", "(", "nodes1", ")", "left2", ",", "right2", ",", "bottom2", ",", "top2", "=", "_helpers", ".", "bbox", ...
r"""Bounding box intersection predicate. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Determines if the bounding box of two sets of control points intersects in :math:`\mathbf{R}^2` with non-trivial intersection (i.e. tangent bounding boxes are insufficient). .. note:: Though we assume (and the code relies on this fact) that the nodes are two-dimensional, we don't check it. Args: nodes1 (numpy.ndarray): Set of control points for a B |eacute| zier shape. nodes2 (numpy.ndarray): Set of control points for a B |eacute| zier shape. Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection.
[ "r", "Bounding", "box", "intersection", "predicate", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L63-L104
train
54,188
dhermes/bezier
src/bezier/_geometric_intersection.py
linearization_error
def linearization_error(nodes): r"""Compute the maximum error of a linear approximation. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. .. note:: This is a helper for :class:`.Linearization`, which is used during the curve-curve intersection process. We use the line .. math:: L(s) = v_0 (1 - s) + v_n s and compute a bound on the maximum error .. math:: \max_{s \in \left[0, 1\right]} \|B(s) - L(s)\|_2. Rather than computing the actual maximum (a tight bound), we use an upper bound via the remainder from Lagrange interpolation in each component. This leaves us with :math:`\frac{s(s - 1)}{2!}` times the second derivative in each component. The second derivative curve is degree :math:`d = n - 2` and is given by .. math:: B''(s) = n(n - 1) \sum_{j = 0}^{d} \binom{d}{j} s^j (1 - s)^{d - j} \cdot \Delta^2 v_j Due to this form (and the convex combination property of B |eacute| zier Curves) we know each component of the second derivative will be bounded by the maximum of that component among the :math:`\Delta^2 v_j`. For example, the curve .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 3 \\ 1 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 9 \\ -2 \end{array}\right] s^2 has :math:`B''(s) \equiv \left[\begin{array}{c} 6 \\ -8 \end{array}\right]` which has norm :math:`10` everywhere, hence the maximum error is .. math:: \left.\frac{s(1 - s)}{2!} \cdot 10\right|_{s = \frac{1}{2}} = \frac{5}{4}. .. image:: ../images/linearization_error.png :align: center .. testsetup:: linearization-error, linearization-error-fail import numpy as np import bezier from bezier._geometric_intersection import linearization_error .. doctest:: linearization-error >>> nodes = np.asfortranarray([ ... [0.0, 3.0, 9.0], ... [0.0, 1.0, -2.0], ... ]) >>> linearization_error(nodes) 1.25 .. testcleanup:: linearization-error import make_images make_images.linearization_error(nodes) As a **non-example**, consider a "pathological" set of control points: .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^3 + \left[\begin{array}{c} 5 \\ 12 \end{array}\right] 3s(1 - s)^2 + \left[\begin{array}{c} 10 \\ 24 \end{array}\right] 3s^2(1 - s) + \left[\begin{array}{c} 30 \\ 72 \end{array}\right] s^3 By construction, this lies on the line :math:`y = \frac{12x}{5}`, but the parametrization is cubic: :math:`12 \cdot x(s) = 5 \cdot y(s) = 180s(s^2 + 1)`. Hence, the fact that the curve is a line is not accounted for and we take the worse case among the nodes in: .. math:: B''(s) = 3 \cdot 2 \cdot \left( \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 15 \\ 36 \end{array}\right] s\right) which gives a nonzero maximum error: .. doctest:: linearization-error-fail >>> nodes = np.asfortranarray([ ... [0.0, 5.0, 10.0, 30.0], ... [0.0, 12.0, 24.0, 72.0], ... ]) >>> linearization_error(nodes) 29.25 Though it may seem that ``0`` is a more appropriate answer, consider the **goal** of this function. We seek to linearize curves and then intersect the linear approximations. Then the :math:`s`-values from the line-line intersection is lifted back to the curves. Thus the error :math:`\|B(s) - L(s)\|_2` is more relevant than the underyling algebraic curve containing :math:`B(s)`. .. note:: It may be more appropriate to use a **relative** linearization error rather than the **absolute** error provided here. It's unclear if the domain :math:`\left[0, 1\right]` means the error is **already** adequately scaled or if the error should be scaled by the arc length of the curve or the (easier-to-compute) length of the line. Args: nodes (numpy.ndarray): Nodes of a curve. Returns: float: The maximum error between the curve and the linear approximation. """ _, num_nodes = nodes.shape degree = num_nodes - 1 if degree == 1: return 0.0 second_deriv = nodes[:, :-2] - 2.0 * nodes[:, 1:-1] + nodes[:, 2:] worst_case = np.max(np.abs(second_deriv), axis=1) # max_{0 <= s <= 1} s(1 - s)/2 = 1/8 = 0.125 multiplier = 0.125 * degree * (degree - 1) # NOTE: worst_case is 1D due to np.max(), so this is the vector norm. return multiplier * np.linalg.norm(worst_case, ord=2)
python
def linearization_error(nodes): r"""Compute the maximum error of a linear approximation. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. .. note:: This is a helper for :class:`.Linearization`, which is used during the curve-curve intersection process. We use the line .. math:: L(s) = v_0 (1 - s) + v_n s and compute a bound on the maximum error .. math:: \max_{s \in \left[0, 1\right]} \|B(s) - L(s)\|_2. Rather than computing the actual maximum (a tight bound), we use an upper bound via the remainder from Lagrange interpolation in each component. This leaves us with :math:`\frac{s(s - 1)}{2!}` times the second derivative in each component. The second derivative curve is degree :math:`d = n - 2` and is given by .. math:: B''(s) = n(n - 1) \sum_{j = 0}^{d} \binom{d}{j} s^j (1 - s)^{d - j} \cdot \Delta^2 v_j Due to this form (and the convex combination property of B |eacute| zier Curves) we know each component of the second derivative will be bounded by the maximum of that component among the :math:`\Delta^2 v_j`. For example, the curve .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 3 \\ 1 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 9 \\ -2 \end{array}\right] s^2 has :math:`B''(s) \equiv \left[\begin{array}{c} 6 \\ -8 \end{array}\right]` which has norm :math:`10` everywhere, hence the maximum error is .. math:: \left.\frac{s(1 - s)}{2!} \cdot 10\right|_{s = \frac{1}{2}} = \frac{5}{4}. .. image:: ../images/linearization_error.png :align: center .. testsetup:: linearization-error, linearization-error-fail import numpy as np import bezier from bezier._geometric_intersection import linearization_error .. doctest:: linearization-error >>> nodes = np.asfortranarray([ ... [0.0, 3.0, 9.0], ... [0.0, 1.0, -2.0], ... ]) >>> linearization_error(nodes) 1.25 .. testcleanup:: linearization-error import make_images make_images.linearization_error(nodes) As a **non-example**, consider a "pathological" set of control points: .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^3 + \left[\begin{array}{c} 5 \\ 12 \end{array}\right] 3s(1 - s)^2 + \left[\begin{array}{c} 10 \\ 24 \end{array}\right] 3s^2(1 - s) + \left[\begin{array}{c} 30 \\ 72 \end{array}\right] s^3 By construction, this lies on the line :math:`y = \frac{12x}{5}`, but the parametrization is cubic: :math:`12 \cdot x(s) = 5 \cdot y(s) = 180s(s^2 + 1)`. Hence, the fact that the curve is a line is not accounted for and we take the worse case among the nodes in: .. math:: B''(s) = 3 \cdot 2 \cdot \left( \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 15 \\ 36 \end{array}\right] s\right) which gives a nonzero maximum error: .. doctest:: linearization-error-fail >>> nodes = np.asfortranarray([ ... [0.0, 5.0, 10.0, 30.0], ... [0.0, 12.0, 24.0, 72.0], ... ]) >>> linearization_error(nodes) 29.25 Though it may seem that ``0`` is a more appropriate answer, consider the **goal** of this function. We seek to linearize curves and then intersect the linear approximations. Then the :math:`s`-values from the line-line intersection is lifted back to the curves. Thus the error :math:`\|B(s) - L(s)\|_2` is more relevant than the underyling algebraic curve containing :math:`B(s)`. .. note:: It may be more appropriate to use a **relative** linearization error rather than the **absolute** error provided here. It's unclear if the domain :math:`\left[0, 1\right]` means the error is **already** adequately scaled or if the error should be scaled by the arc length of the curve or the (easier-to-compute) length of the line. Args: nodes (numpy.ndarray): Nodes of a curve. Returns: float: The maximum error between the curve and the linear approximation. """ _, num_nodes = nodes.shape degree = num_nodes - 1 if degree == 1: return 0.0 second_deriv = nodes[:, :-2] - 2.0 * nodes[:, 1:-1] + nodes[:, 2:] worst_case = np.max(np.abs(second_deriv), axis=1) # max_{0 <= s <= 1} s(1 - s)/2 = 1/8 = 0.125 multiplier = 0.125 * degree * (degree - 1) # NOTE: worst_case is 1D due to np.max(), so this is the vector norm. return multiplier * np.linalg.norm(worst_case, ord=2)
[ "def", "linearization_error", "(", "nodes", ")", ":", "_", ",", "num_nodes", "=", "nodes", ".", "shape", "degree", "=", "num_nodes", "-", "1", "if", "degree", "==", "1", ":", "return", "0.0", "second_deriv", "=", "nodes", "[", ":", ",", ":", "-", "2"...
r"""Compute the maximum error of a linear approximation. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. .. note:: This is a helper for :class:`.Linearization`, which is used during the curve-curve intersection process. We use the line .. math:: L(s) = v_0 (1 - s) + v_n s and compute a bound on the maximum error .. math:: \max_{s \in \left[0, 1\right]} \|B(s) - L(s)\|_2. Rather than computing the actual maximum (a tight bound), we use an upper bound via the remainder from Lagrange interpolation in each component. This leaves us with :math:`\frac{s(s - 1)}{2!}` times the second derivative in each component. The second derivative curve is degree :math:`d = n - 2` and is given by .. math:: B''(s) = n(n - 1) \sum_{j = 0}^{d} \binom{d}{j} s^j (1 - s)^{d - j} \cdot \Delta^2 v_j Due to this form (and the convex combination property of B |eacute| zier Curves) we know each component of the second derivative will be bounded by the maximum of that component among the :math:`\Delta^2 v_j`. For example, the curve .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^2 + \left[\begin{array}{c} 3 \\ 1 \end{array}\right] 2s(1 - s) + \left[\begin{array}{c} 9 \\ -2 \end{array}\right] s^2 has :math:`B''(s) \equiv \left[\begin{array}{c} 6 \\ -8 \end{array}\right]` which has norm :math:`10` everywhere, hence the maximum error is .. math:: \left.\frac{s(1 - s)}{2!} \cdot 10\right|_{s = \frac{1}{2}} = \frac{5}{4}. .. image:: ../images/linearization_error.png :align: center .. testsetup:: linearization-error, linearization-error-fail import numpy as np import bezier from bezier._geometric_intersection import linearization_error .. doctest:: linearization-error >>> nodes = np.asfortranarray([ ... [0.0, 3.0, 9.0], ... [0.0, 1.0, -2.0], ... ]) >>> linearization_error(nodes) 1.25 .. testcleanup:: linearization-error import make_images make_images.linearization_error(nodes) As a **non-example**, consider a "pathological" set of control points: .. math:: B(s) = \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s)^3 + \left[\begin{array}{c} 5 \\ 12 \end{array}\right] 3s(1 - s)^2 + \left[\begin{array}{c} 10 \\ 24 \end{array}\right] 3s^2(1 - s) + \left[\begin{array}{c} 30 \\ 72 \end{array}\right] s^3 By construction, this lies on the line :math:`y = \frac{12x}{5}`, but the parametrization is cubic: :math:`12 \cdot x(s) = 5 \cdot y(s) = 180s(s^2 + 1)`. Hence, the fact that the curve is a line is not accounted for and we take the worse case among the nodes in: .. math:: B''(s) = 3 \cdot 2 \cdot \left( \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 15 \\ 36 \end{array}\right] s\right) which gives a nonzero maximum error: .. doctest:: linearization-error-fail >>> nodes = np.asfortranarray([ ... [0.0, 5.0, 10.0, 30.0], ... [0.0, 12.0, 24.0, 72.0], ... ]) >>> linearization_error(nodes) 29.25 Though it may seem that ``0`` is a more appropriate answer, consider the **goal** of this function. We seek to linearize curves and then intersect the linear approximations. Then the :math:`s`-values from the line-line intersection is lifted back to the curves. Thus the error :math:`\|B(s) - L(s)\|_2` is more relevant than the underyling algebraic curve containing :math:`B(s)`. .. note:: It may be more appropriate to use a **relative** linearization error rather than the **absolute** error provided here. It's unclear if the domain :math:`\left[0, 1\right]` means the error is **already** adequately scaled or if the error should be scaled by the arc length of the curve or the (easier-to-compute) length of the line. Args: nodes (numpy.ndarray): Nodes of a curve. Returns: float: The maximum error between the curve and the linear approximation.
[ "r", "Compute", "the", "maximum", "error", "of", "a", "linear", "approximation", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L107-L254
train
54,189
dhermes/bezier
src/bezier/_geometric_intersection.py
segment_intersection
def segment_intersection(start0, end0, start1, end1): r"""Determine the intersection of two line segments. Assumes each line is parametric .. math:: \begin{alignat*}{2} L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \Delta_0 \\ L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \Delta_1. \end{alignat*} To solve :math:`S_0 + s \Delta_0 = S_1 + t \Delta_1`, we use the cross product: .. math:: \left(S_0 + s \Delta_0\right) \times \Delta_1 = \left(S_1 + t \Delta_1\right) \times \Delta_1 \Longrightarrow s \left(\Delta_0 \times \Delta_1\right) = \left(S_1 - S_0\right) \times \Delta_1. Similarly .. math:: \Delta_0 \times \left(S_0 + s \Delta_0\right) = \Delta_0 \times \left(S_1 + t \Delta_1\right) \Longrightarrow \left(S_1 - S_0\right) \times \Delta_0 = \Delta_0 \times \left(S_0 - S_1\right) = t \left(\Delta_0 \times \Delta_1\right). .. note:: Since our points are in :math:`\mathbf{R}^2`, the "traditional" cross product in :math:`\mathbf{R}^3` will always point in the :math:`z` direction, so in the above we mean the :math:`z` component of the cross product, rather than the entire vector. For example, the diagonal lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 2 \end{array}\right] (1 - t) + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] t \end{align*} intersect at :math:`L_0\left(\frac{1}{4}\right) = L_1\left(\frac{3}{4}\right) = \frac{1}{2} \left[\begin{array}{c} 1 \\ 1 \end{array}\right]`. .. image:: ../images/segment_intersection1.png :align: center .. testsetup:: segment-intersection1, segment-intersection2 import numpy as np from bezier._geometric_intersection import segment_intersection .. doctest:: segment-intersection1 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([0.0, 0.0]) >>> end0 = np.asfortranarray([2.0, 2.0]) >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([1.0, 0.0]) >>> s, t, _ = segment_intersection(start0, end0, start1, end1) >>> s 0.25 >>> t 0.75 .. testcleanup:: segment-intersection1 import make_images make_images.segment_intersection1(start0, end0, start1, end1, s) Taking the parallel (but different) lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 1 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 0 \\ 1 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 3 \end{array}\right] (1 - t) + \left[\begin{array}{c} 3 \\ -1 \end{array}\right] t \end{align*} we should be able to determine that the lines don't intersect, but this function is not meant for that check: .. image:: ../images/segment_intersection2.png :align: center .. doctest:: segment-intersection2 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([1.0, 0.0]) >>> end0 = np.asfortranarray([0.0, 1.0]) >>> start1 = np.asfortranarray([-1.0, 3.0]) >>> end1 = np.asfortranarray([3.0, -1.0]) >>> _, _, success = segment_intersection(start0, end0, start1, end1) >>> success False .. testcleanup:: segment-intersection2 import make_images make_images.segment_intersection2(start0, end0, start1, end1) Instead, we use :func:`parallel_lines_parameters`: .. testsetup:: segment-intersection2-continued import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) end0 = np.asfortranarray([0.0, 1.0]) start1 = np.asfortranarray([-1.0, 3.0]) end1 = np.asfortranarray([3.0, -1.0]) .. doctest:: segment-intersection2-continued >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[float, float, bool]: Pair of :math:`s_{\ast}` and :math:`t_{\ast}` such that the lines intersect: :math:`L_0\left(s_{\ast}\right) = L_1\left(t_{\ast}\right)` and then a boolean indicating if an intersection was found (i.e. if the lines aren't parallel). """ delta0 = end0 - start0 delta1 = end1 - start1 cross_d0_d1 = _helpers.cross_product(delta0, delta1) if cross_d0_d1 == 0.0: return None, None, False else: start_delta = start1 - start0 s = _helpers.cross_product(start_delta, delta1) / cross_d0_d1 t = _helpers.cross_product(start_delta, delta0) / cross_d0_d1 return s, t, True
python
def segment_intersection(start0, end0, start1, end1): r"""Determine the intersection of two line segments. Assumes each line is parametric .. math:: \begin{alignat*}{2} L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \Delta_0 \\ L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \Delta_1. \end{alignat*} To solve :math:`S_0 + s \Delta_0 = S_1 + t \Delta_1`, we use the cross product: .. math:: \left(S_0 + s \Delta_0\right) \times \Delta_1 = \left(S_1 + t \Delta_1\right) \times \Delta_1 \Longrightarrow s \left(\Delta_0 \times \Delta_1\right) = \left(S_1 - S_0\right) \times \Delta_1. Similarly .. math:: \Delta_0 \times \left(S_0 + s \Delta_0\right) = \Delta_0 \times \left(S_1 + t \Delta_1\right) \Longrightarrow \left(S_1 - S_0\right) \times \Delta_0 = \Delta_0 \times \left(S_0 - S_1\right) = t \left(\Delta_0 \times \Delta_1\right). .. note:: Since our points are in :math:`\mathbf{R}^2`, the "traditional" cross product in :math:`\mathbf{R}^3` will always point in the :math:`z` direction, so in the above we mean the :math:`z` component of the cross product, rather than the entire vector. For example, the diagonal lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 2 \end{array}\right] (1 - t) + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] t \end{align*} intersect at :math:`L_0\left(\frac{1}{4}\right) = L_1\left(\frac{3}{4}\right) = \frac{1}{2} \left[\begin{array}{c} 1 \\ 1 \end{array}\right]`. .. image:: ../images/segment_intersection1.png :align: center .. testsetup:: segment-intersection1, segment-intersection2 import numpy as np from bezier._geometric_intersection import segment_intersection .. doctest:: segment-intersection1 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([0.0, 0.0]) >>> end0 = np.asfortranarray([2.0, 2.0]) >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([1.0, 0.0]) >>> s, t, _ = segment_intersection(start0, end0, start1, end1) >>> s 0.25 >>> t 0.75 .. testcleanup:: segment-intersection1 import make_images make_images.segment_intersection1(start0, end0, start1, end1, s) Taking the parallel (but different) lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 1 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 0 \\ 1 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 3 \end{array}\right] (1 - t) + \left[\begin{array}{c} 3 \\ -1 \end{array}\right] t \end{align*} we should be able to determine that the lines don't intersect, but this function is not meant for that check: .. image:: ../images/segment_intersection2.png :align: center .. doctest:: segment-intersection2 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([1.0, 0.0]) >>> end0 = np.asfortranarray([0.0, 1.0]) >>> start1 = np.asfortranarray([-1.0, 3.0]) >>> end1 = np.asfortranarray([3.0, -1.0]) >>> _, _, success = segment_intersection(start0, end0, start1, end1) >>> success False .. testcleanup:: segment-intersection2 import make_images make_images.segment_intersection2(start0, end0, start1, end1) Instead, we use :func:`parallel_lines_parameters`: .. testsetup:: segment-intersection2-continued import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) end0 = np.asfortranarray([0.0, 1.0]) start1 = np.asfortranarray([-1.0, 3.0]) end1 = np.asfortranarray([3.0, -1.0]) .. doctest:: segment-intersection2-continued >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[float, float, bool]: Pair of :math:`s_{\ast}` and :math:`t_{\ast}` such that the lines intersect: :math:`L_0\left(s_{\ast}\right) = L_1\left(t_{\ast}\right)` and then a boolean indicating if an intersection was found (i.e. if the lines aren't parallel). """ delta0 = end0 - start0 delta1 = end1 - start1 cross_d0_d1 = _helpers.cross_product(delta0, delta1) if cross_d0_d1 == 0.0: return None, None, False else: start_delta = start1 - start0 s = _helpers.cross_product(start_delta, delta1) / cross_d0_d1 t = _helpers.cross_product(start_delta, delta0) / cross_d0_d1 return s, t, True
[ "def", "segment_intersection", "(", "start0", ",", "end0", ",", "start1", ",", "end1", ")", ":", "delta0", "=", "end0", "-", "start0", "delta1", "=", "end1", "-", "start1", "cross_d0_d1", "=", "_helpers", ".", "cross_product", "(", "delta0", ",", "delta1",...
r"""Determine the intersection of two line segments. Assumes each line is parametric .. math:: \begin{alignat*}{2} L_0(s) &= S_0 (1 - s) + E_0 s &&= S_0 + s \Delta_0 \\ L_1(t) &= S_1 (1 - t) + E_1 t &&= S_1 + t \Delta_1. \end{alignat*} To solve :math:`S_0 + s \Delta_0 = S_1 + t \Delta_1`, we use the cross product: .. math:: \left(S_0 + s \Delta_0\right) \times \Delta_1 = \left(S_1 + t \Delta_1\right) \times \Delta_1 \Longrightarrow s \left(\Delta_0 \times \Delta_1\right) = \left(S_1 - S_0\right) \times \Delta_1. Similarly .. math:: \Delta_0 \times \left(S_0 + s \Delta_0\right) = \Delta_0 \times \left(S_1 + t \Delta_1\right) \Longrightarrow \left(S_1 - S_0\right) \times \Delta_0 = \Delta_0 \times \left(S_0 - S_1\right) = t \left(\Delta_0 \times \Delta_1\right). .. note:: Since our points are in :math:`\mathbf{R}^2`, the "traditional" cross product in :math:`\mathbf{R}^3` will always point in the :math:`z` direction, so in the above we mean the :math:`z` component of the cross product, rather than the entire vector. For example, the diagonal lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 0 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 2 \\ 2 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 2 \end{array}\right] (1 - t) + \left[\begin{array}{c} 1 \\ 0 \end{array}\right] t \end{align*} intersect at :math:`L_0\left(\frac{1}{4}\right) = L_1\left(\frac{3}{4}\right) = \frac{1}{2} \left[\begin{array}{c} 1 \\ 1 \end{array}\right]`. .. image:: ../images/segment_intersection1.png :align: center .. testsetup:: segment-intersection1, segment-intersection2 import numpy as np from bezier._geometric_intersection import segment_intersection .. doctest:: segment-intersection1 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([0.0, 0.0]) >>> end0 = np.asfortranarray([2.0, 2.0]) >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([1.0, 0.0]) >>> s, t, _ = segment_intersection(start0, end0, start1, end1) >>> s 0.25 >>> t 0.75 .. testcleanup:: segment-intersection1 import make_images make_images.segment_intersection1(start0, end0, start1, end1, s) Taking the parallel (but different) lines .. math:: \begin{align*} L_0(s) &= \left[\begin{array}{c} 1 \\ 0 \end{array}\right] (1 - s) + \left[\begin{array}{c} 0 \\ 1 \end{array}\right] s \\ L_1(t) &= \left[\begin{array}{c} -1 \\ 3 \end{array}\right] (1 - t) + \left[\begin{array}{c} 3 \\ -1 \end{array}\right] t \end{align*} we should be able to determine that the lines don't intersect, but this function is not meant for that check: .. image:: ../images/segment_intersection2.png :align: center .. doctest:: segment-intersection2 :options: +NORMALIZE_WHITESPACE >>> start0 = np.asfortranarray([1.0, 0.0]) >>> end0 = np.asfortranarray([0.0, 1.0]) >>> start1 = np.asfortranarray([-1.0, 3.0]) >>> end1 = np.asfortranarray([3.0, -1.0]) >>> _, _, success = segment_intersection(start0, end0, start1, end1) >>> success False .. testcleanup:: segment-intersection2 import make_images make_images.segment_intersection2(start0, end0, start1, end1) Instead, we use :func:`parallel_lines_parameters`: .. testsetup:: segment-intersection2-continued import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) end0 = np.asfortranarray([0.0, 1.0]) start1 = np.asfortranarray([-1.0, 3.0]) end1 = np.asfortranarray([3.0, -1.0]) .. doctest:: segment-intersection2-continued >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[float, float, bool]: Pair of :math:`s_{\ast}` and :math:`t_{\ast}` such that the lines intersect: :math:`L_0\left(s_{\ast}\right) = L_1\left(t_{\ast}\right)` and then a boolean indicating if an intersection was found (i.e. if the lines aren't parallel).
[ "r", "Determine", "the", "intersection", "of", "two", "line", "segments", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L257-L420
train
54,190
dhermes/bezier
src/bezier/_geometric_intersection.py
parallel_lines_parameters
def parallel_lines_parameters(start0, end0, start1, end1): r"""Checks if two parallel lines ever meet. Meant as a back-up when :func:`segment_intersection` fails. .. note:: This function assumes but never verifies that the lines are parallel. In the case that the segments are parallel and lie on **different** lines, then there is a **guarantee** of no intersection. However, if they are on the exact same line, they may define a shared segment coincident to both lines. In :func:`segment_intersection`, we utilized the normal form of the lines (via the cross product): .. math:: \begin{align*} L_0(s) \times \Delta_0 &\equiv S_0 \times \Delta_0 \\ L_1(t) \times \Delta_1 &\equiv S_1 \times \Delta_1 \end{align*} So, we can detect if :math:`S_1` is on the first line by checking if .. math:: S_0 \times \Delta_0 \stackrel{?}{=} S_1 \times \Delta_0. If it is not on the first line, then we are done, the segments don't meet: .. image:: ../images/parallel_lines_parameters1.png :align: center .. testsetup:: parallel-different1, parallel-different2 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters .. doctest:: parallel-different1 >>> # Line: y = 1 >>> start0 = np.asfortranarray([0.0, 1.0]) >>> end0 = np.asfortranarray([1.0, 1.0]) >>> # Vertical shift up: y = 2 >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([3.0, 2.0]) >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different1 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters1.png") If :math:`S_1` **is** on the first line, we want to check that :math:`S_1` and :math:`E_1` define parameters outside of :math:`\left[0, 1\right]`. To compute these parameters: .. math:: L_1(t) = S_0 + s_{\ast} \Delta_0 \Longrightarrow s_{\ast} = \frac{\Delta_0^T \left( L_1(t) - S_0\right)}{\Delta_0^T \Delta_0}. For example, the intervals :math:`\left[0, 1\right]` and :math:`\left[\frac{3}{2}, 2\right]` (via :math:`S_1 = S_0 + \frac{3}{2} \Delta_0` and :math:`E_1 = S_0 + 2 \Delta_0`) correspond to segments that don't meet: .. image:: ../images/parallel_lines_parameters2.png :align: center .. doctest:: parallel-different2 >>> start0 = np.asfortranarray([1.0, 0.0]) >>> delta0 = np.asfortranarray([2.0, -1.0]) >>> end0 = start0 + 1.0 * delta0 >>> start1 = start0 + 1.5 * delta0 >>> end1 = start0 + 2.0 * delta0 >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different2 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters2.png") but if the intervals overlap, like :math:`\left[0, 1\right]` and :math:`\left[-1, \frac{1}{2}\right]`, the segments meet: .. image:: ../images/parallel_lines_parameters3.png :align: center .. testsetup:: parallel-different3, parallel-different4 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) delta0 = np.asfortranarray([2.0, -1.0]) end0 = start0 + 1.0 * delta0 .. doctest:: parallel-different3 >>> start1 = start0 - 1.5 * delta0 >>> end1 = start0 + 0.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[0. , 0.5 ], [0.75, 1. ]]) .. testcleanup:: parallel-different3 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters3.png") Similarly, if the second interval completely contains the first, the segments meet: .. image:: ../images/parallel_lines_parameters4.png :align: center .. doctest:: parallel-different4 >>> start1 = start0 + 4.5 * delta0 >>> end1 = start0 - 3.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[1. , 0. ], [0.4375, 0.5625]]) .. testcleanup:: parallel-different4 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters4.png") .. note:: This function doesn't currently allow wiggle room around the desired value, i.e. the two values must be bitwise identical. However, the most "correct" version of this function likely should allow for some round off. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[bool, Optional[numpy.ndarray]]: A pair of * Flag indicating if the lines are disjoint. * An optional ``2 x 2`` matrix of ``s-t`` parameters only present if the lines aren't disjoint. The first column will contain the parameters at the beginning of the shared segment and the second column will correspond to the end of the shared segment. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-branches delta0 = end0 - start0 line0_const = _helpers.cross_product(start0, delta0) start1_against = _helpers.cross_product(start1, delta0) if line0_const != start1_against: return True, None # Each array is a 1D vector, so we can use the vector dot product. norm0_sq = np.vdot(delta0, delta0) # S1 = L1(0) = S0 + sA D0 # <==> sA D0 = S1 - S0 # ==> sA (D0^T D0) = D0^T (S1 - S0) s_val0 = np.vdot(start1 - start0, delta0) / norm0_sq # E1 = L1(1) = S0 + sB D0 # <==> sB D0 = E1 - S0 # ==> sB (D0^T D0) = D0^T (E1 - S0) s_val1 = np.vdot(end1 - start0, delta0) / norm0_sq # s = s_val0 + t (s_val1 - s_val0) # t = 0 <==> s = s_val0 # t = 1 <==> s = s_val1 # t = -s_val0 / (s_val1 - s_val0) <==> s = 0 # t = (1 - s_val0) / (s_val1 - s_val0) <==> s = 1 if s_val0 <= s_val1: # In this branch the segments are moving in the same direction, i.e. # (t=0<-->s=s_val0) are both less than (t=1<-->s_val1). if 1.0 < s_val0: return True, None elif s_val0 < 0.0: start_s = 0.0 start_t = -s_val0 / (s_val1 - s_val0) else: start_s = s_val0 start_t = 0.0 if s_val1 < 0.0: return True, None elif 1.0 < s_val1: end_s = 1.0 end_t = (1.0 - s_val0) / (s_val1 - s_val0) else: end_s = s_val1 end_t = 1.0 else: # In this branch the segments are moving in opposite directions, i.e. # in (t=0<-->s=s_val0) and (t=1<-->s_val1) we have 0 < 1 # but ``s_val0 > s_val1``. if s_val0 < 0.0: return True, None elif 1.0 < s_val0: start_s = 1.0 start_t = (s_val0 - 1.0) / (s_val0 - s_val1) else: start_s = s_val0 start_t = 0.0 if 1.0 < s_val1: return True, None elif s_val1 < 0.0: end_s = 0.0 end_t = s_val0 / (s_val0 - s_val1) else: end_s = s_val1 end_t = 1.0 parameters = np.asfortranarray([[start_s, end_s], [start_t, end_t]]) return False, parameters
python
def parallel_lines_parameters(start0, end0, start1, end1): r"""Checks if two parallel lines ever meet. Meant as a back-up when :func:`segment_intersection` fails. .. note:: This function assumes but never verifies that the lines are parallel. In the case that the segments are parallel and lie on **different** lines, then there is a **guarantee** of no intersection. However, if they are on the exact same line, they may define a shared segment coincident to both lines. In :func:`segment_intersection`, we utilized the normal form of the lines (via the cross product): .. math:: \begin{align*} L_0(s) \times \Delta_0 &\equiv S_0 \times \Delta_0 \\ L_1(t) \times \Delta_1 &\equiv S_1 \times \Delta_1 \end{align*} So, we can detect if :math:`S_1` is on the first line by checking if .. math:: S_0 \times \Delta_0 \stackrel{?}{=} S_1 \times \Delta_0. If it is not on the first line, then we are done, the segments don't meet: .. image:: ../images/parallel_lines_parameters1.png :align: center .. testsetup:: parallel-different1, parallel-different2 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters .. doctest:: parallel-different1 >>> # Line: y = 1 >>> start0 = np.asfortranarray([0.0, 1.0]) >>> end0 = np.asfortranarray([1.0, 1.0]) >>> # Vertical shift up: y = 2 >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([3.0, 2.0]) >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different1 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters1.png") If :math:`S_1` **is** on the first line, we want to check that :math:`S_1` and :math:`E_1` define parameters outside of :math:`\left[0, 1\right]`. To compute these parameters: .. math:: L_1(t) = S_0 + s_{\ast} \Delta_0 \Longrightarrow s_{\ast} = \frac{\Delta_0^T \left( L_1(t) - S_0\right)}{\Delta_0^T \Delta_0}. For example, the intervals :math:`\left[0, 1\right]` and :math:`\left[\frac{3}{2}, 2\right]` (via :math:`S_1 = S_0 + \frac{3}{2} \Delta_0` and :math:`E_1 = S_0 + 2 \Delta_0`) correspond to segments that don't meet: .. image:: ../images/parallel_lines_parameters2.png :align: center .. doctest:: parallel-different2 >>> start0 = np.asfortranarray([1.0, 0.0]) >>> delta0 = np.asfortranarray([2.0, -1.0]) >>> end0 = start0 + 1.0 * delta0 >>> start1 = start0 + 1.5 * delta0 >>> end1 = start0 + 2.0 * delta0 >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different2 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters2.png") but if the intervals overlap, like :math:`\left[0, 1\right]` and :math:`\left[-1, \frac{1}{2}\right]`, the segments meet: .. image:: ../images/parallel_lines_parameters3.png :align: center .. testsetup:: parallel-different3, parallel-different4 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) delta0 = np.asfortranarray([2.0, -1.0]) end0 = start0 + 1.0 * delta0 .. doctest:: parallel-different3 >>> start1 = start0 - 1.5 * delta0 >>> end1 = start0 + 0.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[0. , 0.5 ], [0.75, 1. ]]) .. testcleanup:: parallel-different3 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters3.png") Similarly, if the second interval completely contains the first, the segments meet: .. image:: ../images/parallel_lines_parameters4.png :align: center .. doctest:: parallel-different4 >>> start1 = start0 + 4.5 * delta0 >>> end1 = start0 - 3.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[1. , 0. ], [0.4375, 0.5625]]) .. testcleanup:: parallel-different4 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters4.png") .. note:: This function doesn't currently allow wiggle room around the desired value, i.e. the two values must be bitwise identical. However, the most "correct" version of this function likely should allow for some round off. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[bool, Optional[numpy.ndarray]]: A pair of * Flag indicating if the lines are disjoint. * An optional ``2 x 2`` matrix of ``s-t`` parameters only present if the lines aren't disjoint. The first column will contain the parameters at the beginning of the shared segment and the second column will correspond to the end of the shared segment. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-branches delta0 = end0 - start0 line0_const = _helpers.cross_product(start0, delta0) start1_against = _helpers.cross_product(start1, delta0) if line0_const != start1_against: return True, None # Each array is a 1D vector, so we can use the vector dot product. norm0_sq = np.vdot(delta0, delta0) # S1 = L1(0) = S0 + sA D0 # <==> sA D0 = S1 - S0 # ==> sA (D0^T D0) = D0^T (S1 - S0) s_val0 = np.vdot(start1 - start0, delta0) / norm0_sq # E1 = L1(1) = S0 + sB D0 # <==> sB D0 = E1 - S0 # ==> sB (D0^T D0) = D0^T (E1 - S0) s_val1 = np.vdot(end1 - start0, delta0) / norm0_sq # s = s_val0 + t (s_val1 - s_val0) # t = 0 <==> s = s_val0 # t = 1 <==> s = s_val1 # t = -s_val0 / (s_val1 - s_val0) <==> s = 0 # t = (1 - s_val0) / (s_val1 - s_val0) <==> s = 1 if s_val0 <= s_val1: # In this branch the segments are moving in the same direction, i.e. # (t=0<-->s=s_val0) are both less than (t=1<-->s_val1). if 1.0 < s_val0: return True, None elif s_val0 < 0.0: start_s = 0.0 start_t = -s_val0 / (s_val1 - s_val0) else: start_s = s_val0 start_t = 0.0 if s_val1 < 0.0: return True, None elif 1.0 < s_val1: end_s = 1.0 end_t = (1.0 - s_val0) / (s_val1 - s_val0) else: end_s = s_val1 end_t = 1.0 else: # In this branch the segments are moving in opposite directions, i.e. # in (t=0<-->s=s_val0) and (t=1<-->s_val1) we have 0 < 1 # but ``s_val0 > s_val1``. if s_val0 < 0.0: return True, None elif 1.0 < s_val0: start_s = 1.0 start_t = (s_val0 - 1.0) / (s_val0 - s_val1) else: start_s = s_val0 start_t = 0.0 if 1.0 < s_val1: return True, None elif s_val1 < 0.0: end_s = 0.0 end_t = s_val0 / (s_val0 - s_val1) else: end_s = s_val1 end_t = 1.0 parameters = np.asfortranarray([[start_s, end_s], [start_t, end_t]]) return False, parameters
[ "def", "parallel_lines_parameters", "(", "start0", ",", "end0", ",", "start1", ",", "end1", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-branches", "delta0", "=", "end0", "-",...
r"""Checks if two parallel lines ever meet. Meant as a back-up when :func:`segment_intersection` fails. .. note:: This function assumes but never verifies that the lines are parallel. In the case that the segments are parallel and lie on **different** lines, then there is a **guarantee** of no intersection. However, if they are on the exact same line, they may define a shared segment coincident to both lines. In :func:`segment_intersection`, we utilized the normal form of the lines (via the cross product): .. math:: \begin{align*} L_0(s) \times \Delta_0 &\equiv S_0 \times \Delta_0 \\ L_1(t) \times \Delta_1 &\equiv S_1 \times \Delta_1 \end{align*} So, we can detect if :math:`S_1` is on the first line by checking if .. math:: S_0 \times \Delta_0 \stackrel{?}{=} S_1 \times \Delta_0. If it is not on the first line, then we are done, the segments don't meet: .. image:: ../images/parallel_lines_parameters1.png :align: center .. testsetup:: parallel-different1, parallel-different2 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters .. doctest:: parallel-different1 >>> # Line: y = 1 >>> start0 = np.asfortranarray([0.0, 1.0]) >>> end0 = np.asfortranarray([1.0, 1.0]) >>> # Vertical shift up: y = 2 >>> start1 = np.asfortranarray([-1.0, 2.0]) >>> end1 = np.asfortranarray([3.0, 2.0]) >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different1 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters1.png") If :math:`S_1` **is** on the first line, we want to check that :math:`S_1` and :math:`E_1` define parameters outside of :math:`\left[0, 1\right]`. To compute these parameters: .. math:: L_1(t) = S_0 + s_{\ast} \Delta_0 \Longrightarrow s_{\ast} = \frac{\Delta_0^T \left( L_1(t) - S_0\right)}{\Delta_0^T \Delta_0}. For example, the intervals :math:`\left[0, 1\right]` and :math:`\left[\frac{3}{2}, 2\right]` (via :math:`S_1 = S_0 + \frac{3}{2} \Delta_0` and :math:`E_1 = S_0 + 2 \Delta_0`) correspond to segments that don't meet: .. image:: ../images/parallel_lines_parameters2.png :align: center .. doctest:: parallel-different2 >>> start0 = np.asfortranarray([1.0, 0.0]) >>> delta0 = np.asfortranarray([2.0, -1.0]) >>> end0 = start0 + 1.0 * delta0 >>> start1 = start0 + 1.5 * delta0 >>> end1 = start0 + 2.0 * delta0 >>> disjoint, _ = parallel_lines_parameters(start0, end0, start1, end1) >>> disjoint True .. testcleanup:: parallel-different2 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters2.png") but if the intervals overlap, like :math:`\left[0, 1\right]` and :math:`\left[-1, \frac{1}{2}\right]`, the segments meet: .. image:: ../images/parallel_lines_parameters3.png :align: center .. testsetup:: parallel-different3, parallel-different4 import numpy as np from bezier._geometric_intersection import parallel_lines_parameters start0 = np.asfortranarray([1.0, 0.0]) delta0 = np.asfortranarray([2.0, -1.0]) end0 = start0 + 1.0 * delta0 .. doctest:: parallel-different3 >>> start1 = start0 - 1.5 * delta0 >>> end1 = start0 + 0.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[0. , 0.5 ], [0.75, 1. ]]) .. testcleanup:: parallel-different3 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters3.png") Similarly, if the second interval completely contains the first, the segments meet: .. image:: ../images/parallel_lines_parameters4.png :align: center .. doctest:: parallel-different4 >>> start1 = start0 + 4.5 * delta0 >>> end1 = start0 - 3.5 * delta0 >>> disjoint, parameters = parallel_lines_parameters( ... start0, end0, start1, end1) >>> disjoint False >>> parameters array([[1. , 0. ], [0.4375, 0.5625]]) .. testcleanup:: parallel-different4 import make_images make_images.helper_parallel_lines( start0, end0, start1, end1, "parallel_lines_parameters4.png") .. note:: This function doesn't currently allow wiggle room around the desired value, i.e. the two values must be bitwise identical. However, the most "correct" version of this function likely should allow for some round off. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: start0 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_0` of the parametric line :math:`L_0(s)`. end0 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_0` of the parametric line :math:`L_0(s)`. start1 (numpy.ndarray): A 1D NumPy ``2``-array that is the start vector :math:`S_1` of the parametric line :math:`L_1(s)`. end1 (numpy.ndarray): A 1D NumPy ``2``-array that is the end vector :math:`E_1` of the parametric line :math:`L_1(s)`. Returns: Tuple[bool, Optional[numpy.ndarray]]: A pair of * Flag indicating if the lines are disjoint. * An optional ``2 x 2`` matrix of ``s-t`` parameters only present if the lines aren't disjoint. The first column will contain the parameters at the beginning of the shared segment and the second column will correspond to the end of the shared segment.
[ "r", "Checks", "if", "two", "parallel", "lines", "ever", "meet", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L423-L676
train
54,191
dhermes/bezier
src/bezier/_geometric_intersection.py
line_line_collide
def line_line_collide(line1, line2): """Determine if two line segments meet. This is a helper for :func:`convex_hull_collide` in the special case that the two convex hulls are actually just line segments. (Even in this case, this is only problematic if both segments are on a single line.) Args: line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes. line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes. Returns: bool: Indicating if the line segments collide. """ s, t, success = segment_intersection( line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1] ) if success: return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval( t, 0.0, 1.0 ) else: disjoint, _ = parallel_lines_parameters( line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1] ) return not disjoint
python
def line_line_collide(line1, line2): """Determine if two line segments meet. This is a helper for :func:`convex_hull_collide` in the special case that the two convex hulls are actually just line segments. (Even in this case, this is only problematic if both segments are on a single line.) Args: line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes. line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes. Returns: bool: Indicating if the line segments collide. """ s, t, success = segment_intersection( line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1] ) if success: return _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval( t, 0.0, 1.0 ) else: disjoint, _ = parallel_lines_parameters( line1[:, 0], line1[:, 1], line2[:, 0], line2[:, 1] ) return not disjoint
[ "def", "line_line_collide", "(", "line1", ",", "line2", ")", ":", "s", ",", "t", ",", "success", "=", "segment_intersection", "(", "line1", "[", ":", ",", "0", "]", ",", "line1", "[", ":", ",", "1", "]", ",", "line2", "[", ":", ",", "0", "]", "...
Determine if two line segments meet. This is a helper for :func:`convex_hull_collide` in the special case that the two convex hulls are actually just line segments. (Even in this case, this is only problematic if both segments are on a single line.) Args: line1 (numpy.ndarray): ``2 x 2`` array of start and end nodes. line2 (numpy.ndarray): ``2 x 2`` array of start and end nodes. Returns: bool: Indicating if the line segments collide.
[ "Determine", "if", "two", "line", "segments", "meet", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L679-L706
train
54,192
dhermes/bezier
src/bezier/_geometric_intersection.py
convex_hull_collide
def convex_hull_collide(nodes1, nodes2): """Determine if the convex hulls of two curves collide. .. note:: This is a helper for :func:`from_linearized`. Args: nodes1 (numpy.ndarray): Control points of a first curve. nodes2 (numpy.ndarray): Control points of a second curve. Returns: bool: Indicating if the convex hulls collide. """ polygon1 = _helpers.simple_convex_hull(nodes1) _, polygon_size1 = polygon1.shape polygon2 = _helpers.simple_convex_hull(nodes2) _, polygon_size2 = polygon2.shape if polygon_size1 == 2 and polygon_size2 == 2: return line_line_collide(polygon1, polygon2) else: return _helpers.polygon_collide(polygon1, polygon2)
python
def convex_hull_collide(nodes1, nodes2): """Determine if the convex hulls of two curves collide. .. note:: This is a helper for :func:`from_linearized`. Args: nodes1 (numpy.ndarray): Control points of a first curve. nodes2 (numpy.ndarray): Control points of a second curve. Returns: bool: Indicating if the convex hulls collide. """ polygon1 = _helpers.simple_convex_hull(nodes1) _, polygon_size1 = polygon1.shape polygon2 = _helpers.simple_convex_hull(nodes2) _, polygon_size2 = polygon2.shape if polygon_size1 == 2 and polygon_size2 == 2: return line_line_collide(polygon1, polygon2) else: return _helpers.polygon_collide(polygon1, polygon2)
[ "def", "convex_hull_collide", "(", "nodes1", ",", "nodes2", ")", ":", "polygon1", "=", "_helpers", ".", "simple_convex_hull", "(", "nodes1", ")", "_", ",", "polygon_size1", "=", "polygon1", ".", "shape", "polygon2", "=", "_helpers", ".", "simple_convex_hull", ...
Determine if the convex hulls of two curves collide. .. note:: This is a helper for :func:`from_linearized`. Args: nodes1 (numpy.ndarray): Control points of a first curve. nodes2 (numpy.ndarray): Control points of a second curve. Returns: bool: Indicating if the convex hulls collide.
[ "Determine", "if", "the", "convex", "hulls", "of", "two", "curves", "collide", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L709-L731
train
54,193
dhermes/bezier
src/bezier/_geometric_intersection.py
from_linearized
def from_linearized(first, second, intersections): """Determine curve-curve intersection from pair of linearizations. .. note:: This assumes that at least one of ``first`` and ``second`` is not a line. The line-line case should be handled "early" by :func:`check_lines`. .. note:: This assumes the caller has verified that the bounding boxes for ``first`` and ``second`` actually intersect. If there is an intersection along the segments, adds that intersection to ``intersections``. Otherwise, returns without doing anything. Args: first (Linearization): First curve being intersected. second (Linearization): Second curve being intersected. intersections (list): A list of existing intersections. Raises: ValueError: If ``first`` and ``second`` both have linearization error of ``0.0`` (i.e. they are both lines). This is because this function expects the caller to have used :func:`check_lines` already. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-return-statements s, t, success = segment_intersection( first.start_node, first.end_node, second.start_node, second.end_node ) bad_parameters = False if success: if not ( _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(t, 0.0, 1.0) ): bad_parameters = True else: if first.error == 0.0 and second.error == 0.0: raise ValueError(_UNHANDLED_LINES) # Just fall back to a Newton iteration starting in the middle of # the given intervals. bad_parameters = True s = 0.5 t = 0.5 if bad_parameters: # In the unlikely case that we have parallel segments or segments # that intersect outside of [0, 1] x [0, 1], we can still exit # if the convex hulls don't intersect. if not convex_hull_collide(first.curve.nodes, second.curve.nodes): return # Now, promote ``s`` and ``t`` onto the original curves. orig_s = (1 - s) * first.curve.start + s * first.curve.end orig_t = (1 - t) * second.curve.start + t * second.curve.end refined_s, refined_t = _intersection_helpers.full_newton( orig_s, first.curve.original_nodes, orig_t, second.curve.original_nodes ) refined_s, success = _helpers.wiggle_interval(refined_s) if not success: return refined_t, success = _helpers.wiggle_interval(refined_t) if not success: return add_intersection(refined_s, refined_t, intersections)
python
def from_linearized(first, second, intersections): """Determine curve-curve intersection from pair of linearizations. .. note:: This assumes that at least one of ``first`` and ``second`` is not a line. The line-line case should be handled "early" by :func:`check_lines`. .. note:: This assumes the caller has verified that the bounding boxes for ``first`` and ``second`` actually intersect. If there is an intersection along the segments, adds that intersection to ``intersections``. Otherwise, returns without doing anything. Args: first (Linearization): First curve being intersected. second (Linearization): Second curve being intersected. intersections (list): A list of existing intersections. Raises: ValueError: If ``first`` and ``second`` both have linearization error of ``0.0`` (i.e. they are both lines). This is because this function expects the caller to have used :func:`check_lines` already. """ # NOTE: There is no corresponding "enable", but the disable only applies # in this lexical scope. # pylint: disable=too-many-return-statements s, t, success = segment_intersection( first.start_node, first.end_node, second.start_node, second.end_node ) bad_parameters = False if success: if not ( _helpers.in_interval(s, 0.0, 1.0) and _helpers.in_interval(t, 0.0, 1.0) ): bad_parameters = True else: if first.error == 0.0 and second.error == 0.0: raise ValueError(_UNHANDLED_LINES) # Just fall back to a Newton iteration starting in the middle of # the given intervals. bad_parameters = True s = 0.5 t = 0.5 if bad_parameters: # In the unlikely case that we have parallel segments or segments # that intersect outside of [0, 1] x [0, 1], we can still exit # if the convex hulls don't intersect. if not convex_hull_collide(first.curve.nodes, second.curve.nodes): return # Now, promote ``s`` and ``t`` onto the original curves. orig_s = (1 - s) * first.curve.start + s * first.curve.end orig_t = (1 - t) * second.curve.start + t * second.curve.end refined_s, refined_t = _intersection_helpers.full_newton( orig_s, first.curve.original_nodes, orig_t, second.curve.original_nodes ) refined_s, success = _helpers.wiggle_interval(refined_s) if not success: return refined_t, success = _helpers.wiggle_interval(refined_t) if not success: return add_intersection(refined_s, refined_t, intersections)
[ "def", "from_linearized", "(", "first", ",", "second", ",", "intersections", ")", ":", "# NOTE: There is no corresponding \"enable\", but the disable only applies", "# in this lexical scope.", "# pylint: disable=too-many-return-statements", "s", ",", "t", ",", "success", "=...
Determine curve-curve intersection from pair of linearizations. .. note:: This assumes that at least one of ``first`` and ``second`` is not a line. The line-line case should be handled "early" by :func:`check_lines`. .. note:: This assumes the caller has verified that the bounding boxes for ``first`` and ``second`` actually intersect. If there is an intersection along the segments, adds that intersection to ``intersections``. Otherwise, returns without doing anything. Args: first (Linearization): First curve being intersected. second (Linearization): Second curve being intersected. intersections (list): A list of existing intersections. Raises: ValueError: If ``first`` and ``second`` both have linearization error of ``0.0`` (i.e. they are both lines). This is because this function expects the caller to have used :func:`check_lines` already.
[ "Determine", "curve", "-", "curve", "intersection", "from", "pair", "of", "linearizations", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L734-L805
train
54,194
dhermes/bezier
src/bezier/_geometric_intersection.py
add_intersection
def add_intersection(s, t, intersections): r"""Adds an intersection to list of ``intersections``. .. note:: This is a helper for :func:`from_linearized` and :func:`endpoint_check`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Accounts for repeated intersection points. If the intersection has already been found, does nothing. If ``s`` is below :math:`2^{-10}`, it will be replaced with ``1 - s`` and compared against ``1 - s'`` for all ``s'`` already in ``intersections``. (Similar if ``t`` is below the :attr:`.ZERO_THRESHOLD`.) This is perfectly "appropriate" since evaluating a B |eacute| zier curve requires using both ``s`` and ``1 - s``, so both values are equally relevant. Compares :math:`\|p - q\|` to :math:`\|p\|` where :math:`p = (s, t)` is current candidate intersection (or the "normalized" version, such as :math:`p = (1 - s, t)`) and :math:`q` is one of the already added intersections. If the difference is below :math:`2^{-42}` (i.e. :attr`.NEWTON_ERROR_RATIO`) then the intersection is considered to be duplicate. Args: s (float): The first parameter in an intersection. t (float): The second parameter in an intersection. intersections (list): List of existing intersections. """ if not intersections: intersections.append((s, t)) return if s < _intersection_helpers.ZERO_THRESHOLD: candidate_s = 1.0 - s else: candidate_s = s if t < _intersection_helpers.ZERO_THRESHOLD: candidate_t = 1.0 - t else: candidate_t = t norm_candidate = np.linalg.norm([candidate_s, candidate_t], ord=2) for existing_s, existing_t in intersections: # NOTE: |(1 - s1) - (1 - s2)| = |s1 - s2| in exact arithmetic, so # we just compute ``s1 - s2`` rather than using # ``candidate_s`` / ``candidate_t``. Due to round-off, these # differences may be slightly different, but only up to machine # precision. delta_s = s - existing_s delta_t = t - existing_t norm_update = np.linalg.norm([delta_s, delta_t], ord=2) if ( norm_update < _intersection_helpers.NEWTON_ERROR_RATIO * norm_candidate ): return intersections.append((s, t))
python
def add_intersection(s, t, intersections): r"""Adds an intersection to list of ``intersections``. .. note:: This is a helper for :func:`from_linearized` and :func:`endpoint_check`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Accounts for repeated intersection points. If the intersection has already been found, does nothing. If ``s`` is below :math:`2^{-10}`, it will be replaced with ``1 - s`` and compared against ``1 - s'`` for all ``s'`` already in ``intersections``. (Similar if ``t`` is below the :attr:`.ZERO_THRESHOLD`.) This is perfectly "appropriate" since evaluating a B |eacute| zier curve requires using both ``s`` and ``1 - s``, so both values are equally relevant. Compares :math:`\|p - q\|` to :math:`\|p\|` where :math:`p = (s, t)` is current candidate intersection (or the "normalized" version, such as :math:`p = (1 - s, t)`) and :math:`q` is one of the already added intersections. If the difference is below :math:`2^{-42}` (i.e. :attr`.NEWTON_ERROR_RATIO`) then the intersection is considered to be duplicate. Args: s (float): The first parameter in an intersection. t (float): The second parameter in an intersection. intersections (list): List of existing intersections. """ if not intersections: intersections.append((s, t)) return if s < _intersection_helpers.ZERO_THRESHOLD: candidate_s = 1.0 - s else: candidate_s = s if t < _intersection_helpers.ZERO_THRESHOLD: candidate_t = 1.0 - t else: candidate_t = t norm_candidate = np.linalg.norm([candidate_s, candidate_t], ord=2) for existing_s, existing_t in intersections: # NOTE: |(1 - s1) - (1 - s2)| = |s1 - s2| in exact arithmetic, so # we just compute ``s1 - s2`` rather than using # ``candidate_s`` / ``candidate_t``. Due to round-off, these # differences may be slightly different, but only up to machine # precision. delta_s = s - existing_s delta_t = t - existing_t norm_update = np.linalg.norm([delta_s, delta_t], ord=2) if ( norm_update < _intersection_helpers.NEWTON_ERROR_RATIO * norm_candidate ): return intersections.append((s, t))
[ "def", "add_intersection", "(", "s", ",", "t", ",", "intersections", ")", ":", "if", "not", "intersections", ":", "intersections", ".", "append", "(", "(", "s", ",", "t", ")", ")", "return", "if", "s", "<", "_intersection_helpers", ".", "ZERO_THRESHOLD", ...
r"""Adds an intersection to list of ``intersections``. .. note:: This is a helper for :func:`from_linearized` and :func:`endpoint_check`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Accounts for repeated intersection points. If the intersection has already been found, does nothing. If ``s`` is below :math:`2^{-10}`, it will be replaced with ``1 - s`` and compared against ``1 - s'`` for all ``s'`` already in ``intersections``. (Similar if ``t`` is below the :attr:`.ZERO_THRESHOLD`.) This is perfectly "appropriate" since evaluating a B |eacute| zier curve requires using both ``s`` and ``1 - s``, so both values are equally relevant. Compares :math:`\|p - q\|` to :math:`\|p\|` where :math:`p = (s, t)` is current candidate intersection (or the "normalized" version, such as :math:`p = (1 - s, t)`) and :math:`q` is one of the already added intersections. If the difference is below :math:`2^{-42}` (i.e. :attr`.NEWTON_ERROR_RATIO`) then the intersection is considered to be duplicate. Args: s (float): The first parameter in an intersection. t (float): The second parameter in an intersection. intersections (list): List of existing intersections.
[ "r", "Adds", "an", "intersection", "to", "list", "of", "intersections", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L808-L868
train
54,195
dhermes/bezier
src/bezier/_geometric_intersection.py
endpoint_check
def endpoint_check( first, node_first, s, second, node_second, t, intersections ): r"""Check if curve endpoints are identical. .. note:: This is a helper for :func:`tangent_bbox_intersection`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). node_first (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``first``. s (float): The parameter corresponding to ``node_first``, so expected to be one of ``0.0`` or ``1.0``. second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). node_second (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``second``. t (float): The parameter corresponding to ``node_second``, so expected to be one of ``0.0`` or ``1.0``. intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list. """ if _helpers.vector_close(node_first, node_second): orig_s = (1 - s) * first.start + s * first.end orig_t = (1 - t) * second.start + t * second.end add_intersection(orig_s, orig_t, intersections)
python
def endpoint_check( first, node_first, s, second, node_second, t, intersections ): r"""Check if curve endpoints are identical. .. note:: This is a helper for :func:`tangent_bbox_intersection`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). node_first (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``first``. s (float): The parameter corresponding to ``node_first``, so expected to be one of ``0.0`` or ``1.0``. second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). node_second (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``second``. t (float): The parameter corresponding to ``node_second``, so expected to be one of ``0.0`` or ``1.0``. intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list. """ if _helpers.vector_close(node_first, node_second): orig_s = (1 - s) * first.start + s * first.end orig_t = (1 - t) * second.start + t * second.end add_intersection(orig_s, orig_t, intersections)
[ "def", "endpoint_check", "(", "first", ",", "node_first", ",", "s", ",", "second", ",", "node_second", ",", "t", ",", "intersections", ")", ":", "if", "_helpers", ".", "vector_close", "(", "node_first", ",", "node_second", ")", ":", "orig_s", "=", "(", "...
r"""Check if curve endpoints are identical. .. note:: This is a helper for :func:`tangent_bbox_intersection`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). node_first (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``first``. s (float): The parameter corresponding to ``node_first``, so expected to be one of ``0.0`` or ``1.0``. second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). node_second (numpy.ndarray): 1D ``2``-array, one of the endpoints of ``second``. t (float): The parameter corresponding to ``node_second``, so expected to be one of ``0.0`` or ``1.0``. intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list.
[ "r", "Check", "if", "curve", "endpoints", "are", "identical", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L871-L903
train
54,196
dhermes/bezier
src/bezier/_geometric_intersection.py
tangent_bbox_intersection
def tangent_bbox_intersection(first, second, intersections): r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes are tangent, intersection can only occur along that tangency. If the curve is **not** a line, the **only** way the curve can touch the bounding box is at the endpoints. To see this, consider the component .. math:: x(s) = \sum_j W_j x_j. Since :math:`W_j > 0` for :math:`s \in \left(0, 1\right)`, if there is some :math:`k` with :math:`x_k < M = \max x_j`, then for any interior :math:`s` .. math:: x(s) < \sum_j W_j M = M. If all :math:`x_j = M`, then :math:`B(s)` falls on the line :math:`x = M`. (A similar argument holds for the other three component-extrema types.) .. note:: This function assumes callers will not pass curves that can be linearized / are linear. In :func:`_all_intersections`, curves are pre-processed to do any linearization before the subdivision / intersection process begins. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list. """ node_first1 = first.nodes[:, 0] node_first2 = first.nodes[:, -1] node_second1 = second.nodes[:, 0] node_second2 = second.nodes[:, -1] endpoint_check( first, node_first1, 0.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first1, 0.0, second, node_second2, 1.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second2, 1.0, intersections )
python
def tangent_bbox_intersection(first, second, intersections): r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes are tangent, intersection can only occur along that tangency. If the curve is **not** a line, the **only** way the curve can touch the bounding box is at the endpoints. To see this, consider the component .. math:: x(s) = \sum_j W_j x_j. Since :math:`W_j > 0` for :math:`s \in \left(0, 1\right)`, if there is some :math:`k` with :math:`x_k < M = \max x_j`, then for any interior :math:`s` .. math:: x(s) < \sum_j W_j M = M. If all :math:`x_j = M`, then :math:`B(s)` falls on the line :math:`x = M`. (A similar argument holds for the other three component-extrema types.) .. note:: This function assumes callers will not pass curves that can be linearized / are linear. In :func:`_all_intersections`, curves are pre-processed to do any linearization before the subdivision / intersection process begins. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list. """ node_first1 = first.nodes[:, 0] node_first2 = first.nodes[:, -1] node_second1 = second.nodes[:, 0] node_second2 = second.nodes[:, -1] endpoint_check( first, node_first1, 0.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first1, 0.0, second, node_second2, 1.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second1, 0.0, intersections ) endpoint_check( first, node_first2, 1.0, second, node_second2, 1.0, intersections )
[ "def", "tangent_bbox_intersection", "(", "first", ",", "second", ",", "intersections", ")", ":", "node_first1", "=", "first", ".", "nodes", "[", ":", ",", "0", "]", "node_first2", "=", "first", ".", "nodes", "[", ":", ",", "-", "1", "]", "node_second1", ...
r"""Check if two curves with tangent bounding boxes intersect. .. note:: This is a helper for :func:`intersect_one_round`. These functions are used (directly or indirectly) by :func:`_all_intersections` exclusively, and that function has a Fortran equivalent. If the bounding boxes are tangent, intersection can only occur along that tangency. If the curve is **not** a line, the **only** way the curve can touch the bounding box is at the endpoints. To see this, consider the component .. math:: x(s) = \sum_j W_j x_j. Since :math:`W_j > 0` for :math:`s \in \left(0, 1\right)`, if there is some :math:`k` with :math:`x_k < M = \max x_j`, then for any interior :math:`s` .. math:: x(s) < \sum_j W_j M = M. If all :math:`x_j = M`, then :math:`B(s)` falls on the line :math:`x = M`. (A similar argument holds for the other three component-extrema types.) .. note:: This function assumes callers will not pass curves that can be linearized / are linear. In :func:`_all_intersections`, curves are pre-processed to do any linearization before the subdivision / intersection process begins. Args: first (SubdividedCurve): First curve being intersected (assumed in :math:\mathbf{R}^2`). second (SubdividedCurve): Second curve being intersected (assumed in :math:\mathbf{R}^2`). intersections (list): A list of already encountered intersections. If these curves intersect at their tangency, then those intersections will be added to this list.
[ "r", "Check", "if", "two", "curves", "with", "tangent", "bounding", "boxes", "intersect", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L906-L970
train
54,197
dhermes/bezier
src/bezier/_geometric_intersection.py
bbox_line_intersect
def bbox_line_intersect(nodes, line_start, line_end): r"""Determine intersection of a bounding box and a line. We do this by first checking if either the start or end node of the segment are contained in the bounding box. If they aren't, then checks if the line segment intersects any of the four sides of the bounding box. .. note:: This function is "half-finished". It makes no distinction between "tangent" intersections of the box and segment and other types of intersection. However, the distinction is worthwhile, so this function should be "upgraded" at some point. Args: nodes (numpy.ndarray): Points (``2 x N``) that determine a bounding box. line_start (numpy.ndarray): Beginning of a line segment (1D ``2``-array). line_end (numpy.ndarray): End of a line segment (1D ``2``-array). Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection. """ left, right, bottom, top = _helpers.bbox(nodes) if _helpers.in_interval( line_start[0], left, right ) and _helpers.in_interval(line_start[1], bottom, top): return BoxIntersectionType.INTERSECTION if _helpers.in_interval(line_end[0], left, right) and _helpers.in_interval( line_end[1], bottom, top ): return BoxIntersectionType.INTERSECTION # NOTE: We allow ``segment_intersection`` to fail below (i.e. # ``success=False``). At first, this may appear to "ignore" # some potential intersections of parallel lines. However, # no intersections will be missed. If parallel lines don't # overlap, then there is nothing to miss. If they do overlap, # then either the segment will have endpoints on the box (already # covered by the checks above) or the segment will contain an # entire side of the box, which will force it to intersect the 3 # edges that meet at the two ends of those sides. The parallel # edge will be skipped, but the other two will be covered. # Bottom Edge s_bottom, t_bottom, success = segment_intersection( np.asfortranarray([left, bottom]), np.asfortranarray([right, bottom]), line_start, line_end, ) if ( success and _helpers.in_interval(s_bottom, 0.0, 1.0) and _helpers.in_interval(t_bottom, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # Right Edge s_right, t_right, success = segment_intersection( np.asfortranarray([right, bottom]), np.asfortranarray([right, top]), line_start, line_end, ) if ( success and _helpers.in_interval(s_right, 0.0, 1.0) and _helpers.in_interval(t_right, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # Top Edge s_top, t_top, success = segment_intersection( np.asfortranarray([right, top]), np.asfortranarray([left, top]), line_start, line_end, ) if ( success and _helpers.in_interval(s_top, 0.0, 1.0) and _helpers.in_interval(t_top, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # NOTE: We skip the "last" edge. This is because any curve # that doesn't have an endpoint on a curve must cross # at least two, so we will have already covered such curves # in one of the branches above. return BoxIntersectionType.DISJOINT
python
def bbox_line_intersect(nodes, line_start, line_end): r"""Determine intersection of a bounding box and a line. We do this by first checking if either the start or end node of the segment are contained in the bounding box. If they aren't, then checks if the line segment intersects any of the four sides of the bounding box. .. note:: This function is "half-finished". It makes no distinction between "tangent" intersections of the box and segment and other types of intersection. However, the distinction is worthwhile, so this function should be "upgraded" at some point. Args: nodes (numpy.ndarray): Points (``2 x N``) that determine a bounding box. line_start (numpy.ndarray): Beginning of a line segment (1D ``2``-array). line_end (numpy.ndarray): End of a line segment (1D ``2``-array). Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection. """ left, right, bottom, top = _helpers.bbox(nodes) if _helpers.in_interval( line_start[0], left, right ) and _helpers.in_interval(line_start[1], bottom, top): return BoxIntersectionType.INTERSECTION if _helpers.in_interval(line_end[0], left, right) and _helpers.in_interval( line_end[1], bottom, top ): return BoxIntersectionType.INTERSECTION # NOTE: We allow ``segment_intersection`` to fail below (i.e. # ``success=False``). At first, this may appear to "ignore" # some potential intersections of parallel lines. However, # no intersections will be missed. If parallel lines don't # overlap, then there is nothing to miss. If they do overlap, # then either the segment will have endpoints on the box (already # covered by the checks above) or the segment will contain an # entire side of the box, which will force it to intersect the 3 # edges that meet at the two ends of those sides. The parallel # edge will be skipped, but the other two will be covered. # Bottom Edge s_bottom, t_bottom, success = segment_intersection( np.asfortranarray([left, bottom]), np.asfortranarray([right, bottom]), line_start, line_end, ) if ( success and _helpers.in_interval(s_bottom, 0.0, 1.0) and _helpers.in_interval(t_bottom, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # Right Edge s_right, t_right, success = segment_intersection( np.asfortranarray([right, bottom]), np.asfortranarray([right, top]), line_start, line_end, ) if ( success and _helpers.in_interval(s_right, 0.0, 1.0) and _helpers.in_interval(t_right, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # Top Edge s_top, t_top, success = segment_intersection( np.asfortranarray([right, top]), np.asfortranarray([left, top]), line_start, line_end, ) if ( success and _helpers.in_interval(s_top, 0.0, 1.0) and _helpers.in_interval(t_top, 0.0, 1.0) ): return BoxIntersectionType.INTERSECTION # NOTE: We skip the "last" edge. This is because any curve # that doesn't have an endpoint on a curve must cross # at least two, so we will have already covered such curves # in one of the branches above. return BoxIntersectionType.DISJOINT
[ "def", "bbox_line_intersect", "(", "nodes", ",", "line_start", ",", "line_end", ")", ":", "left", ",", "right", ",", "bottom", ",", "top", "=", "_helpers", ".", "bbox", "(", "nodes", ")", "if", "_helpers", ".", "in_interval", "(", "line_start", "[", "0",...
r"""Determine intersection of a bounding box and a line. We do this by first checking if either the start or end node of the segment are contained in the bounding box. If they aren't, then checks if the line segment intersects any of the four sides of the bounding box. .. note:: This function is "half-finished". It makes no distinction between "tangent" intersections of the box and segment and other types of intersection. However, the distinction is worthwhile, so this function should be "upgraded" at some point. Args: nodes (numpy.ndarray): Points (``2 x N``) that determine a bounding box. line_start (numpy.ndarray): Beginning of a line segment (1D ``2``-array). line_end (numpy.ndarray): End of a line segment (1D ``2``-array). Returns: int: Enum from ``BoxIntersectionType`` indicating the type of bounding box intersection.
[ "r", "Determine", "intersection", "of", "a", "bounding", "box", "and", "a", "line", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L973-L1066
train
54,198
dhermes/bezier
src/bezier/_geometric_intersection.py
intersect_one_round
def intersect_one_round(candidates, intersections): """Perform one step of the intersection process. .. note:: This is a helper for :func:`_all_intersections` and that function has a Fortran equivalent. Checks if the bounding boxes of each pair in ``candidates`` intersect. If the bounding boxes do not intersect, the pair is discarded. Otherwise, the pair is "accepted". Then we attempt to linearize each curve in an "accepted" pair and track the overall linearization error for every curve encountered. Args: candidates (Union[list, itertools.chain]): An iterable of pairs of curves (or linearized curves). intersections (list): A list of already encountered intersections. If any intersections can be readily determined during this round of subdivision, then they will be added to this list. Returns: list: Returns a list of the next round of ``candidates``. """ next_candidates = [] # 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: both_linearized = False if first.__class__ is Linearization: if second.__class__ is Linearization: both_linearized = True bbox_int = bbox_intersect( first.curve.nodes, second.curve.nodes ) else: bbox_int = bbox_line_intersect( second.nodes, first.start_node, first.end_node ) else: if second.__class__ is Linearization: bbox_int = bbox_line_intersect( first.nodes, second.start_node, second.end_node ) else: bbox_int = bbox_intersect(first.nodes, second.nodes) if bbox_int == BoxIntersectionType.DISJOINT: continue elif bbox_int == BoxIntersectionType.TANGENT and not both_linearized: # NOTE: Ignore tangent bounding boxes in the linearized case # because ``tangent_bbox_intersection()`` assumes that both # curves are not linear. tangent_bbox_intersection(first, second, intersections) continue if both_linearized: # If both ``first`` and ``second`` are linearizations, then # we can intersect them immediately. from_linearized(first, second, intersections) continue # If we haven't ``continue``-d, add the accepted pair. # NOTE: This may be a wasted computation, e.g. if ``first`` # or ``second`` occur in multiple accepted pairs (the caller # only passes one pair at a time). However, in practice # the number of such pairs will be small so this cost # will be low. lin1 = six.moves.map(Linearization.from_shape, first.subdivide()) lin2 = six.moves.map(Linearization.from_shape, second.subdivide()) next_candidates.extend(itertools.product(lin1, lin2)) return next_candidates
python
def intersect_one_round(candidates, intersections): """Perform one step of the intersection process. .. note:: This is a helper for :func:`_all_intersections` and that function has a Fortran equivalent. Checks if the bounding boxes of each pair in ``candidates`` intersect. If the bounding boxes do not intersect, the pair is discarded. Otherwise, the pair is "accepted". Then we attempt to linearize each curve in an "accepted" pair and track the overall linearization error for every curve encountered. Args: candidates (Union[list, itertools.chain]): An iterable of pairs of curves (or linearized curves). intersections (list): A list of already encountered intersections. If any intersections can be readily determined during this round of subdivision, then they will be added to this list. Returns: list: Returns a list of the next round of ``candidates``. """ next_candidates = [] # 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: both_linearized = False if first.__class__ is Linearization: if second.__class__ is Linearization: both_linearized = True bbox_int = bbox_intersect( first.curve.nodes, second.curve.nodes ) else: bbox_int = bbox_line_intersect( second.nodes, first.start_node, first.end_node ) else: if second.__class__ is Linearization: bbox_int = bbox_line_intersect( first.nodes, second.start_node, second.end_node ) else: bbox_int = bbox_intersect(first.nodes, second.nodes) if bbox_int == BoxIntersectionType.DISJOINT: continue elif bbox_int == BoxIntersectionType.TANGENT and not both_linearized: # NOTE: Ignore tangent bounding boxes in the linearized case # because ``tangent_bbox_intersection()`` assumes that both # curves are not linear. tangent_bbox_intersection(first, second, intersections) continue if both_linearized: # If both ``first`` and ``second`` are linearizations, then # we can intersect them immediately. from_linearized(first, second, intersections) continue # If we haven't ``continue``-d, add the accepted pair. # NOTE: This may be a wasted computation, e.g. if ``first`` # or ``second`` occur in multiple accepted pairs (the caller # only passes one pair at a time). However, in practice # the number of such pairs will be small so this cost # will be low. lin1 = six.moves.map(Linearization.from_shape, first.subdivide()) lin2 = six.moves.map(Linearization.from_shape, second.subdivide()) next_candidates.extend(itertools.product(lin1, lin2)) return next_candidates
[ "def", "intersect_one_round", "(", "candidates", ",", "intersections", ")", ":", "next_candidates", "=", "[", "]", "# 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", "cand...
Perform one step of the intersection process. .. note:: This is a helper for :func:`_all_intersections` and that function has a Fortran equivalent. Checks if the bounding boxes of each pair in ``candidates`` intersect. If the bounding boxes do not intersect, the pair is discarded. Otherwise, the pair is "accepted". Then we attempt to linearize each curve in an "accepted" pair and track the overall linearization error for every curve encountered. Args: candidates (Union[list, itertools.chain]): An iterable of pairs of curves (or linearized curves). intersections (list): A list of already encountered intersections. If any intersections can be readily determined during this round of subdivision, then they will be added to this list. Returns: list: Returns a list of the next round of ``candidates``.
[ "Perform", "one", "step", "of", "the", "intersection", "process", "." ]
4f941f82637a8e70a5b159a9203132192e23406b
https://github.com/dhermes/bezier/blob/4f941f82637a8e70a5b159a9203132192e23406b/src/bezier/_geometric_intersection.py#L1069-L1142
train
54,199