diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9e9bc7aa18fc4a8d1b4452a71ecae6b2395dde0f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__init__.py @@ -0,0 +1,129 @@ +""" +============================================================= +Spatial algorithms and data structures (:mod:`scipy.spatial`) +============================================================= + +.. currentmodule:: scipy.spatial + +.. toctree:: + :hidden: + + spatial.distance + +Spatial transformations +======================= + +These are contained in the `scipy.spatial.transform` submodule. + +Nearest-neighbor queries +======================== +.. autosummary:: + :toctree: generated/ + + KDTree -- class for efficient nearest-neighbor queries + cKDTree -- class for efficient nearest-neighbor queries (faster implementation) + Rectangle + +Distance metrics +================ + +Distance metrics are contained in the :mod:`scipy.spatial.distance` submodule. + +Delaunay triangulation, convex hulls, and Voronoi diagrams +========================================================== + +.. autosummary:: + :toctree: generated/ + + Delaunay -- compute Delaunay triangulation of input points + ConvexHull -- compute a convex hull for input points + Voronoi -- compute a Voronoi diagram hull from input points + SphericalVoronoi -- compute a Voronoi diagram from input points on the surface of a sphere + HalfspaceIntersection -- compute the intersection points of input halfspaces + +Plotting helpers +================ + +.. autosummary:: + :toctree: generated/ + + delaunay_plot_2d -- plot 2-D triangulation + convex_hull_plot_2d -- plot 2-D convex hull + voronoi_plot_2d -- plot 2-D Voronoi diagram + +.. seealso:: :ref:`Tutorial ` + + +Simplex representation +====================== +The simplices (triangles, tetrahedra, etc.) appearing in the Delaunay +tessellation (N-D simplices), convex hull facets, and Voronoi ridges +(N-1-D simplices) are represented in the following scheme:: + + tess = Delaunay(points) + hull = ConvexHull(points) + voro = Voronoi(points) + + # coordinates of the jth vertex of the ith simplex + tess.points[tess.simplices[i, j], :] # tessellation element + hull.points[hull.simplices[i, j], :] # convex hull facet + voro.vertices[voro.ridge_vertices[i, j], :] # ridge between Voronoi cells + +For Delaunay triangulations and convex hulls, the neighborhood +structure of the simplices satisfies the condition: +``tess.neighbors[i,j]`` is the neighboring simplex of the ith +simplex, opposite to the ``j``-vertex. It is -1 in case of no neighbor. + +Convex hull facets also define a hyperplane equation:: + + (hull.equations[i,:-1] * coord).sum() + hull.equations[i,-1] == 0 + +Similar hyperplane equations for the Delaunay triangulation correspond +to the convex hull facets on the corresponding N+1-D +paraboloid. + +The Delaunay triangulation objects offer a method for locating the +simplex containing a given point, and barycentric coordinate +computations. + +Functions +--------- + +.. autosummary:: + :toctree: generated/ + + tsearch + distance_matrix + minkowski_distance + minkowski_distance_p + procrustes + geometric_slerp + +Warnings / Errors used in :mod:`scipy.spatial` +---------------------------------------------- +.. autosummary:: + :toctree: generated/ + + QhullError +""" # noqa: E501 + +from ._kdtree import * +from ._ckdtree import * +from ._qhull import * +from ._spherical_voronoi import SphericalVoronoi +from ._plotutils import * +from ._procrustes import procrustes +from ._geometric_slerp import geometric_slerp + +# Deprecated namespaces, to be removed in v2.0.0 +from . import ckdtree, kdtree, qhull + +__all__ = [s for s in dir() if not s.startswith('_')] + +from . import distance, transform + +__all__ += ['distance', 'transform'] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_geometric_slerp.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_geometric_slerp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52be143fab300791fe9ca5139e0a1b24df7ae997 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_geometric_slerp.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_kdtree.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_kdtree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfd807b1083534d50a5e74e480078de15fa38b02 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/_kdtree.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/kdtree.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/kdtree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa1079d59f283f8aa628a2dd02b5b5689e81dbaa Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/kdtree.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/qhull.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/qhull.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4316d0baa472ba9b2563b832d3662496bb62fbfa Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/__pycache__/qhull.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_ckdtree.pyi b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_ckdtree.pyi new file mode 100644 index 0000000000000000000000000000000000000000..42670067a38c3021d20aeb39bb04920ab9ccde24 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_ckdtree.pyi @@ -0,0 +1,214 @@ +from __future__ import annotations +from typing import ( + Any, + Generic, + overload, + TypeVar, +) + +import numpy as np +import numpy.typing as npt +from scipy.sparse import coo_matrix, dok_matrix + +from typing import Literal + +# TODO: Replace `ndarray` with a 1D float64 array when possible +_BoxType = TypeVar("_BoxType", None, npt.NDArray[np.float64]) + +# Copied from `numpy.typing._scalar_like._ScalarLike` +# TODO: Expand with 0D arrays once we have shape support +_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic + +_WeightType = npt.ArrayLike | tuple[npt.ArrayLike | None, npt.ArrayLike | None] + +class cKDTreeNode: + @property + def data_points(self) -> npt.NDArray[np.float64]: ... + @property + def indices(self) -> npt.NDArray[np.intp]: ... + + # These are read-only attributes in cython, which behave like properties + @property + def level(self) -> int: ... + @property + def split_dim(self) -> int: ... + @property + def children(self) -> int: ... + @property + def start_idx(self) -> int: ... + @property + def end_idx(self) -> int: ... + @property + def split(self) -> float: ... + @property + def lesser(self) -> cKDTreeNode | None: ... + @property + def greater(self) -> cKDTreeNode | None: ... + +class cKDTree(Generic[_BoxType]): + @property + def n(self) -> int: ... + @property + def m(self) -> int: ... + @property + def leafsize(self) -> int: ... + @property + def size(self) -> int: ... + @property + def tree(self) -> cKDTreeNode: ... + + # These are read-only attributes in cython, which behave like properties + @property + def data(self) -> npt.NDArray[np.float64]: ... + @property + def maxes(self) -> npt.NDArray[np.float64]: ... + @property + def mins(self) -> npt.NDArray[np.float64]: ... + @property + def indices(self) -> npt.NDArray[np.float64]: ... + @property + def boxsize(self) -> _BoxType: ... + + # NOTE: In practice `__init__` is used as constructor, not `__new__`. + # The latter gives us more flexibility in setting the generic parameter + # though. + @overload + def __new__( # type: ignore[misc] + cls, + data: npt.ArrayLike, + leafsize: int = ..., + compact_nodes: bool = ..., + copy_data: bool = ..., + balanced_tree: bool = ..., + boxsize: None = ..., + ) -> cKDTree[None]: ... + @overload + def __new__( + cls, + data: npt.ArrayLike, + leafsize: int = ..., + compact_nodes: bool = ..., + copy_data: bool = ..., + balanced_tree: bool = ..., + boxsize: npt.ArrayLike = ..., + ) -> cKDTree[npt.NDArray[np.float64]]: ... + + # TODO: returns a 2-tuple of scalars if `x.ndim == 1` and `k == 1`, + # returns a 2-tuple of arrays otherwise + def query( + self, + x: npt.ArrayLike, + k: npt.ArrayLike = ..., + eps: float = ..., + p: float = ..., + distance_upper_bound: float = ..., + workers: int | None = ..., + ) -> tuple[Any, Any]: ... + + # TODO: returns a list scalars if `x.ndim <= 1`, + # returns an object array of lists otherwise + def query_ball_point( + self, + x: npt.ArrayLike, + r: npt.ArrayLike, + p: float, + eps: float = ..., + workers: int | None = ..., + return_sorted: bool | None = ..., + return_length: bool = ... + ) -> Any: ... + + def query_ball_tree( + self, + other: cKDTree, + r: float, + p: float, + eps: float = ..., + ) -> list[list[int]]: ... + + @overload + def query_pairs( # type: ignore[misc] + self, + r: float, + p: float = ..., + eps: float = ..., + output_type: Literal["set"] = ..., + ) -> set[tuple[int, int]]: ... + @overload + def query_pairs( + self, + r: float, + p: float = ..., + eps: float = ..., + output_type: Literal["ndarray"] = ..., + ) -> npt.NDArray[np.intp]: ... + + @overload + def count_neighbors( # type: ignore[misc] + self, + other: cKDTree, + r: _ArrayLike0D, + p: float = ..., + weights: None | tuple[None, None] = ..., + cumulative: bool = ..., + ) -> int: ... + @overload + def count_neighbors( # type: ignore[misc] + self, + other: cKDTree, + r: _ArrayLike0D, + p: float = ..., + weights: _WeightType = ..., + cumulative: bool = ..., + ) -> np.float64: ... + @overload + def count_neighbors( # type: ignore[misc] + self, + other: cKDTree, + r: npt.ArrayLike, + p: float = ..., + weights: None | tuple[None, None] = ..., + cumulative: bool = ..., + ) -> npt.NDArray[np.intp]: ... + @overload + def count_neighbors( + self, + other: cKDTree, + r: npt.ArrayLike, + p: float = ..., + weights: _WeightType = ..., + cumulative: bool = ..., + ) -> npt.NDArray[np.float64]: ... + + @overload + def sparse_distance_matrix( # type: ignore[misc] + self, + other: cKDTree, + max_distance: float, + p: float = ..., + output_type: Literal["dok_matrix"] = ..., + ) -> dok_matrix: ... + @overload + def sparse_distance_matrix( # type: ignore[misc] + self, + other: cKDTree, + max_distance: float, + p: float = ..., + output_type: Literal["coo_matrix"] = ..., + ) -> coo_matrix: ... + @overload + def sparse_distance_matrix( # type: ignore[misc] + self, + other: cKDTree, + max_distance: float, + p: float = ..., + output_type: Literal["dict"] = ..., + ) -> dict[tuple[int, int], float]: ... + @overload + def sparse_distance_matrix( + self, + other: cKDTree, + max_distance: float, + p: float = ..., + output_type: Literal["ndarray"] = ..., + ) -> npt.NDArray[np.void]: ... diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_pybind.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_pybind.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..99ffc166ce8e80f318c574bc4934b13a7a2a92ac Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_pybind.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_wrap.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_wrap.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b3d611710c12736c9f7f6cc901fdbf151432b5db Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_distance_wrap.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a7a81a1209bff2b1758aa2d6a5248a3d4360fd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +__all__ = ['geometric_slerp'] + +import warnings +from typing import TYPE_CHECKING + +import numpy as np +from scipy.spatial.distance import euclidean + +if TYPE_CHECKING: + import numpy.typing as npt + + +def _geometric_slerp(start, end, t): + # create an orthogonal basis using QR decomposition + basis = np.vstack([start, end]) + Q, R = np.linalg.qr(basis.T) + signs = 2 * (np.diag(R) >= 0) - 1 + Q = Q.T * signs.T[:, np.newaxis] + R = R.T * signs.T[:, np.newaxis] + + # calculate the angle between `start` and `end` + c = np.dot(start, end) + s = np.linalg.det(R) + omega = np.arctan2(s, c) + + # interpolate + start, end = Q + s = np.sin(t * omega) + c = np.cos(t * omega) + return start * c[:, np.newaxis] + end * s[:, np.newaxis] + + +def geometric_slerp( + start: npt.ArrayLike, + end: npt.ArrayLike, + t: npt.ArrayLike, + tol: float = 1e-7, +) -> np.ndarray: + """ + Geometric spherical linear interpolation. + + The interpolation occurs along a unit-radius + great circle arc in arbitrary dimensional space. + + Parameters + ---------- + start : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + end : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + t : float or (n_points,) 1D array-like + A float or 1D array-like of doubles representing interpolation + parameters, with values required in the inclusive interval + between 0 and 1. A common approach is to generate the array + with ``np.linspace(0, 1, n_pts)`` for linearly spaced points. + Ascending, descending, and scrambled orders are permitted. + tol : float + The absolute tolerance for determining if the start and end + coordinates are antipodes. + + Returns + ------- + result : (t.size, D) + An array of doubles containing the interpolated + spherical path and including start and + end when 0 and 1 t are used. The + interpolated values should correspond to the + same sort order provided in the t array. The result + may be 1-dimensional if ``t`` is a float. + + Raises + ------ + ValueError + If ``start`` and ``end`` are antipodes, not on the + unit n-sphere, or for a variety of degenerate conditions. + + See Also + -------- + scipy.spatial.transform.Slerp : 3-D Slerp that works with quaternions + + Notes + ----- + The implementation is based on the mathematical formula provided in [1]_, + and the first known presentation of this algorithm, derived from study of + 4-D geometry, is credited to Glenn Davis in a footnote of the original + quaternion Slerp publication by Ken Shoemake [2]_. + + .. versionadded:: 1.5.0 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Slerp#Geometric_Slerp + .. [2] Ken Shoemake (1985) Animating rotation with quaternion curves. + ACM SIGGRAPH Computer Graphics, 19(3): 245-254. + + Examples + -------- + Interpolate four linearly-spaced values on the circumference of + a circle spanning 90 degrees: + + >>> import numpy as np + >>> from scipy.spatial import geometric_slerp + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> start = np.array([1, 0]) + >>> end = np.array([0, 1]) + >>> t_vals = np.linspace(0, 1, 4) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + + The interpolated results should be at 30 degree intervals + recognizable on the unit circle: + + >>> ax.scatter(result[...,0], result[...,1], c='k') + >>> circle = plt.Circle((0, 0), 1, color='grey') + >>> ax.add_artist(circle) + >>> ax.set_aspect('equal') + >>> plt.show() + + Attempting to interpolate between antipodes on a circle is + ambiguous because there are two possible paths, and on a + sphere there are infinite possible paths on the geodesic surface. + Nonetheless, one of the ambiguous paths is returned along + with a warning: + + >>> opposite_pole = np.array([-1, 0]) + >>> with np.testing.suppress_warnings() as sup: + ... sup.filter(UserWarning) + ... geometric_slerp(start, + ... opposite_pole, + ... t_vals) + array([[ 1.00000000e+00, 0.00000000e+00], + [ 5.00000000e-01, 8.66025404e-01], + [-5.00000000e-01, 8.66025404e-01], + [-1.00000000e+00, 1.22464680e-16]]) + + Extend the original example to a sphere and plot interpolation + points in 3D: + + >>> from mpl_toolkits.mplot3d import proj3d + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + + Plot the unit sphere for reference (optional): + + >>> u = np.linspace(0, 2 * np.pi, 100) + >>> v = np.linspace(0, np.pi, 100) + >>> x = np.outer(np.cos(u), np.sin(v)) + >>> y = np.outer(np.sin(u), np.sin(v)) + >>> z = np.outer(np.ones(np.size(u)), np.cos(v)) + >>> ax.plot_surface(x, y, z, color='y', alpha=0.1) + + Interpolating over a larger number of points + may provide the appearance of a smooth curve on + the surface of the sphere, which is also useful + for discretized integration calculations on a + sphere surface: + + >>> start = np.array([1, 0, 0]) + >>> end = np.array([0, 0, 1]) + >>> t_vals = np.linspace(0, 1, 200) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + >>> ax.plot(result[...,0], + ... result[...,1], + ... result[...,2], + ... c='k') + >>> plt.show() + """ + + start = np.asarray(start, dtype=np.float64) + end = np.asarray(end, dtype=np.float64) + t = np.asarray(t) + + if t.ndim > 1: + raise ValueError("The interpolation parameter " + "value must be one dimensional.") + + if start.ndim != 1 or end.ndim != 1: + raise ValueError("Start and end coordinates " + "must be one-dimensional") + + if start.size != end.size: + raise ValueError("The dimensions of start and " + "end must match (have same size)") + + if start.size < 2 or end.size < 2: + raise ValueError("The start and end coordinates must " + "both be in at least two-dimensional " + "space") + + if np.array_equal(start, end): + return np.linspace(start, start, t.size) + + # for points that violate equation for n-sphere + for coord in [start, end]: + if not np.allclose(np.linalg.norm(coord), 1.0, + rtol=1e-9, + atol=0): + raise ValueError("start and end are not" + " on a unit n-sphere") + + if not isinstance(tol, float): + raise ValueError("tol must be a float") + else: + tol = np.fabs(tol) + + coord_dist = euclidean(start, end) + + # diameter of 2 within tolerance means antipodes, which is a problem + # for all unit n-spheres (even the 0-sphere would have an ambiguous path) + if np.allclose(coord_dist, 2.0, rtol=0, atol=tol): + warnings.warn("start and end are antipodes " + "using the specified tolerance; " + "this may cause ambiguous slerp paths", + stacklevel=2) + + t = np.asarray(t, dtype=np.float64) + + if t.size == 0: + return np.empty((0, start.size)) + + if t.min() < 0 or t.max() > 1: + raise ValueError("interpolation parameter must be in [0, 1]") + + if t.ndim == 0: + return _geometric_slerp(start, + end, + np.atleast_1d(t)).ravel() + else: + return _geometric_slerp(start, + end, + t) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_hausdorff.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_hausdorff.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1e6713a98fd52ddada559eb735801c97824afd3a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_hausdorff.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_kdtree.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_kdtree.py new file mode 100644 index 0000000000000000000000000000000000000000..f65412e9e4ad3a0e0da3876c861430d678fe858c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_kdtree.py @@ -0,0 +1,920 @@ +# Copyright Anne M. Archibald 2008 +# Released under the scipy license +import numpy as np +from ._ckdtree import cKDTree, cKDTreeNode + +__all__ = ['minkowski_distance_p', 'minkowski_distance', + 'distance_matrix', + 'Rectangle', 'KDTree'] + + +def minkowski_distance_p(x, y, p=2): + """Compute the pth power of the L**p distance between two arrays. + + For efficiency, this function computes the L**p distance but does + not extract the pth root. If `p` is 1 or infinity, this is equal to + the actual L**p distance. + + The last dimensions of `x` and `y` must be the same length. Any + other dimensions must be compatible for broadcasting. + + Parameters + ---------- + x : (..., K) array_like + Input array. + y : (..., K) array_like + Input array. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + + Returns + ------- + dist : ndarray + pth power of the distance between the input arrays. + + Examples + -------- + >>> from scipy.spatial import minkowski_distance_p + >>> minkowski_distance_p([[0, 0], [0, 0]], [[1, 1], [0, 1]]) + array([2, 1]) + + """ + x = np.asarray(x) + y = np.asarray(y) + + # Find smallest common datatype with float64 (return type of this + # function) - addresses #10262. + # Don't just cast to float64 for complex input case. + common_datatype = np.promote_types(np.promote_types(x.dtype, y.dtype), + 'float64') + + # Make sure x and y are NumPy arrays of correct datatype. + x = x.astype(common_datatype) + y = y.astype(common_datatype) + + if p == np.inf: + return np.amax(np.abs(y-x), axis=-1) + elif p == 1: + return np.sum(np.abs(y-x), axis=-1) + else: + return np.sum(np.abs(y-x)**p, axis=-1) + + +def minkowski_distance(x, y, p=2): + """Compute the L**p distance between two arrays. + + The last dimensions of `x` and `y` must be the same length. Any + other dimensions must be compatible for broadcasting. + + Parameters + ---------- + x : (..., K) array_like + Input array. + y : (..., K) array_like + Input array. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + + Returns + ------- + dist : ndarray + Distance between the input arrays. + + Examples + -------- + >>> from scipy.spatial import minkowski_distance + >>> minkowski_distance([[0, 0], [0, 0]], [[1, 1], [0, 1]]) + array([ 1.41421356, 1. ]) + + """ + x = np.asarray(x) + y = np.asarray(y) + if p == np.inf or p == 1: + return minkowski_distance_p(x, y, p) + else: + return minkowski_distance_p(x, y, p)**(1./p) + + +class Rectangle: + """Hyperrectangle class. + + Represents a Cartesian product of intervals. + """ + def __init__(self, maxes, mins): + """Construct a hyperrectangle.""" + self.maxes = np.maximum(maxes,mins).astype(float) + self.mins = np.minimum(maxes,mins).astype(float) + self.m, = self.maxes.shape + + def __repr__(self): + return "" % list(zip(self.mins, self.maxes)) + + def volume(self): + """Total volume.""" + return np.prod(self.maxes-self.mins) + + def split(self, d, split): + """Produce two hyperrectangles by splitting. + + In general, if you need to compute maximum and minimum + distances to the children, it can be done more efficiently + by updating the maximum and minimum distances to the parent. + + Parameters + ---------- + d : int + Axis to split hyperrectangle along. + split : float + Position along axis `d` to split at. + + """ + mid = np.copy(self.maxes) + mid[d] = split + less = Rectangle(self.mins, mid) + mid = np.copy(self.mins) + mid[d] = split + greater = Rectangle(mid, self.maxes) + return less, greater + + def min_distance_point(self, x, p=2.): + """ + Return the minimum distance between input and points in the + hyperrectangle. + + Parameters + ---------- + x : array_like + Input. + p : float, optional + Input. + + """ + return minkowski_distance( + 0, np.maximum(0, np.maximum(self.mins-x, x-self.maxes)), + p + ) + + def max_distance_point(self, x, p=2.): + """ + Return the maximum distance between input and points in the hyperrectangle. + + Parameters + ---------- + x : array_like + Input array. + p : float, optional + Input. + + """ + return minkowski_distance(0, np.maximum(self.maxes-x, x-self.mins), p) + + def min_distance_rectangle(self, other, p=2.): + """ + Compute the minimum distance between points in the two hyperrectangles. + + Parameters + ---------- + other : hyperrectangle + Input. + p : float + Input. + + """ + return minkowski_distance( + 0, + np.maximum(0, np.maximum(self.mins-other.maxes, + other.mins-self.maxes)), + p + ) + + def max_distance_rectangle(self, other, p=2.): + """ + Compute the maximum distance between points in the two hyperrectangles. + + Parameters + ---------- + other : hyperrectangle + Input. + p : float, optional + Input. + + """ + return minkowski_distance( + 0, np.maximum(self.maxes-other.mins, other.maxes-self.mins), p) + + +class KDTree(cKDTree): + """kd-tree for quick nearest-neighbor lookup. + + This class provides an index into a set of k-dimensional points + which can be used to rapidly look up the nearest neighbors of any + point. + + Parameters + ---------- + data : array_like, shape (n,m) + The n data points of dimension m to be indexed. This array is + not copied unless this is necessary to produce a contiguous + array of doubles, and so modifying this data will result in + bogus results. The data are also copied if the kd-tree is built + with copy_data=True. + leafsize : positive int, optional + The number of points at which the algorithm switches over to + brute-force. Default: 10. + compact_nodes : bool, optional + If True, the kd-tree is built to shrink the hyperrectangles to + the actual data range. This usually gives a more compact tree that + is robust against degenerated input data and gives faster queries + at the expense of longer build time. Default: True. + copy_data : bool, optional + If True the data is always copied to protect the kd-tree against + data corruption. Default: False. + balanced_tree : bool, optional + If True, the median is used to split the hyperrectangles instead of + the midpoint. This usually gives a more compact tree and + faster queries at the expense of longer build time. Default: True. + boxsize : array_like or scalar, optional + Apply a m-d toroidal topology to the KDTree.. The topology is generated + by :math:`x_i + n_i L_i` where :math:`n_i` are integers and :math:`L_i` + is the boxsize along i-th dimension. The input data shall be wrapped + into :math:`[0, L_i)`. A ValueError is raised if any of the data is + outside of this bound. + + Notes + ----- + The algorithm used is described in Maneewongvatana and Mount 1999. + The general idea is that the kd-tree is a binary tree, each of whose + nodes represents an axis-aligned hyperrectangle. Each node specifies + an axis and splits the set of points based on whether their coordinate + along that axis is greater than or less than a particular value. + + During construction, the axis and splitting point are chosen by the + "sliding midpoint" rule, which ensures that the cells do not all + become long and thin. + + The tree can be queried for the r closest neighbors of any given point + (optionally returning only those within some maximum distance of the + point). It can also be queried, with a substantial gain in efficiency, + for the r approximate closest neighbors. + + For large dimensions (20 is already large) do not expect this to run + significantly faster than brute force. High-dimensional nearest-neighbor + queries are a substantial open problem in computer science. + + Attributes + ---------- + data : ndarray, shape (n,m) + The n data points of dimension m to be indexed. This array is + not copied unless this is necessary to produce a contiguous + array of doubles. The data are also copied if the kd-tree is built + with `copy_data=True`. + leafsize : positive int + The number of points at which the algorithm switches over to + brute-force. + m : int + The dimension of a single data-point. + n : int + The number of data points. + maxes : ndarray, shape (m,) + The maximum value in each dimension of the n data points. + mins : ndarray, shape (m,) + The minimum value in each dimension of the n data points. + size : int + The number of nodes in the tree. + + """ + + class node: + @staticmethod + def _create(ckdtree_node=None): + """Create either an inner or leaf node, wrapping a cKDTreeNode instance""" + if ckdtree_node is None: + return KDTree.node(ckdtree_node) + elif ckdtree_node.split_dim == -1: + return KDTree.leafnode(ckdtree_node) + else: + return KDTree.innernode(ckdtree_node) + + def __init__(self, ckdtree_node=None): + if ckdtree_node is None: + ckdtree_node = cKDTreeNode() + self._node = ckdtree_node + + def __lt__(self, other): + return id(self) < id(other) + + def __gt__(self, other): + return id(self) > id(other) + + def __le__(self, other): + return id(self) <= id(other) + + def __ge__(self, other): + return id(self) >= id(other) + + def __eq__(self, other): + return id(self) == id(other) + + class leafnode(node): + @property + def idx(self): + return self._node.indices + + @property + def children(self): + return self._node.children + + class innernode(node): + def __init__(self, ckdtreenode): + assert isinstance(ckdtreenode, cKDTreeNode) + super().__init__(ckdtreenode) + self.less = KDTree.node._create(ckdtreenode.lesser) + self.greater = KDTree.node._create(ckdtreenode.greater) + + @property + def split_dim(self): + return self._node.split_dim + + @property + def split(self): + return self._node.split + + @property + def children(self): + return self._node.children + + @property + def tree(self): + if not hasattr(self, "_tree"): + self._tree = KDTree.node._create(super().tree) + + return self._tree + + def __init__(self, data, leafsize=10, compact_nodes=True, copy_data=False, + balanced_tree=True, boxsize=None): + data = np.asarray(data) + if data.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + + # Note KDTree has different default leafsize from cKDTree + super().__init__(data, leafsize, compact_nodes, copy_data, + balanced_tree, boxsize) + + def query( + self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf, workers=1): + r"""Query the kd-tree for nearest neighbors. + + Parameters + ---------- + x : array_like, last dimension self.m + An array of points to query. + k : int or Sequence[int], optional + Either the number of nearest neighbors to return, or a list of the + k-th nearest neighbors to return, starting from 1. + eps : nonnegative float, optional + Return approximate nearest neighbors; the kth returned value + is guaranteed to be no further than (1+eps) times the + distance to the real kth nearest neighbor. + p : float, 1<=p<=infinity, optional + Which Minkowski p-norm to use. + 1 is the sum-of-absolute-values distance ("Manhattan" distance). + 2 is the usual Euclidean distance. + infinity is the maximum-coordinate-difference distance. + A large, finite p may cause a ValueError if overflow can occur. + distance_upper_bound : nonnegative float, optional + Return only neighbors within this distance. This is used to prune + tree searches, so if you are doing a series of nearest-neighbor + queries, it may help to supply the distance to the nearest neighbor + of the most recent point. + workers : int, optional + Number of workers to use for parallel processing. If -1 is given + all CPU threads are used. Default: 1. + + .. versionadded:: 1.6.0 + + Returns + ------- + d : float or array of floats + The distances to the nearest neighbors. + If ``x`` has shape ``tuple+(self.m,)``, then ``d`` has shape + ``tuple+(k,)``. + When k == 1, the last dimension of the output is squeezed. + Missing neighbors are indicated with infinite distances. + Hits are sorted by distance (nearest first). + + .. versionchanged:: 1.9.0 + Previously if ``k=None``, then `d` was an object array of + shape ``tuple``, containing lists of distances. This behavior + has been removed, use `query_ball_point` instead. + + i : integer or array of integers + The index of each neighbor in ``self.data``. + ``i`` is the same shape as d. + Missing neighbors are indicated with ``self.n``. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> x, y = np.mgrid[0:5, 2:8] + >>> tree = KDTree(np.c_[x.ravel(), y.ravel()]) + + To query the nearest neighbours and return squeezed result, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=1) + >>> print(dd, ii, sep='\n') + [2. 0.2236068] + [ 0 13] + + To query the nearest neighbours and return unsqueezed result, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1]) + >>> print(dd, ii, sep='\n') + [[2. ] + [0.2236068]] + [[ 0] + [13]] + + To query the second nearest neighbours and return unsqueezed result, + use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[2]) + >>> print(dd, ii, sep='\n') + [[2.23606798] + [0.80622577]] + [[ 6] + [19]] + + To query the first and second nearest neighbours, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=2) + >>> print(dd, ii, sep='\n') + [[2. 2.23606798] + [0.2236068 0.80622577]] + [[ 0 6] + [13 19]] + + or, be more specific + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1, 2]) + >>> print(dd, ii, sep='\n') + [[2. 2.23606798] + [0.2236068 0.80622577]] + [[ 0 6] + [13 19]] + + """ + x = np.asarray(x) + if x.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + + if k is None: + raise ValueError("k must be an integer or a sequence of integers") + + d, i = super().query(x, k, eps, p, distance_upper_bound, workers) + if isinstance(i, int): + i = np.intp(i) + return d, i + + def query_ball_point(self, x, r, p=2., eps=0, workers=1, + return_sorted=None, return_length=False): + """Find all points within distance r of point(s) x. + + Parameters + ---------- + x : array_like, shape tuple + (self.m,) + The point or points to search for neighbors of. + r : array_like, float + The radius of points to return, must broadcast to the length of x. + p : float, optional + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + eps : nonnegative float, optional + Approximate search. Branches of the tree are not explored if their + nearest points are further than ``r / (1 + eps)``, and branches are + added in bulk if their furthest points are nearer than + ``r * (1 + eps)``. + workers : int, optional + Number of jobs to schedule for parallel processing. If -1 is given + all processors are used. Default: 1. + + .. versionadded:: 1.6.0 + return_sorted : bool, optional + Sorts returned indices if True and does not sort them if False. If + None, does not sort single point queries, but does sort + multi-point queries which was the behavior before this option + was added. + + .. versionadded:: 1.6.0 + return_length : bool, optional + Return the number of points inside the radius instead of a list + of the indices. + + .. versionadded:: 1.6.0 + + Returns + ------- + results : list or array of lists + If `x` is a single point, returns a list of the indices of the + neighbors of `x`. If `x` is an array of points, returns an object + array of shape tuple containing lists of neighbors. + + Notes + ----- + If you have many points whose neighbors you want to find, you may save + substantial amounts of time by putting them in a KDTree and using + query_ball_tree. + + Examples + -------- + >>> import numpy as np + >>> from scipy import spatial + >>> x, y = np.mgrid[0:5, 0:5] + >>> points = np.c_[x.ravel(), y.ravel()] + >>> tree = spatial.KDTree(points) + >>> sorted(tree.query_ball_point([2, 0], 1)) + [5, 10, 11, 15] + + Query multiple points and plot the results: + + >>> import matplotlib.pyplot as plt + >>> points = np.asarray(points) + >>> plt.plot(points[:,0], points[:,1], '.') + >>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1): + ... nearby_points = points[results] + ... plt.plot(nearby_points[:,0], nearby_points[:,1], 'o') + >>> plt.margins(0.1, 0.1) + >>> plt.show() + + """ + x = np.asarray(x) + if x.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + return super().query_ball_point( + x, r, p, eps, workers, return_sorted, return_length) + + def query_ball_tree(self, other, r, p=2., eps=0): + """ + Find all pairs of points between `self` and `other` whose distance is + at most r. + + Parameters + ---------- + other : KDTree instance + The tree containing points to search against. + r : float + The maximum distance, has to be positive. + p : float, optional + Which Minkowski norm to use. `p` has to meet the condition + ``1 <= p <= infinity``. + eps : float, optional + Approximate search. Branches of the tree are not explored + if their nearest points are further than ``r/(1+eps)``, and + branches are added in bulk if their furthest points are nearer + than ``r * (1+eps)``. `eps` has to be non-negative. + + Returns + ------- + results : list of lists + For each element ``self.data[i]`` of this tree, ``results[i]`` is a + list of the indices of its neighbors in ``other.data``. + + Examples + -------- + You can search all pairs of points between two kd-trees within a distance: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((15, 2)) + >>> points2 = rng.random((15, 2)) + >>> plt.figure(figsize=(6, 6)) + >>> plt.plot(points1[:, 0], points1[:, 1], "xk", markersize=14) + >>> plt.plot(points2[:, 0], points2[:, 1], "og", markersize=14) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2) + >>> for i in range(len(indexes)): + ... for j in indexes[i]: + ... plt.plot([points1[i, 0], points2[j, 0]], + ... [points1[i, 1], points2[j, 1]], "-r") + >>> plt.show() + + """ + return super().query_ball_tree(other, r, p, eps) + + def query_pairs(self, r, p=2., eps=0, output_type='set'): + """Find all pairs of points in `self` whose distance is at most r. + + Parameters + ---------- + r : positive float + The maximum distance. + p : float, optional + Which Minkowski norm to use. `p` has to meet the condition + ``1 <= p <= infinity``. + eps : float, optional + Approximate search. Branches of the tree are not explored + if their nearest points are further than ``r/(1+eps)``, and + branches are added in bulk if their furthest points are nearer + than ``r * (1+eps)``. `eps` has to be non-negative. + output_type : string, optional + Choose the output container, 'set' or 'ndarray'. Default: 'set' + + .. versionadded:: 1.6.0 + + Returns + ------- + results : set or ndarray + Set of pairs ``(i,j)``, with ``i < j``, for which the corresponding + positions are close. If output_type is 'ndarray', an ndarry is + returned instead of a set. + + Examples + -------- + You can search all pairs of points in a kd-tree within a distance: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points = rng.random((20, 2)) + >>> plt.figure(figsize=(6, 6)) + >>> plt.plot(points[:, 0], points[:, 1], "xk", markersize=14) + >>> kd_tree = KDTree(points) + >>> pairs = kd_tree.query_pairs(r=0.2) + >>> for (i, j) in pairs: + ... plt.plot([points[i, 0], points[j, 0]], + ... [points[i, 1], points[j, 1]], "-r") + >>> plt.show() + + """ + return super().query_pairs(r, p, eps, output_type) + + def count_neighbors(self, other, r, p=2., weights=None, cumulative=True): + """Count how many nearby pairs can be formed. + + Count the number of pairs ``(x1,x2)`` can be formed, with ``x1`` drawn + from ``self`` and ``x2`` drawn from ``other``, and where + ``distance(x1, x2, p) <= r``. + + Data points on ``self`` and ``other`` are optionally weighted by the + ``weights`` argument. (See below) + + This is adapted from the "two-point correlation" algorithm described by + Gray and Moore [1]_. See notes for further discussion. + + Parameters + ---------- + other : KDTree + The other tree to draw points from, can be the same tree as self. + r : float or one-dimensional array of floats + The radius to produce a count for. Multiple radii are searched with + a single tree traversal. + If the count is non-cumulative(``cumulative=False``), ``r`` defines + the edges of the bins, and must be non-decreasing. + p : float, optional + 1<=p<=infinity. + Which Minkowski p-norm to use. + Default 2.0. + A finite large p may cause a ValueError if overflow can occur. + weights : tuple, array_like, or None, optional + If None, the pair-counting is unweighted. + If given as a tuple, weights[0] is the weights of points in + ``self``, and weights[1] is the weights of points in ``other``; + either can be None to indicate the points are unweighted. + If given as an array_like, weights is the weights of points in + ``self`` and ``other``. For this to make sense, ``self`` and + ``other`` must be the same tree. If ``self`` and ``other`` are two + different trees, a ``ValueError`` is raised. + Default: None + + .. versionadded:: 1.6.0 + cumulative : bool, optional + Whether the returned counts are cumulative. When cumulative is set + to ``False`` the algorithm is optimized to work with a large number + of bins (>10) specified by ``r``. When ``cumulative`` is set to + True, the algorithm is optimized to work with a small number of + ``r``. Default: True + + .. versionadded:: 1.6.0 + + Returns + ------- + result : scalar or 1-D array + The number of pairs. For unweighted counts, the result is integer. + For weighted counts, the result is float. + If cumulative is False, ``result[i]`` contains the counts with + ``(-inf if i == 0 else r[i-1]) < R <= r[i]`` + + Notes + ----- + Pair-counting is the basic operation used to calculate the two point + correlation functions from a data set composed of position of objects. + + Two point correlation function measures the clustering of objects and + is widely used in cosmology to quantify the large scale structure + in our Universe, but it may be useful for data analysis in other fields + where self-similar assembly of objects also occur. + + The Landy-Szalay estimator for the two point correlation function of + ``D`` measures the clustering signal in ``D``. [2]_ + + For example, given the position of two sets of objects, + + - objects ``D`` (data) contains the clustering signal, and + + - objects ``R`` (random) that contains no signal, + + .. math:: + + \\xi(r) = \\frac{ - 2 f + f^2}{f^2}, + + where the brackets represents counting pairs between two data sets + in a finite bin around ``r`` (distance), corresponding to setting + `cumulative=False`, and ``f = float(len(D)) / float(len(R))`` is the + ratio between number of objects from data and random. + + The algorithm implemented here is loosely based on the dual-tree + algorithm described in [1]_. We switch between two different + pair-cumulation scheme depending on the setting of ``cumulative``. + The computing time of the method we use when for + ``cumulative == False`` does not scale with the total number of bins. + The algorithm for ``cumulative == True`` scales linearly with the + number of bins, though it is slightly faster when only + 1 or 2 bins are used. [5]_. + + As an extension to the naive pair-counting, + weighted pair-counting counts the product of weights instead + of number of pairs. + Weighted pair-counting is used to estimate marked correlation functions + ([3]_, section 2.2), + or to properly calculate the average of data per distance bin + (e.g. [4]_, section 2.1 on redshift). + + .. [1] Gray and Moore, + "N-body problems in statistical learning", + Mining the sky, 2000, + https://arxiv.org/abs/astro-ph/0012333 + + .. [2] Landy and Szalay, + "Bias and variance of angular correlation functions", + The Astrophysical Journal, 1993, + http://adsabs.harvard.edu/abs/1993ApJ...412...64L + + .. [3] Sheth, Connolly and Skibba, + "Marked correlations in galaxy formation models", + Arxiv e-print, 2005, + https://arxiv.org/abs/astro-ph/0511773 + + .. [4] Hawkins, et al., + "The 2dF Galaxy Redshift Survey: correlation functions, + peculiar velocities and the matter density of the Universe", + Monthly Notices of the Royal Astronomical Society, 2002, + http://adsabs.harvard.edu/abs/2003MNRAS.346...78H + + .. [5] https://github.com/scipy/scipy/pull/5647#issuecomment-168474926 + + Examples + -------- + You can count neighbors number between two kd-trees within a distance: + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((5, 2)) + >>> points2 = rng.random((5, 2)) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> kd_tree1.count_neighbors(kd_tree2, 0.2) + 1 + + This number is same as the total pair number calculated by + `query_ball_tree`: + + >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2) + >>> sum([len(i) for i in indexes]) + 1 + + """ + return super().count_neighbors(other, r, p, weights, cumulative) + + def sparse_distance_matrix( + self, other, max_distance, p=2., output_type='dok_matrix'): + """Compute a sparse distance matrix. + + Computes a distance matrix between two KDTrees, leaving as zero + any distance greater than max_distance. + + Parameters + ---------- + other : KDTree + + max_distance : positive float + + p : float, 1<=p<=infinity + Which Minkowski p-norm to use. + A finite large p may cause a ValueError if overflow can occur. + + output_type : string, optional + Which container to use for output data. Options: 'dok_matrix', + 'coo_matrix', 'dict', or 'ndarray'. Default: 'dok_matrix'. + + .. versionadded:: 1.6.0 + + Returns + ------- + result : dok_matrix, coo_matrix, dict or ndarray + Sparse matrix representing the results in "dictionary of keys" + format. If a dict is returned the keys are (i,j) tuples of indices. + If output_type is 'ndarray' a record array with fields 'i', 'j', + and 'v' is returned, + + Examples + -------- + You can compute a sparse distance matrix between two kd-trees: + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((5, 2)) + >>> points2 = rng.random((5, 2)) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> sdm = kd_tree1.sparse_distance_matrix(kd_tree2, 0.3) + >>> sdm.toarray() + array([[0. , 0. , 0.12295571, 0. , 0. ], + [0. , 0. , 0. , 0. , 0. ], + [0.28942611, 0. , 0. , 0.2333084 , 0. ], + [0. , 0. , 0. , 0. , 0. ], + [0.24617575, 0.29571802, 0.26836782, 0. , 0. ]]) + + You can check distances above the `max_distance` are zeros: + + >>> from scipy.spatial import distance_matrix + >>> distance_matrix(points1, points2) + array([[0.56906522, 0.39923701, 0.12295571, 0.8658745 , 0.79428925], + [0.37327919, 0.7225693 , 0.87665969, 0.32580855, 0.75679479], + [0.28942611, 0.30088013, 0.6395831 , 0.2333084 , 0.33630734], + [0.31994999, 0.72658602, 0.71124834, 0.55396483, 0.90785663], + [0.24617575, 0.29571802, 0.26836782, 0.57714465, 0.6473269 ]]) + + """ + return super().sparse_distance_matrix( + other, max_distance, p, output_type) + + +def distance_matrix(x, y, p=2, threshold=1000000): + """Compute the distance matrix. + + Returns the matrix of all pair-wise distances. + + Parameters + ---------- + x : (M, K) array_like + Matrix of M vectors in K dimensions. + y : (N, K) array_like + Matrix of N vectors in K dimensions. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + threshold : positive int + If ``M * N * K`` > `threshold`, algorithm uses a Python loop instead + of large temporary arrays. + + Returns + ------- + result : (M, N) ndarray + Matrix containing the distance from every vector in `x` to every vector + in `y`. + + Examples + -------- + >>> from scipy.spatial import distance_matrix + >>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]]) + array([[ 1. , 1.41421356], + [ 1.41421356, 1. ]]) + + """ + + x = np.asarray(x) + m, k = x.shape + y = np.asarray(y) + n, kk = y.shape + + if k != kk: + raise ValueError(f"x contains {k}-dimensional vectors but y contains " + f"{kk}-dimensional vectors") + + if m*n*k <= threshold: + return minkowski_distance(x[:,np.newaxis,:],y[np.newaxis,:,:],p) + else: + result = np.empty((m,n),dtype=float) # FIXME: figure out the best dtype + if m < n: + for i in range(m): + result[i,:] = minkowski_distance(x[i],y,p) + else: + for j in range(n): + result[:,j] = minkowski_distance(x,y[j],p) + return result diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_plotutils.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_plotutils.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7e0998a5a75d0cab18effc1ca05ede708c0f0a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_plotutils.py @@ -0,0 +1,270 @@ +import numpy as np +from scipy._lib.decorator import decorator as _decorator + +__all__ = ['delaunay_plot_2d', 'convex_hull_plot_2d', 'voronoi_plot_2d'] + + +@_decorator +def _held_figure(func, obj, ax=None, **kw): + import matplotlib.pyplot as plt + + if ax is None: + fig = plt.figure() + ax = fig.gca() + return func(obj, ax=ax, **kw) + + # As of matplotlib 2.0, the "hold" mechanism is deprecated. + # When matplotlib 1.x is no longer supported, this check can be removed. + was_held = getattr(ax, 'ishold', lambda: True)() + if was_held: + return func(obj, ax=ax, **kw) + try: + ax.hold(True) + return func(obj, ax=ax, **kw) + finally: + ax.hold(was_held) + + +def _adjust_bounds(ax, points): + margin = 0.1 * np.ptp(points, axis=0) + xy_min = points.min(axis=0) - margin + xy_max = points.max(axis=0) + margin + ax.set_xlim(xy_min[0], xy_max[0]) + ax.set_ylim(xy_min[1], xy_max[1]) + + +@_held_figure +def delaunay_plot_2d(tri, ax=None): + """ + Plot the given Delaunay triangulation in 2-D + + Parameters + ---------- + tri : scipy.spatial.Delaunay instance + Triangulation to plot + ax : matplotlib.axes.Axes instance, optional + Axes to plot on + + Returns + ------- + fig : matplotlib.figure.Figure instance + Figure for the plot + + See Also + -------- + Delaunay + matplotlib.pyplot.triplot + + Notes + ----- + Requires Matplotlib. + + Examples + -------- + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.spatial import Delaunay, delaunay_plot_2d + + The Delaunay triangulation of a set of random points: + + >>> rng = np.random.default_rng() + >>> points = rng.random((30, 2)) + >>> tri = Delaunay(points) + + Plot it: + + >>> _ = delaunay_plot_2d(tri) + >>> plt.show() + + """ + if tri.points.shape[1] != 2: + raise ValueError("Delaunay triangulation is not 2-D") + + x, y = tri.points.T + ax.plot(x, y, 'o') + ax.triplot(x, y, tri.simplices.copy()) + + _adjust_bounds(ax, tri.points) + + return ax.figure + + +@_held_figure +def convex_hull_plot_2d(hull, ax=None): + """ + Plot the given convex hull diagram in 2-D + + Parameters + ---------- + hull : scipy.spatial.ConvexHull instance + Convex hull to plot + ax : matplotlib.axes.Axes instance, optional + Axes to plot on + + Returns + ------- + fig : matplotlib.figure.Figure instance + Figure for the plot + + See Also + -------- + ConvexHull + + Notes + ----- + Requires Matplotlib. + + + Examples + -------- + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.spatial import ConvexHull, convex_hull_plot_2d + + The convex hull of a random set of points: + + >>> rng = np.random.default_rng() + >>> points = rng.random((30, 2)) + >>> hull = ConvexHull(points) + + Plot it: + + >>> _ = convex_hull_plot_2d(hull) + >>> plt.show() + + """ + from matplotlib.collections import LineCollection + + if hull.points.shape[1] != 2: + raise ValueError("Convex hull is not 2-D") + + ax.plot(hull.points[:, 0], hull.points[:, 1], 'o') + line_segments = [hull.points[simplex] for simplex in hull.simplices] + ax.add_collection(LineCollection(line_segments, + colors='k', + linestyle='solid')) + _adjust_bounds(ax, hull.points) + + return ax.figure + + +@_held_figure +def voronoi_plot_2d(vor, ax=None, **kw): + """ + Plot the given Voronoi diagram in 2-D + + Parameters + ---------- + vor : scipy.spatial.Voronoi instance + Diagram to plot + ax : matplotlib.axes.Axes instance, optional + Axes to plot on + show_points : bool, optional + Add the Voronoi points to the plot. + show_vertices : bool, optional + Add the Voronoi vertices to the plot. + line_colors : string, optional + Specifies the line color for polygon boundaries + line_width : float, optional + Specifies the line width for polygon boundaries + line_alpha : float, optional + Specifies the line alpha for polygon boundaries + point_size : float, optional + Specifies the size of points + + Returns + ------- + fig : matplotlib.figure.Figure instance + Figure for the plot + + See Also + -------- + Voronoi + + Notes + ----- + Requires Matplotlib. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.spatial import Voronoi, voronoi_plot_2d + + Create a set of points for the example: + + >>> rng = np.random.default_rng() + >>> points = rng.random((10,2)) + + Generate the Voronoi diagram for the points: + + >>> vor = Voronoi(points) + + Use `voronoi_plot_2d` to plot the diagram: + + >>> fig = voronoi_plot_2d(vor) + + Use `voronoi_plot_2d` to plot the diagram again, with some settings + customized: + + >>> fig = voronoi_plot_2d(vor, show_vertices=False, line_colors='orange', + ... line_width=2, line_alpha=0.6, point_size=2) + >>> plt.show() + + """ + from matplotlib.collections import LineCollection + + if vor.points.shape[1] != 2: + raise ValueError("Voronoi diagram is not 2-D") + + if kw.get('show_points', True): + point_size = kw.get('point_size', None) + ax.plot(vor.points[:, 0], vor.points[:, 1], '.', markersize=point_size) + if kw.get('show_vertices', True): + ax.plot(vor.vertices[:, 0], vor.vertices[:, 1], 'o') + + line_colors = kw.get('line_colors', 'k') + line_width = kw.get('line_width', 1.0) + line_alpha = kw.get('line_alpha', 1.0) + + center = vor.points.mean(axis=0) + ptp_bound = np.ptp(vor.points, axis=0) + + finite_segments = [] + infinite_segments = [] + for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices): + simplex = np.asarray(simplex) + if np.all(simplex >= 0): + finite_segments.append(vor.vertices[simplex]) + else: + i = simplex[simplex >= 0][0] # finite end Voronoi vertex + + t = vor.points[pointidx[1]] - vor.points[pointidx[0]] # tangent + t /= np.linalg.norm(t) + n = np.array([-t[1], t[0]]) # normal + + midpoint = vor.points[pointidx].mean(axis=0) + direction = np.sign(np.dot(midpoint - center, n)) * n + if (vor.furthest_site): + direction = -direction + aspect_factor = abs(ptp_bound.max() / ptp_bound.min()) + far_point = vor.vertices[i] + direction * ptp_bound.max() * aspect_factor + + infinite_segments.append([vor.vertices[i], far_point]) + + ax.add_collection(LineCollection(finite_segments, + colors=line_colors, + lw=line_width, + alpha=line_alpha, + linestyle='solid')) + ax.add_collection(LineCollection(infinite_segments, + colors=line_colors, + lw=line_width, + alpha=line_alpha, + linestyle='dashed')) + + _adjust_bounds(ax, vor.points) + + return ax.figure diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_procrustes.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..ec460056ca06ebdff007423f91577cbd8f22e24c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_procrustes.py @@ -0,0 +1,132 @@ +""" +This module provides functions to perform full Procrustes analysis. + +This code was originally written by Justin Kucynski and ported over from +scikit-bio by Yoshiki Vazquez-Baeza. +""" + +import numpy as np +from scipy.linalg import orthogonal_procrustes + + +__all__ = ['procrustes'] + + +def procrustes(data1, data2): + r"""Procrustes analysis, a similarity test for two data sets. + + Each input matrix is a set of points or vectors (the rows of the matrix). + The dimension of the space is the number of columns of each matrix. Given + two identically sized matrices, procrustes standardizes both such that: + + - :math:`tr(AA^{T}) = 1`. + + - Both sets of points are centered around the origin. + + Procrustes ([1]_, [2]_) then applies the optimal transform to the second + matrix (including scaling/dilation, rotations, and reflections) to minimize + :math:`M^{2}=\sum(data1-data2)^{2}`, or the sum of the squares of the + pointwise differences between the two input datasets. + + This function was not designed to handle datasets with different numbers of + datapoints (rows). If two data sets have different dimensionality + (different number of columns), simply add columns of zeros to the smaller + of the two. + + Parameters + ---------- + data1 : array_like + Matrix, n rows represent points in k (columns) space `data1` is the + reference data, after it is standardised, the data from `data2` will be + transformed to fit the pattern in `data1` (must have >1 unique points). + data2 : array_like + n rows of data in k space to be fit to `data1`. Must be the same + shape ``(numrows, numcols)`` as data1 (must have >1 unique points). + + Returns + ------- + mtx1 : array_like + A standardized version of `data1`. + mtx2 : array_like + The orientation of `data2` that best fits `data1`. Centered, but not + necessarily :math:`tr(AA^{T}) = 1`. + disparity : float + :math:`M^{2}` as defined above. + + Raises + ------ + ValueError + If the input arrays are not two-dimensional. + If the shape of the input arrays is different. + If the input arrays have zero columns or zero rows. + + See Also + -------- + scipy.linalg.orthogonal_procrustes + scipy.spatial.distance.directed_hausdorff : Another similarity test + for two data sets + + Notes + ----- + - The disparity should not depend on the order of the input matrices, but + the output matrices will, as only the first output matrix is guaranteed + to be scaled such that :math:`tr(AA^{T}) = 1`. + + - Duplicate data points are generally ok, duplicating a data point will + increase its effect on the procrustes fit. + + - The disparity scales as the number of points per input matrix. + + References + ---------- + .. [1] Krzanowski, W. J. (2000). "Principles of Multivariate analysis". + .. [2] Gower, J. C. (1975). "Generalized procrustes analysis". + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial import procrustes + + The matrix ``b`` is a rotated, shifted, scaled and mirrored version of + ``a`` here: + + >>> a = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], 'd') + >>> b = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], 'd') + >>> mtx1, mtx2, disparity = procrustes(a, b) + >>> round(disparity) + 0.0 + + """ + mtx1 = np.array(data1, dtype=np.float64, copy=True) + mtx2 = np.array(data2, dtype=np.float64, copy=True) + + if mtx1.ndim != 2 or mtx2.ndim != 2: + raise ValueError("Input matrices must be two-dimensional") + if mtx1.shape != mtx2.shape: + raise ValueError("Input matrices must be of same shape") + if mtx1.size == 0: + raise ValueError("Input matrices must be >0 rows and >0 cols") + + # translate all the data to the origin + mtx1 -= np.mean(mtx1, 0) + mtx2 -= np.mean(mtx2, 0) + + norm1 = np.linalg.norm(mtx1) + norm2 = np.linalg.norm(mtx2) + + if norm1 == 0 or norm2 == 0: + raise ValueError("Input matrices must contain >1 unique points") + + # change scaling of data (in rows) such that trace(mtx*mtx') = 1 + mtx1 /= norm1 + mtx2 /= norm2 + + # transform mtx2 to minimize disparity + R, s = orthogonal_procrustes(mtx1, mtx2) + mtx2 = np.dot(mtx2, R.T) * s + + # measure the dissimilarity between the two datasets + disparity = np.sum(np.square(mtx1 - mtx2)) + + return mtx1, mtx2, disparity + diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_qhull.pyi b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_qhull.pyi new file mode 100644 index 0000000000000000000000000000000000000000..416128eab5f53cdc8f45c422bcc140451223bd3f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_qhull.pyi @@ -0,0 +1,213 @@ +''' +Static type checking stub file for scipy/spatial/qhull.pyx +''' + + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from typing_extensions import final + +class QhullError(RuntimeError): + ... + +@final +class _Qhull: + # Read-only cython attribute that behaves, more or less, like a property + @property + def ndim(self) -> int: ... + mode_option: bytes + options: bytes + furthest_site: bool + + def __init__( + self, + mode_option: bytes, + points: NDArray[np.float64], + options: None | bytes = ..., + required_options: None | bytes = ..., + furthest_site: bool = ..., + incremental: bool = ..., + interior_point: None | NDArray[np.float64] = ..., + ) -> None: ... + def check_active(self) -> None: ... + def close(self) -> None: ... + def get_points(self) -> NDArray[np.float64]: ... + def add_points( + self, + points: ArrayLike, + interior_point: ArrayLike = ... + ) -> None: ... + def get_paraboloid_shift_scale(self) -> tuple[float, float]: ... + def volume_area(self) -> tuple[float, float]: ... + def triangulate(self) -> None: ... + def get_simplex_facet_array(self) -> tuple[ + NDArray[np.intc], + NDArray[np.intc], + NDArray[np.float64], + NDArray[np.intc], + NDArray[np.intc], + ]: ... + def get_hull_points(self) -> NDArray[np.float64]: ... + def get_hull_facets(self) -> tuple[ + list[list[int]], + NDArray[np.float64], + ]: ... + def get_voronoi_diagram(self) -> tuple[ + NDArray[np.float64], + NDArray[np.intc], + list[list[int]], + list[list[int]], + NDArray[np.intp], + ]: ... + def get_extremes_2d(self) -> NDArray[np.intc]: ... + +def _get_barycentric_transforms( + points: NDArray[np.float64], + simplices: NDArray[np.intc], + eps: float +) -> NDArray[np.float64]: ... + +class _QhullUser: + ndim: int + npoints: int + min_bound: NDArray[np.float64] + max_bound: NDArray[np.float64] + + def __init__(self, qhull: _Qhull, incremental: bool = ...) -> None: ... + def close(self) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def _add_points( + self, + points: ArrayLike, + restart: bool = ..., + interior_point: ArrayLike = ... + ) -> None: ... + +class Delaunay(_QhullUser): + furthest_site: bool + paraboloid_scale: float + paraboloid_shift: float + simplices: NDArray[np.intc] + neighbors: NDArray[np.intc] + equations: NDArray[np.float64] + coplanar: NDArray[np.intc] + good: NDArray[np.intc] + nsimplex: int + vertices: NDArray[np.intc] + + def __init__( + self, + points: ArrayLike, + furthest_site: bool = ..., + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points( + self, + points: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def transform(self) -> NDArray[np.float64]: ... + @property + def vertex_to_simplex(self) -> NDArray[np.intc]: ... + @property + def vertex_neighbor_vertices(self) -> tuple[ + NDArray[np.intc], + NDArray[np.intc], + ]: ... + @property + def convex_hull(self) -> NDArray[np.intc]: ... + def find_simplex( + self, + xi: ArrayLike, + bruteforce: bool = ..., + tol: float = ... + ) -> NDArray[np.intc]: ... + def plane_distance(self, xi: ArrayLike) -> NDArray[np.float64]: ... + def lift_points(self, x: ArrayLike) -> NDArray[np.float64]: ... + +def tsearch(tri: Delaunay, xi: ArrayLike) -> NDArray[np.intc]: ... +def _copy_docstr(dst: object, src: object) -> None: ... + +class ConvexHull(_QhullUser): + simplices: NDArray[np.intc] + neighbors: NDArray[np.intc] + equations: NDArray[np.float64] + coplanar: NDArray[np.intc] + good: None | NDArray[np.bool_] + volume: float + area: float + nsimplex: int + + def __init__( + self, + points: ArrayLike, + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points(self, points: ArrayLike, + restart: bool = ...) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def vertices(self) -> NDArray[np.intc]: ... + +class Voronoi(_QhullUser): + vertices: NDArray[np.float64] + ridge_points: NDArray[np.intc] + ridge_vertices: list[list[int]] + regions: list[list[int]] + point_region: NDArray[np.intp] + furthest_site: bool + + def __init__( + self, + points: ArrayLike, + furthest_site: bool = ..., + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_points( + self, + points: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def points(self) -> NDArray[np.float64]: ... + @property + def ridge_dict(self) -> dict[tuple[int, int], list[int]]: ... + +class HalfspaceIntersection(_QhullUser): + interior_point: NDArray[np.float64] + dual_facets: list[list[int]] + dual_equations: NDArray[np.float64] + dual_points: NDArray[np.float64] + dual_volume: float + dual_area: float + intersections: NDArray[np.float64] + ndim: int + nineq: int + + def __init__( + self, + halfspaces: ArrayLike, + interior_point: ArrayLike, + incremental: bool = ..., + qhull_options: None | str = ... + ) -> None: ... + def _update(self, qhull: _Qhull) -> None: ... + def add_halfspaces( + self, + halfspaces: ArrayLike, + restart: bool = ... + ) -> None: ... + @property + def halfspaces(self) -> NDArray[np.float64]: ... + @property + def dual_vertices(self) -> NDArray[np.integer]: ... diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_spherical_voronoi.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_spherical_voronoi.py new file mode 100644 index 0000000000000000000000000000000000000000..6b9ba82429235469ada83de917d8f9d65d1a4088 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_spherical_voronoi.py @@ -0,0 +1,341 @@ +""" +Spherical Voronoi Code + +.. versionadded:: 0.18.0 + +""" +# +# Copyright (C) Tyler Reddy, Ross Hemsley, Edd Edmondson, +# Nikolai Nowaczyk, Joe Pitt-Francis, 2015. +# +# Distributed under the same BSD license as SciPy. +# + +import numpy as np +import scipy +from . import _voronoi +from scipy.spatial import cKDTree + +__all__ = ['SphericalVoronoi'] + + +def calculate_solid_angles(R): + """Calculates the solid angles of plane triangles. Implements the method of + Van Oosterom and Strackee [VanOosterom]_ with some modifications. Assumes + that input points have unit norm.""" + # Original method uses a triple product `R1 . (R2 x R3)` for the numerator. + # This is equal to the determinant of the matrix [R1 R2 R3], which can be + # computed with better stability. + numerator = np.linalg.det(R) + denominator = 1 + (np.einsum('ij,ij->i', R[:, 0], R[:, 1]) + + np.einsum('ij,ij->i', R[:, 1], R[:, 2]) + + np.einsum('ij,ij->i', R[:, 2], R[:, 0])) + return np.abs(2 * np.arctan2(numerator, denominator)) + + +class SphericalVoronoi: + """ Voronoi diagrams on the surface of a sphere. + + .. versionadded:: 0.18.0 + + Parameters + ---------- + points : ndarray of floats, shape (npoints, ndim) + Coordinates of points from which to construct a spherical + Voronoi diagram. + radius : float, optional + Radius of the sphere (Default: 1) + center : ndarray of floats, shape (ndim,) + Center of sphere (Default: origin) + threshold : float + Threshold for detecting duplicate points and + mismatches between points and sphere parameters. + (Default: 1e-06) + + Attributes + ---------- + points : double array of shape (npoints, ndim) + the points in `ndim` dimensions to generate the Voronoi diagram from + radius : double + radius of the sphere + center : double array of shape (ndim,) + center of the sphere + vertices : double array of shape (nvertices, ndim) + Voronoi vertices corresponding to points + regions : list of list of integers of shape (npoints, _ ) + the n-th entry is a list consisting of the indices + of the vertices belonging to the n-th point in points + + Methods + ------- + calculate_areas + Calculates the areas of the Voronoi regions. For 2D point sets, the + regions are circular arcs. The sum of the areas is `2 * pi * radius`. + For 3D point sets, the regions are spherical polygons. The sum of the + areas is `4 * pi * radius**2`. + + Raises + ------ + ValueError + If there are duplicates in `points`. + If the provided `radius` is not consistent with `points`. + + Notes + ----- + The spherical Voronoi diagram algorithm proceeds as follows. The Convex + Hull of the input points (generators) is calculated, and is equivalent to + their Delaunay triangulation on the surface of the sphere [Caroli]_. + The Convex Hull neighbour information is then used to + order the Voronoi region vertices around each generator. The latter + approach is substantially less sensitive to floating point issues than + angle-based methods of Voronoi region vertex sorting. + + Empirical assessment of spherical Voronoi algorithm performance suggests + quadratic time complexity (loglinear is optimal, but algorithms are more + challenging to implement). + + References + ---------- + .. [Caroli] Caroli et al. Robust and Efficient Delaunay triangulations of + points on or close to a sphere. Research Report RR-7004, 2009. + + .. [VanOosterom] Van Oosterom and Strackee. The solid angle of a plane + triangle. IEEE Transactions on Biomedical Engineering, + 2, 1983, pp 125--126. + + See Also + -------- + Voronoi : Conventional Voronoi diagrams in N dimensions. + + Examples + -------- + Do some imports and take some points on a cube: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.spatial import SphericalVoronoi, geometric_slerp + >>> from mpl_toolkits.mplot3d import proj3d + >>> # set input data + >>> points = np.array([[0, 0, 1], [0, 0, -1], [1, 0, 0], + ... [0, 1, 0], [0, -1, 0], [-1, 0, 0], ]) + + Calculate the spherical Voronoi diagram: + + >>> radius = 1 + >>> center = np.array([0, 0, 0]) + >>> sv = SphericalVoronoi(points, radius, center) + + Generate plot: + + >>> # sort vertices (optional, helpful for plotting) + >>> sv.sort_vertices_of_regions() + >>> t_vals = np.linspace(0, 1, 2000) + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + >>> # plot the unit sphere for reference (optional) + >>> u = np.linspace(0, 2 * np.pi, 100) + >>> v = np.linspace(0, np.pi, 100) + >>> x = np.outer(np.cos(u), np.sin(v)) + >>> y = np.outer(np.sin(u), np.sin(v)) + >>> z = np.outer(np.ones(np.size(u)), np.cos(v)) + >>> ax.plot_surface(x, y, z, color='y', alpha=0.1) + >>> # plot generator points + >>> ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b') + >>> # plot Voronoi vertices + >>> ax.scatter(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2], + ... c='g') + >>> # indicate Voronoi regions (as Euclidean polygons) + >>> for region in sv.regions: + ... n = len(region) + ... for i in range(n): + ... start = sv.vertices[region][i] + ... end = sv.vertices[region][(i + 1) % n] + ... result = geometric_slerp(start, end, t_vals) + ... ax.plot(result[..., 0], + ... result[..., 1], + ... result[..., 2], + ... c='k') + >>> ax.azim = 10 + >>> ax.elev = 40 + >>> _ = ax.set_xticks([]) + >>> _ = ax.set_yticks([]) + >>> _ = ax.set_zticks([]) + >>> fig.set_size_inches(4, 4) + >>> plt.show() + + """ + def __init__(self, points, radius=1, center=None, threshold=1e-06): + + if radius is None: + raise ValueError('`radius` is `None`. ' + 'Please provide a floating point number ' + '(i.e. `radius=1`).') + + self.radius = float(radius) + self.points = np.array(points).astype(np.float64) + self._dim = self.points.shape[1] + if center is None: + self.center = np.zeros(self._dim) + else: + self.center = np.array(center, dtype=float) + + # test degenerate input + self._rank = np.linalg.matrix_rank(self.points - self.points[0], + tol=threshold * self.radius) + if self._rank < self._dim: + raise ValueError(f"Rank of input points must be at least {self._dim}") + + if cKDTree(self.points).query_pairs(threshold * self.radius): + raise ValueError("Duplicate generators present.") + + radii = np.linalg.norm(self.points - self.center, axis=1) + max_discrepancy = np.abs(radii - self.radius).max() + if max_discrepancy >= threshold * self.radius: + raise ValueError("Radius inconsistent with generators.") + + self._calc_vertices_regions() + + def _calc_vertices_regions(self): + """ + Calculates the Voronoi vertices and regions of the generators stored + in self.points. The vertices will be stored in self.vertices and the + regions in self.regions. + + This algorithm was discussed at PyData London 2015 by + Tyler Reddy, Ross Hemsley and Nikolai Nowaczyk + """ + # get Convex Hull + conv = scipy.spatial.ConvexHull(self.points) + # get circumcenters of Convex Hull triangles from facet equations + # for 3D input circumcenters will have shape: (2N-4, 3) + self.vertices = self.radius * conv.equations[:, :-1] + self.center + self._simplices = conv.simplices + # calculate regions from triangulation + # for 3D input simplex_indices will have shape: (2N-4,) + simplex_indices = np.arange(len(self._simplices)) + # for 3D input tri_indices will have shape: (6N-12,) + tri_indices = np.column_stack([simplex_indices] * self._dim).ravel() + # for 3D input point_indices will have shape: (6N-12,) + point_indices = self._simplices.ravel() + # for 3D input indices will have shape: (6N-12,) + indices = np.argsort(point_indices, kind='mergesort') + # for 3D input flattened_groups will have shape: (6N-12,) + flattened_groups = tri_indices[indices].astype(np.intp) + # intervals will have shape: (N+1,) + intervals = np.cumsum(np.bincount(point_indices + 1)) + # split flattened groups to get nested list of unsorted regions + groups = [list(flattened_groups[intervals[i]:intervals[i + 1]]) + for i in range(len(intervals) - 1)] + self.regions = groups + + def sort_vertices_of_regions(self): + """Sort indices of the vertices to be (counter-)clockwise ordered. + + Raises + ------ + TypeError + If the points are not three-dimensional. + + Notes + ----- + For each region in regions, it sorts the indices of the Voronoi + vertices such that the resulting points are in a clockwise or + counterclockwise order around the generator point. + + This is done as follows: Recall that the n-th region in regions + surrounds the n-th generator in points and that the k-th + Voronoi vertex in vertices is the circumcenter of the k-th triangle + in self._simplices. For each region n, we choose the first triangle + (=Voronoi vertex) in self._simplices and a vertex of that triangle + not equal to the center n. These determine a unique neighbor of that + triangle, which is then chosen as the second triangle. The second + triangle will have a unique vertex not equal to the current vertex or + the center. This determines a unique neighbor of the second triangle, + which is then chosen as the third triangle and so forth. We proceed + through all the triangles (=Voronoi vertices) belonging to the + generator in points and obtain a sorted version of the vertices + of its surrounding region. + """ + if self._dim != 3: + raise TypeError("Only supported for three-dimensional point sets") + _voronoi.sort_vertices_of_regions(self._simplices, self.regions) + + def _calculate_areas_3d(self): + self.sort_vertices_of_regions() + sizes = [len(region) for region in self.regions] + csizes = np.cumsum(sizes) + num_regions = csizes[-1] + + # We create a set of triangles consisting of one point and two Voronoi + # vertices. The vertices of each triangle are adjacent in the sorted + # regions list. + point_indices = [i for i, size in enumerate(sizes) + for j in range(size)] + + nbrs1 = np.array([r for region in self.regions for r in region]) + + # The calculation of nbrs2 is a vectorized version of: + # np.array([r for region in self.regions for r in np.roll(region, 1)]) + nbrs2 = np.roll(nbrs1, 1) + indices = np.roll(csizes, 1) + indices[0] = 0 + nbrs2[indices] = nbrs1[csizes - 1] + + # Normalize points and vertices. + pnormalized = (self.points - self.center) / self.radius + vnormalized = (self.vertices - self.center) / self.radius + + # Create the complete set of triangles and calculate their solid angles + triangles = np.hstack([pnormalized[point_indices], + vnormalized[nbrs1], + vnormalized[nbrs2] + ]).reshape((num_regions, 3, 3)) + triangle_solid_angles = calculate_solid_angles(triangles) + + # Sum the solid angles of the triangles in each region + solid_angles = np.cumsum(triangle_solid_angles)[csizes - 1] + solid_angles[1:] -= solid_angles[:-1] + + # Get polygon areas using A = omega * r**2 + return solid_angles * self.radius**2 + + def _calculate_areas_2d(self): + # Find start and end points of arcs + arcs = self.points[self._simplices] - self.center + + # Calculate the angle subtended by arcs + d = np.sum((arcs[:, 1] - arcs[:, 0]) ** 2, axis=1) + theta = np.arccos(1 - (d / (2 * (self.radius ** 2)))) + + # Get areas using A = r * theta + areas = self.radius * theta + + # Correct arcs which go the wrong way (single-hemisphere inputs) + signs = np.sign(np.einsum('ij,ij->i', arcs[:, 0], + self.vertices - self.center)) + indices = np.where(signs < 0) + areas[indices] = 2 * np.pi * self.radius - areas[indices] + return areas + + def calculate_areas(self): + """Calculates the areas of the Voronoi regions. + + For 2D point sets, the regions are circular arcs. The sum of the areas + is `2 * pi * radius`. + + For 3D point sets, the regions are spherical polygons. The sum of the + areas is `4 * pi * radius**2`. + + .. versionadded:: 1.5.0 + + Returns + ------- + areas : double array of shape (npoints,) + The areas of the Voronoi regions. + """ + if self._dim == 2: + return self._calculate_areas_2d() + elif self._dim == 3: + return self._calculate_areas_3d() + else: + raise TypeError("Only supported for 2D and 3D point sets") diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9bef11278f0426ef4aeebc3d570ebb97efb3070e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.pyi b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c7c361ff69414d50a6ebcfe2c837025b60083940 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/_voronoi.pyi @@ -0,0 +1,4 @@ + +import numpy as np + +def sort_vertices_of_regions(simplices: np.ndarray, regions: list[list[int]]) -> None: ... # noqa: E501 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/ckdtree.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/ckdtree.py new file mode 100644 index 0000000000000000000000000000000000000000..b838f29cc0d9af6dfd672a15a0337ca680f9eeaf --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/ckdtree.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.spatial` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'cKDTree', + 'cKDTreeNode', + 'coo_entries', + 'operator', + 'ordered_pairs', + 'os', + 'scipy', + 'threading', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="spatial", module="ckdtree", + private_modules=["_ckdtree"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.py new file mode 100644 index 0000000000000000000000000000000000000000..d57a0472953b4d91888bf0def7b6a3f007c4c3b7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.py @@ -0,0 +1,2993 @@ +""" +Distance computations (:mod:`scipy.spatial.distance`) +===================================================== + +.. sectionauthor:: Damian Eads + +Function reference +------------------ + +Distance matrix computation from a collection of raw observation vectors +stored in a rectangular array. + +.. autosummary:: + :toctree: generated/ + + pdist -- pairwise distances between observation vectors. + cdist -- distances between two collections of observation vectors + squareform -- convert distance matrix to a condensed one and vice versa + directed_hausdorff -- directed Hausdorff distance between arrays + +Predicates for checking the validity of distance matrices, both +condensed and redundant. Also contained in this module are functions +for computing the number of observations in a distance matrix. + +.. autosummary:: + :toctree: generated/ + + is_valid_dm -- checks for a valid distance matrix + is_valid_y -- checks for a valid condensed distance matrix + num_obs_dm -- # of observations in a distance matrix + num_obs_y -- # of observations in a condensed distance matrix + +Distance functions between two numeric vectors ``u`` and ``v``. Computing +distances over a large collection of vectors is inefficient for these +functions. Use ``pdist`` for this purpose. + +.. autosummary:: + :toctree: generated/ + + braycurtis -- the Bray-Curtis distance. + canberra -- the Canberra distance. + chebyshev -- the Chebyshev distance. + cityblock -- the Manhattan distance. + correlation -- the Correlation distance. + cosine -- the Cosine distance. + euclidean -- the Euclidean distance. + jensenshannon -- the Jensen-Shannon distance. + mahalanobis -- the Mahalanobis distance. + minkowski -- the Minkowski distance. + seuclidean -- the normalized Euclidean distance. + sqeuclidean -- the squared Euclidean distance. + +Distance functions between two boolean vectors (representing sets) ``u`` and +``v``. As in the case of numerical vectors, ``pdist`` is more efficient for +computing the distances between all pairs. + +.. autosummary:: + :toctree: generated/ + + dice -- the Dice dissimilarity. + hamming -- the Hamming distance. + jaccard -- the Jaccard distance. + kulczynski1 -- the Kulczynski 1 distance. + rogerstanimoto -- the Rogers-Tanimoto dissimilarity. + russellrao -- the Russell-Rao dissimilarity. + sokalmichener -- the Sokal-Michener dissimilarity. + sokalsneath -- the Sokal-Sneath dissimilarity. + yule -- the Yule dissimilarity. + +:func:`hamming` also operates over discrete numerical vectors. +""" + +# Copyright (C) Damian Eads, 2007-2008. New BSD License. + +__all__ = [ + 'braycurtis', + 'canberra', + 'cdist', + 'chebyshev', + 'cityblock', + 'correlation', + 'cosine', + 'dice', + 'directed_hausdorff', + 'euclidean', + 'hamming', + 'is_valid_dm', + 'is_valid_y', + 'jaccard', + 'jensenshannon', + 'kulczynski1', + 'mahalanobis', + 'minkowski', + 'num_obs_dm', + 'num_obs_y', + 'pdist', + 'rogerstanimoto', + 'russellrao', + 'seuclidean', + 'sokalmichener', + 'sokalsneath', + 'sqeuclidean', + 'squareform', + 'yule' +] + + +import math +import warnings +import numpy as np +import dataclasses + +from typing import Optional, Callable + +from functools import partial +from scipy._lib._util import _asarray_validated + +from . import _distance_wrap +from . import _hausdorff +from ..linalg import norm +from ..special import rel_entr + +from . import _distance_pybind + + +def _copy_array_if_base_present(a): + """Copy the array if its base points to a parent array.""" + if a.base is not None: + return a.copy() + return a + + +def _correlation_cdist_wrap(XA, XB, dm, **kwargs): + XA = XA - XA.mean(axis=1, keepdims=True) + XB = XB - XB.mean(axis=1, keepdims=True) + _distance_wrap.cdist_cosine_double_wrap(XA, XB, dm, **kwargs) + + +def _correlation_pdist_wrap(X, dm, **kwargs): + X2 = X - X.mean(axis=1, keepdims=True) + _distance_wrap.pdist_cosine_double_wrap(X2, dm, **kwargs) + + +def _convert_to_type(X, out_type): + return np.ascontiguousarray(X, dtype=out_type) + + +def _nbool_correspond_all(u, v, w=None): + if u.dtype == v.dtype == bool and w is None: + not_u = ~u + not_v = ~v + nff = (not_u & not_v).sum() + nft = (not_u & v).sum() + ntf = (u & not_v).sum() + ntt = (u & v).sum() + else: + dtype = np.result_type(int, u.dtype, v.dtype) + u = u.astype(dtype) + v = v.astype(dtype) + not_u = 1.0 - u + not_v = 1.0 - v + if w is not None: + not_u = w * not_u + u = w * u + nff = (not_u * not_v).sum() + nft = (not_u * v).sum() + ntf = (u * not_v).sum() + ntt = (u * v).sum() + return (nff, nft, ntf, ntt) + + +def _nbool_correspond_ft_tf(u, v, w=None): + if u.dtype == v.dtype == bool and w is None: + not_u = ~u + not_v = ~v + nft = (not_u & v).sum() + ntf = (u & not_v).sum() + else: + dtype = np.result_type(int, u.dtype, v.dtype) + u = u.astype(dtype) + v = v.astype(dtype) + not_u = 1.0 - u + not_v = 1.0 - v + if w is not None: + not_u = w * not_u + u = w * u + nft = (not_u * v).sum() + ntf = (u * not_v).sum() + return (nft, ntf) + + +def _validate_cdist_input(XA, XB, mA, mB, n, metric_info, **kwargs): + # get supported types + types = metric_info.types + # choose best type + typ = types[types.index(XA.dtype)] if XA.dtype in types else types[0] + # validate data + XA = _convert_to_type(XA, out_type=typ) + XB = _convert_to_type(XB, out_type=typ) + + # validate kwargs + _validate_kwargs = metric_info.validator + if _validate_kwargs: + kwargs = _validate_kwargs((XA, XB), mA + mB, n, **kwargs) + return XA, XB, typ, kwargs + + +def _validate_weight_with_size(X, m, n, **kwargs): + w = kwargs.pop('w', None) + if w is None: + return kwargs + + if w.ndim != 1 or w.shape[0] != n: + raise ValueError("Weights must have same size as input vector. " + f"{w.shape[0]} vs. {n}") + + kwargs['w'] = _validate_weights(w) + return kwargs + + +def _validate_hamming_kwargs(X, m, n, **kwargs): + w = kwargs.get('w', np.ones((n,), dtype='double')) + + if w.ndim != 1 or w.shape[0] != n: + raise ValueError( + "Weights must have same size as input vector. %d vs. %d" % (w.shape[0], n) + ) + + kwargs['w'] = _validate_weights(w) + return kwargs + + +def _validate_mahalanobis_kwargs(X, m, n, **kwargs): + VI = kwargs.pop('VI', None) + if VI is None: + if m <= n: + # There are fewer observations than the dimension of + # the observations. + raise ValueError("The number of observations (%d) is too " + "small; the covariance matrix is " + "singular. For observations with %d " + "dimensions, at least %d observations " + "are required." % (m, n, n + 1)) + if isinstance(X, tuple): + X = np.vstack(X) + CV = np.atleast_2d(np.cov(X.astype(np.float64, copy=False).T)) + VI = np.linalg.inv(CV).T.copy() + kwargs["VI"] = _convert_to_double(VI) + return kwargs + + +def _validate_minkowski_kwargs(X, m, n, **kwargs): + kwargs = _validate_weight_with_size(X, m, n, **kwargs) + if 'p' not in kwargs: + kwargs['p'] = 2. + else: + if kwargs['p'] <= 0: + raise ValueError("p must be greater than 0") + + return kwargs + + +def _validate_pdist_input(X, m, n, metric_info, **kwargs): + # get supported types + types = metric_info.types + # choose best type + typ = types[types.index(X.dtype)] if X.dtype in types else types[0] + # validate data + X = _convert_to_type(X, out_type=typ) + + # validate kwargs + _validate_kwargs = metric_info.validator + if _validate_kwargs: + kwargs = _validate_kwargs(X, m, n, **kwargs) + return X, typ, kwargs + + +def _validate_seuclidean_kwargs(X, m, n, **kwargs): + V = kwargs.pop('V', None) + if V is None: + if isinstance(X, tuple): + X = np.vstack(X) + V = np.var(X.astype(np.float64, copy=False), axis=0, ddof=1) + else: + V = np.asarray(V, order='c') + if len(V.shape) != 1: + raise ValueError('Variance vector V must ' + 'be one-dimensional.') + if V.shape[0] != n: + raise ValueError('Variance vector V must be of the same ' + 'dimension as the vectors on which the distances ' + 'are computed.') + kwargs['V'] = _convert_to_double(V) + return kwargs + + +def _validate_vector(u, dtype=None): + # XXX Is order='c' really necessary? + u = np.asarray(u, dtype=dtype, order='c') + if u.ndim == 1: + return u + raise ValueError("Input vector should be 1-D.") + + +def _validate_weights(w, dtype=np.float64): + w = _validate_vector(w, dtype=dtype) + if np.any(w < 0): + raise ValueError("Input weights should be all non-negative") + return w + + +def directed_hausdorff(u, v, seed=0): + """ + Compute the directed Hausdorff distance between two 2-D arrays. + + Distances between pairs are calculated using a Euclidean metric. + + Parameters + ---------- + u : (M,N) array_like + Input array with M points in N dimensions. + v : (O,N) array_like + Input array with O points in N dimensions. + seed : int or None, optional + Local `numpy.random.RandomState` seed. Default is 0, a random + shuffling of u and v that guarantees reproducibility. + + Returns + ------- + d : double + The directed Hausdorff distance between arrays `u` and `v`, + + index_1 : int + index of point contributing to Hausdorff pair in `u` + + index_2 : int + index of point contributing to Hausdorff pair in `v` + + Raises + ------ + ValueError + An exception is thrown if `u` and `v` do not have + the same number of columns. + + See Also + -------- + scipy.spatial.procrustes : Another similarity test for two data sets + + Notes + ----- + Uses the early break technique and the random sampling approach + described by [1]_. Although worst-case performance is ``O(m * o)`` + (as with the brute force algorithm), this is unlikely in practice + as the input data would have to require the algorithm to explore + every single point interaction, and after the algorithm shuffles + the input points at that. The best case performance is O(m), which + is satisfied by selecting an inner loop distance that is less than + cmax and leads to an early break as often as possible. The authors + have formally shown that the average runtime is closer to O(m). + + .. versionadded:: 0.19.0 + + References + ---------- + .. [1] A. A. Taha and A. Hanbury, "An efficient algorithm for + calculating the exact Hausdorff distance." IEEE Transactions On + Pattern Analysis And Machine Intelligence, vol. 37 pp. 2153-63, + 2015. + + Examples + -------- + Find the directed Hausdorff distance between two 2-D arrays of + coordinates: + + >>> from scipy.spatial.distance import directed_hausdorff + >>> import numpy as np + >>> u = np.array([(1.0, 0.0), + ... (0.0, 1.0), + ... (-1.0, 0.0), + ... (0.0, -1.0)]) + >>> v = np.array([(2.0, 0.0), + ... (0.0, 2.0), + ... (-2.0, 0.0), + ... (0.0, -4.0)]) + + >>> directed_hausdorff(u, v)[0] + 2.23606797749979 + >>> directed_hausdorff(v, u)[0] + 3.0 + + Find the general (symmetric) Hausdorff distance between two 2-D + arrays of coordinates: + + >>> max(directed_hausdorff(u, v)[0], directed_hausdorff(v, u)[0]) + 3.0 + + Find the indices of the points that generate the Hausdorff distance + (the Hausdorff pair): + + >>> directed_hausdorff(v, u)[1:] + (3, 3) + + """ + u = np.asarray(u, dtype=np.float64, order='c') + v = np.asarray(v, dtype=np.float64, order='c') + if u.shape[1] != v.shape[1]: + raise ValueError('u and v need to have the same ' + 'number of columns') + result = _hausdorff.directed_hausdorff(u, v, seed) + return result + + +def minkowski(u, v, p=2, w=None): + """ + Compute the Minkowski distance between two 1-D arrays. + + The Minkowski distance between 1-D arrays `u` and `v`, + is defined as + + .. math:: + + {\\|u-v\\|}_p = (\\sum{|u_i - v_i|^p})^{1/p}. + + + \\left(\\sum{w_i(|(u_i - v_i)|^p)}\\right)^{1/p}. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + p : scalar + The order of the norm of the difference :math:`{\\|u-v\\|}_p`. Note + that for :math:`0 < p < 1`, the triangle inequality only holds with + an additional multiplicative factor, i.e. it is only a quasi-metric. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + minkowski : double + The Minkowski distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.minkowski([1, 0, 0], [0, 1, 0], 1) + 2.0 + >>> distance.minkowski([1, 0, 0], [0, 1, 0], 2) + 1.4142135623730951 + >>> distance.minkowski([1, 0, 0], [0, 1, 0], 3) + 1.2599210498948732 + >>> distance.minkowski([1, 1, 0], [0, 1, 0], 1) + 1.0 + >>> distance.minkowski([1, 1, 0], [0, 1, 0], 2) + 1.0 + >>> distance.minkowski([1, 1, 0], [0, 1, 0], 3) + 1.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if p <= 0: + raise ValueError("p must be greater than 0") + u_v = u - v + if w is not None: + w = _validate_weights(w) + if p == 1: + root_w = w + elif p == 2: + # better precision and speed + root_w = np.sqrt(w) + elif p == np.inf: + root_w = (w != 0) + else: + root_w = np.power(w, 1/p) + u_v = root_w * u_v + dist = norm(u_v, ord=p) + return dist + + +def euclidean(u, v, w=None): + """ + Computes the Euclidean distance between two 1-D arrays. + + The Euclidean distance between 1-D arrays `u` and `v`, is defined as + + .. math:: + + {\\|u-v\\|}_2 + + \\left(\\sum{(w_i |(u_i - v_i)|^2)}\\right)^{1/2} + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + euclidean : double + The Euclidean distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.euclidean([1, 0, 0], [0, 1, 0]) + 1.4142135623730951 + >>> distance.euclidean([1, 1, 0], [0, 1, 0]) + 1.0 + + """ + return minkowski(u, v, p=2, w=w) + + +def sqeuclidean(u, v, w=None): + """ + Compute the squared Euclidean distance between two 1-D arrays. + + The squared Euclidean distance between `u` and `v` is defined as + + .. math:: + + \\sum_i{w_i |u_i - v_i|^2} + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + sqeuclidean : double + The squared Euclidean distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.sqeuclidean([1, 0, 0], [0, 1, 0]) + 2.0 + >>> distance.sqeuclidean([1, 1, 0], [0, 1, 0]) + 1.0 + + """ + # Preserve float dtypes, but convert everything else to np.float64 + # for stability. + utype, vtype = None, None + if not (hasattr(u, "dtype") and np.issubdtype(u.dtype, np.inexact)): + utype = np.float64 + if not (hasattr(v, "dtype") and np.issubdtype(v.dtype, np.inexact)): + vtype = np.float64 + + u = _validate_vector(u, dtype=utype) + v = _validate_vector(v, dtype=vtype) + u_v = u - v + u_v_w = u_v # only want weights applied once + if w is not None: + w = _validate_weights(w) + u_v_w = w * u_v + return np.dot(u_v, u_v_w) + + +def correlation(u, v, w=None, centered=True): + """ + Compute the correlation distance between two 1-D arrays. + + The correlation distance between `u` and `v`, is + defined as + + .. math:: + + 1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})} + {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2} + + where :math:`\\bar{u}` is the mean of the elements of `u` + and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + centered : bool, optional + If True, `u` and `v` will be centered. Default is True. + + Returns + ------- + correlation : double + The correlation distance between 1-D array `u` and `v`. + + Examples + -------- + Find the correlation between two arrays. + + >>> from scipy.spatial.distance import correlation + >>> correlation([1, 0, 1], [1, 1, 0]) + 1.5 + + Using a weighting array, the correlation can be calculated as: + + >>> correlation([1, 0, 1], [1, 1, 0], w=[0.9, 0.1, 0.1]) + 1.1 + + If centering is not needed, the correlation can be calculated as: + + >>> correlation([1, 0, 1], [1, 1, 0], centered=False) + 0.5 + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + w = w / w.sum() + if centered: + if w is not None: + umu = np.dot(u, w) + vmu = np.dot(v, w) + else: + umu = np.mean(u) + vmu = np.mean(v) + u = u - umu + v = v - vmu + if w is not None: + vw = v * w + uw = u * w + else: + vw, uw = v, u + uv = np.dot(u, vw) + uu = np.dot(u, uw) + vv = np.dot(v, vw) + dist = 1.0 - uv / math.sqrt(uu * vv) + # Clip the result to avoid rounding error + return np.clip(dist, 0.0, 2.0) + + +def cosine(u, v, w=None): + """ + Compute the Cosine distance between 1-D arrays. + + The Cosine distance between `u` and `v`, is defined as + + .. math:: + + 1 - \\frac{u \\cdot v} + {\\|u\\|_2 \\|v\\|_2}. + + where :math:`u \\cdot v` is the dot product of :math:`u` and + :math:`v`. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + cosine : double + The Cosine distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.cosine([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.cosine([100, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.cosine([1, 1, 0], [0, 1, 0]) + 0.29289321881345254 + + """ + # cosine distance is also referred to as 'uncentered correlation', + # or 'reflective correlation' + return correlation(u, v, w=w, centered=False) + + +def hamming(u, v, w=None): + """ + Compute the Hamming distance between two 1-D arrays. + + The Hamming distance between 1-D arrays `u` and `v`, is simply the + proportion of disagreeing components in `u` and `v`. If `u` and `v` are + boolean vectors, the Hamming distance is + + .. math:: + + \\frac{c_{01} + c_{10}}{n} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n`. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + hamming : double + The Hamming distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.hamming([1, 0, 0], [0, 1, 0]) + 0.66666666666666663 + >>> distance.hamming([1, 0, 0], [1, 1, 0]) + 0.33333333333333331 + >>> distance.hamming([1, 0, 0], [2, 0, 0]) + 0.33333333333333331 + >>> distance.hamming([1, 0, 0], [3, 0, 0]) + 0.33333333333333331 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if u.shape != v.shape: + raise ValueError('The 1d arrays must have equal lengths.') + u_ne_v = u != v + if w is not None: + w = _validate_weights(w) + if w.shape != u.shape: + raise ValueError("'w' should have the same length as 'u' and 'v'.") + w = w / w.sum() + return np.dot(u_ne_v, w) + return np.mean(u_ne_v) + + +def jaccard(u, v, w=None): + """ + Compute the Jaccard-Needham dissimilarity between two boolean 1-D arrays. + + The Jaccard-Needham dissimilarity between 1-D boolean arrays `u` and `v`, + is defined as + + .. math:: + + \\frac{c_{TF} + c_{FT}} + {c_{TT} + c_{FT} + c_{TF}} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + jaccard : double + The Jaccard distance between vectors `u` and `v`. + + Notes + ----- + When both `u` and `v` lead to a `0/0` division i.e. there is no overlap + between the items in the vectors the returned distance is 0. See the + Wikipedia page on the Jaccard index [1]_, and this paper [2]_. + + .. versionchanged:: 1.2.0 + Previously, when `u` and `v` lead to a `0/0` division, the function + would return NaN. This was changed to return 0 instead. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Jaccard_index + .. [2] S. Kosub, "A note on the triangle inequality for the Jaccard + distance", 2016, :arxiv:`1612.02696` + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.jaccard([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.jaccard([1, 0, 0], [1, 1, 0]) + 0.5 + >>> distance.jaccard([1, 0, 0], [1, 2, 0]) + 0.5 + >>> distance.jaccard([1, 0, 0], [1, 1, 1]) + 0.66666666666666663 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + + nonzero = np.bitwise_or(u != 0, v != 0) + unequal_nonzero = np.bitwise_and((u != v), nonzero) + if w is not None: + w = _validate_weights(w) + nonzero = w * nonzero + unequal_nonzero = w * unequal_nonzero + a = np.float64(unequal_nonzero.sum()) + b = np.float64(nonzero.sum()) + return (a / b) if b != 0 else 0 + + +def kulczynski1(u, v, *, w=None): + """ + Compute the Kulczynski 1 dissimilarity between two boolean 1-D arrays. + + The Kulczynski 1 dissimilarity between two boolean 1-D arrays `u` and `v` + of length ``n``, is defined as + + .. math:: + + \\frac{c_{11}} + {c_{01} + c_{10}} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k \\in {0, 1, ..., n-1}`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + kulczynski1 : float + The Kulczynski 1 distance between vectors `u` and `v`. + + Notes + ----- + This measure has a minimum value of 0 and no upper limit. + It is un-defined when there are no non-matches. + + .. versionadded:: 1.8.0 + + References + ---------- + .. [1] Kulczynski S. et al. Bulletin + International de l'Academie Polonaise des Sciences + et des Lettres, Classe des Sciences Mathematiques + et Naturelles, Serie B (Sciences Naturelles). 1927; + Supplement II: 57-203. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.kulczynski1([1, 0, 0], [0, 1, 0]) + 0.0 + >>> distance.kulczynski1([True, False, False], [True, True, False]) + 1.0 + >>> distance.kulczynski1([True, False, False], [True]) + 0.5 + >>> distance.kulczynski1([1, 0, 0], [3, 1, 0]) + -3.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + (_, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w) + + return ntt / (ntf + nft) + + +def seuclidean(u, v, V): + """ + Return the standardized Euclidean distance between two 1-D arrays. + + The standardized Euclidean distance between two n-vectors `u` and `v` is + + .. math:: + + \\sqrt{\\sum\\limits_i \\frac{1}{V_i} \\left(u_i-v_i \\right)^2} + + ``V`` is the variance vector; ``V[I]`` is the variance computed over all the i-th + components of the points. If not passed, it is automatically computed. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + V : (N,) array_like + `V` is an 1-D array of component variances. It is usually computed + among a larger collection vectors. + + Returns + ------- + seuclidean : double + The standardized Euclidean distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [0.1, 0.1, 0.1]) + 4.4721359549995796 + >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [1, 0.1, 0.1]) + 3.3166247903553998 + >>> distance.seuclidean([1, 0, 0], [0, 1, 0], [10, 0.1, 0.1]) + 3.1780497164141406 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + V = _validate_vector(V, dtype=np.float64) + if V.shape[0] != u.shape[0] or u.shape[0] != v.shape[0]: + raise TypeError('V must be a 1-D array of the same dimension ' + 'as u and v.') + return euclidean(u, v, w=1/V) + + +def cityblock(u, v, w=None): + """ + Compute the City Block (Manhattan) distance. + + Computes the Manhattan distance between two 1-D arrays `u` and `v`, + which is defined as + + .. math:: + + \\sum_i {\\left| u_i - v_i \\right|}. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + cityblock : double + The City Block (Manhattan) distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.cityblock([1, 0, 0], [0, 1, 0]) + 2 + >>> distance.cityblock([1, 0, 0], [0, 2, 0]) + 3 + >>> distance.cityblock([1, 0, 0], [1, 1, 0]) + 1 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + l1_diff = abs(u - v) + if w is not None: + w = _validate_weights(w) + l1_diff = w * l1_diff + return l1_diff.sum() + + +def mahalanobis(u, v, VI): + """ + Compute the Mahalanobis distance between two 1-D arrays. + + The Mahalanobis distance between 1-D arrays `u` and `v`, is defined as + + .. math:: + + \\sqrt{ (u-v) V^{-1} (u-v)^T } + + where ``V`` is the covariance matrix. Note that the argument `VI` + is the inverse of ``V``. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + VI : array_like + The inverse of the covariance matrix. + + Returns + ------- + mahalanobis : double + The Mahalanobis distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> iv = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]] + >>> distance.mahalanobis([1, 0, 0], [0, 1, 0], iv) + 1.0 + >>> distance.mahalanobis([0, 2, 0], [0, 1, 0], iv) + 1.0 + >>> distance.mahalanobis([2, 0, 0], [0, 1, 0], iv) + 1.7320508075688772 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + VI = np.atleast_2d(VI) + delta = u - v + m = np.dot(np.dot(delta, VI), delta) + return np.sqrt(m) + + +def chebyshev(u, v, w=None): + """ + Compute the Chebyshev distance. + + Computes the Chebyshev distance between two 1-D arrays `u` and `v`, + which is defined as + + .. math:: + + \\max_i {|u_i-v_i|}. + + Parameters + ---------- + u : (N,) array_like + Input vector. + v : (N,) array_like + Input vector. + w : (N,) array_like, optional + Unused, as 'max' is a weightless operation. Here for API consistency. + + Returns + ------- + chebyshev : double + The Chebyshev distance between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.chebyshev([1, 0, 0], [0, 1, 0]) + 1 + >>> distance.chebyshev([1, 1, 0], [0, 1, 0]) + 1 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + has_weight = w > 0 + if has_weight.sum() < w.size: + u = u[has_weight] + v = v[has_weight] + return max(abs(u - v)) + + +def braycurtis(u, v, w=None): + """ + Compute the Bray-Curtis distance between two 1-D arrays. + + Bray-Curtis distance is defined as + + .. math:: + + \\sum{|u_i-v_i|} / \\sum{|u_i+v_i|} + + The Bray-Curtis distance is in the range [0, 1] if all coordinates are + positive, and is undefined if the inputs are of length zero. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + braycurtis : double + The Bray-Curtis distance between 1-D arrays `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.braycurtis([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.braycurtis([1, 1, 0], [0, 1, 0]) + 0.33333333333333331 + + """ + u = _validate_vector(u) + v = _validate_vector(v, dtype=np.float64) + l1_diff = abs(u - v) + l1_sum = abs(u + v) + if w is not None: + w = _validate_weights(w) + l1_diff = w * l1_diff + l1_sum = w * l1_sum + return l1_diff.sum() / l1_sum.sum() + + +def canberra(u, v, w=None): + """ + Compute the Canberra distance between two 1-D arrays. + + The Canberra distance is defined as + + .. math:: + + d(u,v) = \\sum_i \\frac{|u_i-v_i|} + {|u_i|+|v_i|}. + + Parameters + ---------- + u : (N,) array_like + Input array. + v : (N,) array_like + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + canberra : double + The Canberra distance between vectors `u` and `v`. + + Notes + ----- + When `u[i]` and `v[i]` are 0 for given i, then the fraction 0/0 = 0 is + used in the calculation. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.canberra([1, 0, 0], [0, 1, 0]) + 2.0 + >>> distance.canberra([1, 1, 0], [0, 1, 0]) + 1.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v, dtype=np.float64) + if w is not None: + w = _validate_weights(w) + with np.errstate(invalid='ignore'): + abs_uv = abs(u - v) + abs_u = abs(u) + abs_v = abs(v) + d = abs_uv / (abs_u + abs_v) + if w is not None: + d = w * d + d = np.nansum(d) + return d + + +def jensenshannon(p, q, base=None, *, axis=0, keepdims=False): + """ + Compute the Jensen-Shannon distance (metric) between + two probability arrays. This is the square root + of the Jensen-Shannon divergence. + + The Jensen-Shannon distance between two probability + vectors `p` and `q` is defined as, + + .. math:: + + \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}} + + where :math:`m` is the pointwise mean of :math:`p` and :math:`q` + and :math:`D` is the Kullback-Leibler divergence. + + This routine will normalize `p` and `q` if they don't sum to 1.0. + + Parameters + ---------- + p : (N,) array_like + left probability vector + q : (N,) array_like + right probability vector + base : double, optional + the base of the logarithm used to compute the output + if not given, then the routine uses the default base of + scipy.stats.entropy. + axis : int, optional + Axis along which the Jensen-Shannon distances are computed. The default + is 0. + + .. versionadded:: 1.7.0 + keepdims : bool, optional + If this is set to `True`, the reduced axes are left in the + result as dimensions with size one. With this option, + the result will broadcast correctly against the input array. + Default is False. + + .. versionadded:: 1.7.0 + + Returns + ------- + js : double or ndarray + The Jensen-Shannon distances between `p` and `q` along the `axis`. + + Notes + ----- + + .. versionadded:: 1.2.0 + + Examples + -------- + >>> from scipy.spatial import distance + >>> import numpy as np + >>> distance.jensenshannon([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], 2.0) + 1.0 + >>> distance.jensenshannon([1.0, 0.0], [0.5, 0.5]) + 0.46450140402245893 + >>> distance.jensenshannon([1.0, 0.0, 0.0], [1.0, 0.0, 0.0]) + 0.0 + >>> a = np.array([[1, 2, 3, 4], + ... [5, 6, 7, 8], + ... [9, 10, 11, 12]]) + >>> b = np.array([[13, 14, 15, 16], + ... [17, 18, 19, 20], + ... [21, 22, 23, 24]]) + >>> distance.jensenshannon(a, b, axis=0) + array([0.1954288, 0.1447697, 0.1138377, 0.0927636]) + >>> distance.jensenshannon(a, b, axis=1) + array([0.1402339, 0.0399106, 0.0201815]) + + """ + p = np.asarray(p) + q = np.asarray(q) + p = p / np.sum(p, axis=axis, keepdims=True) + q = q / np.sum(q, axis=axis, keepdims=True) + m = (p + q) / 2.0 + left = rel_entr(p, m) + right = rel_entr(q, m) + left_sum = np.sum(left, axis=axis, keepdims=keepdims) + right_sum = np.sum(right, axis=axis, keepdims=keepdims) + js = left_sum + right_sum + if base is not None: + js /= np.log(base) + return np.sqrt(js / 2.0) + + +def yule(u, v, w=None): + """ + Compute the Yule dissimilarity between two boolean 1-D arrays. + + The Yule dissimilarity is defined as + + .. math:: + + \\frac{R}{c_{TT} * c_{FF} + \\frac{R}{2}} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2.0 * c_{TF} * c_{FT}`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + yule : double + The Yule dissimilarity between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.yule([1, 0, 0], [0, 1, 0]) + 2.0 + >>> distance.yule([1, 1, 0], [0, 1, 0]) + 0.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + (nff, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w) + half_R = ntf * nft + if half_R == 0: + return 0.0 + else: + return float(2.0 * half_R / (ntt * nff + half_R)) + + +def dice(u, v, w=None): + """ + Compute the Dice dissimilarity between two boolean 1-D arrays. + + The Dice dissimilarity between `u` and `v`, is + + .. math:: + + \\frac{c_{TF} + c_{FT}} + {2c_{TT} + c_{FT} + c_{TF}} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n`. + + Parameters + ---------- + u : (N,) array_like, bool + Input 1-D array. + v : (N,) array_like, bool + Input 1-D array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + dice : double + The Dice dissimilarity between 1-D arrays `u` and `v`. + + Notes + ----- + This function computes the Dice dissimilarity index. To compute the + Dice similarity index, convert one to the other with similarity = + 1 - dissimilarity. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.dice([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.dice([1, 0, 0], [1, 1, 0]) + 0.3333333333333333 + >>> distance.dice([1, 0, 0], [2, 0, 0]) + -0.3333333333333333 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + if u.dtype == v.dtype == bool and w is None: + ntt = (u & v).sum() + else: + dtype = np.result_type(int, u.dtype, v.dtype) + u = u.astype(dtype) + v = v.astype(dtype) + if w is None: + ntt = (u * v).sum() + else: + ntt = (u * v * w).sum() + (nft, ntf) = _nbool_correspond_ft_tf(u, v, w=w) + return float((ntf + nft) / np.array(2.0 * ntt + ntf + nft)) + + +def rogerstanimoto(u, v, w=None): + """ + Compute the Rogers-Tanimoto dissimilarity between two boolean 1-D arrays. + + The Rogers-Tanimoto dissimilarity between two boolean 1-D arrays + `u` and `v`, is defined as + + .. math:: + \\frac{R} + {c_{TT} + c_{FF} + R} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + rogerstanimoto : double + The Rogers-Tanimoto dissimilarity between vectors + `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.rogerstanimoto([1, 0, 0], [0, 1, 0]) + 0.8 + >>> distance.rogerstanimoto([1, 0, 0], [1, 1, 0]) + 0.5 + >>> distance.rogerstanimoto([1, 0, 0], [2, 0, 0]) + -1.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + (nff, nft, ntf, ntt) = _nbool_correspond_all(u, v, w=w) + return float(2.0 * (ntf + nft)) / float(ntt + nff + (2.0 * (ntf + nft))) + + +def russellrao(u, v, w=None): + """ + Compute the Russell-Rao dissimilarity between two boolean 1-D arrays. + + The Russell-Rao dissimilarity between two boolean 1-D arrays, `u` and + `v`, is defined as + + .. math:: + + \\frac{n - c_{TT}} + {n} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + russellrao : double + The Russell-Rao dissimilarity between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.russellrao([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.russellrao([1, 0, 0], [1, 1, 0]) + 0.6666666666666666 + >>> distance.russellrao([1, 0, 0], [2, 0, 0]) + 0.3333333333333333 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if u.dtype == v.dtype == bool and w is None: + ntt = (u & v).sum() + n = float(len(u)) + elif w is None: + ntt = (u * v).sum() + n = float(len(u)) + else: + w = _validate_weights(w) + ntt = (u * v * w).sum() + n = w.sum() + return float(n - ntt) / n + + +def sokalmichener(u, v, w=None): + """ + Compute the Sokal-Michener dissimilarity between two boolean 1-D arrays. + + The Sokal-Michener dissimilarity between boolean 1-D arrays `u` and `v`, + is defined as + + .. math:: + + \\frac{R} + {S + R} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n`, :math:`R = 2 * (c_{TF} + c_{FT})` and + :math:`S = c_{FF} + c_{TT}`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + sokalmichener : double + The Sokal-Michener dissimilarity between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.sokalmichener([1, 0, 0], [0, 1, 0]) + 0.8 + >>> distance.sokalmichener([1, 0, 0], [1, 1, 0]) + 0.5 + >>> distance.sokalmichener([1, 0, 0], [2, 0, 0]) + -1.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if w is not None: + w = _validate_weights(w) + nff, nft, ntf, ntt = _nbool_correspond_all(u, v, w=w) + return float(2.0 * (ntf + nft)) / float(ntt + nff + 2.0 * (ntf + nft)) + + +def sokalsneath(u, v, w=None): + """ + Compute the Sokal-Sneath dissimilarity between two boolean 1-D arrays. + + The Sokal-Sneath dissimilarity between `u` and `v`, + + .. math:: + + \\frac{R} + {c_{TT} + R} + + where :math:`c_{ij}` is the number of occurrences of + :math:`\\mathtt{u[k]} = i` and :math:`\\mathtt{v[k]} = j` for + :math:`k < n` and :math:`R = 2(c_{TF} + c_{FT})`. + + Parameters + ---------- + u : (N,) array_like, bool + Input array. + v : (N,) array_like, bool + Input array. + w : (N,) array_like, optional + The weights for each value in `u` and `v`. Default is None, + which gives each value a weight of 1.0 + + Returns + ------- + sokalsneath : double + The Sokal-Sneath dissimilarity between vectors `u` and `v`. + + Examples + -------- + >>> from scipy.spatial import distance + >>> distance.sokalsneath([1, 0, 0], [0, 1, 0]) + 1.0 + >>> distance.sokalsneath([1, 0, 0], [1, 1, 0]) + 0.66666666666666663 + >>> distance.sokalsneath([1, 0, 0], [2, 1, 0]) + 0.0 + >>> distance.sokalsneath([1, 0, 0], [3, 1, 0]) + -2.0 + + """ + u = _validate_vector(u) + v = _validate_vector(v) + if u.dtype == v.dtype == bool and w is None: + ntt = (u & v).sum() + elif w is None: + ntt = (u * v).sum() + else: + w = _validate_weights(w) + ntt = (u * v * w).sum() + (nft, ntf) = _nbool_correspond_ft_tf(u, v, w=w) + denom = np.array(ntt + 2.0 * (ntf + nft)) + if not denom.any(): + raise ValueError('Sokal-Sneath dissimilarity is not defined for ' + 'vectors that are entirely false.') + return float(2.0 * (ntf + nft)) / denom + + +_convert_to_double = partial(_convert_to_type, out_type=np.float64) +_convert_to_bool = partial(_convert_to_type, out_type=bool) + +# adding python-only wrappers to _distance_wrap module +_distance_wrap.pdist_correlation_double_wrap = _correlation_pdist_wrap +_distance_wrap.cdist_correlation_double_wrap = _correlation_cdist_wrap + + +@dataclasses.dataclass(frozen=True) +class CDistMetricWrapper: + metric_name: str + + def __call__(self, XA, XB, *, out=None, **kwargs): + XA = np.ascontiguousarray(XA) + XB = np.ascontiguousarray(XB) + mA, n = XA.shape + mB, _ = XB.shape + metric_name = self.metric_name + metric_info = _METRICS[metric_name] + XA, XB, typ, kwargs = _validate_cdist_input( + XA, XB, mA, mB, n, metric_info, **kwargs) + + w = kwargs.pop('w', None) + if w is not None: + metric = metric_info.dist_func + return _cdist_callable( + XA, XB, metric=metric, out=out, w=w, **kwargs) + + dm = _prepare_out_argument(out, np.float64, (mA, mB)) + # get cdist wrapper + cdist_fn = getattr(_distance_wrap, f'cdist_{metric_name}_{typ}_wrap') + cdist_fn(XA, XB, dm, **kwargs) + return dm + + +@dataclasses.dataclass(frozen=True) +class PDistMetricWrapper: + metric_name: str + + def __call__(self, X, *, out=None, **kwargs): + X = np.ascontiguousarray(X) + m, n = X.shape + metric_name = self.metric_name + metric_info = _METRICS[metric_name] + X, typ, kwargs = _validate_pdist_input( + X, m, n, metric_info, **kwargs) + out_size = (m * (m - 1)) // 2 + w = kwargs.pop('w', None) + if w is not None: + metric = metric_info.dist_func + return _pdist_callable( + X, metric=metric, out=out, w=w, **kwargs) + + dm = _prepare_out_argument(out, np.float64, (out_size,)) + # get pdist wrapper + pdist_fn = getattr(_distance_wrap, f'pdist_{metric_name}_{typ}_wrap') + pdist_fn(X, dm, **kwargs) + return dm + + +@dataclasses.dataclass(frozen=True) +class MetricInfo: + # Name of python distance function + canonical_name: str + # All aliases, including canonical_name + aka: set[str] + # unvectorized distance function + dist_func: Callable + # Optimized cdist function + cdist_func: Callable + # Optimized pdist function + pdist_func: Callable + # function that checks kwargs and computes default values: + # f(X, m, n, **kwargs) + validator: Optional[Callable] = None + # list of supported types: + # X (pdist) and XA (cdist) are used to choose the type. if there is no + # match the first type is used. Default double + types: list[str] = dataclasses.field(default_factory=lambda: ['double']) + # true if out array must be C-contiguous + requires_contiguous_out: bool = True + + +# Registry of implemented metrics: +_METRIC_INFOS = [ + MetricInfo( + canonical_name='braycurtis', + aka={'braycurtis'}, + dist_func=braycurtis, + cdist_func=_distance_pybind.cdist_braycurtis, + pdist_func=_distance_pybind.pdist_braycurtis, + ), + MetricInfo( + canonical_name='canberra', + aka={'canberra'}, + dist_func=canberra, + cdist_func=_distance_pybind.cdist_canberra, + pdist_func=_distance_pybind.pdist_canberra, + ), + MetricInfo( + canonical_name='chebyshev', + aka={'chebychev', 'chebyshev', 'cheby', 'cheb', 'ch'}, + dist_func=chebyshev, + cdist_func=_distance_pybind.cdist_chebyshev, + pdist_func=_distance_pybind.pdist_chebyshev, + ), + MetricInfo( + canonical_name='cityblock', + aka={'cityblock', 'cblock', 'cb', 'c'}, + dist_func=cityblock, + cdist_func=_distance_pybind.cdist_cityblock, + pdist_func=_distance_pybind.pdist_cityblock, + ), + MetricInfo( + canonical_name='correlation', + aka={'correlation', 'co'}, + dist_func=correlation, + cdist_func=CDistMetricWrapper('correlation'), + pdist_func=PDistMetricWrapper('correlation'), + ), + MetricInfo( + canonical_name='cosine', + aka={'cosine', 'cos'}, + dist_func=cosine, + cdist_func=CDistMetricWrapper('cosine'), + pdist_func=PDistMetricWrapper('cosine'), + ), + MetricInfo( + canonical_name='dice', + aka={'dice'}, + types=['bool'], + dist_func=dice, + cdist_func=_distance_pybind.cdist_dice, + pdist_func=_distance_pybind.pdist_dice, + ), + MetricInfo( + canonical_name='euclidean', + aka={'euclidean', 'euclid', 'eu', 'e'}, + dist_func=euclidean, + cdist_func=_distance_pybind.cdist_euclidean, + pdist_func=_distance_pybind.pdist_euclidean, + ), + MetricInfo( + canonical_name='hamming', + aka={'matching', 'hamming', 'hamm', 'ha', 'h'}, + types=['double', 'bool'], + validator=_validate_hamming_kwargs, + dist_func=hamming, + cdist_func=_distance_pybind.cdist_hamming, + pdist_func=_distance_pybind.pdist_hamming, + ), + MetricInfo( + canonical_name='jaccard', + aka={'jaccard', 'jacc', 'ja', 'j'}, + types=['double', 'bool'], + dist_func=jaccard, + cdist_func=_distance_pybind.cdist_jaccard, + pdist_func=_distance_pybind.pdist_jaccard, + ), + MetricInfo( + canonical_name='jensenshannon', + aka={'jensenshannon', 'js'}, + dist_func=jensenshannon, + cdist_func=CDistMetricWrapper('jensenshannon'), + pdist_func=PDistMetricWrapper('jensenshannon'), + ), + MetricInfo( + canonical_name='kulczynski1', + aka={'kulczynski1'}, + types=['bool'], + dist_func=kulczynski1, + cdist_func=_distance_pybind.cdist_kulczynski1, + pdist_func=_distance_pybind.pdist_kulczynski1, + ), + MetricInfo( + canonical_name='mahalanobis', + aka={'mahalanobis', 'mahal', 'mah'}, + validator=_validate_mahalanobis_kwargs, + dist_func=mahalanobis, + cdist_func=CDistMetricWrapper('mahalanobis'), + pdist_func=PDistMetricWrapper('mahalanobis'), + ), + MetricInfo( + canonical_name='minkowski', + aka={'minkowski', 'mi', 'm', 'pnorm'}, + validator=_validate_minkowski_kwargs, + dist_func=minkowski, + cdist_func=_distance_pybind.cdist_minkowski, + pdist_func=_distance_pybind.pdist_minkowski, + ), + MetricInfo( + canonical_name='rogerstanimoto', + aka={'rogerstanimoto'}, + types=['bool'], + dist_func=rogerstanimoto, + cdist_func=_distance_pybind.cdist_rogerstanimoto, + pdist_func=_distance_pybind.pdist_rogerstanimoto, + ), + MetricInfo( + canonical_name='russellrao', + aka={'russellrao'}, + types=['bool'], + dist_func=russellrao, + cdist_func=_distance_pybind.cdist_russellrao, + pdist_func=_distance_pybind.pdist_russellrao, + ), + MetricInfo( + canonical_name='seuclidean', + aka={'seuclidean', 'se', 's'}, + validator=_validate_seuclidean_kwargs, + dist_func=seuclidean, + cdist_func=CDistMetricWrapper('seuclidean'), + pdist_func=PDistMetricWrapper('seuclidean'), + ), + MetricInfo( + canonical_name='sokalmichener', + aka={'sokalmichener'}, + types=['bool'], + dist_func=sokalmichener, + cdist_func=_distance_pybind.cdist_sokalmichener, + pdist_func=_distance_pybind.pdist_sokalmichener, + ), + MetricInfo( + canonical_name='sokalsneath', + aka={'sokalsneath'}, + types=['bool'], + dist_func=sokalsneath, + cdist_func=_distance_pybind.cdist_sokalsneath, + pdist_func=_distance_pybind.pdist_sokalsneath, + ), + MetricInfo( + canonical_name='sqeuclidean', + aka={'sqeuclidean', 'sqe', 'sqeuclid'}, + dist_func=sqeuclidean, + cdist_func=_distance_pybind.cdist_sqeuclidean, + pdist_func=_distance_pybind.pdist_sqeuclidean, + ), + MetricInfo( + canonical_name='yule', + aka={'yule'}, + types=['bool'], + dist_func=yule, + cdist_func=_distance_pybind.cdist_yule, + pdist_func=_distance_pybind.pdist_yule, + ), +] + +_METRICS = {info.canonical_name: info for info in _METRIC_INFOS} +_METRIC_ALIAS = {alias: info + for info in _METRIC_INFOS + for alias in info.aka} + +_METRICS_NAMES = list(_METRICS.keys()) + +_TEST_METRICS = {'test_' + info.canonical_name: info for info in _METRIC_INFOS} + + +def pdist(X, metric='euclidean', *, out=None, **kwargs): + """ + Pairwise distances between observations in n-dimensional space. + + See Notes for common calling conventions. + + Parameters + ---------- + X : array_like + An m by n array of m original observations in an + n-dimensional space. + metric : str or function, optional + The distance metric to use. The distance function can + be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', + 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', + 'jaccard', 'jensenshannon', 'kulczynski1', + 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', + 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', + 'sqeuclidean', 'yule'. + out : ndarray, optional + The output array. + If not None, condensed distance matrix Y is stored in this array. + **kwargs : dict, optional + Extra arguments to `metric`: refer to each metric documentation for a + list of all possible arguments. + + Some possible arguments: + + p : scalar + The p-norm to apply for Minkowski, weighted and unweighted. + Default: 2. + + w : ndarray + The weight vector for metrics that support weights (e.g., Minkowski). + + V : ndarray + The variance vector for standardized Euclidean. + Default: var(X, axis=0, ddof=1) + + VI : ndarray + The inverse of the covariance matrix for Mahalanobis. + Default: inv(cov(X.T)).T + + Returns + ------- + Y : ndarray + Returns a condensed distance matrix Y. For each :math:`i` and :math:`j` + (where :math:`i 0` (note + that this is only a quasi-metric if :math:`0 < p < 1`). + + 3. ``Y = pdist(X, 'cityblock')`` + + Computes the city block or Manhattan distance between the + points. + + 4. ``Y = pdist(X, 'seuclidean', V=None)`` + + Computes the standardized Euclidean distance. The standardized + Euclidean distance between two n-vectors ``u`` and ``v`` is + + .. math:: + + \\sqrt{\\sum {(u_i-v_i)^2 / V[x_i]}} + + + V is the variance vector; V[i] is the variance computed over all + the i'th components of the points. If not passed, it is + automatically computed. + + 5. ``Y = pdist(X, 'sqeuclidean')`` + + Computes the squared Euclidean distance :math:`\\|u-v\\|_2^2` between + the vectors. + + 6. ``Y = pdist(X, 'cosine')`` + + Computes the cosine distance between vectors u and v, + + .. math:: + + 1 - \\frac{u \\cdot v} + {{\\|u\\|}_2 {\\|v\\|}_2} + + where :math:`\\|*\\|_2` is the 2-norm of its argument ``*``, and + :math:`u \\cdot v` is the dot product of ``u`` and ``v``. + + 7. ``Y = pdist(X, 'correlation')`` + + Computes the correlation distance between vectors u and v. This is + + .. math:: + + 1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})} + {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2} + + where :math:`\\bar{v}` is the mean of the elements of vector v, + and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`. + + 8. ``Y = pdist(X, 'hamming')`` + + Computes the normalized Hamming distance, or the proportion of + those vector elements between two n-vectors ``u`` and ``v`` + which disagree. To save memory, the matrix ``X`` can be of type + boolean. + + 9. ``Y = pdist(X, 'jaccard')`` + + Computes the Jaccard distance between the points. Given two + vectors, ``u`` and ``v``, the Jaccard distance is the + proportion of those elements ``u[i]`` and ``v[i]`` that + disagree. + + 10. ``Y = pdist(X, 'jensenshannon')`` + + Computes the Jensen-Shannon distance between two probability arrays. + Given two probability vectors, :math:`p` and :math:`q`, the + Jensen-Shannon distance is + + .. math:: + + \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}} + + where :math:`m` is the pointwise mean of :math:`p` and :math:`q` + and :math:`D` is the Kullback-Leibler divergence. + + 11. ``Y = pdist(X, 'chebyshev')`` + + Computes the Chebyshev distance between the points. The + Chebyshev distance between two n-vectors ``u`` and ``v`` is the + maximum norm-1 distance between their respective elements. More + precisely, the distance is given by + + .. math:: + + d(u,v) = \\max_i {|u_i-v_i|} + + 12. ``Y = pdist(X, 'canberra')`` + + Computes the Canberra distance between the points. The + Canberra distance between two points ``u`` and ``v`` is + + .. math:: + + d(u,v) = \\sum_i \\frac{|u_i-v_i|} + {|u_i|+|v_i|} + + + 13. ``Y = pdist(X, 'braycurtis')`` + + Computes the Bray-Curtis distance between the points. The + Bray-Curtis distance between two points ``u`` and ``v`` is + + + .. math:: + + d(u,v) = \\frac{\\sum_i {|u_i-v_i|}} + {\\sum_i {|u_i+v_i|}} + + 14. ``Y = pdist(X, 'mahalanobis', VI=None)`` + + Computes the Mahalanobis distance between the points. The + Mahalanobis distance between two points ``u`` and ``v`` is + :math:`\\sqrt{(u-v)(1/V)(u-v)^T}` where :math:`(1/V)` (the ``VI`` + variable) is the inverse covariance. If ``VI`` is not None, + ``VI`` will be used as the inverse covariance matrix. + + 15. ``Y = pdist(X, 'yule')`` + + Computes the Yule distance between each pair of boolean + vectors. (see yule function documentation) + + 16. ``Y = pdist(X, 'matching')`` + + Synonym for 'hamming'. + + 17. ``Y = pdist(X, 'dice')`` + + Computes the Dice distance between each pair of boolean + vectors. (see dice function documentation) + + 18. ``Y = pdist(X, 'kulczynski1')`` + + Computes the kulczynski1 distance between each pair of + boolean vectors. (see kulczynski1 function documentation) + + 19. ``Y = pdist(X, 'rogerstanimoto')`` + + Computes the Rogers-Tanimoto distance between each pair of + boolean vectors. (see rogerstanimoto function documentation) + + 20. ``Y = pdist(X, 'russellrao')`` + + Computes the Russell-Rao distance between each pair of + boolean vectors. (see russellrao function documentation) + + 21. ``Y = pdist(X, 'sokalmichener')`` + + Computes the Sokal-Michener distance between each pair of + boolean vectors. (see sokalmichener function documentation) + + 22. ``Y = pdist(X, 'sokalsneath')`` + + Computes the Sokal-Sneath distance between each pair of + boolean vectors. (see sokalsneath function documentation) + + 23. ``Y = pdist(X, 'kulczynski1')`` + + Computes the Kulczynski 1 distance between each pair of + boolean vectors. (see kulczynski1 function documentation) + + 24. ``Y = pdist(X, f)`` + + Computes the distance between all pairs of vectors in X + using the user supplied 2-arity function f. For example, + Euclidean distance between the vectors could be computed + as follows:: + + dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum())) + + Note that you should avoid passing a reference to one of + the distance functions defined in this library. For example,:: + + dm = pdist(X, sokalsneath) + + would calculate the pair-wise distances between the vectors in + X using the Python function sokalsneath. This would result in + sokalsneath being called :math:`{n \\choose 2}` times, which + is inefficient. Instead, the optimized C version is more + efficient, and we call it using the following syntax.:: + + dm = pdist(X, 'sokalsneath') + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial.distance import pdist + + ``x`` is an array of five points in three-dimensional space. + + >>> x = np.array([[2, 0, 2], [2, 2, 3], [-2, 4, 5], [0, 1, 9], [2, 2, 4]]) + + ``pdist(x)`` with no additional arguments computes the 10 pairwise + Euclidean distances: + + >>> pdist(x) + array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949, + 6.40312424, 1. , 5.38516481, 4.58257569, 5.47722558]) + + The following computes the pairwise Minkowski distances with ``p = 3.5``: + + >>> pdist(x, metric='minkowski', p=3.5) + array([2.04898923, 5.1154929 , 7.02700737, 2.43802731, 4.19042714, + 6.03956994, 1. , 4.45128103, 4.10636143, 5.0619695 ]) + + The pairwise city block or Manhattan distances: + + >>> pdist(x, metric='cityblock') + array([ 3., 11., 10., 4., 8., 9., 1., 9., 7., 8.]) + + """ + # You can also call this as: + # Y = pdist(X, 'test_abc') + # where 'abc' is the metric being tested. This computes the distance + # between all pairs of vectors in X using the distance metric 'abc' but + # with a more succinct, verifiable, but less efficient implementation. + + X = _asarray_validated(X, sparse_ok=False, objects_ok=True, mask_ok=True, + check_finite=False) + + s = X.shape + if len(s) != 2: + raise ValueError('A 2-dimensional array must be passed.') + + m, n = s + + if callable(metric): + mstr = getattr(metric, '__name__', 'UnknownCustomMetric') + metric_info = _METRIC_ALIAS.get(mstr, None) + + if metric_info is not None: + X, typ, kwargs = _validate_pdist_input( + X, m, n, metric_info, **kwargs) + + return _pdist_callable(X, metric=metric, out=out, **kwargs) + elif isinstance(metric, str): + mstr = metric.lower() + metric_info = _METRIC_ALIAS.get(mstr, None) + + if metric_info is not None: + pdist_fn = metric_info.pdist_func + return pdist_fn(X, out=out, **kwargs) + elif mstr.startswith("test_"): + metric_info = _TEST_METRICS.get(mstr, None) + if metric_info is None: + raise ValueError(f'Unknown "Test" Distance Metric: {mstr[5:]}') + X, typ, kwargs = _validate_pdist_input( + X, m, n, metric_info, **kwargs) + return _pdist_callable( + X, metric=metric_info.dist_func, out=out, **kwargs) + else: + raise ValueError('Unknown Distance Metric: %s' % mstr) + else: + raise TypeError('2nd argument metric must be a string identifier ' + 'or a function.') + + +def squareform(X, force="no", checks=True): + """ + Convert a vector-form distance vector to a square-form distance + matrix, and vice-versa. + + Parameters + ---------- + X : array_like + Either a condensed or redundant distance matrix. + force : str, optional + As with MATLAB(TM), if force is equal to ``'tovector'`` or + ``'tomatrix'``, the input will be treated as a distance matrix or + distance vector respectively. + checks : bool, optional + If set to False, no checks will be made for matrix + symmetry nor zero diagonals. This is useful if it is known that + ``X - X.T1`` is small and ``diag(X)`` is close to zero. + These values are ignored any way so they do not disrupt the + squareform transformation. + + Returns + ------- + Y : ndarray + If a condensed distance matrix is passed, a redundant one is + returned, or if a redundant one is passed, a condensed distance + matrix is returned. + + Notes + ----- + 1. ``v = squareform(X)`` + + Given a square n-by-n symmetric distance matrix ``X``, + ``v = squareform(X)`` returns a ``n * (n-1) / 2`` + (i.e. binomial coefficient n choose 2) sized vector `v` + where :math:`v[{n \\choose 2} - {n-i \\choose 2} + (j-i-1)]` + is the distance between distinct points ``i`` and ``j``. + If ``X`` is non-square or asymmetric, an error is raised. + + 2. ``X = squareform(v)`` + + Given a ``n * (n-1) / 2`` sized vector ``v`` + for some integer ``n >= 1`` encoding distances as described, + ``X = squareform(v)`` returns a n-by-n distance matrix ``X``. + The ``X[i, j]`` and ``X[j, i]`` values are set to + :math:`v[{n \\choose 2} - {n-i \\choose 2} + (j-i-1)]` + and all diagonal elements are zero. + + In SciPy 0.19.0, ``squareform`` stopped casting all input types to + float64, and started returning arrays of the same dtype as the input. + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial.distance import pdist, squareform + + ``x`` is an array of five points in three-dimensional space. + + >>> x = np.array([[2, 0, 2], [2, 2, 3], [-2, 4, 5], [0, 1, 9], [2, 2, 4]]) + + ``pdist(x)`` computes the Euclidean distances between each pair of + points in ``x``. The distances are returned in a one-dimensional + array with length ``5*(5 - 1)/2 = 10``. + + >>> distvec = pdist(x) + >>> distvec + array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949, + 6.40312424, 1. , 5.38516481, 4.58257569, 5.47722558]) + + ``squareform(distvec)`` returns the 5x5 distance matrix. + + >>> m = squareform(distvec) + >>> m + array([[0. , 2.23606798, 6.40312424, 7.34846923, 2.82842712], + [2.23606798, 0. , 4.89897949, 6.40312424, 1. ], + [6.40312424, 4.89897949, 0. , 5.38516481, 4.58257569], + [7.34846923, 6.40312424, 5.38516481, 0. , 5.47722558], + [2.82842712, 1. , 4.58257569, 5.47722558, 0. ]]) + + When given a square distance matrix ``m``, ``squareform(m)`` returns + the one-dimensional condensed distance vector associated with the + matrix. In this case, we recover ``distvec``. + + >>> squareform(m) + array([2.23606798, 6.40312424, 7.34846923, 2.82842712, 4.89897949, + 6.40312424, 1. , 5.38516481, 4.58257569, 5.47722558]) + """ + X = np.ascontiguousarray(X) + + s = X.shape + + if force.lower() == 'tomatrix': + if len(s) != 1: + raise ValueError("Forcing 'tomatrix' but input X is not a " + "distance vector.") + elif force.lower() == 'tovector': + if len(s) != 2: + raise ValueError("Forcing 'tovector' but input X is not a " + "distance matrix.") + + # X = squareform(v) + if len(s) == 1: + if s[0] == 0: + return np.zeros((1, 1), dtype=X.dtype) + + # Grab the closest value to the square root of the number + # of elements times 2 to see if the number of elements + # is indeed a binomial coefficient. + d = int(np.ceil(np.sqrt(s[0] * 2))) + + # Check that v is of valid dimensions. + if d * (d - 1) != s[0] * 2: + raise ValueError('Incompatible vector size. It must be a binomial ' + 'coefficient n choose 2 for some integer n >= 2.') + + # Allocate memory for the distance matrix. + M = np.zeros((d, d), dtype=X.dtype) + + # Since the C code does not support striding using strides. + # The dimensions are used instead. + X = _copy_array_if_base_present(X) + + # Fill in the values of the distance matrix. + _distance_wrap.to_squareform_from_vector_wrap(M, X) + + # Return the distance matrix. + return M + elif len(s) == 2: + if s[0] != s[1]: + raise ValueError('The matrix argument must be square.') + if checks: + is_valid_dm(X, throw=True, name='X') + + # One-side of the dimensions is set here. + d = s[0] + + if d <= 1: + return np.array([], dtype=X.dtype) + + # Create a vector. + v = np.zeros((d * (d - 1)) // 2, dtype=X.dtype) + + # Since the C code does not support striding using strides. + # The dimensions are used instead. + X = _copy_array_if_base_present(X) + + # Convert the vector to squareform. + _distance_wrap.to_vector_from_squareform_wrap(X, v) + return v + else: + raise ValueError(('The first argument must be one or two dimensional ' + 'array. A %d-dimensional array is not ' + 'permitted') % len(s)) + + +def is_valid_dm(D, tol=0.0, throw=False, name="D", warning=False): + """ + Return True if input array is a valid distance matrix. + + Distance matrices must be 2-dimensional numpy arrays. + They must have a zero-diagonal, and they must be symmetric. + + Parameters + ---------- + D : array_like + The candidate object to test for validity. + tol : float, optional + The distance matrix should be symmetric. `tol` is the maximum + difference between entries ``ij`` and ``ji`` for the distance + metric to be considered symmetric. + throw : bool, optional + An exception is thrown if the distance matrix passed is not valid. + name : str, optional + The name of the variable to checked. This is useful if + throw is set to True so the offending variable can be identified + in the exception message when an exception is thrown. + warning : bool, optional + Instead of throwing an exception, a warning message is + raised. + + Returns + ------- + valid : bool + True if the variable `D` passed is a valid distance matrix. + + Notes + ----- + Small numerical differences in `D` and `D.T` and non-zeroness of + the diagonal are ignored if they are within the tolerance specified + by `tol`. + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial.distance import is_valid_dm + + This matrix is a valid distance matrix. + + >>> d = np.array([[0.0, 1.1, 1.2, 1.3], + ... [1.1, 0.0, 1.0, 1.4], + ... [1.2, 1.0, 0.0, 1.5], + ... [1.3, 1.4, 1.5, 0.0]]) + >>> is_valid_dm(d) + True + + In the following examples, the input is not a valid distance matrix. + + Not square: + + >>> is_valid_dm([[0, 2, 2], [2, 0, 2]]) + False + + Nonzero diagonal element: + + >>> is_valid_dm([[0, 1, 1], [1, 2, 3], [1, 3, 0]]) + False + + Not symmetric: + + >>> is_valid_dm([[0, 1, 3], [2, 0, 1], [3, 1, 0]]) + False + + """ + D = np.asarray(D, order='c') + valid = True + try: + s = D.shape + if len(D.shape) != 2: + if name: + raise ValueError(('Distance matrix \'%s\' must have shape=2 ' + '(i.e. be two-dimensional).') % name) + else: + raise ValueError('Distance matrix must have shape=2 (i.e. ' + 'be two-dimensional).') + if tol == 0.0: + if not (D == D.T).all(): + if name: + raise ValueError(('Distance matrix \'%s\' must be ' + 'symmetric.') % name) + else: + raise ValueError('Distance matrix must be symmetric.') + if not (D[range(0, s[0]), range(0, s[0])] == 0).all(): + if name: + raise ValueError(('Distance matrix \'%s\' diagonal must ' + 'be zero.') % name) + else: + raise ValueError('Distance matrix diagonal must be zero.') + else: + if not (D - D.T <= tol).all(): + if name: + raise ValueError(f'Distance matrix \'{name}\' must be ' + f'symmetric within tolerance {tol:5.5f}.') + else: + raise ValueError('Distance matrix must be symmetric within ' + 'tolerance %5.5f.' % tol) + if not (D[range(0, s[0]), range(0, s[0])] <= tol).all(): + if name: + raise ValueError(f'Distance matrix \'{name}\' diagonal must be ' + f'close to zero within tolerance {tol:5.5f}.') + else: + raise ValueError(('Distance matrix \'{}\' diagonal must be close ' + 'to zero within tolerance {:5.5f}.').format(*tol)) + except Exception as e: + if throw: + raise + if warning: + warnings.warn(str(e), stacklevel=2) + valid = False + return valid + + +def is_valid_y(y, warning=False, throw=False, name=None): + """ + Return True if the input array is a valid condensed distance matrix. + + Condensed distance matrices must be 1-dimensional numpy arrays. + Their length must be a binomial coefficient :math:`{n \\choose 2}` + for some positive integer n. + + Parameters + ---------- + y : array_like + The condensed distance matrix. + warning : bool, optional + Invokes a warning if the variable passed is not a valid + condensed distance matrix. The warning message explains why + the distance matrix is not valid. `name` is used when + referencing the offending variable. + throw : bool, optional + Throws an exception if the variable passed is not a valid + condensed distance matrix. + name : bool, optional + Used when referencing the offending variable in the + warning or exception message. + + Returns + ------- + bool + True if the input array is a valid condensed distance matrix, + False otherwise. + + Examples + -------- + >>> from scipy.spatial.distance import is_valid_y + + This vector is a valid condensed distance matrix. The length is 6, + which corresponds to ``n = 4``, since ``4*(4 - 1)/2`` is 6. + + >>> v = [1.0, 1.2, 1.0, 0.5, 1.3, 0.9] + >>> is_valid_y(v) + True + + An input vector with length, say, 7, is not a valid condensed distance + matrix. + + >>> is_valid_y([1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7]) + False + + """ + y = np.asarray(y, order='c') + valid = True + try: + if len(y.shape) != 1: + if name: + raise ValueError(('Condensed distance matrix \'%s\' must ' + 'have shape=1 (i.e. be one-dimensional).') + % name) + else: + raise ValueError('Condensed distance matrix must have shape=1 ' + '(i.e. be one-dimensional).') + n = y.shape[0] + d = int(np.ceil(np.sqrt(n * 2))) + if (d * (d - 1) / 2) != n: + if name: + raise ValueError(('Length n of condensed distance matrix ' + '\'%s\' must be a binomial coefficient, i.e.' + 'there must be a k such that ' + '(k \\choose 2)=n)!') % name) + else: + raise ValueError('Length n of condensed distance matrix must ' + 'be a binomial coefficient, i.e. there must ' + 'be a k such that (k \\choose 2)=n)!') + except Exception as e: + if throw: + raise + if warning: + warnings.warn(str(e), stacklevel=2) + valid = False + return valid + + +def num_obs_dm(d): + """ + Return the number of original observations that correspond to a + square, redundant distance matrix. + + Parameters + ---------- + d : array_like + The target distance matrix. + + Returns + ------- + num_obs_dm : int + The number of observations in the redundant distance matrix. + + Examples + -------- + Find the number of original observations corresponding + to a square redundant distance matrix d. + + >>> from scipy.spatial.distance import num_obs_dm + >>> d = [[0, 100, 200], [100, 0, 150], [200, 150, 0]] + >>> num_obs_dm(d) + 3 + """ + d = np.asarray(d, order='c') + is_valid_dm(d, tol=np.inf, throw=True, name='d') + return d.shape[0] + + +def num_obs_y(Y): + """ + Return the number of original observations that correspond to a + condensed distance matrix. + + Parameters + ---------- + Y : array_like + Condensed distance matrix. + + Returns + ------- + n : int + The number of observations in the condensed distance matrix `Y`. + + Examples + -------- + Find the number of original observations corresponding to a + condensed distance matrix Y. + + >>> from scipy.spatial.distance import num_obs_y + >>> Y = [1, 2, 3.5, 7, 10, 4] + >>> num_obs_y(Y) + 4 + """ + Y = np.asarray(Y, order='c') + is_valid_y(Y, throw=True, name='Y') + k = Y.shape[0] + if k == 0: + raise ValueError("The number of observations cannot be determined on " + "an empty distance matrix.") + d = int(np.ceil(np.sqrt(k * 2))) + if (d * (d - 1) / 2) != k: + raise ValueError("Invalid condensed distance matrix passed. Must be " + "some k where k=(n choose 2) for some n >= 2.") + return d + + +def _prepare_out_argument(out, dtype, expected_shape): + if out is None: + return np.empty(expected_shape, dtype=dtype) + + if out.shape != expected_shape: + raise ValueError("Output array has incorrect shape.") + if not out.flags.c_contiguous: + raise ValueError("Output array must be C-contiguous.") + if out.dtype != np.float64: + raise ValueError("Output array must be double type.") + return out + + +def _pdist_callable(X, *, out, metric, **kwargs): + n = X.shape[0] + out_size = (n * (n - 1)) // 2 + dm = _prepare_out_argument(out, np.float64, (out_size,)) + k = 0 + for i in range(X.shape[0] - 1): + for j in range(i + 1, X.shape[0]): + dm[k] = metric(X[i], X[j], **kwargs) + k += 1 + return dm + + +def _cdist_callable(XA, XB, *, out, metric, **kwargs): + mA = XA.shape[0] + mB = XB.shape[0] + dm = _prepare_out_argument(out, np.float64, (mA, mB)) + for i in range(mA): + for j in range(mB): + dm[i, j] = metric(XA[i], XB[j], **kwargs) + return dm + + +def cdist(XA, XB, metric='euclidean', *, out=None, **kwargs): + """ + Compute distance between each pair of the two collections of inputs. + + See Notes for common calling conventions. + + Parameters + ---------- + XA : array_like + An :math:`m_A` by :math:`n` array of :math:`m_A` + original observations in an :math:`n`-dimensional space. + Inputs are converted to float type. + XB : array_like + An :math:`m_B` by :math:`n` array of :math:`m_B` + original observations in an :math:`n`-dimensional space. + Inputs are converted to float type. + metric : str or callable, optional + The distance metric to use. If a string, the distance function can be + 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', + 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'jensenshannon', + 'kulczynski1', 'mahalanobis', 'matching', 'minkowski', + 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', + 'sokalsneath', 'sqeuclidean', 'yule'. + **kwargs : dict, optional + Extra arguments to `metric`: refer to each metric documentation for a + list of all possible arguments. + + Some possible arguments: + + p : scalar + The p-norm to apply for Minkowski, weighted and unweighted. + Default: 2. + + w : array_like + The weight vector for metrics that support weights (e.g., Minkowski). + + V : array_like + The variance vector for standardized Euclidean. + Default: var(vstack([XA, XB]), axis=0, ddof=1) + + VI : array_like + The inverse of the covariance matrix for Mahalanobis. + Default: inv(cov(vstack([XA, XB].T))).T + + out : ndarray + The output array + If not None, the distance matrix Y is stored in this array. + + Returns + ------- + Y : ndarray + A :math:`m_A` by :math:`m_B` distance matrix is returned. + For each :math:`i` and :math:`j`, the metric + ``dist(u=XA[i], v=XB[j])`` is computed and stored in the + :math:`ij` th entry. + + Raises + ------ + ValueError + An exception is thrown if `XA` and `XB` do not have + the same number of columns. + + Notes + ----- + The following are common calling conventions: + + 1. ``Y = cdist(XA, XB, 'euclidean')`` + + Computes the distance between :math:`m` points using + Euclidean distance (2-norm) as the distance metric between the + points. The points are arranged as :math:`m` + :math:`n`-dimensional row vectors in the matrix X. + + 2. ``Y = cdist(XA, XB, 'minkowski', p=2.)`` + + Computes the distances using the Minkowski distance + :math:`\\|u-v\\|_p` (:math:`p`-norm) where :math:`p > 0` (note + that this is only a quasi-metric if :math:`0 < p < 1`). + + 3. ``Y = cdist(XA, XB, 'cityblock')`` + + Computes the city block or Manhattan distance between the + points. + + 4. ``Y = cdist(XA, XB, 'seuclidean', V=None)`` + + Computes the standardized Euclidean distance. The standardized + Euclidean distance between two n-vectors ``u`` and ``v`` is + + .. math:: + + \\sqrt{\\sum {(u_i-v_i)^2 / V[x_i]}}. + + V is the variance vector; V[i] is the variance computed over all + the i'th components of the points. If not passed, it is + automatically computed. + + 5. ``Y = cdist(XA, XB, 'sqeuclidean')`` + + Computes the squared Euclidean distance :math:`\\|u-v\\|_2^2` between + the vectors. + + 6. ``Y = cdist(XA, XB, 'cosine')`` + + Computes the cosine distance between vectors u and v, + + .. math:: + + 1 - \\frac{u \\cdot v} + {{\\|u\\|}_2 {\\|v\\|}_2} + + where :math:`\\|*\\|_2` is the 2-norm of its argument ``*``, and + :math:`u \\cdot v` is the dot product of :math:`u` and :math:`v`. + + 7. ``Y = cdist(XA, XB, 'correlation')`` + + Computes the correlation distance between vectors u and v. This is + + .. math:: + + 1 - \\frac{(u - \\bar{u}) \\cdot (v - \\bar{v})} + {{\\|(u - \\bar{u})\\|}_2 {\\|(v - \\bar{v})\\|}_2} + + where :math:`\\bar{v}` is the mean of the elements of vector v, + and :math:`x \\cdot y` is the dot product of :math:`x` and :math:`y`. + + + 8. ``Y = cdist(XA, XB, 'hamming')`` + + Computes the normalized Hamming distance, or the proportion of + those vector elements between two n-vectors ``u`` and ``v`` + which disagree. To save memory, the matrix ``X`` can be of type + boolean. + + 9. ``Y = cdist(XA, XB, 'jaccard')`` + + Computes the Jaccard distance between the points. Given two + vectors, ``u`` and ``v``, the Jaccard distance is the + proportion of those elements ``u[i]`` and ``v[i]`` that + disagree where at least one of them is non-zero. + + 10. ``Y = cdist(XA, XB, 'jensenshannon')`` + + Computes the Jensen-Shannon distance between two probability arrays. + Given two probability vectors, :math:`p` and :math:`q`, the + Jensen-Shannon distance is + + .. math:: + + \\sqrt{\\frac{D(p \\parallel m) + D(q \\parallel m)}{2}} + + where :math:`m` is the pointwise mean of :math:`p` and :math:`q` + and :math:`D` is the Kullback-Leibler divergence. + + 11. ``Y = cdist(XA, XB, 'chebyshev')`` + + Computes the Chebyshev distance between the points. The + Chebyshev distance between two n-vectors ``u`` and ``v`` is the + maximum norm-1 distance between their respective elements. More + precisely, the distance is given by + + .. math:: + + d(u,v) = \\max_i {|u_i-v_i|}. + + 12. ``Y = cdist(XA, XB, 'canberra')`` + + Computes the Canberra distance between the points. The + Canberra distance between two points ``u`` and ``v`` is + + .. math:: + + d(u,v) = \\sum_i \\frac{|u_i-v_i|} + {|u_i|+|v_i|}. + + 13. ``Y = cdist(XA, XB, 'braycurtis')`` + + Computes the Bray-Curtis distance between the points. The + Bray-Curtis distance between two points ``u`` and ``v`` is + + + .. math:: + + d(u,v) = \\frac{\\sum_i (|u_i-v_i|)} + {\\sum_i (|u_i+v_i|)} + + 14. ``Y = cdist(XA, XB, 'mahalanobis', VI=None)`` + + Computes the Mahalanobis distance between the points. The + Mahalanobis distance between two points ``u`` and ``v`` is + :math:`\\sqrt{(u-v)(1/V)(u-v)^T}` where :math:`(1/V)` (the ``VI`` + variable) is the inverse covariance. If ``VI`` is not None, + ``VI`` will be used as the inverse covariance matrix. + + 15. ``Y = cdist(XA, XB, 'yule')`` + + Computes the Yule distance between the boolean + vectors. (see `yule` function documentation) + + 16. ``Y = cdist(XA, XB, 'matching')`` + + Synonym for 'hamming'. + + 17. ``Y = cdist(XA, XB, 'dice')`` + + Computes the Dice distance between the boolean vectors. (see + `dice` function documentation) + + 18. ``Y = cdist(XA, XB, 'kulczynski1')`` + + Computes the kulczynski distance between the boolean + vectors. (see `kulczynski1` function documentation) + + 19. ``Y = cdist(XA, XB, 'rogerstanimoto')`` + + Computes the Rogers-Tanimoto distance between the boolean + vectors. (see `rogerstanimoto` function documentation) + + 20. ``Y = cdist(XA, XB, 'russellrao')`` + + Computes the Russell-Rao distance between the boolean + vectors. (see `russellrao` function documentation) + + 21. ``Y = cdist(XA, XB, 'sokalmichener')`` + + Computes the Sokal-Michener distance between the boolean + vectors. (see `sokalmichener` function documentation) + + 22. ``Y = cdist(XA, XB, 'sokalsneath')`` + + Computes the Sokal-Sneath distance between the vectors. (see + `sokalsneath` function documentation) + + 23. ``Y = cdist(XA, XB, f)`` + + Computes the distance between all pairs of vectors in X + using the user supplied 2-arity function f. For example, + Euclidean distance between the vectors could be computed + as follows:: + + dm = cdist(XA, XB, lambda u, v: np.sqrt(((u-v)**2).sum())) + + Note that you should avoid passing a reference to one of + the distance functions defined in this library. For example,:: + + dm = cdist(XA, XB, sokalsneath) + + would calculate the pair-wise distances between the vectors in + X using the Python function `sokalsneath`. This would result in + sokalsneath being called :math:`{n \\choose 2}` times, which + is inefficient. Instead, the optimized C version is more + efficient, and we call it using the following syntax:: + + dm = cdist(XA, XB, 'sokalsneath') + + Examples + -------- + Find the Euclidean distances between four 2-D coordinates: + + >>> from scipy.spatial import distance + >>> import numpy as np + >>> coords = [(35.0456, -85.2672), + ... (35.1174, -89.9711), + ... (35.9728, -83.9422), + ... (36.1667, -86.7833)] + >>> distance.cdist(coords, coords, 'euclidean') + array([[ 0. , 4.7044, 1.6172, 1.8856], + [ 4.7044, 0. , 6.0893, 3.3561], + [ 1.6172, 6.0893, 0. , 2.8477], + [ 1.8856, 3.3561, 2.8477, 0. ]]) + + + Find the Manhattan distance from a 3-D point to the corners of the unit + cube: + + >>> a = np.array([[0, 0, 0], + ... [0, 0, 1], + ... [0, 1, 0], + ... [0, 1, 1], + ... [1, 0, 0], + ... [1, 0, 1], + ... [1, 1, 0], + ... [1, 1, 1]]) + >>> b = np.array([[ 0.1, 0.2, 0.4]]) + >>> distance.cdist(a, b, 'cityblock') + array([[ 0.7], + [ 0.9], + [ 1.3], + [ 1.5], + [ 1.5], + [ 1.7], + [ 2.1], + [ 2.3]]) + + """ + # You can also call this as: + # Y = cdist(XA, XB, 'test_abc') + # where 'abc' is the metric being tested. This computes the distance + # between all pairs of vectors in XA and XB using the distance metric 'abc' + # but with a more succinct, verifiable, but less efficient implementation. + + XA = np.asarray(XA) + XB = np.asarray(XB) + + s = XA.shape + sB = XB.shape + + if len(s) != 2: + raise ValueError('XA must be a 2-dimensional array.') + if len(sB) != 2: + raise ValueError('XB must be a 2-dimensional array.') + if s[1] != sB[1]: + raise ValueError('XA and XB must have the same number of columns ' + '(i.e. feature dimension.)') + + mA = s[0] + mB = sB[0] + n = s[1] + + if callable(metric): + mstr = getattr(metric, '__name__', 'Unknown') + metric_info = _METRIC_ALIAS.get(mstr, None) + if metric_info is not None: + XA, XB, typ, kwargs = _validate_cdist_input( + XA, XB, mA, mB, n, metric_info, **kwargs) + return _cdist_callable(XA, XB, metric=metric, out=out, **kwargs) + elif isinstance(metric, str): + mstr = metric.lower() + metric_info = _METRIC_ALIAS.get(mstr, None) + if metric_info is not None: + cdist_fn = metric_info.cdist_func + return cdist_fn(XA, XB, out=out, **kwargs) + elif mstr.startswith("test_"): + metric_info = _TEST_METRICS.get(mstr, None) + if metric_info is None: + raise ValueError(f'Unknown "Test" Distance Metric: {mstr[5:]}') + XA, XB, typ, kwargs = _validate_cdist_input( + XA, XB, mA, mB, n, metric_info, **kwargs) + return _cdist_callable( + XA, XB, metric=metric_info.dist_func, out=out, **kwargs) + else: + raise ValueError('Unknown Distance Metric: %s' % mstr) + else: + raise TypeError('2nd argument metric must be a string identifier ' + 'or a function.') diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.pyi b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0e231b46dd3b2d248e54d1259b384b9e48facd9a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/distance.pyi @@ -0,0 +1,211 @@ +from __future__ import annotations +from typing import (overload, Any, SupportsFloat, Literal, Protocol, SupportsIndex) + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +# Anything that can be parsed by `np.float64.__init__` and is thus +# compatible with `ndarray.__setitem__` (for a float64 array) +_FloatValue = None | str | bytes | SupportsFloat | SupportsIndex + +class _MetricCallback1(Protocol): + def __call__( + self, __XA: NDArray[Any], __XB: NDArray[Any] + ) -> _FloatValue: ... + +class _MetricCallback2(Protocol): + def __call__( + self, __XA: NDArray[Any], __XB: NDArray[Any], **kwargs: Any + ) -> _FloatValue: ... + +# TODO: Use a single protocol with a parameter specification variable +# once available (PEP 612) +_MetricCallback = _MetricCallback1 | _MetricCallback2 + +_MetricKind = Literal[ + 'braycurtis', + 'canberra', + 'chebychev', 'chebyshev', 'cheby', 'cheb', 'ch', + 'cityblock', 'cblock', 'cb', 'c', + 'correlation', 'co', + 'cosine', 'cos', + 'dice', + 'euclidean', 'euclid', 'eu', 'e', + 'hamming', 'hamm', 'ha', 'h', + 'minkowski', 'mi', 'm', 'pnorm', + 'jaccard', 'jacc', 'ja', 'j', + 'jensenshannon', 'js', + 'kulczynski1', + 'mahalanobis', 'mahal', 'mah', + 'rogerstanimoto', + 'russellrao', + 'seuclidean', 'se', 's', + 'sokalmichener', + 'sokalsneath', + 'sqeuclidean', 'sqe', 'sqeuclid', + 'yule', +] + +# Function annotations + +def braycurtis( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def canberra( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +# TODO: Add `metric`-specific overloads +# Returns a float64 or float128 array, depending on the input dtype +@overload +def cdist( + XA: ArrayLike, + XB: ArrayLike, + metric: _MetricKind = ..., + *, + out: None | NDArray[np.floating[Any]] = ..., + p: float = ..., + w: ArrayLike | None = ..., + V: ArrayLike | None = ..., + VI: ArrayLike | None = ..., +) -> NDArray[np.floating[Any]]: ... +@overload +def cdist( + XA: ArrayLike, + XB: ArrayLike, + metric: _MetricCallback, + *, + out: None | NDArray[np.floating[Any]] = ..., + **kwargs: Any, +) -> NDArray[np.floating[Any]]: ... + +# TODO: Wait for dtype support; the return type is +# dependent on the input arrays dtype +def chebyshev( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> Any: ... + +# TODO: Wait for dtype support; the return type is +# dependent on the input arrays dtype +def cityblock( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> Any: ... + +def correlation( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ..., centered: bool = ... +) -> np.float64: ... + +def cosine( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def dice( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def directed_hausdorff( + u: ArrayLike, v: ArrayLike, seed: int | None = ... +) -> tuple[float, int, int]: ... + +def euclidean( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def hamming( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def is_valid_dm( + D: ArrayLike, + tol: float = ..., + throw: bool = ..., + name: str | None = ..., + warning: bool = ..., +) -> bool: ... + +def is_valid_y( + y: ArrayLike, + warning: bool = ..., + throw: bool = ..., + name: str | None = ..., +) -> bool: ... + +def jaccard( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def jensenshannon( + p: ArrayLike, q: ArrayLike, base: float | None = ... +) -> np.float64: ... + +def kulczynski1( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def mahalanobis( + u: ArrayLike, v: ArrayLike, VI: ArrayLike +) -> np.float64: ... + +def minkowski( + u: ArrayLike, v: ArrayLike, p: float = ..., w: ArrayLike | None = ... +) -> float: ... + +def num_obs_dm(d: ArrayLike) -> int: ... + +def num_obs_y(Y: ArrayLike) -> int: ... + +# TODO: Add `metric`-specific overloads +@overload +def pdist( + X: ArrayLike, + metric: _MetricKind = ..., + *, + out: None | NDArray[np.floating[Any]] = ..., + p: float = ..., + w: ArrayLike | None = ..., + V: ArrayLike | None = ..., + VI: ArrayLike | None = ..., +) -> NDArray[np.floating[Any]]: ... +@overload +def pdist( + X: ArrayLike, + metric: _MetricCallback, + *, + out: None | NDArray[np.floating[Any]] = ..., + **kwargs: Any, +) -> NDArray[np.floating[Any]]: ... + +def seuclidean( + u: ArrayLike, v: ArrayLike, V: ArrayLike +) -> float: ... + +def sokalmichener( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def sokalsneath( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def sqeuclidean( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def squareform( + X: ArrayLike, + force: Literal["no", "tomatrix", "tovector"] = ..., + checks: bool = ..., +) -> NDArray[Any]: ... + +def rogerstanimoto( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def russellrao( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def yule( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/kdtree.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/kdtree.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a6bab41e94733fccbb96313db6fcd868d284ea --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/kdtree.py @@ -0,0 +1,26 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.spatial` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'KDTree', + 'Rectangle', + 'cKDTree', + 'cKDTreeNode', + 'distance_matrix', + 'minkowski_distance', + 'minkowski_distance_p', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="spatial", module="kdtree", + private_modules=["_kdtree"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d51bf239bfe48077e66a36bcbf59f6dbadaf95 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.spatial` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'ConvexHull', + 'Delaunay', + 'HalfspaceIntersection', + 'QhullError', + 'Voronoi', + 'tsearch', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="spatial", module="qhull", + private_modules=["_qhull"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull_src/COPYING.txt b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull_src/COPYING.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ac02a07f45d562410025f05305c31d1ec39a28c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/qhull_src/COPYING.txt @@ -0,0 +1,38 @@ + Qhull, Copyright (c) 1993-2019 + + C.B. Barber + Arlington, MA + + and + + The National Science and Technology Research Center for + Computation and Visualization of Geometric Structures + (The Geometry Center) + University of Minnesota + + email: qhull@qhull.org + +This software includes Qhull from C.B. Barber and The Geometry Center. +Qhull is copyrighted as noted above. Qhull is free software and may +be obtained via http from www.qhull.org. It may be freely copied, modified, +and redistributed under the following conditions: + +1. All copyright notices must remain intact in all files. + +2. A copy of this text file must be distributed along with any copies + of Qhull that you redistribute; this includes copies that you have + modified, or copies of programs or other software products that + include Qhull. + +3. If you modify Qhull, you must include a notice giving the + name of the person performing the modification, the date of + modification, and the reason for such modification. + +4. When distributing modified versions of Qhull, or other software + products that include Qhull, you must provide notice that the original + source code may be obtained as noted above. + +5. There is no warranty or other guarantee of fitness for Qhull, it is + provided solely "as is". Bug reports or fixes may be sent to + qhull_bug@qhull.org; the authors may or may not act on them as + they desire. diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abe4a32f20d1f8740910a16de9e67a53621bc3e3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__init__.py @@ -0,0 +1,29 @@ +""" +Spatial Transformations (:mod:`scipy.spatial.transform`) +======================================================== + +.. currentmodule:: scipy.spatial.transform + +This package implements various spatial transformations. For now, +only rotations are supported. + +Rotations in 3 dimensions +------------------------- +.. autosummary:: + :toctree: generated/ + + Rotation + Slerp + RotationSpline +""" +from ._rotation import Rotation, Slerp +from ._rotation_spline import RotationSpline + +# Deprecated namespaces, to be removed in v2.0.0 +from . import rotation + +__all__ = ['Rotation', 'Slerp', 'RotationSpline'] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdcf9310aa714c4554fbede7d9a8a39688ce8534 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_groups.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_groups.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cce9e73ad831666a7c0ba080c982bf0402c2f4ec Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_groups.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_spline.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_spline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07c7e744c338f5e0fbde466158e7911c55909a71 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/_rotation_spline.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/rotation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/rotation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15c48b6cffe4b8306569fe40db4231162c116407 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/__pycache__/rotation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/_rotation_groups.py b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/_rotation_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..870e9b9e2b44bff56b8228a70607e29f8173accc --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/_rotation_groups.py @@ -0,0 +1,140 @@ +import numpy as np +from scipy.constants import golden as phi + + +def icosahedral(cls): + g1 = tetrahedral(cls).as_quat() + a = 0.5 + b = 0.5 / phi + c = phi / 2 + g2 = np.array([[+a, +b, +c, 0], + [+a, +b, -c, 0], + [+a, +c, 0, +b], + [+a, +c, 0, -b], + [+a, -b, +c, 0], + [+a, -b, -c, 0], + [+a, -c, 0, +b], + [+a, -c, 0, -b], + [+a, 0, +b, +c], + [+a, 0, +b, -c], + [+a, 0, -b, +c], + [+a, 0, -b, -c], + [+b, +a, 0, +c], + [+b, +a, 0, -c], + [+b, +c, +a, 0], + [+b, +c, -a, 0], + [+b, -a, 0, +c], + [+b, -a, 0, -c], + [+b, -c, +a, 0], + [+b, -c, -a, 0], + [+b, 0, +c, +a], + [+b, 0, +c, -a], + [+b, 0, -c, +a], + [+b, 0, -c, -a], + [+c, +a, +b, 0], + [+c, +a, -b, 0], + [+c, +b, 0, +a], + [+c, +b, 0, -a], + [+c, -a, +b, 0], + [+c, -a, -b, 0], + [+c, -b, 0, +a], + [+c, -b, 0, -a], + [+c, 0, +a, +b], + [+c, 0, +a, -b], + [+c, 0, -a, +b], + [+c, 0, -a, -b], + [0, +a, +c, +b], + [0, +a, +c, -b], + [0, +a, -c, +b], + [0, +a, -c, -b], + [0, +b, +a, +c], + [0, +b, +a, -c], + [0, +b, -a, +c], + [0, +b, -a, -c], + [0, +c, +b, +a], + [0, +c, +b, -a], + [0, +c, -b, +a], + [0, +c, -b, -a]]) + return cls.from_quat(np.concatenate((g1, g2))) + + +def octahedral(cls): + g1 = tetrahedral(cls).as_quat() + c = np.sqrt(2) / 2 + g2 = np.array([[+c, 0, 0, +c], + [0, +c, 0, +c], + [0, 0, +c, +c], + [0, 0, -c, +c], + [0, -c, 0, +c], + [-c, 0, 0, +c], + [0, +c, +c, 0], + [0, -c, +c, 0], + [+c, 0, +c, 0], + [-c, 0, +c, 0], + [+c, +c, 0, 0], + [-c, +c, 0, 0]]) + return cls.from_quat(np.concatenate((g1, g2))) + + +def tetrahedral(cls): + g1 = np.eye(4) + c = 0.5 + g2 = np.array([[c, -c, -c, +c], + [c, -c, +c, +c], + [c, +c, -c, +c], + [c, +c, +c, +c], + [c, -c, -c, -c], + [c, -c, +c, -c], + [c, +c, -c, -c], + [c, +c, +c, -c]]) + return cls.from_quat(np.concatenate((g1, g2))) + + +def dicyclic(cls, n, axis=2): + g1 = cyclic(cls, n, axis).as_rotvec() + + thetas = np.linspace(0, np.pi, n, endpoint=False) + rv = np.pi * np.vstack([np.zeros(n), np.cos(thetas), np.sin(thetas)]).T + g2 = np.roll(rv, axis, axis=1) + return cls.from_rotvec(np.concatenate((g1, g2))) + + +def cyclic(cls, n, axis=2): + thetas = np.linspace(0, 2 * np.pi, n, endpoint=False) + rv = np.vstack([thetas, np.zeros(n), np.zeros(n)]).T + return cls.from_rotvec(np.roll(rv, axis, axis=1)) + + +def create_group(cls, group, axis='Z'): + if not isinstance(group, str): + raise ValueError("`group` argument must be a string") + + permitted_axes = ['x', 'y', 'z', 'X', 'Y', 'Z'] + if axis not in permitted_axes: + raise ValueError("`axis` must be one of " + ", ".join(permitted_axes)) + + if group in ['I', 'O', 'T']: + symbol = group + order = 1 + elif group[:1] in ['C', 'D'] and group[1:].isdigit(): + symbol = group[:1] + order = int(group[1:]) + else: + raise ValueError("`group` must be one of 'I', 'O', 'T', 'Dn', 'Cn'") + + if order < 1: + raise ValueError("Group order must be positive") + + axis = 'xyz'.index(axis.lower()) + if symbol == 'I': + return icosahedral(cls) + elif symbol == 'O': + return octahedral(cls) + elif symbol == 'T': + return tetrahedral(cls) + elif symbol == 'D': + return dicyclic(cls, order, axis=axis) + elif symbol == 'C': + return cyclic(cls, order, axis=axis) + else: + assert False diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e8720aeda89ac74c808f913f41eec50daf97c22 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation_spline.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation_spline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a8df9507a0b62cd0e98d5918f1d5ebfe6dc6c18 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation_spline.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f51192680ec15abbb75abf5e62b9050a7f5095f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a5a5006349161c6d5c53db3343577a22183b810 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/cosine_cdf.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91a3c52023f45d0bd1f187d1e40842e166de3715 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/expn_asy.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..086c1abaf39fe36013e325d536753acad3ff6c7b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_asy.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3831f8dc965f91f6720727e21dea7b7ef94a8de0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/gammainc_data.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e254d39e1a3099503a5db9faac187477bae8266c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/lambertw.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60df0c5a73f399fb8df1817238a42949206e1648 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/loggamma.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0ddb3a7723863df19023e3062e2420f1adac7da Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/struve_convergence.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a6ad645a96f49d8e7367e173e0335e3e89ba375 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/utils.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff328ad6358c754b2ceae8a00e214643985b574b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..def06a66e37f223fb23eb9a0cfe0a4cd75aabd9f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wright_bessel_data.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49afc3167c7bafbe1a0b68981347f326c09470d8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/wrightomega.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a63c7329e37eaa311e8d311394b70fe332d5b2c6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/__pycache__/zetac.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py new file mode 100644 index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py @@ -0,0 +1,17 @@ +import mpmath + + +def f(x): + return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi) + + +# Note: 40 digits might be overkill; a few more digits than the default +# might be sufficient. +mpmath.mp.dps = 40 +ts = mpmath.taylor(f, -mpmath.pi, 20) +p, q = mpmath.pade(ts, 9, 10) + +p = [float(c) for c in p] +q = [float(c) for c in q] +print('p =', p) +print('q =', q) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py @@ -0,0 +1,54 @@ +"""Precompute the polynomials for the asymptotic expansion of the +generalized exponential integral. + +Sources +------- +[1] NIST, Digital Library of Mathematical Functions, + https://dlmf.nist.gov/8.20#ii + +""" +import os + +try: + import sympy + from sympy import Poly + x = sympy.symbols('x') +except ImportError: + pass + + +def generate_A(K): + A = [Poly(1, x)] + for k in range(K): + A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff()) + return A + + +WARNING = """\ +/* This file was automatically generated by _precompute/expn_asy.py. + * Do not edit it manually! + */ +""" + + +def main(): + print(__doc__) + fn = os.path.join('..', 'cephes', 'expn.h') + + K = 12 + A = generate_A(K) + with open(fn + '.new', 'w') as f: + f.write(WARNING) + f.write(f"#define nA {len(A)}\n") + for k, Ak in enumerate(A): + ', '.join([str(x.evalf(18)) for x in Ak.coeffs()]) + f.write(f"static const double A{k}[] = {{tmp}};\n") + ", ".join([f"A{k}" for k in range(K + 1)]) + f.write("static const double *A[] = {{tmp}};\n") + ", ".join([str(Ak.degree()) for Ak in A]) + f.write("static const int Adegs[] = {{tmp}};\n") + os.rename(fn + '.new', fn) + + +if __name__ == "__main__": + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py new file mode 100644 index 0000000000000000000000000000000000000000..98035457c78706ae01c02273ae1ab458b4ca140d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py @@ -0,0 +1,116 @@ +""" +Precompute coefficients of Temme's asymptotic expansion for gammainc. + +This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram. + +Sources: +[1] NIST, "Digital Library of Mathematical Functions", + https://dlmf.nist.gov/ + +""" +import os +from scipy.special._precompute.utils import lagrange_inversion + +try: + import mpmath as mp +except ImportError: + pass + + +def compute_a(n): + """a_k from DLMF 5.11.6""" + a = [mp.sqrt(2)/2] + for k in range(1, n): + ak = a[-1]/k + for j in range(1, len(a)): + ak -= a[j]*a[-j]/(j + 1) + ak /= a[0]*(1 + mp.mpf(1)/(k + 1)) + a.append(ak) + return a + + +def compute_g(n): + """g_k from DLMF 5.11.3/5.11.5""" + a = compute_a(2*n) + g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)] + return g + + +def eta(lam): + """Function from DLMF 8.12.1 shifted to be centered at 0.""" + if lam > 0: + return mp.sqrt(2*(lam - mp.log(lam + 1))) + elif lam < 0: + return -mp.sqrt(2*(lam - mp.log(lam + 1))) + else: + return 0 + + +def compute_alpha(n): + """alpha_n from DLMF 8.12.13""" + coeffs = mp.taylor(eta, 0, n - 1) + return lagrange_inversion(coeffs) + + +def compute_d(K, N): + """d_{k, n} from DLMF 8.12.12""" + M = N + 2*K + d0 = [-mp.mpf(1)/3] + alpha = compute_alpha(M + 2) + for n in range(1, M): + d0.append((n + 2)*alpha[n+2]) + d = [d0] + g = compute_g(K) + for k in range(1, K): + dk = [] + for n in range(M - 2*k): + dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2]) + d.append(dk) + for k in range(K): + d[k] = d[k][:N] + return d + + +header = \ +r"""/* This file was automatically generated by _precomp/gammainc.py. + * Do not edit it manually! + */ + +#ifndef IGAM_H +#define IGAM_H + +#define K {} +#define N {} + +static const double d[K][N] = +{{""" + +footer = \ +r""" +#endif +""" + + +def main(): + print(__doc__) + K = 25 + N = 25 + with mp.workdps(50): + d = compute_d(K, N) + fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h') + with open(fn + '.new', 'w') as f: + f.write(header.format(K, N)) + for k, row in enumerate(d): + row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row] + f.write('{') + f.write(", ".join(row)) + if k < K - 1: + f.write('},\n') + else: + f.write('}};\n') + f.write(footer) + os.rename(fn + '.new', fn) + + +if __name__ == "__main__": + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ce8ae5f51b77f37367dc26cf08f3a0e64e3429a4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py @@ -0,0 +1,124 @@ +"""Compute gammainc and gammaincc for large arguments and parameters +and save the values to data files for use in tests. We can't just +compare to mpmath's gammainc in test_mpmath.TestSystematic because it +would take too long. + +Note that mpmath's gammainc is computed using hypercomb, but since it +doesn't allow the user to increase the maximum number of terms used in +the series it doesn't converge for many arguments. To get around this +we copy the mpmath implementation but use more terms. + +This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB +ram. + +Sources: +[1] Fredrik Johansson and others. mpmath: a Python library for + arbitrary-precision floating-point arithmetic (version 0.19), + December 2013. http://mpmath.org/. + +""" +import os +from time import time +import numpy as np +from numpy import pi + +from scipy.special._mptestutils import mpf2float + +try: + import mpmath as mp +except ImportError: + pass + + +def gammainc(a, x, dps=50, maxterms=10**8): + """Compute gammainc exactly like mpmath does but allow for more + summands in hypercomb. See + + mpmath/functions/expintegrals.py#L134 + + in the mpmath github repository. + + """ + with mp.workdps(dps): + z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x) + G = [z] + negb = mp.fneg(b, exact=True) + + def h(z): + T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b + return (T1,) + + res = mp.hypercomb(h, [z], maxterms=maxterms) + return mpf2float(res) + + +def gammaincc(a, x, dps=50, maxterms=10**8): + """Compute gammaincc exactly like mpmath does but allow for more + terms in hypercomb. See + + mpmath/functions/expintegrals.py#L187 + + in the mpmath github repository. + + """ + with mp.workdps(dps): + z, a = a, x + + if mp.isint(z): + try: + # mpmath has a fast integer path + return mpf2float(mp.gammainc(z, a=a, regularized=True)) + except mp.libmp.NoConvergence: + pass + nega = mp.fneg(a, exact=True) + G = [z] + # Use 2F0 series when possible; fall back to lower gamma representation + try: + def h(z): + r = z-1 + return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)] + return mpf2float(mp.hypercomb(h, [z], force_series=True)) + except mp.libmp.NoConvergence: + def h(z): + T1 = [], [1, z-1], [z], G, [], [], 0 + T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a + return T1, T2 + return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms)) + + +def main(): + t0 = time() + # It would be nice to have data for larger values, but either this + # requires prohibitively large precision (dps > 800) or mpmath has + # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a + # value around 0.03, while the true value should be close to 0.5 + # (DLMF 8.12.15). + print(__doc__) + pwd = os.path.dirname(__file__) + r = np.logspace(4, 14, 30) + ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30) + utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30) + + regimes = [(gammainc, ltheta), (gammaincc, utheta)] + for func, theta in regimes: + rg, thetag = np.meshgrid(r, theta) + a, x = rg*np.cos(thetag), rg*np.sin(thetag) + a, x = a.flatten(), x.flatten() + dataset = [] + for i, (a0, x0) in enumerate(zip(a, x)): + if func == gammaincc: + # Exploit the fast integer path in gammaincc whenever + # possible so that the computation doesn't take too + # long + a0, x0 = np.floor(a0), np.floor(x0) + dataset.append((a0, x0, func(a0, x0))) + dataset = np.array(dataset) + filename = os.path.join(pwd, '..', 'tests', 'data', 'local', + f'{func.__name__}.txt') + np.savetxt(filename, dataset) + + print(f"{(time() - t0)/60} minutes elapsed") + + +if __name__ == "__main__": + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py new file mode 100644 index 0000000000000000000000000000000000000000..1fdbf35b2cf85f1f7a6e73579546ed5cfe508fa6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py @@ -0,0 +1,68 @@ +"""Compute a Pade approximation for the principal branch of the +Lambert W function around 0 and compare it to various other +approximations. + +""" +import numpy as np + +try: + import mpmath + import matplotlib.pyplot as plt +except ImportError: + pass + + +def lambertw_pade(): + derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)] + p, q = mpmath.pade(derivs, 3, 2) + return p, q + + +def main(): + print(__doc__) + with mpmath.workdps(50): + p, q = lambertw_pade() + p, q = p[::-1], q[::-1] + print(f"p = {p}") + print(f"q = {q}") + + x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75) + x, y = np.meshgrid(x, y) + z = x + 1j*y + lambertw_std = [] + for z0 in z.flatten(): + lambertw_std.append(complex(mpmath.lambertw(z0))) + lambertw_std = np.array(lambertw_std).reshape(x.shape) + + fig, axes = plt.subplots(nrows=3, ncols=1) + # Compare Pade approximation to true result + p = np.array([float(p0) for p0 in p]) + q = np.array([float(q0) for q0 in q]) + pade_approx = np.polyval(p, z)/np.polyval(q, z) + pade_err = abs(pade_approx - lambertw_std) + axes[0].pcolormesh(x, y, pade_err) + # Compare two terms of asymptotic series to true result + asy_approx = np.log(z) - np.log(np.log(z)) + asy_err = abs(asy_approx - lambertw_std) + axes[1].pcolormesh(x, y, asy_err) + # Compare two terms of the series around the branch point to the + # true result + p = np.sqrt(2*(np.exp(1)*z + 1)) + series_approx = -1 + p - p**2/3 + series_err = abs(series_approx - lambertw_std) + im = axes[2].pcolormesh(x, y, series_err) + + fig.colorbar(im, ax=axes.ravel().tolist()) + plt.show() + + fig, ax = plt.subplots(nrows=1, ncols=1) + pade_better = pade_err < asy_err + im = ax.pcolormesh(x, y, pade_better) + t = np.linspace(-0.3, 0.3) + ax.plot(-2.5*abs(t) - 0.2, t, 'r') + fig.colorbar(im, ax=ax) + plt.show() + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py @@ -0,0 +1,43 @@ +"""Precompute series coefficients for log-Gamma.""" + +try: + import mpmath +except ImportError: + pass + + +def stirling_series(N): + with mpmath.workdps(100): + coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1)) + for n in range(1, N + 1)] + return coeffs + + +def taylor_series_at_1(N): + coeffs = [] + with mpmath.workdps(100): + coeffs.append(-mpmath.euler) + for n in range(2, N + 1): + coeffs.append((-1)**n*mpmath.zeta(n)/n) + return coeffs + + +def main(): + print(__doc__) + print() + stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in stirling_series(8)[::-1]] + taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in taylor_series_at_1(23)[::-1]] + print("Stirling series coefficients") + print("----------------------------") + print("\n".join(stirling_coeffs)) + print() + print("Taylor series coefficients") + print("--------------------------") + print("\n".join(taylor_coeffs)) + print() + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py @@ -0,0 +1,131 @@ +""" +Convergence regions of the expansions used in ``struve.c`` + +Note that for v >> z both functions tend rapidly to 0, +and for v << -z, they tend to infinity. + +The floating-point functions over/underflow in the lower left and right +corners of the figure. + + +Figure legend +============= + +Red region + Power series is close (1e-12) to the mpmath result + +Blue region + Asymptotic series is close to the mpmath result + +Green region + Bessel series is close to the mpmath result + +Dotted colored lines + Boundaries of the regions + +Solid colored lines + Boundaries estimated by the routine itself. These will be used + for determining which of the results to use. + +Black dashed line + The line z = 0.7*|v| + 12 + +""" +import numpy as np +import matplotlib.pyplot as plt + +import mpmath + + +def err_metric(a, b, atol=1e-290): + m = abs(a - b) / (atol + abs(b)) + m[np.isinf(b) & (a == b)] = 0 + return m + + +def do_plot(is_h=True): + from scipy.special._ufuncs import (_struve_power_series, + _struve_asymp_large_z, + _struve_bessel_series) + + vs = np.linspace(-1000, 1000, 91) + zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]]) + + rp = _struve_power_series(vs[:,None], zs[None,:], is_h) + ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h) + rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h) + + mpmath.mp.dps = 50 + if is_h: + def sh(v, z): + return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z))) + else: + def sh(v, z): + return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z))) + ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:]) + + err_a = err_metric(ra[0], ex) + 1e-300 + err_p = err_metric(rp[0], ex) + 1e-300 + err_b = err_metric(rb[0], ex) + 1e-300 + + err_est_a = abs(ra[1]/ra[0]) + err_est_p = abs(rp[1]/rp[0]) + err_est_b = abs(rb[1]/rb[0]) + + z_cutoff = 0.7*abs(vs) + 12 + + levels = [-1000, -12] + + plt.cla() + + plt.hold(1) + plt.contourf(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], alpha=0.1) + plt.contourf(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], alpha=0.1) + + plt.contour(vs, zs, np.log10(err_p).T, + levels=levels, colors=['r', 'r'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_a).T, + levels=levels, colors=['b', 'b'], linestyles=[':', ':']) + plt.contour(vs, zs, np.log10(err_b).T, + levels=levels, colors=['g', 'g'], linestyles=[':', ':']) + + lp = plt.contour(vs, zs, np.log10(err_est_p).T, + levels=levels, colors=['r', 'r'], linestyles=['-', '-']) + la = plt.contour(vs, zs, np.log10(err_est_a).T, + levels=levels, colors=['b', 'b'], linestyles=['-', '-']) + lb = plt.contour(vs, zs, np.log10(err_est_b).T, + levels=levels, colors=['g', 'g'], linestyles=['-', '-']) + + plt.clabel(lp, fmt={-1000: 'P', -12: 'P'}) + plt.clabel(la, fmt={-1000: 'A', -12: 'A'}) + plt.clabel(lb, fmt={-1000: 'B', -12: 'B'}) + + plt.plot(vs, z_cutoff, 'k--') + + plt.xlim(vs.min(), vs.max()) + plt.ylim(zs.min(), zs.max()) + + plt.xlabel('v') + plt.ylabel('z') + + +def main(): + plt.clf() + plt.subplot(121) + do_plot(True) + plt.title('Struve H') + + plt.subplot(122) + do_plot(False) + plt.title('Struve L') + + plt.savefig('struve_convergence.png') + plt.show() + + +if __name__ == "__main__": + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/utils.py @@ -0,0 +1,38 @@ +try: + import mpmath as mp +except ImportError: + pass + +try: + from sympy.abc import x +except ImportError: + pass + + +def lagrange_inversion(a): + """Given a series + + f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1), + + use the Lagrange inversion formula to compute a series + + g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1) + + so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so + necessarily b[0] = 0 too. + + The algorithm is naive and could be improved, but speed isn't an + issue here and it's easy to read. + + """ + n = len(a) + f = sum(a[i]*x**i for i in range(n)) + h = (x/f).series(x, 0, n).removeO() + hpower = [h**0] + for k in range(n): + hpower.append((hpower[-1]*h).expand()) + b = [mp.mpf(0)] + for k in range(1, n): + b.append(hpower[k].coeff(x, k - 1)/k) + b = [mp.mpf(x) for x in b] + return b diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..51d56b1cd5c47c7ef005d21aad9827a1e85ec0d9 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py @@ -0,0 +1,342 @@ +"""Precompute coefficients of several series expansions +of Wright's generalized Bessel function Phi(a, b, x). + +See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x. +""" +from argparse import ArgumentParser, RawTextHelpFormatter +import numpy as np +from scipy.integrate import quad +from scipy.optimize import minimize_scalar, curve_fit +from time import time + +try: + import sympy + from sympy import EulerGamma, Rational, S, Sum, \ + factorial, gamma, gammasimp, pi, polygamma, symbols, zeta + from sympy.polys.polyfuncs import horner +except ImportError: + pass + + +def series_small_a(): + """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5. + """ + order = 5 + a, b, x, k = symbols("a b x k") + A = [] # terms with a + X = [] # terms with x + B = [] # terms with b (polygammas) + # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i]) + expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity)) + expression = gamma(b)/sympy.exp(x) * expression + + # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0) + for n in range(0, order+1): + term = expression.diff(a, n).subs(a, 0).simplify().doit() + # set the whole bracket involving polygammas to 1 + x_part = (term.subs(polygamma(0, b), 1) + .replace(polygamma, lambda *args: 0)) + # sign convention: x part always positive + x_part *= (-1)**n + + A.append(a**n/factorial(n)) + X.append(horner(x_part)) + B.append(horner((term/x_part).simplify())) + + s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n" + s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n" + for name, c in zip(['A', 'X', 'B'], [A, X, B]): + for i in range(len(c)): + s += f"\n{name}[{i}] = " + str(c[i]) + return s + + +# expansion of digamma +def dg_series(z, n): + """Symbolic expansion of digamma(z) in z=0 to order n. + + See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2 + """ + k = symbols("k") + return -1/z - EulerGamma + \ + sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1)) + + +def pg_series(k, z, n): + """Symbolic expansion of polygamma(k, z) in z=0 to order n.""" + return sympy.diff(dg_series(z, n+k), z, k) + + +def series_small_a_small_b(): + """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5. + + Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and + polygamma functions. + + digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2) + digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2) + polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2) + and so on. + """ + order = 5 + a, b, x, k = symbols("a b x k") + M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3") + c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3} + A = [] # terms with a + X = [] # terms with x + B = [] # terms with b (polygammas expanded) + C = [] # terms that generate B + # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i]) + # B[0] = 1 + # B[k] = sum(C[k] * b**k/k!, k=0..) + # Note: C[k] can be obtained from a series expansion of 1/gamma(b). + expression = gamma(b)/sympy.exp(x) * \ + Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity)) + + # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0) + for n in range(0, order+1): + term = expression.diff(a, n).subs(a, 0).simplify().doit() + # set the whole bracket involving polygammas to 1 + x_part = (term.subs(polygamma(0, b), 1) + .replace(polygamma, lambda *args: 0)) + # sign convention: x part always positive + x_part *= (-1)**n + # expansion of polygamma part with 1/gamma(b) + pg_part = term/x_part/gamma(b) + if n >= 1: + # Note: highest term is digamma^n + pg_part = pg_part.replace(polygamma, + lambda k, x: pg_series(k, x, order+1+n)) + pg_part = (pg_part.series(b, 0, n=order+1-n) + .removeO() + .subs(polygamma(2, 1), -2*zeta(3)) + .simplify() + ) + + A.append(a**n/factorial(n)) + X.append(horner(x_part)) + B.append(pg_part) + + # Calculate C and put in the k! + C = sympy.Poly(B[1].subs(c_subs), b).coeffs() + C.reverse() + for i in range(len(C)): + C[i] = (C[i] * factorial(i)).simplify() + + s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5." + s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n" + s += "B[0] = 1\n" + s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n" + s += "\nM_PI = pi" + s += "\nM_EG = EulerGamma" + s += "\nM_Z3 = zeta(3)" + for name, c in zip(['A', 'X'], [A, X]): + for i in range(len(c)): + s += f"\n{name}[{i}] = " + s += str(c[i]) + # For C, do also compute the values numerically + for i in range(len(C)): + s += f"\n# C[{i}] = " + s += str(C[i]) + s += f"\nC[{i}] = " + s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)}) + .evalf(17)) + + # Does B have the assumed structure? + s += "\n\nTest if B[i] does have the assumed structure." + s += "\nC[i] are derived from B[1] alone." + s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .." + test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)]) + test = (test - B[2].subs(c_subs)).simplify() + s += f"\ntest successful = {test==S(0)}" + s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .." + test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)]) + test = (test - B[3].subs(c_subs)).simplify() + s += f"\ntest successful = {test==S(0)}" + return s + + +def asymptotic_series(): + """Asymptotic expansion for large x. + + Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k + Z = (a*x)^(1/(1+a)) + + Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and + a_1). With slightly different notation, Paris (2017) lists coefficients + c_k up to order k=3. + Paris (2017) uses ZP = (1+a)/a * Z (ZP = Z of Paris) and + C_k = C_0 * (-a/(1+a))^k * c_k + """ + order = 8 + + class g(sympy.Function): + """Helper function g according to Wright (1935) + + g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...) + + Note: Wright (1935) uses square root of above definition. + """ + nargs = 3 + + @classmethod + def eval(cls, n, rho, v): + if not n >= 0: + raise ValueError("must have n >= 0") + elif n == 0: + return 1 + else: + return g(n-1, rho, v) \ + + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \ + / gammasimp(gamma(3+n)/gamma(3))*v**n + + class coef_C(sympy.Function): + """Calculate coefficients C_m for integer m. + + C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of + Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b) + * g(rho, v)^(-m-1/2) + """ + nargs = 3 + + @classmethod + def eval(cls, m, rho, beta): + if not m >= 0: + raise ValueError("must have m >= 0") + + v = symbols("v") + expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2)) + res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m) + res = res * (gamma(m + Rational(1, 2)) / (2*pi) + * (2/(rho+1))**(m + Rational(1, 2))) + return res + + # in order to have nice ordering/sorting of expressions, we set a = xa. + xa, b, xap1 = symbols("xa b xap1") + C0 = coef_C(0, xa, b) + # a1 = a(1, rho, beta) + s = "Asymptotic expansion for large x\n" + s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n" + s += " * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n" + s += "Z = pow(a * x, 1/(1+a))\n" + s += "A[k] = pow(a, k)\n" + s += "B[k] = pow(b, k)\n" + s += "Ap1[k] = pow(1+a, k)\n\n" + s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n" + for i in range(1, order+1): + expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify() + factor = [x.denominator() for x in sympy.Poly(expr).coeffs()] + factor = sympy.lcm(factor) + expr = (expr * factor).simplify().collect(b, sympy.factor) + expr = expr.xreplace({xa+1: xap1}) + s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n" + s += f"C[{i}] *= {str(expr)}\n\n" + import re + re_a = re.compile(r'xa\*\*(\d+)') + s = re_a.sub(r'A[\1]', s) + re_b = re.compile(r'b\*\*(\d+)') + s = re_b.sub(r'B[\1]', s) + s = s.replace('xap1', 'Ap1[1]') + s = s.replace('xa', 'a') + # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10 + # or more digits. + re_digits = re.compile(r'(\d{10,})') + s = re_digits.sub(r'\1.', s) + return s + + +def optimal_epsilon_integral(): + """Fit optimal choice of epsilon for integral representation. + + The integrand of + int_0^pi P(eps, a, b, x, phi) * dphi + can exhibit oscillatory behaviour. It stems from the cosine of P and can be + minimized by minimizing the arc length of the argument + f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi + of cos(f(phi)). + We minimize the arc length in eps for a grid of values (a, b, x) and fit a + parametric function to it. + """ + def fp(eps, a, b, x, phi): + """Derivative of f w.r.t. phi.""" + eps_a = np.power(1. * eps, -a) + return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b + + def arclength(eps, a, b, x, epsrel=1e-2, limit=100): + """Compute Arc length of f. + + Note that the arc length of a function f from t0 to t1 is given by + int_t0^t1 sqrt(1 + f'(t)^2) dt + """ + return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2), + 0, np.pi, + epsrel=epsrel, limit=100)[0] + + # grid of minimal arc length values + data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8] + data_b = [0, 1, 4, 7, 10] + data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4] + data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x) + data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(), + data_x.flatten()) + best_eps = [] + for i in range(data_x.size): + best_eps.append( + minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i], + data_x[i]), + bounds=(1e-3, 1000), + method='Bounded', options={'xatol': 1e-3}).x + ) + best_eps = np.array(best_eps) + # pandas would be nice, but here a dictionary is enough + df = {'a': data_a, + 'b': data_b, + 'x': data_x, + 'eps': best_eps, + } + + def func(data, A0, A1, A2, A3, A4, A5): + """Compute parametric function to fit.""" + a = data['a'] + b = data['b'] + x = data['x'] + return (A0 * b * np.exp(-0.5 * a) + + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a) + + A4 / (1 + np.exp(A5 * a)))) + + func_params = list(curve_fit(func, df, df['eps'], method='trf')[0]) + + s = "Fit optimal eps for integrand P via minimal arc length\n" + s += "with parametric function:\n" + s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n" + s += " - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n" + s += "Fitted parameters A0 to A5 are:\n" + s += ', '.join([f'{x:.5g}' for x in func_params]) + return s + + +def main(): + t0 = time() + parser = ArgumentParser(description=__doc__, + formatter_class=RawTextHelpFormatter) + parser.add_argument('action', type=int, choices=[1, 2, 3, 4], + help='chose what expansion to precompute\n' + '1 : Series for small a\n' + '2 : Series for small a and small b\n' + '3 : Asymptotic series for large x\n' + ' This may take some time (>4h).\n' + '4 : Fit optimal eps for integral representation.' + ) + args = parser.parse_args() + + switch = {1: lambda: print(series_small_a()), + 2: lambda: print(series_small_a_small_b()), + 3: lambda: print(asymptotic_series()), + 4: lambda: print(optimal_epsilon_integral()) + } + switch.get(args.action, lambda: print("Invalid input."))() + print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n") + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py new file mode 100644 index 0000000000000000000000000000000000000000..1de9b4fe552ca9178c452194ab84af6ca5daac71 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py @@ -0,0 +1,152 @@ +"""Compute a grid of values for Wright's generalized Bessel function +and save the values to data files for use in tests. Using mpmath directly in +tests would take too long. + +This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro. +""" +from functools import lru_cache +import os +from time import time + +import numpy as np +from scipy.special._mptestutils import mpf2float + +try: + import mpmath as mp +except ImportError: + pass + +# exp_inf: smallest value x for which exp(x) == inf +exp_inf = 709.78271289338403 + + +# 64 Byte per value +@lru_cache(maxsize=100_000) +def rgamma_cached(x, dps): + with mp.workdps(dps): + return mp.rgamma(x) + + +def mp_wright_bessel(a, b, x, dps=50, maxterms=2000): + """Compute Wright's generalized Bessel function as Series with mpmath. + """ + with mp.workdps(dps): + a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x) + res = mp.nsum(lambda k: x**k / mp.fac(k) + * rgamma_cached(a * k + b, dps=dps), + [0, mp.inf], + tol=dps, method='s', steps=[maxterms] + ) + return mpf2float(res) + + +def main(): + t0 = time() + print(__doc__) + pwd = os.path.dirname(__file__) + eps = np.finfo(float).eps * 100 + + a_range = np.array([eps, + 1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps), + 1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps), + 0.1, 0.5, + 1 * (1 - eps), 1, 1 * (1 + eps), + 1.5, 2, 4.999, 5, 10]) + b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100]) + x_range = np.array([0, eps, 1 - eps, 1, 1 + eps, + 1.5, + 2 - eps, 2, 2 + eps, + 9 - eps, 9, 9 + eps, + 10 * (1 - eps), 10, 10 * (1 + eps), + 100 * (1 - eps), 100, 100 * (1 + eps), + 500, exp_inf, 1e3, 1e5, 1e10, 1e20]) + + a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range, + indexing='ij') + a_range = a_range.flatten() + b_range = b_range.flatten() + x_range = x_range.flatten() + + # filter out some values, especially too large x + bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf)) + bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf)) + bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3)) + bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3)) + bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4)) + bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5)) + bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6)) + bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7)) + bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8)) + bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9)) + bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10)) + bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11)) + bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12)) + bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13)) + bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14)) + bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15)) + bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16)) + bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17)) + bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18)) + bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18)) + bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19)) + bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20)) + + # filter out known values that do not meet the required numerical accuracy + # see test test_wright_data_grid_failures + failing = np.array([ + [0.1, 100, 709.7827128933841], + [0.5, 10, 709.7827128933841], + [0.5, 10, 1000], + [0.5, 100, 1000], + [1, 20, 100000], + [1, 100, 100000], + [1.0000000000000222, 20, 100000], + [1.0000000000000222, 100, 100000], + [1.5, 0, 500], + [1.5, 2.220446049250313e-14, 500], + [1.5, 1.e-10, 500], + [1.5, 1.e-05, 500], + [1.5, 0.1, 500], + [1.5, 20, 100000], + [1.5, 100, 100000], + ]).tolist() + + does_fail = np.full_like(a_range, False, dtype=bool) + for i in range(x_range.size): + if [a_range[i], b_range[i], x_range[i]] in failing: + does_fail[i] = True + + # filter and flatten + a_range = a_range[bool_filter] + b_range = b_range[bool_filter] + x_range = x_range[bool_filter] + does_fail = does_fail[bool_filter] + + dataset = [] + print(f"Computing {x_range.size} single points.") + print("Tests will fail for the following data points:") + for i in range(x_range.size): + a = a_range[i] + b = b_range[i] + x = x_range[i] + # take care of difficult corner cases + maxterms = 1000 + if a < 1e-6 and x >= exp_inf/10: + maxterms = 2000 + f = mp_wright_bessel(a, b, x, maxterms=maxterms) + if does_fail[i]: + print("failing data point a, b, x, value = " + f"[{a}, {b}, {x}, {f}]") + else: + dataset.append((a, b, x, f)) + dataset = np.array(dataset) + + filename = os.path.join(pwd, '..', 'tests', 'data', 'local', + 'wright_bessel.txt') + np.savetxt(filename, dataset) + + print(f"{(time() - t0)/60:.1f} minutes elapsed") + + +if __name__ == "__main__": + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py new file mode 100644 index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py @@ -0,0 +1,41 @@ +import numpy as np + +try: + import mpmath +except ImportError: + pass + + +def mpmath_wrightomega(x): + return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5')) + + +def wrightomega_series_error(x): + series = x + desired = mpmath_wrightomega(x) + return abs(series - desired) / desired + + +def wrightomega_exp_error(x): + exponential_approx = mpmath.exp(x) + desired = mpmath_wrightomega(x) + return abs(exponential_approx - desired) / desired + + +def main(): + desired_error = 2 * np.finfo(float).eps + print('Series Error') + for x in [1e5, 1e10, 1e15, 1e20]: + with mpmath.workdps(100): + error = wrightomega_series_error(x) + print(x, error, error < desired_error) + + print('Exp error') + for x in [-10, -25, -50, -100, -200, -400, -700, -740]: + with mpmath.workdps(100): + error = wrightomega_exp_error(x) + print(x, error, error < desired_error) + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py new file mode 100644 index 0000000000000000000000000000000000000000..d408b1a2fffb6872287452923fcc9394adc13a7c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py @@ -0,0 +1,27 @@ +"""Compute the Taylor series for zeta(x) - 1 around x = 0.""" +try: + import mpmath +except ImportError: + pass + + +def zetac_series(N): + coeffs = [] + with mpmath.workdps(100): + coeffs.append(-1.5) + for n in range(1, N): + coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n) + coeffs.append(coeff) + return coeffs + + +def main(): + print(__doc__) + coeffs = zetac_series(10) + coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0) + for x in coeffs] + print("\n".join(coeffs[::-1])) + + +if __name__ == '__main__': + main() diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/binom.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/binom.h new file mode 100644 index 0000000000000000000000000000000000000000..0641b28a8dac29f93cac0857bf2432d4cbc0e747 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/binom.h @@ -0,0 +1,85 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * + * Original authors: Pauli Virtanen, Eric Moore + */ + +// Binomial coefficient + +#pragma once + +#include "config.h" + +#include "cephes/beta.h" +#include "cephes/gamma.h" + +namespace special { + +SPECFUN_HOST_DEVICE inline double binom(double n, double k) { + double kx, nx, num, den, dk, sgn; + + if (n < 0) { + nx = std::floor(n); + if (n == nx) { + // Undefined + return std::numeric_limits::quiet_NaN(); + } + } + + kx = std::floor(k); + if (k == kx && (std::abs(n) > 1E-8 || n == 0)) { + /* Integer case: use multiplication formula for less rounding + * error for cases where the result is an integer. + * + * This cannot be used for small nonzero n due to loss of + * precision. */ + nx = std::floor(n); + if (nx == n && kx > nx / 2 && nx > 0) { + // Reduce kx by symmetry + kx = nx - kx; + } + + if (kx >= 0 && kx < 20) { + num = 1.0; + den = 1.0; + for (int i = 1; i < 1 + static_cast(kx); i++) { + num *= i + n - kx; + den *= i; + if (std::abs(num) > 1E50) { + num /= den; + den = 1.0; + } + } + return num / den; + } + } + + // general case + if (n >= 1E10 * k and k > 0) { + // avoid under/overflows intermediate results + return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1)); + } + if (k > 1E8 * std::abs(n)) { + // avoid loss of precision + num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ... + num /= M_PI * std::pow(std::abs(k), n); + if (k > 0) { + kx = std::floor(k); + if (static_cast(kx) == kx) { + dk = k - kx; + sgn = (static_cast(kx) % 2 == 0) ? 1 : -1; + } else { + dk = k; + sgn = 1; + } + return num * std::sin((dk - n) * M_PI) * sgn; + } + kx = std::floor(k); + if (static_cast(kx) == kx) { + return 0; + } + return num * std::sin(k * M_PI); + } + return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k); +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/beta.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/beta.h new file mode 100644 index 0000000000000000000000000000000000000000..45acb23748f81e244b38f7374c701d8c5074c753 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/beta.h @@ -0,0 +1,255 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* beta.c + * + * Beta function + * + * + * + * SYNOPSIS: + * + * double a, b, y, beta(); + * + * y = beta( a, b ); + * + * + * + * DESCRIPTION: + * + * - - + * | (a) | (b) + * beta( a, b ) = -----------. + * - + * | (a+b) + * + * For large arguments the logarithm of the function is + * evaluated using lgam(), then exponentiated. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 8.1e-14 1.1e-14 + * + * ERROR MESSAGES: + * + * message condition value returned + * beta overflow log(beta) > MAXLOG 0.0 + * a or b <0 integer 0.0 + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "const.h" +#include "gamma.h" + +namespace special { +namespace cephes { + + SPECFUN_HOST_DEVICE double beta(double, double); + SPECFUN_HOST_DEVICE double lbeta(double, double); + + namespace detail { + constexpr double beta_ASYMP_FACTOR = 1e6; + + /* + * Asymptotic expansion for ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1). + */ + SPECFUN_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) { + double r = lgam_sgn(b, sgn); + r -= b * std::log(a); + + r += b * (1 - b) / (2 * a); + r += b * (1 - b) * (1 - 2 * b) / (12 * a * a); + r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a); + + return r; + } + + /* + * Special case for a negative integer argument + */ + + SPECFUN_HOST_DEVICE inline double beta_negint(int a, double b) { + int sgn; + if (b == static_cast(b) && 1 - a - b > 0) { + sgn = (static_cast(b) % 2 == 0) ? 1 : -1; + return sgn * special::cephes::beta(1 - a - b, b); + } else { + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + } + + SPECFUN_HOST_DEVICE inline double lbeta_negint(int a, double b) { + double r; + if (b == static_cast(b) && 1 - a - b > 0) { + r = special::cephes::lbeta(1 - a - b, b); + return r; + } else { + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return std::numeric_limits::infinity(); + } + } + } // namespace detail + + SPECFUN_HOST_DEVICE inline double beta(double a, double b) { + double y; + int sign = 1; + + if (a <= 0.0) { + if (a == std::floor(a)) { + if (a == static_cast(a)) { + return detail::beta_negint(static_cast(a), b); + } else { + goto overflow; + } + } + } + + if (b <= 0.0) { + if (b == std::floor(b)) { + if (b == static_cast(b)) { + return detail::beta_negint(static_cast(b), a); + } else { + goto overflow; + } + } + } + + if (std::abs(a) < std::abs(b)) { + y = a; + a = b; + b = y; + } + + if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) { + /* Avoid loss of precision in lgam(a + b) - lgam(a) */ + y = detail::lbeta_asymp(a, b, &sign); + return sign * std::exp(y); + } + + y = a + b; + if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) { + int sgngam; + y = detail::lgam_sgn(y, &sgngam); + sign *= sgngam; /* keep track of the sign */ + y = detail::lgam_sgn(b, &sgngam) - y; + sign *= sgngam; + y = detail::lgam_sgn(a, &sgngam) + y; + sign *= sgngam; + if (y > detail::MAXLOG) { + goto overflow; + } + return (sign * std::exp(y)); + } + + y = Gamma(y); + a = Gamma(a); + b = Gamma(b); + if (y == 0.0) + goto overflow; + + if (std::abs(std::abs(a) - std::abs(y)) > std::abs(std::abs(b) - std::abs(y))) { + y = b / y; + y *= a; + } else { + y = a / y; + y *= b; + } + + return (y); + + overflow: + set_error("beta", SF_ERROR_OVERFLOW, NULL); + return (sign * std::numeric_limits::infinity()); + } + + /* Natural log of |beta|. */ + + SPECFUN_HOST_DEVICE inline double lbeta(double a, double b) { + double y; + int sign; + + sign = 1; + + if (a <= 0.0) { + if (a == std::floor(a)) { + if (a == static_cast(a)) { + return detail::lbeta_negint(static_cast(a), b); + } else { + goto over; + } + } + } + + if (b <= 0.0) { + if (b == std::floor(b)) { + if (b == static_cast(b)) { + return detail::lbeta_negint(static_cast(b), a); + } else { + goto over; + } + } + } + + if (std::abs(a) < std::abs(b)) { + y = a; + a = b; + b = y; + } + + if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) { + /* Avoid loss of precision in lgam(a + b) - lgam(a) */ + y = detail::lbeta_asymp(a, b, &sign); + return y; + } + + y = a + b; + if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) { + int sgngam; + y = detail::lgam_sgn(y, &sgngam); + sign *= sgngam; /* keep track of the sign */ + y = detail::lgam_sgn(b, &sgngam) - y; + sign *= sgngam; + y = detail::lgam_sgn(a, &sgngam) + y; + sign *= sgngam; + return (y); + } + + y = Gamma(y); + a = Gamma(a); + b = Gamma(b); + if (y == 0.0) { + over: + set_error("lbeta", SF_ERROR_OVERFLOW, NULL); + return (sign * std::numeric_limits::infinity()); + } + + if (std::abs(std::abs(a) - std::abs(y)) > std::abs(std::abs(b) - std::abs(y))) { + y = b / y; + y *= a; + } else { + y = a / y; + y *= b; + } + + if (y < 0) { + y = -y; + } + + return (std::log(y)); + } +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/const.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/const.h new file mode 100644 index 0000000000000000000000000000000000000000..06299581f01a81de3ff79be5f876511c99ef306a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/const.h @@ -0,0 +1,77 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + * + * Since we support only IEEE-754 floating point numbers, conditional logic + * supporting other arithmetic types has been removed. + */ + +/* + * + * + * const.c + * + * Globally declared constants + * + * + * + * SYNOPSIS: + * + * extern double nameofconstant; + * + * + * + * + * DESCRIPTION: + * + * This file contains a number of mathematical constants and + * also some needed size parameters of the computer arithmetic. + * The values are supplied as arrays of hexadecimal integers + * for IEEE arithmetic, and in a normal decimal scientific notation for + * other machines. The particular notation used is determined + * by a symbol (IBMPC, or UNK) defined in the include file + * mconf.h. + * + * The default size parameters are as follows. + * + * For UNK mode: + * MACHEP = 1.38777878078144567553E-17 2**-56 + * MAXLOG = 8.8029691931113054295988E1 log(2**127) + * MINLOG = -8.872283911167299960540E1 log(2**-128) + * + * For IEEE arithmetic (IBMPC): + * MACHEP = 1.11022302462515654042E-16 2**-53 + * MAXLOG = 7.09782712893383996843E2 log(2**1024) + * MINLOG = -7.08396418532264106224E2 log(2**-1022) + * + * The global symbols for mathematical constants are + * SQ2OPI = 7.9788456080286535587989E-1 sqrt( 2/pi ) + * LOGSQ2 = 3.46573590279972654709E-1 log(2)/2 + * THPIO4 = 2.35619449019234492885 3*pi/4 + * + * These lists are subject to change. + */ +/* const.c */ + +/* + * Cephes Math Library Release 2.3: March, 1995 + * Copyright 1984, 1995 by Stephen L. Moshier + */ +#pragma once + +namespace special { +namespace cephes { + namespace detail { + constexpr double MACHEP = 1.11022302462515654042E-16; // 2**-53 + constexpr double MAXLOG = 7.09782712893383996732E2; // log(DBL_MAX) + constexpr double MINLOG = -7.451332191019412076235E2; // log 2**-1022 + constexpr double SQ2OPI = 7.9788456080286535587989E-1; // sqrt( 2/pi ) + constexpr double LOGSQ2 = 3.46573590279972654709E-1; // log(2)/2 + constexpr double THPIO4 = 2.35619449019234492885; // 3*pi/4 + // Following two added by SciPy developers. + // Euler's constant + constexpr double SCIPY_EULER = 0.577215664901532860606512090082402431; + // e as long double + constexpr long double SCIPY_El = 2.718281828459045235360287471352662498L; + } // namespace detail +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/gamma.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/gamma.h new file mode 100644 index 0000000000000000000000000000000000000000..0a923bb0bc28eed010902f113888e4beb975c775 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/gamma.h @@ -0,0 +1,343 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* + * Gamma function + * + * + * + * SYNOPSIS: + * + * double x, y, Gamma(); + * + * y = Gamma( x ); + * + * + * + * DESCRIPTION: + * + * Returns Gamma function of the argument. The result is + * correctly signed. + * + * Arguments |x| <= 34 are reduced by recurrence and the function + * approximated by a rational function of degree 6/7 in the + * interval (2,3). Large arguments are handled by Stirling's + * formula. Large negative arguments are made positive using + * a reflection formula. + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -170,-33 20000 2.3e-15 3.3e-16 + * IEEE -33, 33 20000 9.4e-16 2.2e-16 + * IEEE 33, 171.6 20000 2.3e-15 3.2e-16 + * + * Error for arguments outside the test range will be larger + * owing to error amplification by the exponential function. + * + */ + +/* lgam() + * + * Natural logarithm of Gamma function + * + * + * + * SYNOPSIS: + * + * double x, y, lgam(); + * + * y = lgam( x ); + * + * + * + * DESCRIPTION: + * + * Returns the base e (2.718...) logarithm of the absolute + * value of the Gamma function of the argument. + * + * For arguments greater than 13, the logarithm of the Gamma + * function is approximated by the logarithmic version of + * Stirling's formula using a polynomial approximation of + * degree 4. Arguments between -33 and +33 are reduced by + * recurrence to the interval [2,3] of a rational approximation. + * The cosecant reflection formula is employed for arguments + * less than -33. + * + * Arguments greater than MAXLGM return INFINITY and an error + * message. MAXLGM = 2.556348e305 for IEEE arithmetic. + * + * + * + * ACCURACY: + * + * + * arithmetic domain # trials peak rms + * IEEE 0, 3 28000 5.4e-16 1.1e-16 + * IEEE 2.718, 2.556e305 40000 3.5e-16 8.3e-17 + * The error criterion was relative when the function magnitude + * was greater than one but absolute when it was less than one. + * + * The following test used the relative error criterion, though + * at certain points the relative error could be much higher than + * indicated. + * IEEE -200, -4 10000 4.8e-16 1.3e-16 + * + */ + +/* + * Cephes Math Library Release 2.2: July, 1992 + * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "polevl.h" + +namespace special { +namespace cephes { + namespace detail { + constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2, + 4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1, + 9.99999999999999996796E-1}; + + constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3, + 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, + 7.14304917030273074085E-2, 1.00000000000000000320E0}; + + constexpr double MAXGAM = 171.624376956302725; + constexpr double LOGPI = 1.14472988584940017414; + + /* Stirling's formula for the Gamma function */ + constexpr double gamma_STIR[5] = { + 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3, + 3.47222221605458667310E-3, 8.33333333333482257126E-2, + }; + + constexpr double MAXSTIR = 143.01608; + constexpr double SQTPI = 2.50662827463100050242E0; + + /* Gamma function computed by Stirling's formula. + * The polynomial STIR is valid for 33 <= x <= 172. + */ + SPECFUN_HOST_DEVICE inline double stirf(double x) { + double y, w, v; + + if (x >= MAXGAM) { + return (std::numeric_limits::infinity()); + } + w = 1.0 / x; + w = 1.0 + w * special::cephes::polevl(w, gamma_STIR, 4); + y = std::exp(x); + if (x > MAXSTIR) { /* Avoid overflow in pow() */ + v = std::pow(x, 0.5 * x - 0.25); + y = v * (v / y); + } else { + y = std::pow(x, x - 0.5) / y; + } + y = SQTPI * y * w; + return (y); + } + } // namespace detail + + SPECFUN_HOST_DEVICE inline double Gamma(double x) { + double p, q, z; + int i; + int sgngam = 1; + + if (!std::isfinite(x)) { + return x; + } + q = std::abs(x); + + if (q > 33.0) { + if (x < 0.0) { + p = floor(q); + if (p == q) { + gamnan: + set_error("Gamma", SF_ERROR_OVERFLOW, NULL); + return (std::numeric_limits::infinity()); + } + i = p; + if ((i & 1) == 0) { + sgngam = -1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = q - p; + } + z = q * std::sin(M_PI * z); + if (z == 0.0) { + return (sgngam * std::numeric_limits::infinity()); + } + z = std::abs(z); + z = M_PI / (z * detail::stirf(q)); + } else { + z = detail::stirf(x); + } + return (sgngam * z); + } + + z = 1.0; + while (x >= 3.0) { + x -= 1.0; + z *= x; + } + + while (x < 0.0) { + if (x > -1.E-9) { + goto small; + } + z /= x; + x += 1.0; + } + + while (x < 2.0) { + if (x < 1.e-9) { + goto small; + } + z /= x; + x += 1.0; + } + + if (x == 2.0) { + return (z); + } + + x -= 2.0; + p = polevl(x, detail::gamma_P, 6); + q = polevl(x, detail::gamma_Q, 7); + return (z * p / q); + + small: + if (x == 0.0) { + goto gamnan; + } else + return (z / ((1.0 + 0.5772156649015329 * x) * x)); + } + + namespace detail { + /* A[]: Stirling's formula expansion of log Gamma + * B[], C[]: log Gamma function between 2 and 3 + */ + constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4, + -2.77777777730099687205E-3, 8.33333333333331927722E-2}; + + constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5, + -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5}; + + constexpr double gamma_C[] = { + /* 1.00000000000000000000E0, */ + -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, + -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6}; + + /* log( sqrt( 2*pi ) ) */ + constexpr double LS2PI = 0.91893853320467274178; + + constexpr double MAXLGM = 2.556348e305; + + SPECFUN_HOST_DEVICE double lgam_sgn(double x, int *sign) { + double p, q, u, w, z; + int i; + + *sign = 1; + + if (!std::isfinite(x)) { + return x; + } + + if (x < -34.0) { + q = -x; + w = lgam_sgn(q, sign); + p = floor(q); + if (p == q) { + lgsing: + set_error("lgam", SF_ERROR_SINGULAR, NULL); + return (std::numeric_limits::infinity()); + } + i = p; + if ((i & 1) == 0) { + *sign = -1; + } else { + *sign = 1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = p - q; + } + z = q * std::sin(M_PI * z); + if (z == 0.0) { + goto lgsing; + } + /* z = log(M_PI) - log( z ) - w; */ + z = LOGPI - std::log(z) - w; + return (z); + } + + if (x < 13.0) { + z = 1.0; + p = 0.0; + u = x; + while (u >= 3.0) { + p -= 1.0; + u = x + p; + z *= u; + } + while (u < 2.0) { + if (u == 0.0) { + goto lgsing; + } + z /= u; + p += 1.0; + u = x + p; + } + if (z < 0.0) { + *sign = -1; + z = -z; + } else { + *sign = 1; + } + if (u == 2.0) { + return (std::log(z)); + } + p -= 2.0; + x = x + p; + p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6); + return (std::log(z) + p); + } + + if (x > MAXLGM) { + return (*sign * std::numeric_limits::infinity()); + } + + q = (x - 0.5) * std::log(x) - x + LS2PI; + if (x > 1.0e8) { + return (q); + } + + p = 1.0 / (x * x); + if (x >= 1000.0) { + q += ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / + x; + } else { + q += polevl(p, gamma_A, 4) / x; + } + return (q); + } + } // namespace detail + + /* Logarithm of Gamma function */ + SPECFUN_HOST_DEVICE double lgam(double x) { + int sign; + return detail::lgam_sgn(x, &sign); + } + +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/polevl.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/polevl.h new file mode 100644 index 0000000000000000000000000000000000000000..07a591cad5fd552045598184ea1eae6e2b0dced7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/polevl.h @@ -0,0 +1,165 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* polevl.c + * p1evl.c + * + * Evaluate polynomial + * + * + * + * SYNOPSIS: + * + * int N; + * double x, y, coef[N+1], polevl[]; + * + * y = polevl( x, coef, N ); + * + * + * + * DESCRIPTION: + * + * Evaluates polynomial of degree N: + * + * 2 N + * y = C + C x + C x +...+ C x + * 0 1 2 N + * + * Coefficients are stored in reverse order: + * + * coef[0] = C , ..., coef[N] = C . + * N 0 + * + * The function p1evl() assumes that c_N = 1.0 so that coefficent + * is omitted from the array. Its calling arguments are + * otherwise the same as polevl(). + * + * + * SPEED: + * + * In the interest of speed, there are no checks for out + * of bounds arithmetic. This routine is used by most of + * the functions in the library. Depending on available + * equipment features, the user may wish to rewrite the + * program in microcode or assembly language. + * + */ + +/* + * Cephes Math Library Release 2.1: December, 1988 + * Copyright 1984, 1987, 1988 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ + +/* Sources: + * [1] Holin et. al., "Polynomial and Rational Function Evaluation", + * https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/roots/rational.html + */ + +/* Scipy changes: + * - 06-23-2016: add code for evaluating rational functions + */ +#pragma once + +#include "../config.h" + +namespace special { +namespace cephes { + SPECFUN_HOST_DEVICE inline double polevl(double x, const double coef[], int N) { + double ans; + int i; + const double *p; + + p = coef; + ans = *p++; + i = N; + + do { + ans = ans * x + *p++; + } while (--i); + + return (ans); + } + + /* p1evl() */ + /* N + * Evaluate polynomial when coefficient of x is 1.0. + * That is, C_{N} is assumed to be 1, and that coefficient + * is not included in the input array coef. + * coef must have length N and contain the polynomial coefficients + * stored as + * coef[0] = C_{N-1} + * coef[1] = C_{N-2} + * ... + * coef[N-2] = C_1 + * coef[N-1] = C_0 + * Otherwise same as polevl. + */ + + SPECFUN_HOST_DEVICE inline double p1evl(double x, const double coef[], int N) { + double ans; + const double *p; + int i; + + p = coef; + ans = x + *p++; + i = N - 1; + + do + ans = ans * x + *p++; + while (--i); + + return (ans); + } + + /* Evaluate a rational function. See [1]. */ + + SPECFUN_HOST_DEVICE inline double ratevl(double x, const double num[], int M, const double denom[], int N) { + int i, dir; + double y, num_ans, denom_ans; + double absx = std::abs(x); + const double *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + + if (absx > 1) { + i = N - M; + return std::pow(x, i) * num_ans / denom_ans; + } else { + return num_ans / denom_ans; + } + } +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/psi.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/psi.h new file mode 100644 index 0000000000000000000000000000000000000000..10fefeb107e1c23d4b2180af8c251dc12ce62da6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/psi.h @@ -0,0 +1,194 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* psi.c + * + * Psi (digamma) function + * + * + * SYNOPSIS: + * + * double x, y, psi(); + * + * y = psi( x ); + * + * + * DESCRIPTION: + * + * d - + * psi(x) = -- ln | (x) + * dx + * + * is the logarithmic derivative of the gamma function. + * For integer x, + * n-1 + * - + * psi(n) = -EUL + > 1/k. + * - + * k=1 + * + * This formula is used for 0 < n <= 10. If x is negative, it + * is transformed to a positive argument by the reflection + * formula psi(1-x) = psi(x) + pi cot(pi x). + * For general positive x, the argument is made greater than 10 + * using the recurrence psi(x+1) = psi(x) + 1/x. + * Then the following asymptotic expansion is applied: + * + * inf. B + * - 2k + * psi(x) = log(x) - 1/2x - > ------- + * - 2k + * k=1 2k x + * + * where the B2k are Bernoulli numbers. + * + * ACCURACY: + * Relative error (except absolute when |psi| < 1): + * arithmetic domain # trials peak rms + * IEEE 0,30 30000 1.3e-15 1.4e-16 + * IEEE -30,0 40000 1.5e-15 2.2e-16 + * + * ERROR MESSAGES: + * message condition value returned + * psi singularity x integer <=0 INFINITY + */ + +/* + * Cephes Math Library Release 2.8: June, 2000 + * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier + */ + +/* + * Code for the rational approximation on [1, 2] is: + * + * (C) Copyright John Maddock 2006. + * Use, modification and distribution are subject to the + * Boost Software License, Version 1.0. (See accompanying file + * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" +#include "polevl.h" + +namespace special { +namespace cephes { + namespace detail { + constexpr double psi_A[] = {8.33333333333333333333E-2, -2.10927960927960927961E-2, 7.57575757575757575758E-3, + -4.16666666666666666667E-3, 3.96825396825396825397E-3, -8.33333333333333333333E-3, + 8.33333333333333333333E-2}; + + constexpr float psi_Y = 0.99558162689208984f; + + constexpr double psi_root1 = 1569415565.0 / 1073741824.0; + constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0; + constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19; + + constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784, + -0.65031853770896507, -0.32555031186804491, 0.25479851061131551}; + constexpr double psi_Q[] = {-0.55789841321675513e-6, + 0.0021284987017821144, + 0.054151797245674225, + 0.43593529692665969, + 1.4606242909763515, + 2.0767117023730469, + 1.0}; + + SPECFUN_HOST_DEVICE double digamma_imp_1_2(double x) { + /* + * Rational approximation on [1, 2] taken from Boost. + * + * Now for the approximation, we use the form: + * + * digamma(x) = (x - root) * (Y + R(x-1)) + * + * Where root is the location of the positive root of digamma, + * Y is a constant, and R is optimised for low absolute error + * compared to Y. + * + * Maximum Deviation Found: 1.466e-18 + * At double precision, max error found: 2.452e-17 + */ + double r, g; + + g = x - psi_root1; + g -= psi_root2; + g -= psi_root3; + r = special::cephes::polevl(x - 1.0, psi_P, 5) / special::cephes::polevl(x - 1.0, psi_Q, 6); + + return g * psi_Y + g * r; + } + + SPECFUN_HOST_DEVICE double psi_asy(double x) { + double y, z; + + if (x < 1.0e17) { + z = 1.0 / (x * x); + y = z * special::cephes::polevl(z, psi_A, 6); + } else { + y = 0.0; + } + + return std::log(x) - (0.5 / x) - y; + } + } // namespace detail + + SPECFUN_HOST_DEVICE double psi(double x) { + double y = 0.0; + double q, r; + int i, n; + + if (std::isnan(x)) { + return x; + } else if (x == std::numeric_limits::infinity()) { + return x; + } else if (x == -std::numeric_limits::infinity()) { + return std::numeric_limits::quiet_NaN(); + } else if (x == 0) { + set_error("psi", SF_ERROR_SINGULAR, NULL); + return std::copysign(std::numeric_limits::infinity(), -x); + } else if (x < 0.0) { + /* argument reduction before evaluating tan(pi * x) */ + r = std::modf(x, &q); + if (r == 0.0) { + set_error("psi", SF_ERROR_SINGULAR, NULL); + return std::numeric_limits::quiet_NaN(); + } + y = -M_PI / std::tan(M_PI * r); + x = 1.0 - x; + } + + /* check for positive integer up to 10 */ + if ((x <= 10.0) && (x == std::floor(x))) { + n = static_cast(x); + for (i = 1; i < n; i++) { + y += 1.0 / i; + } + y -= detail::SCIPY_EULER; + return y; + } + + /* use the recurrence relation to move x into [1, 2] */ + if (x < 1.0) { + y -= 1.0 / x; + x += 1.0; + } else if (x < 10.0) { + while (x > 2.0) { + x -= 1.0; + y += 1.0 / x; + } + } + if ((1.0 <= x) && (x <= 2.0)) { + y += detail::digamma_imp_1_2(x); + return y; + } + + /* x is large, use the asymptotic series */ + y += detail::psi_asy(x); + return y; + } +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/trig.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/trig.h new file mode 100644 index 0000000000000000000000000000000000000000..26a3cf8ad7e5a29ee433cf95c2747b5054854cdd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/trig.h @@ -0,0 +1,56 @@ +/* Translated into C++ by SciPy developers in 2024. + * + * Original author: Josh Wilson, 2020. + */ + +/* + * Implement sin(pi * x) and cos(pi * x) for real x. Since the periods + * of these functions are integral (and thus representable in double + * precision), it's possible to compute them with greater accuracy + * than sin(x) and cos(x). + */ +#pragma once + +#include "../config.h" + +namespace special { +namespace cephes { + + /* Compute sin(pi * x). */ + SPECFUN_HOST_DEVICE double sinpi(double x) { + double s = 1.0; + + if (x < 0.0) { + x = -x; + s = -1.0; + } + + double r = fmod(x, 2.0); + if (r < 0.5) { + return s * sin(M_PI * r); + } else if (r > 1.5) { + return s * sin(M_PI * (r - 2.0)); + } else { + return -s * sin(M_PI * (r - 1.0)); + } + } + + /* Compute cos(pi * x) */ + SPECFUN_HOST_DEVICE double cospi(double x) { + if (x < 0.0) { + x = -x; + } + + double r = fmod(x, 2.0); + if (r == 0.5) { + // We don't want to return -0.0 + return 0.0; + } + if (r < 1.0) { + return -sin(M_PI * (r - 0.5)); + } else { + return sin(M_PI * (r - 1.5)); + } + } +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/zeta.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/zeta.h new file mode 100644 index 0000000000000000000000000000000000000000..6246865d469fcc86122dd28e056e8eea6c14d2cd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/cephes/zeta.h @@ -0,0 +1,172 @@ +/* Translated into C++ by SciPy developers in 2024. + * Original header with Copyright information appears below. + */ + +/* zeta.c + * + * Riemann zeta function of two arguments + * + * + * + * SYNOPSIS: + * + * double x, q, y, zeta(); + * + * y = zeta( x, q ); + * + * + * + * DESCRIPTION: + * + * + * + * inf. + * - -x + * zeta(x,q) = > (k+q) + * - + * k=0 + * + * where x > 1 and q is not a negative integer or zero. + * The Euler-Maclaurin summation formula is used to obtain + * the expansion + * + * n + * - -x + * zeta(x,q) = > (k+q) + * - + * k=1 + * + * 1-x inf. B x(x+1)...(x+2j) + * (n+q) 1 - 2j + * + --------- - ------- + > -------------------- + * x-1 x - x+2j+1 + * 2(n+q) j=1 (2j)! (n+q) + * + * where the B2j are Bernoulli numbers. Note that (see zetac.c) + * zeta(x,1) = zetac(x) + 1. + * + * + * + * ACCURACY: + * + * + * + * REFERENCE: + * + * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals, + * Series, and Products, p. 1073; Academic Press, 1980. + * + */ + +/* + * Cephes Math Library Release 2.0: April, 1987 + * Copyright 1984, 1987 by Stephen L. Moshier + * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 + */ +#pragma once + +#include "../config.h" +#include "../error.h" +#include "const.h" + +namespace special { +namespace cephes { + + namespace detail { + /* Expansion coefficients + * for Euler-Maclaurin summation formula + * (2k)! / B2k + * where B2k are Bernoulli numbers + */ + constexpr double zeta_A[] = { + 12.0, + -720.0, + 30240.0, + -1209600.0, + 47900160.0, + -1.8924375803183791606e9, /*1.307674368e12/691 */ + 7.47242496e10, + -2.950130727918164224e12, /*1.067062284288e16/3617 */ + 1.1646782814350067249e14, /*5.109094217170944e18/43867 */ + -4.5979787224074726105e15, /*8.028576626982912e20/174611 */ + 1.8152105401943546773e17, /*1.5511210043330985984e23/854513 */ + -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091 */ + }; + + /* 30 Nov 86 -- error in third coefficient fixed */ + } // namespace detail + + SPECFUN_HOST_DEVICE double zeta(double x, double q) { + int i; + double a, b, k, s, t, w; + + if (x == 1.0) + goto retinf; + + if (x < 1.0) { + domerr: + set_error("zeta", SF_ERROR_DOMAIN, NULL); + return (std::numeric_limits::quiet_NaN()); + } + + if (q <= 0.0) { + if (q == floor(q)) { + set_error("zeta", SF_ERROR_SINGULAR, NULL); + retinf: + return (std::numeric_limits::infinity()); + } + if (x != std::floor(x)) + goto domerr; /* because q^-x not defined */ + } + + /* Asymptotic expansion + * https://dlmf.nist.gov/25.11#E43 + */ + if (q > 1e8) { + return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x); + } + + /* Euler-Maclaurin summation formula */ + + /* Permit negative q but continue sum until n+q > +9 . + * This case should be handled by a reflection formula. + * If q<0 and x is an integer, there is a relation to + * the polyGamma function. + */ + s = std::pow(q, -x); + a = q; + i = 0; + b = 0.0; + while ((i < 9) || (a <= 9.0)) { + i += 1; + a += 1.0; + b = std::pow(a, -x); + s += b; + if (std::abs(b / s) < detail::MACHEP) + goto done; + } + + w = a; + s += b * w / (x - 1.0); + s -= 0.5 * b; + a = 1.0; + k = 0.0; + for (i = 0; i < 12; i++) { + a *= x + k; + b /= w; + t = a * b / detail::zeta_A[i]; + s = s + t; + t = std::abs(t / s); + if (t < detail::MACHEP) + goto done; + k += 1.0; + a *= x + k; + b /= w; + k += 1.0; + } + done: + return (s); + } + +} // namespace cephes +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/config.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/config.h new file mode 100644 index 0000000000000000000000000000000000000000..aa899f0b4c0c2ae8166071f829970f7753b3348a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/config.h @@ -0,0 +1,158 @@ +#pragma once + +// Define math constants if they are not available +#ifndef M_E +#define M_E 2.71828182845904523536 +#endif + +#ifndef M_LOG2E +#define M_LOG2E 1.44269504088896340736 +#endif + +#ifndef M_LOG10E +#define M_LOG10E 0.434294481903251827651 +#endif + +#ifndef M_LN2 +#define M_LN2 0.693147180559945309417 +#endif + +#ifndef M_LN10 +#define M_LN10 2.30258509299404568402 +#endif + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#ifndef M_PI_2 +#define M_PI_2 1.57079632679489661923 +#endif + +#ifndef M_PI_4 +#define M_PI_4 0.785398163397448309616 +#endif + +#ifndef M_1_PI +#define M_1_PI 0.318309886183790671538 +#endif + +#ifndef M_2_PI +#define M_2_PI 0.636619772367581343076 +#endif + +#ifndef M_2_SQRTPI +#define M_2_SQRTPI 1.12837916709551257390 +#endif + +#ifndef M_SQRT2 +#define M_SQRT2 1.41421356237309504880 +#endif + +#ifndef M_SQRT1_2 +#define M_SQRT1_2 0.707106781186547524401 +#endif + +#ifdef __CUDACC__ +#define SPECFUN_HOST_DEVICE __host__ __device__ + +#include +#include + +// Fallback to global namespace for functions unsupported on NVRTC Jit +#ifdef _LIBCUDACXX_COMPILER_NVRTC +#include +#endif + +namespace std { + +SPECFUN_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); } + +SPECFUN_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); } + +SPECFUN_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); } + +SPECFUN_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); } + +SPECFUN_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); } + +SPECFUN_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); } + +SPECFUN_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); } + +SPECFUN_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); } + +SPECFUN_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); } + +SPECFUN_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); } + +SPECFUN_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); } + +SPECFUN_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); } + +// Fallback to global namespace for functions unsupported on NVRTC +#ifndef _LIBCUDACXX_COMPILER_NVRTC +SPECFUN_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); } +SPECFUN_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); } +SPECFUN_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); } +SPECFUN_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); } +SPECFUN_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); } +SPECFUN_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); } + +#else +SPECFUN_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); } +SPECFUN_HOST_DEVICE inline double floor(double x) { return ::floor(x); } +SPECFUN_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); } +SPECFUN_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); } +SPECFUN_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); } +SPECFUN_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); } +#endif + +template +using numeric_limits = cuda::std::numeric_limits; + +// Must use thrust for complex types in order to support CuPy +template +using complex = thrust::complex; + +template +SPECFUN_HOST_DEVICE T abs(const complex &z) { + return thrust::abs(z); +} + +template +SPECFUN_HOST_DEVICE complex exp(const complex &z) { + return thrust::exp(z); +} + +template +SPECFUN_HOST_DEVICE complex log(const complex &z) { + return thrust::log(z); +} + +template +SPECFUN_HOST_DEVICE T norm(const complex &z) { + return thrust::norm(z); +} + +template +SPECFUN_HOST_DEVICE complex sqrt(const complex &z) { + return thrust::sqrt(z); +} + +template +SPECFUN_HOST_DEVICE complex conj(const complex &z) { + return thrust::conj(z); +} + +} // namespace std + +#else +#define SPECFUN_HOST_DEVICE + +#include +#include +#include +#include + +#endif diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/digamma.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/digamma.h new file mode 100644 index 0000000000000000000000000000000000000000..e7cd669c12cef0e0024c18a81ad3c44d1f2121d3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/digamma.h @@ -0,0 +1,198 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header comment appears below. + */ + +/* An implementation of the digamma function for complex arguments. + * + * Author: Josh Wilson + * + * Distributed under the same license as Scipy. + * + * Sources: + * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov + * + * [2] mpmath (version 0.19), http://mpmath.org + */ + +#pragma once + +#include "cephes/psi.h" +#include "cephes/zeta.h" +#include "config.h" +#include "error.h" +#include "trig.h" + +namespace special { +namespace detail { + // All of the following were computed with mpmath + // Location of the positive root + constexpr double digamma_posroot = 1.4616321449683623; + // Value of the positive root + constexpr double digamma_posrootval = -9.2412655217294275e-17; + // Location of the negative root + constexpr double digamma_negroot = -0.504083008264455409; + // Value of the negative root + constexpr double digamma_negrootval = 7.2897639029768949e-17; + + template + SPECFUN_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) { + T res = rootval; + T coeff = -1.0; + + z = z - root; + T term; + for (int n = 1; n < 100; n++) { + coeff *= -z; + term = coeff * cephes::zeta(n + 1, root); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + + SPECFUN_HOST_DEVICE inline std::complex digamma_forward_recurrence(std::complex z, + std::complex psiz, int n) { + /* Compute digamma(z + n) using digamma(z) using the recurrence + * relation + * + * digamma(z + 1) = digamma(z) + 1/z. + * + * See https://dlmf.nist.gov/5.5#E2 */ + std::complex res = psiz; + + for (int k = 0; k < n; k++) { + res += 1.0 / (z + static_cast(k)); + } + return res; + } + + SPECFUN_HOST_DEVICE inline std::complex digamma_backward_recurrence(std::complex z, + std::complex psiz, int n) { + /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */ + std::complex res = psiz; + + for (int k = 1; k < n + 1; k++) { + res -= 1.0 / (z - static_cast(k)); + } + return res; + } + + SPECFUN_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) { + /* Evaluate digamma using an asymptotic series. See + * + * https://dlmf.nist.gov/5.11#E2 */ + double bernoulli2k[] = { + 0.166666666666666667, -0.0333333333333333333, 0.0238095238095238095, -0.0333333333333333333, + 0.0757575757575757576, -0.253113553113553114, 1.16666666666666667, -7.09215686274509804, + 54.9711779448621554, -529.124242424242424, 6192.12318840579710, -86580.2531135531136, + 1425517.16666666667, -27298231.0678160920, 601580873.900642368, -15116315767.0921569}; + std::complex rzz = 1.0 / z / z; + std::complex zfac = 1.0; + std::complex term; + std::complex res; + + if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) { + /* Check for infinity (or nan) and return early. + * Result of division by complex infinity is implementation dependent. + * and has been observed to vary between C++ stdlib and CUDA stdlib. + */ + return std::log(z); + } + + res = std::log(z) - 0.5 / z; + + for (int k = 1; k < 17; k++) { + zfac *= rzz; + term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k)); + res += term; + if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) { + break; + } + } + return res; + } + +} // namespace detail + +SPECFUN_HOST_DEVICE inline double digamma(double z) { + /* Wrap Cephes' psi to take advantage of the series expansion around + * the smallest negative zero. + */ + if (std::abs(z - detail::digamma_negroot) < 0.3) { + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + return cephes::psi(z); +} + +SPECFUN_HOST_DEVICE inline std::complex digamma(std::complex z) { + /* + * Compute the digamma function for complex arguments. The strategy + * is: + * + * - Around the two zeros closest to the origin (posroot and negroot) + * use a Taylor series with precomputed zero order coefficient. + * - If close to the origin, use a recurrence relation to step away + * from the origin. + * - If close to the negative real axis, use the reflection formula + * to move to the right halfplane. + * - If |z| is large (> 16), use the asymptotic series. + * - If |z| is small, use a recurrence relation to make |z| large + * enough to use the asymptotic series. + */ + double absz = std::abs(z); + std::complex res = 0; + /* Use the asymptotic series for z away from the negative real axis + * with abs(z) > smallabsz. */ + int smallabsz = 16; + /* Use the reflection principle for z with z.real < 0 that are within + * smallimag of the negative real axis. + * int smallimag = 6 # unused below except in a comment */ + + if (z.real() <= 0.0 && std::ceil(z.real()) == z) { + // Poles + set_error("digamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (std::abs(z - detail::digamma_negroot) < 0.3) { + // First negative root. + return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval); + } + + if (z.real() < 0 and std::abs(z.imag()) < smallabsz) { + /* Reflection formula for digamma. See + * + *https://dlmf.nist.gov/5.5#E4 + */ + res = -M_PI * cospi(z) / sinpi(z); + z = 1.0 - z; + absz = std::abs(z); + } + + if (absz < 0.5) { + /* Use one step of the recurrence relation to step away from + * the pole. */ + res = -1.0 / z; + z += 1.0; + absz = std::abs(z); + } + + if (std::abs(z - detail::digamma_posroot) < 0.5) { + res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval); + } else if (absz > smallabsz) { + res += detail::digamma_asymptotic_series(z); + } else if (z.real() >= 0.0) { + double n = std::trunc(smallabsz - absz) + 1; + std::complex init = detail::digamma_asymptotic_series(z + n); + res += detail::digamma_backward_recurrence(z + n, init, n); + } else { + // z.real() < 0, absz < smallabsz, and z.imag() > smallimag + double n = std::trunc(smallabsz - absz) - 1; + std::complex init = detail::digamma_asymptotic_series(z - n); + res += detail::digamma_forward_recurrence(z - n, init, n); + } + return res; +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/error.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/error.h new file mode 100644 index 0000000000000000000000000000000000000000..11b80605881402395ce91a045efb495dac696804 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/error.h @@ -0,0 +1,42 @@ +#pragma once + +// should be included from config.h, but that won't work until we've cleanly separated out the C and C++ parts of the +// code +#ifdef __CUDACC__ +#define SPECFUN_HOST_DEVICE __host__ __device__ +#else +#define SPECFUN_HOST_DEVICE +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SF_ERROR_OK = 0, /* no error */ + SF_ERROR_SINGULAR, /* singularity encountered */ + SF_ERROR_UNDERFLOW, /* floating point underflow */ + SF_ERROR_OVERFLOW, /* floating point overflow */ + SF_ERROR_SLOW, /* too many iterations required */ + SF_ERROR_LOSS, /* loss of precision */ + SF_ERROR_NO_RESULT, /* no result obtained */ + SF_ERROR_DOMAIN, /* out of domain */ + SF_ERROR_ARG, /* invalid input parameter */ + SF_ERROR_OTHER, /* unclassified error */ + SF_ERROR__LAST +} sf_error_t; + +#ifdef __cplusplus +namespace special { + +#ifndef SP_SPECFUN_ERROR + SPECFUN_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) { + // nothing + } +#else + void set_error(const char *func_name, sf_error_t code, const char *fmt, ...); +#endif +} // namespace special + +} // closes extern "C" +#endif diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/evalpoly.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/evalpoly.h new file mode 100644 index 0000000000000000000000000000000000000000..0fcd162b58878e604185b0d2311816c963e63a0c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/evalpoly.h @@ -0,0 +1,47 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * + * Original author: Josh Wilson, 2016. + */ + +/* Evaluate polynomials. + * + * All of the coefficients are stored in reverse order, i.e. if the + * polynomial is + * + * u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0, + * + * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0. + * + * References + * ---------- + * [1] Knuth, "The Art of Computer Programming, Volume II" + */ + +#pragma once + +#include "config.h" + +namespace special { + +SPECFUN_HOST_DEVICE inline std::complex cevalpoly(const double *coeffs, int degree, std::complex z) { + /* Evaluate a polynomial with real coefficients at a complex point. + * + * Uses equation (3) in section 4.6.4 of [1]. Note that it is more + * efficient than Horner's method. + */ + double a = coeffs[0]; + double b = coeffs[1]; + double r = 2 * z.real(); + double s = std::norm(z); + double tmp; + + for (int j = 2; j < degree + 1; j++) { + tmp = b; + b = std::fma(-s, a, coeffs[j]); + a = std::fma(r, a, tmp); + } + + return z * a + b; +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/lambertw.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/lambertw.h new file mode 100644 index 0000000000000000000000000000000000000000..10d2c7a273f4756cb8b412cafa545c23927f9354 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/lambertw.h @@ -0,0 +1,145 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * Original header with Copyright information appears below. + */ + +/* Implementation of the Lambert W function [1]. Based on MPMath + * Implementation [2], and documentation [3]. + * + * Copyright: Yosef Meller, 2009 + * Author email: mellerf@netvision.net.il + * + * Distributed under the same license as SciPy + * + * + * References: + * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359, + * available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf + * [2] mpmath source code, + https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461 + * [3] + https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function + * + + * TODO: use a series expansion when extremely close to the branch point + * at `-1/e` and make sure that the proper branch is chosen there. + */ + +#pragma once + +#include "config.h" +#include "error.h" +#include "evalpoly.h" + +namespace special { +constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1) +constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0) + +namespace detail { + SPECFUN_HOST_DEVICE inline std::complex lambertw_branchpt(std::complex z) { + // Series for W(z, 0) around the branch point; see 4.22 in [1]. + double coeffs[] = {-1.0 / 3.0, 1.0, -1.0}; + std::complex p = std::sqrt(2.0 * (M_E * z + 1.0)); + + return cevalpoly(coeffs, 2, p); + } + + SPECFUN_HOST_DEVICE inline std::complex lambertw_pade0(std::complex z) { + // (3, 2) Pade approximation for W(z, 0) around 0. + double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0}; + double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0}; + + /* This only gets evaluated close to 0, so we don't need a more + * careful algorithm that avoids overflow in the numerator for + * large z. */ + return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z); + } + + SPECFUN_HOST_DEVICE inline std::complex lambertw_asy(std::complex z, long k) { + /* Compute the W function using the first two terms of the + * asymptotic series. See 4.20 in [1]. + */ + std::complex w = std::log(z) + 2.0 * M_PI * k * std::complex(0, 1); + return w - std::log(w); + } + +} // namespace detail + +SPECFUN_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, double tol) { + double absz; + std::complex w; + std::complex ew, wew, wewz, wn; + + if (std::isnan(z.real()) || std::isnan(z.imag())) { + return z; + } + if (z.real() == std::numeric_limits::infinity()) { + return z + 2.0 * M_PI * k * std::complex(0, 1); + } + if (z.real() == -std::numeric_limits::infinity()) { + return -z + (2.0 * M_PI * k + M_PI) * std::complex(0, 1); + } + if (z == 0.0) { + if (k == 0) { + return z; + } + set_error("lambertw", SF_ERROR_SINGULAR, NULL); + return -std::numeric_limits::infinity(); + } + if (z == 1.0 && k == 0) { + // Split out this case because the asymptotic series blows up + return OMEGA; + } + + absz = std::abs(z); + // Get an initial guess for Halley's method + if (k == 0) { + if (std::abs(z + EXPN1) < 0.3) { + w = detail::lambertw_branchpt(z); + } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 && + -2.5 * std::abs(z.imag()) - 0.2 < z.real()) { + /* Empirically determined decision boundary where the Pade + * approximation is more accurate. */ + w = detail::lambertw_pade0(z); + } else { + w = detail::lambertw_asy(z, k); + } + } else if (k == -1) { + if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) { + w = std::log(-z.real()); + } else { + w = detail::lambertw_asy(z, k); + } + } else { + w = detail::lambertw_asy(z, k); + } + + // Halley's method; see 5.9 in [1] + if (w.real() >= 0) { + // Rearrange the formula to avoid overflow in exp + for (int i = 0; i < 100; i++) { + ew = std::exp(-w); + wewz = w - z * ew; + wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0)); + if (std::abs(wn - w) <= tol * std::abs(wn)) { + return wn; + } + w = wn; + } + } else { + for (int i = 0; i < 100; i++) { + ew = std::exp(w); + wew = w * ew; + wewz = wew - z; + wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0)); + if (std::abs(wn - w) <= tol * std::abs(wn)) { + return wn; + } + w = wn; + } + } + + set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag()); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/loggamma.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/loggamma.h new file mode 100644 index 0000000000000000000000000000000000000000..02b27873f57da735c1d6b3bbce592e7315412d3c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/loggamma.h @@ -0,0 +1,158 @@ +/* Translated from Cython into C++ by SciPy developers in 2024. + * Original header comment appears below. + */ + +/* An implementation of the principal branch of the logarithm of + * Gamma. Also contains implementations of Gamma and 1/Gamma which are + * easily computed from log-Gamma. + * + * Author: Josh Wilson + * + * Distributed under the same license as Scipy. + * + * References + * ---------- + * [1] Hare, "Computing the Principal Branch of log-Gamma", + * Journal of Algorithms, 1997. + * + * [2] Julia, + * https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl + */ + +#pragma once + +#include "cephes/gamma.h" +#include "config.h" +#include "error.h" +#include "evalpoly.h" +#include "trig.h" +#include "zlog1.h" + +namespace special { + +namespace detail { + constexpr double loggamma_SMALLX = 7; + constexpr double loggamma_SMALLY = 7; + constexpr double loggamma_HLOG2PI = 0.918938533204672742; // log(2*pi)/2 + constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi) + constexpr double loggamma_TAYLOR_RADIUS = 0.2; + + SPECFUN_HOST_DEVICE std::complex loggamma_stirling(std::complex z) { + /* Stirling series for log-Gamma + * + * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the + * (2*n)th Bernoulli number. See (1.1) in [1]. + */ + double coeffs[] = {-2.955065359477124183E-2, 6.4102564102564102564E-3, -1.9175269175269175269E-3, + 8.4175084175084175084E-4, -5.952380952380952381E-4, 7.9365079365079365079E-4, + -2.7777777777777777778E-3, 8.3333333333333333333E-2}; + std::complex rz = 1.0 / z; + std::complex rzz = rz / z; + + return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz); + } + + SPECFUN_HOST_DEVICE std::complex loggamma_recurrence(std::complex z) { + /* Backward recurrence relation. + * + * See Proposition 2.2 in [1] and the Julia implementation [2]. + * + */ + int signflips = 0; + int sb = 0; + std::complex shiftprod = z; + + z += 1.0; + int nsb; + while (z.real() <= loggamma_SMALLX) { + shiftprod *= z; + nsb = std::signbit(shiftprod.imag()); + signflips += nsb != 0 && sb == 0 ? 1 : 0; + sb = nsb; + z += 1.0; + } + return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex(0, 1); + } + + SPECFUN_HOST_DEVICE std::complex loggamma_taylor(std::complex z) { + /* Taylor series for log-Gamma around z = 1. + * + * It is + * + * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ... + * + * where gamma is the Euler-Mascheroni constant. + */ + + double coeffs[] = { + -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2, + -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2, + -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2, + -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1, + -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1, + -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1}; + + z -= 1.0; + return z * cevalpoly(coeffs, 22, z); + } +} // namespace detail + +SPECFUN_HOST_DEVICE inline double loggamma(double x) { + if (x < 0.0) { + return std::numeric_limits::quiet_NaN(); + } + return cephes::lgam(x); +} + +SPECFUN_HOST_DEVICE inline std::complex loggamma(std::complex z) { + // Compute the principal branch of log-Gamma + + if (std::isnan(z.real()) || std::isnan(z.imag())) { + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (z.real() <= 0 and z == std::floor(z.real())) { + set_error("loggamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) { + return detail::loggamma_stirling(z); + } + if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) { + return detail::loggamma_taylor(z); + } + if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) { + // Recurrence relation and the Taylor series around 1. + return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0); + } + if (z.real() < 0.1) { + // Reflection formula; see Proposition 3.1 in [1] + double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25); + return std::complex(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z); + } + if (std::signbit(z.imag()) == 0) { + // z.imag() >= 0 but is not -0.0 + return detail::loggamma_recurrence(z); + } + return std::conj(detail::loggamma_recurrence(std::conj(z))); +} + +SPECFUN_HOST_DEVICE inline std::complex gamma(std::complex z) { + // Compute Gamma(z) using loggamma. + if (z.real() <= 0 && z == std::floor(z.real())) { + // Poles + set_error("gamma", SF_ERROR_SINGULAR, NULL); + return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()}; + } + return std::exp(loggamma(z)); +} + +SPECFUN_HOST_DEVICE inline std::complex rgamma(std::complex z) { + // Compute 1/Gamma(z) using loggamma. + if (z.real() <= 0 && z == std::floor(z.real())) { + // Zeros at 0, -1, -2, ... + return 0.0; + } + return std::exp(-loggamma(z)); +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/trig.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/trig.h new file mode 100644 index 0000000000000000000000000000000000000000..ea8754428b04f6f4b627111385ace697d2eb63f4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/trig.h @@ -0,0 +1,99 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * + * Original author: Josh Wilson, 2016. + */ + +/* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods + * of these functions are integral (and thus better representable in + * floating point), it's possible to compute them with greater accuracy + * than sin(z), cos(z). + */ + +#pragma once + +#include "cephes/trig.h" +#include "config.h" +#include "evalpoly.h" + +namespace special { + +SPECFUN_HOST_DEVICE inline std::complex sinpi(std::complex z) { + double x = z.real(); + double piy = M_PI * z.imag(); + double abspiy = std::abs(piy); + double sinpix = cephes::sinpi(x); + double cospix = cephes::cospi(x); + + if (abspiy < 700) { + return {sinpix * std::cosh(piy), cospix * std::sinh(piy)}; + } + + /* Have to be careful--sinh/cosh could overflow while cos/sin are small. + * At this large of values + * + * cosh(y) ~ exp(y)/2 + * sinh(y) ~ sgn(y)*exp(y)/2 + * + * so we can compute exp(y/2), scale by the right factor of sin/cos + * and then multiply by exp(y/2) to avoid overflow. */ + double exphpiy = std::exp(abspiy / 2); + double coshfac; + double sinhfac; + if (exphpiy == std::numeric_limits::infinity()) { + if (sinpix == 0.0) { + // Preserve the sign of zero. + coshfac = std::copysign(0.0, sinpix); + } else { + coshfac = std::copysign(std::numeric_limits::infinity(), sinpix); + } + if (cospix == 0.0) { + // Preserve the sign of zero. + sinhfac = std::copysign(0.0, cospix); + } else { + sinhfac = std::copysign(std::numeric_limits::infinity(), cospix); + } + return {coshfac, sinhfac}; + } + + coshfac = 0.5 * sinpix * exphpiy; + sinhfac = 0.5 * cospix * exphpiy; + return {coshfac * exphpiy, sinhfac * exphpiy}; +} + +SPECFUN_HOST_DEVICE inline std::complex cospi(std::complex z) { + double x = z.real(); + double piy = M_PI * z.imag(); + double abspiy = std::abs(piy); + double sinpix = cephes::sinpi(x); + double cospix = cephes::cospi(x); + + if (abspiy < 700) { + return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)}; + } + + // See csinpi(z) for an idea of what's going on here. + double exphpiy = std::exp(abspiy / 2); + double coshfac; + double sinhfac; + if (exphpiy == std::numeric_limits::infinity()) { + if (sinpix == 0.0) { + // Preserve the sign of zero. + coshfac = std::copysign(0.0, cospix); + } else { + coshfac = std::copysign(std::numeric_limits::infinity(), cospix); + } + if (cospix == 0.0) { + // Preserve the sign of zero. + sinhfac = std::copysign(0.0, sinpix); + } else { + sinhfac = std::copysign(std::numeric_limits::infinity(), sinpix); + } + return {coshfac, sinhfac}; + } + + coshfac = 0.5 * cospix * exphpiy; + sinhfac = 0.5 * sinpix * exphpiy; + return {coshfac * exphpiy, sinhfac * exphpiy}; +} + +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/special/zlog1.h b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/zlog1.h new file mode 100644 index 0000000000000000000000000000000000000000..37a23f1387babe4dbbf6963cb348dec6a9b9c4f4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/special/zlog1.h @@ -0,0 +1,35 @@ +/* Translated from Cython into C++ by SciPy developers in 2023. + * + * Original author: Josh Wilson, 2016. + */ + +#pragma once + +#include "config.h" + +namespace special { +namespace detail { + + SPECFUN_HOST_DEVICE inline std::complex zlog1(std::complex z) { + /* Compute log, paying special attention to accuracy around 1. We + * implement this ourselves because some systems (most notably the + * Travis CI machines) are weak in this regime. */ + std::complex coeff = -1.0; + std::complex res = 0.0; + + if (std::abs(z - 1.0) > 0.1) { + return std::log(z); + } + + z -= 1.0; + for (int n = 1; n < 17; n++) { + coeff *= -z; + res += coeff / static_cast(n); + if (std::abs(res / coeff) < std::numeric_limits::epsilon()) { + break; + } + } + return res; + } +} // namespace detail +} // namespace special diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bc803dd91cc1aad08cb6d746e2145cb876f8bb8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_loggamma.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a106f2c8020877ffbfaa2029d352e0b453dba5c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/__pycache__/test_orthogonal.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/boost.npz b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/boost.npz new file mode 100644 index 0000000000000000000000000000000000000000..a3cba7656ee5445c3c94b8695f526de05973cadf --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/boost.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d73ecbbb51654522342ba0470a6263a9684e617c2b8374565fe3a79593f4b231 +size 1270643 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/local.npz b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/local.npz new file mode 100644 index 0000000000000000000000000000000000000000..7a1d159f5fa6dc3c5521bda8cf3049ee24945857 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special/tests/data/local.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:102b876c27ec4d2f8041d5ab2fb6dfefc8147021335160f515455e53e06871ff +size 203438