code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
if _verify:
if param_vals.ndim != 2:
raise ValueError("Parameter values must be 2D array")
for s, t in param_vals:
self._verify_cartesian(s, t)
return _surface_helpers.evaluate_cartesian_multi(
self._nodes, self._degree, para... | def evaluate_cartesian_multi(self, param_vals, _verify=True) | r"""Compute multiple points on the surface.
Assumes ``param_vals`` has two columns of Cartesian coordinates.
See :meth:`evaluate_cartesian` for more details on how each row of
parameter values is evaluated.
.. image:: ../../images/surface_evaluate_cartesian_multi.png
:align:... | 5.084914 | 5.010271 | 1.014898 |
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,... | 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 (... | 3.234876 | 3.214976 | 1.00619 |
r
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=Fal... | 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 / fr... | 2.958495 | 2.688272 | 1.100519 |
r
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:]... | 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... | 3.798906 | 3.363984 | 1.129288 |
r
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
... | 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 assume... | 4.255775 | 3.724289 | 1.142708 |
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:
... | 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 i... | 3.055079 | 2.947403 | 1.036532 |
r
# NOTE: We somewhat replicate code in ``evaluate_hodograph()``
# here. This is so we don't re-compute the nodes for the first
# (and possibly second) derivatives every time they are evaluated.
_, num_nodes1 = np.shape(nodes1)
first_deriv1 = (num_nodes1 - 1) * (nodes1[:, 1:] - nodes... | def full_newton_nonzero(s, nodes1, t, nodes2) | r"""Perform a Newton iteration until convergence to a solution.
This is the "implementation" for :func:`full_newton`. In this
function, we assume that :math:`s` and :math:`t` are nonzero.
Args:
s (float): The parameter along the first curve where the iteration
will start.
nodes... | 2.822502 | 2.70904 | 1.041883 |
r
if s < ZERO_THRESHOLD:
reversed1 = np.asfortranarray(nodes1[:, ::-1])
if t < ZERO_THRESHOLD:
reversed2 = np.asfortranarray(nodes2[:, ::-1])
refined_s, refined_t = full_newton_nonzero(
1.0 - s, reversed1, 1.0 - t, reversed2
)
retur... | def full_newton(s, nodes1, t, nodes2) | r"""Perform a Newton iteration until convergence to a solution.
This assumes :math:`s` and :math:`t` are sufficiently close to an
intersection. It **does not** govern the maximum distance away
that the solution can lie, though the subdivided intervals that contain
:math:`s` and :math:`t` could be used.... | 1.906318 | 1.808701 | 1.053971 |
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 startin... | 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 d... | 2.702985 | 2.436379 | 1.109427 |
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_... | 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. som... | 2.707881 | 2.821885 | 0.9596 |
# 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[:] =... | 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... | 4.617172 | 4.579943 | 1.008129 |
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
... | 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. | 5.202797 | 4.00452 | 1.299231 |
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(m... | 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. | 3.388347 | 2.876565 | 1.177915 |
c_compiler = self.F90_COMPILER.c_compiler
static_lib_dir = os.path.join(self.build_lib, "bezier", "lib")
if not os.path.exists(static_lib_dir):
os.makedirs(static_lib_dir)
c_compiler.create_static_lib(
obj_files, "bezier", output_dir=static_lib_dir
... | def _default_static_lib(self, obj_files) | Create a static library (i.e. a ``.a`` / ``.lib`` file).
Args:
obj_files (List[str]): List of paths of compiled object files. | 3.76741 | 3.929071 | 0.958855 |
if not self.inplace:
return
shutil.move(
os.path.join(self.build_lib, "bezier", "lib"),
os.path.join("src", "bezier"),
) | def _default_cleanup(self) | Default cleanup after :meth:`run`.
For in-place builds, moves the built shared library into the source
directory. | 6.702115 | 4.894418 | 1.369338 |
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 side... | 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 piecewis... | 8.433585 | 6.069531 | 1.389495 |
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 = s... | 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.
Rai... | 4.042235 | 3.370845 | 1.199176 |
r
edges = tuple(edge._nodes for edge in self._edges)
return _surface_helpers.compute_area(edges) | 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:`\... | 22.257587 | 22.699228 | 0.980544 |
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) | 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.
R... | 4.21926 | 4.97916 | 0.847384 |
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" roun... | 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... | 4.490247 | 4.252305 | 1.055956 |
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 *... | 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:
... | 3.142378 | 2.749427 | 1.142921 |
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... | 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`
... | 3.561659 | 3.468417 | 1.026883 |
r
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) | 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
... | 6.71838 | 4.98367 | 1.348079 |
r
# 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 = no... | 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 paramete... | 3.173386 | 2.999048 | 1.058131 |
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) | Post-process a generated journal file on Travis macOS.
Args:
journal_filename (str): The name of the journal file. | 2.14403 | 2.541285 | 0.84368 |
sphinx_modules.append(match.group("module"))
return "`{}`_".format(match.group("value")) | def mod_replace(match, sphinx_modules) | Convert Sphinx ``:mod:`` to plain reST link.
Args:
match (_sre.SRE_Match): A match (from ``re``) to be used
in substitution.
sphinx_modules (list): List to be track the modules that have been
encountered.
Returns:
str: The ``match`` converted to a link. | 6.610589 | 8.435123 | 0.783698 |
sphinx_docs.append(match.group("path"))
return "`{}`_".format(match.group("value")) | def doc_replace(match, sphinx_docs) | Convert Sphinx ``:doc:`` to plain reST link.
Args:
match (_sre.SRE_Match): A match (from ``re``) to be used
in substitution.
sphinx_docs (list): List to be track the documents that have been
encountered.
Returns:
str: The ``match`` converted to a link. | 6.685159 | 8.527143 | 0.783986 |
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) | 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. | 1.922695 | 2.164854 | 0.888141 |
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 = BERNST... | 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 argu... | 2.815319 | 2.729577 | 1.031412 |
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"
... | 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. | 5.892575 | 5.84526 | 1.008095 |
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,
... | 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. | 3.874048 | 3.955105 | 0.979506 |
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": T... | 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 ... | 3.017913 | 2.990371 | 1.00921 |
# 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_bu... | 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. | 3.467225 | 3.250815 | 1.066571 |
version = "{version}"
_index_verify(
RELEASE_INDEX_FILE,
side_effect=release_docs_side_effect,
pypi="",
pypi_img="",
versions="\n\n",
versions_img="",
rtd_version=version,
revision=version,
circleci_badge=CIRCLECI_BADGE_RELEASE,
... | def release_docs_index_verify() | Populate template and compare to ``docs/index.rst.release.template``.
Raises:
ValueError: If the current ``index.rst.release.template`` doesn't
agree with the expected value computed from the template. | 4.808025 | 5.093731 | 0.94391 |
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(
... | 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. | 3.083972 | 2.774308 | 1.111618 |
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,
... | 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. | 3.556184 | 2.834427 | 1.254639 |
# NOTE: This may be (a) slower and (b) less precise than
# hard-coding the determinant.
sylvester_mat = np.zeros((6, 6), order="F")
delta = nodes - np.asfortranarray([[x_val], [y_val]])
delta[:, 1:3] *= 3.0
# Swap rows/columns so that x-y are right next to each other.
# This will ... | def _evaluate3(nodes, x_val, y_val) | Helper for :func:`evaluate` when ``nodes`` is degree 3.
Args:
nodes (numpy.ndarray): ``2 x 4`` 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)`. | 5.314831 | 5.705532 | 0.931522 |
r
_, 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]
# ... | 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... | 2.359468 | 2.194434 | 1.075206 |
r
(x_val,), (y_val,) = _curve_helpers.evaluate_multi(
nodes2, np.asfortranarray([t])
)
return evaluate(nodes1, x_val, y_val) | def eval_intersection_polynomial(nodes1, nodes2, t) | r"""Evaluates a parametric curve **on** an implicitized algebraic curve.
Uses :func:`evaluate` to evaluate :math:`f_1(x, y)`, the implicitization
of ``nodes1``. Then plugs ``t`` into the second parametric curve to
get an ``x``- and ``y``-coordinate and evaluate the
**intersection polynomial**:
.. ... | 8.93923 | 10.727153 | 0.833327 |
r
# We manually invert the Vandermonde matrix:
# [1 0][c0] = [n0]
# [1 1][c1] [n1]
val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0)
val1 = eval_intersection_polynomial(nodes1, nodes2, 1.0)
# [c0] = [ 1 0][n0]
# [c1] = [-1 1][n1]
return np.asfortranarray([val0, -val0 + val1]... | def _to_power_basis11(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that each curve is
degree one. In this case, B |eacute| zout's `theorem`_ tells us
that the **intersection polynomial** is degree :math:`1 \cdot 1`
hence we return two coefficients.
Args:
... | 4.576233 | 4.612113 | 0.99222 |
r
# We manually invert the Vandermonde matrix:
# [1 0 0 ][c0] = [n0]
# [1 1/2 1/4][c1] [n1]
# [1 1 1 ][c2] [n2]
val0 = eval_intersection_polynomial(nodes1, nodes2, 0.0)
val1 = eval_intersection_polynomial(nodes1, nodes2, 0.5)
val2 = eval_intersection_polynomial(nodes1, nodes2, ... | def _to_power_basis12(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that the first curve is
degree one and the second is degree two. In this case, B |eacute|
zout's `theorem`_ tells us that the **intersection polynomial** is
degree :math:`1 \cdot 2` hence we re... | 2.930813 | 2.992422 | 0.979412 |
r
# We manually invert the Vandermonde matrix:
# Use exact f.p. numbers to avoid round-off wherever possible.
# [1 0 0 0 ][c0] = [n0]
# [1 1/4 1/16 1/64 ][c1] [n1]
# [1 3/4 9/16 27/64][c2] [n2]
# [1 1 1 1 ][c3] [n3]
val0 = eval_intersection_polynomial(nodes1, nodes2... | def _to_power_basis13(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that the first curve is
degree one and the second is degree three. In this case, B |eacute|
zout's `theorem`_ tells us that the **intersection polynomial** is
degree :math:`1 \cdot 3` hence we ... | 3.024282 | 3.003043 | 1.007072 |
r
# We manually invert the Vandermonde matrix:
# [1 0 0 0 0 ][c0] = [n0]
# [1 1/4 1/16 1/64 1/256 ][c1] [n1]
# [1 1/2 1/4 1/8 1/16 ][c2] [n2]
# [1 3/4 9/16 27/64 81/256][c3] [n3]
# [1 1 1 1 1 ][c4] [n4]
val0 = eval_intersection_polynomial(nodes1, no... | def _to_power_basis_degree4(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that B |eacute| zout's
`theorem`_ tells us the **intersection polynomial** is degree
:math:`4`. This happens if the two curves have degrees two and two
or have degrees one and four.
Args:
... | 2.302773 | 2.308055 | 0.997712 |
r
evaluated = [
eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB7
]
return polynomial.polyfit(_CHEB7, evaluated, 6) | def _to_power_basis23(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that the first curve is
degree two and the second is degree three. In this case, B |eacute|
zout's `theorem`_ tells us that the **intersection polynomial** is
degree :math:`2 \cdot 3` hence we ... | 17.080175 | 19.324953 | 0.88384 |
r
evaluated = [
eval_intersection_polynomial(nodes1, nodes2, t_val) for t_val in _CHEB9
]
return polynomial.polyfit(_CHEB9, evaluated, 8) | def _to_power_basis_degree8(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that B |eacute| zout's
`theorem`_ tells us the **intersection polynomial** is degree
:math:`8`. This happens if the two curves have degrees one and eight
or have degrees two and four.
.. n... | 14.93725 | 16.960541 | 0.880706 |
r
evaluated = [
eval_intersection_polynomial(nodes1, nodes2, t_val)
for t_val in _CHEB10
]
return polynomial.polyfit(_CHEB10, evaluated, 9) | def _to_power_basis33(nodes1, nodes2) | r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that each curve is
degree three. In this case, B |eacute| zout's `theorem`_ tells us
that the **intersection polynomial** is degree :math:`3 \cdot 3`
hence we return ten coefficients.
.. n... | 14.93922 | 16.171797 | 0.923782 |
# NOTE: There is no corresponding "enable", but the disable only applies
# in this lexical scope.
# pylint: disable=too-many-return-statements
_, num_nodes1 = nodes1.shape
_, num_nodes2 = nodes2.shape
if num_nodes1 == 2:
if num_nodes2 == 2:
return _to_power_basis11... | def to_power_basis(nodes1, nodes2) | Compute the coefficients of an **intersection polynomial**.
.. note::
This assumes that the degree of the curve given by ``nodes1`` is
less than or equal to the degree of that given by ``nodes2``.
Args:
nodes1 (numpy.ndarray): The nodes in the first curve.
nodes2 (numpy.ndarray)... | 2.225914 | 2.177615 | 1.02218 |
r
num_coeffs, = coeffs.shape
result = 0.0
for i in six.moves.xrange(num_coeffs):
coeff_i = coeffs[i]
result += coeff_i * coeff_i / (2.0 * i + 1.0)
for j in six.moves.xrange(i + 1, num_coeffs):
coeff_j = coeffs[j]
result += 2.0 * coeff_i * coeff_j / (i + j ... | def polynomial_norm(coeffs) | r"""Computes :math:`L_2` norm of polynomial on :math:`\left[0, 1\right]`.
We have
.. math::
\left\langle f, f \right\rangle = \sum_{i, j}
\int_0^1 c_i c_j x^{i + j} \, dx = \sum_{i, j}
\frac{c_i c_j}{i + j + 1} = \sum_{i} \frac{c_i^2}{2 i + 1}
+ 2 \sum_{j > i} \frac{c_... | 2.129238 | 2.23059 | 0.954563 |
r
l2_norm = polynomial_norm(coeffs)
if l2_norm < threshold:
return np.zeros(coeffs.shape, order="F")
else:
coeffs /= l2_norm
return coeffs | def normalize_polynomial(coeffs, threshold=_L2_THRESHOLD) | r"""Normalizes a polynomial in the :math:`L_2` sense.
Does so on the interval :math:\left[0, 1\right]` via
:func:`polynomial_norm`.
Args:
coeffs (numpy.ndarray): ``d + 1``-array of coefficients in monomial /
power basis.
threshold (Optional[float]): The point :math:`\tau` below... | 4.593846 | 4.756809 | 0.965741 |
r
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)``.
... | 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) + ... | 3.67871 | 3.739726 | 0.983685 |
r
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
... | 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 rewri... | 4.461204 | 4.124866 | 1.081539 |
r
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 con... | 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 (... | 4.820023 | 3.574448 | 1.348467 |
r
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) = ... | 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 i... | 7.767292 | 6.733819 | 1.153475 |
r
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 ... | 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]`. | 5.334093 | 6.044183 | 0.882517 |
r
while np.abs(coeffs[-1]) < threshold:
coeffs = coeffs[:-1]
return coeffs | 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.
... | 5.251932 | 8.81497 | 0.595797 |
r
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 Horne... | 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)9002... | 4.169611 | 4.131067 | 1.00933 |
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) | 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): ... | 3.416739 | 3.270063 | 1.044854 |
r
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_... | 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:`... | 3.391843 | 3.136844 | 1.081291 |
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... | 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... | 1.774886 | 1.778754 | 0.997826 |
r
# 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.... | 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 ... | 4.752194 | 4.606332 | 1.031666 |
r
# Only attempt this if the bounding boxes intersect.
bbox_int = _geometric_intersection.bbox_intersect(
nodes_first, nodes_second
)
if bbox_int == _DISJOINT:
return np.empty((2, 0), order="F"), False
return intersect_curves(nodes_first, nodes_second), False | def all_intersections(nodes_first, nodes_second) | r"""Find the points of intersection among a pair of curves.
.. note::
This assumes both curves are :math:`\mathbf{R}^2`, but does not
**explicitly** check this. However, functions used here will fail if
that assumption fails.
Args:
nodes_first (numpy.ndarray): Control points of a... | 8.605122 | 7.00559 | 1.228322 |
r
# 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
... | 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 th... | 3.568772 | 3.653738 | 0.976746 |
left, bottom = np.min(nodes, axis=1)
right, top = np.max(nodes, axis=1)
return left, right, bottom, top | 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... | 2.706527 | 3.242117 | 0.834802 |
r
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) | 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
... | 2.68015 | 2.916582 | 0.918935 |
return np.dot(mat2.T, mat1.T).T | 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-c... | 4.673744 | 10.834727 | 0.431367 |
r
if -wiggle < value < wiggle:
return 0.0, True
elif wiggle <= value <= 1.0 - wiggle:
return value, True
elif 1.0 - wiggle < value < 1.0 + wiggle:
return 1.0, True
else:
return np.nan, False | def _wiggle_interval(value, wiggle=0.5 ** 44) | r"""Check if ``value`` is in :math:`\left[0, 1\right]`.
Allows a little bit of wiggle room outside the interval. Any value
within ``wiggle`` of ``0.0` will be converted to ``0.0` and similar
for ``1.0``.
.. note::
There is also a Fortran implementation of this function, which
will be us... | 2.886445 | 3.212544 | 0.898492 |
delta1 = candidate1 - start
delta2 = candidate2 - start
return cross_product(delta1, delta2) | 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
... | 3.098347 | 4.570051 | 0.677968 |
index = bisect.bisect_left(values, value)
if index >= len(values):
return False
return values[index] == value | 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 cont... | 2.455555 | 3.173619 | 0.77374 |
r
# 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.shap... | 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 ... | 3.152372 | 3.191267 | 0.987812 |
# 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 poly... | 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 `... | 3.377935 | 3.498447 | 0.965553 |
direction = np.empty((2,), order="F")
for polygon in (polygon1, polygon2):
_, polygon_size = polygon.shape
for index in six.moves.xrange(polygon_size):
# NOTE: When ``index == 0`` this will "wrap around" and refer
# to index ``-1``.
direction[:] = p... | def _polygon_collide(polygon1, polygon2) | Determines if two **convex** polygons collide.
.. _SAT: https://en.wikipedia.org/wiki/Hyperplane_separation_theorem
.. _see also: https://hackmd.io/s/ryFmIZrsl
This code uses the Separating axis theorem (`SAT`_) to quickly
determine if the polygons intersect. `See also`_.
.. note::
There ... | 5.99953 | 6.417168 | 0.934919 |
# 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 magn... | 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).
* W... | 2.297088 | 2.285965 | 1.004866 |
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... | 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 ... | 2.346977 | 2.462986 | 0.952899 |
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... | 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, ..... | 4.58665 | 4.272782 | 1.073458 |
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
... | def visit_literal_block(self, node) | Visit a ``literal_block`` node.
This verifies the state of each literal / code block. | 5.468312 | 5.568182 | 0.982064 |
r
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 ==... | 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 ... | 2.668797 | 2.488419 | 1.072487 |
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]... | 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`` a... | 2.851101 | 3.056552 | 0.932784 |
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... | 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 hul... | 2.71324 | 3.096501 | 0.876228 |
# 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
... | 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 boundin... | 4.13556 | 3.892708 | 1.062386 |
r
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_... | 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.
Accoun... | 3.655658 | 3.042263 | 1.201625 |
r
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
) | 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 (SubdividedCur... | 4.418459 | 4.483924 | 0.9854 |
r
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, nod... | 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... | 1.91618 | 1.991113 | 0.962366 |
r
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(
l... | 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 funct... | 3.071994 | 3.032528 | 1.013014 |
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:
... | 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. Other... | 4.136862 | 4.01962 | 1.029167 |
pruned = []
# NOTE: In the below we replace ``isinstance(a, B)`` with
# ``a.__class__ is B``, which is a 3-3.5x speedup.
for first, second in candidates:
if first.__class__ is Linearization:
nodes1 = first.curve.nodes
else:
nodes1 = first.nodes
... | def prune_candidates(candidates) | Reduce number of candidate intersection pairs.
.. note::
This is a helper for :func:`_all_intersections`.
Uses more strict bounding box intersection predicate by forming the
actual convex hull of each candidate curve segment and then checking
if those convex hulls collide.
Args:
c... | 4.323586 | 3.961859 | 1.091303 |
_, num_nodes1 = nodes1.shape
_, num_nodes2 = nodes2.shape
for _ in six.moves.xrange(num_nodes2 - num_nodes1):
nodes1 = _curve_helpers.elevate_nodes(nodes1)
for _ in six.moves.xrange(num_nodes1 - num_nodes2):
nodes2 = _curve_helpers.elevate_nodes(nodes2)
return nodes1, nodes2 | def make_same_degree(nodes1, nodes2) | Degree-elevate a curve so two curves have matching degree.
Args:
nodes1 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
nodes2 (numpy.ndarray): Set of control points for a
B |eacute| zier curve.
Returns:
Tuple[numpy.ndarray, numpy.ndarray]: T... | 2.62196 | 2.322437 | 1.128969 |
# NOTE: In the below we replace ``isinstance(a, B)`` with
# ``a.__class__ is B``, which is a 3-3.5x speedup.
if not (
first.__class__ is Linearization
and second.__class__ is Linearization
and first.error == 0.0
and second.error == 0.0
):
return False, ... | def check_lines(first, second) | Checks if two curves are lines and tries to intersect them.
.. note::
This is a helper for :func:`._all_intersections`.
If they are not lines / not linearized, immediately returns :data:`False`
with no "return value".
If they are lines, attempts to intersect them (even if they are parallel
... | 3.434983 | 3.1185 | 1.101486 |
r
curve_first = SubdividedCurve(nodes_first, nodes_first)
curve_second = SubdividedCurve(nodes_second, nodes_second)
candidate1 = Linearization.from_shape(curve_first)
candidate2 = Linearization.from_shape(curve_second)
# Handle the line-line intersection case as a one-off.
both_linear, resu... | def _all_intersections(nodes_first, nodes_second) | r"""Find the points of intersection among a pair of curves.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
.. note::
This assumes both curves are in :math:`\mathbf{R}^2`, but does not
**explicitly** check this. However, f... | 4.793577 | 4.551582 | 1.053167 |
left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self.nodes)
midpoint = 0.5 * (self.start + self.end)
left = SubdividedCurve(
left_nodes, self.original_nodes, start=self.start, end=midpoint
)
right = SubdividedCurve(
right_nodes, self.orig... | def subdivide(self) | Split the curve into a left and right half.
See :meth:`.Curve.subdivide` for more information.
Returns:
Tuple[SubdividedCurve, SubdividedCurve]: The left and right
sub-curves. | 3.082664 | 2.944422 | 1.046951 |
# NOTE: In the below we replace ``isinstance(a, B)`` with
# ``a.__class__ is B``, which is a 3-3.5x speedup.
if shape.__class__ is cls:
return shape
else:
error = linearization_error(shape.nodes)
if error < _ERROR_VAL:
l... | def from_shape(cls, shape) | Try to linearize a curve (or an already linearized curve).
Args:
shape (Union[SubdividedCurve, \
~bezier._geometric_intersection.Linearization]): A curve or an
already linearized curve.
Returns:
Union[SubdividedCurve, \
~bezier._geometric... | 8.7145 | 7.711915 | 1.130005 |
r
return _curve_helpers.evaluate_multi(
self._nodes, np.asfortranarray([s])
) | def evaluate(self, s) | r"""Evaluate :math:`B(s)` along the curve.
This method acts as a (partial) inverse to :meth:`locate`.
See :meth:`evaluate_multi` for more details.
.. image:: ../../images/curve_evaluate.png
:align: center
.. doctest:: curve-eval
:options: +NORMALIZE_WHITESPACE
... | 31.337774 | 20.573507 | 1.52321 |
if self._dimension != 2:
raise NotImplementedError(
"2D is the only supported dimension",
"Current dimension",
self._dimension,
)
s_vals = np.linspace(0.0, 1.0, num_pts)
points = self.evaluate_multi(s_vals)
... | def plot(self, num_pts, color=None, alpha=None, ax=None) | Plot the current curve.
Args:
num_pts (int): Number of points to plot.
color (Optional[Tuple[float, float, float]]): Color as RGB profile.
alpha (Optional[float]): The alpha channel for the color.
ax (Optional[matplotlib.artist.Artist]): matplotlib axis object
... | 3.111944 | 3.030656 | 1.026822 |
r
left_nodes, right_nodes = _curve_helpers.subdivide_nodes(self._nodes)
left = Curve(left_nodes, self._degree, _copy=False)
right = Curve(right_nodes, self._degree, _copy=False)
return left, right | def subdivide(self) | r"""Split the curve :math:`B(s)` into a left and right half.
Takes the interval :math:`\left[0, 1\right]` and splits the curve into
:math:`B_1 = B\left(\left[0, \frac{1}{2}\right]\right)` and
:math:`B_2 = B\left(\left[\frac{1}{2}, 1\right]\right)`. In
order to do this, also reparameteri... | 4.6535 | 4.149691 | 1.121409 |
if _verify:
if not isinstance(other, Curve):
raise TypeError(
"Can only intersect with another curve", "Received", other
)
if self._dimension != 2 or other._dimension != 2:
raise NotImplementedError(
... | def intersect(
self, other, strategy=IntersectionStrategy.GEOMETRIC, _verify=True
) | Find the points of intersection with another curve.
See :doc:`../../algorithms/curve-curve-intersection` for more details.
.. image:: ../../images/curve_intersect.png
:align: center
.. doctest:: curve-intersect
:options: +NORMALIZE_WHITESPACE
>>> nodes1 = np.... | 3.276409 | 3.031492 | 1.080791 |
r
new_nodes = _curve_helpers.elevate_nodes(self._nodes)
return Curve(new_nodes, self._degree + 1, _copy=False) | def elevate(self) | r"""Return a degree-elevated version of the current curve.
Does this by converting the current nodes :math:`v_0, \ldots, v_n`
to new nodes :math:`w_0, \ldots, w_{n + 1}` where
.. math::
\begin{align*}
w_0 &= v_0 \\
w_j &= \frac{j}{n + 1} v_{j - 1} + \frac{n + ... | 12.371865 | 10.860466 | 1.139165 |
r
new_nodes = _curve_helpers.reduce_pseudo_inverse(self._nodes)
return Curve(new_nodes, self._degree - 1, _copy=False) | def reduce_(self) | r"""Return a degree-reduced version of the current curve.
.. _pseudo-inverse:
https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_pseudoinverse
Does this by converting the current nodes :math:`v_0, \ldots, v_n`
to new nodes :math:`w_0, \ldots, w_{n - 1}` that correspond to
... | 14.001407 | 12.808734 | 1.093114 |
new_nodes = _curve_helpers.specialize_curve(self._nodes, start, end)
return Curve(new_nodes, self._degree, _copy=False) | def specialize(self, start, end) | Specialize the curve to a given sub-interval.
.. image:: ../../images/curve_specialize.png
:align: center
.. doctest:: curve-specialize
>>> nodes = np.asfortranarray([
... [0.0, 0.5, 1.0],
... [0.0, 1.0, 0.0],
... ])
>>> curve ... | 7.258794 | 7.626965 | 0.951728 |
r
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
)
... | def locate(self, point) | r"""Find a point on the current curve.
Solves for :math:`s` in :math:`B(s) = p`.
This method acts as a (partial) inverse to :meth:`evaluate`.
.. note::
A unique solution is only guaranteed if the current curve has no
self-intersections. This code assumes, but doesn't ch... | 5.537017 | 5.188289 | 1.067215 |
with open(c_source, "r") as file_obj:
contents = file_obj.read().rstrip()
# Replace the path to the Cython include files.
py_version = "python{}.{}".format(*sys.version_info[:2])
lib_path = os.path.join(
".nox", virtualenv_dirname, "lib", py_version, "site-packages", ""
)
co... | def clean_file(c_source, virtualenv_dirname) | Strip trailing whitespace and clean up "local" names in C source.
These source files are autogenerated from the ``cython`` CLI.
Args:
c_source (str): Path to a ``.c`` source file.
virtualenv_dirname (str): The name of the ``virtualenv``
directory where Cython is installed (this is ... | 3.114178 | 2.933048 | 1.061755 |
# "Spoof" the ``setup.py`` helper modules.
sys.modules["setup_helpers"] = object()
sys.modules["setup_helpers_macos"] = object()
sys.modules["setup_helpers_windows"] = object()
filename = os.path.join(_ROOT_DIR, "setup.py")
loader = importlib.machinery.SourceFileLoader("setup", filename)
... | def get_version() | Get the current version from ``setup.py``.
Assumes that importing ``setup.py`` will have no side-effects (i.e.
assumes the behavior is guarded by ``if __name__ == "__main__"``).
Returns:
str: The current version in ``setup.py``. | 4.13579 | 4.17325 | 0.991024 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.