bundles / scipy 1.18.0 / scipy / spatial / _ckdtree / cKDTree / sparse_distance_matrix
cython_function_or_method
scipy.spatial._ckdtree:cKDTree.sparse_distance_matrix
Signature
def sparse_distance_matrix(other, max_distance, p = 2.0, output_type = dok_matrix)Summary
Compute a sparse distance matrix
Extended Summary
Computes a distance matrix between two cKDTrees, leaving as zero any distance greater than max_distance.
Parameters
other: cKDTreeThe other KDTree to compute distances against.
max_distance: positive floatMaximum distance within which neighbors are returned. Distances above this value are returned as zero.
p: float, 1<=p<=infinityWhich Minkowski p-norm to use. A finite large p may cause a ValueError if overflow can occur.
output_type: str, optionalWhich container to use for output data. Options:
'dok_array','coo_array','dict', or'ndarray'. Legacy options'dok_matrix'and'coo_matrix'are still available. Default:'dok_matrix'.
Returns
result: dok_array, coo_array, dict or ndarraySparse 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 cKDTree rng = np.random.default_rng() points1 = rng.random((5, 2)) points2 = rng.random((5, 2)) kdtree1 = cKDTree(points1) kdtree2 = cKDTree(points2) sdm = kdtree1.sparse_distance_matrix(kdtree2, 0.3, output_type="dok_array")✓
sdm.toarray()
✗array([[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0. ],
[0.16705, 0. , 0. , 0. , 0. ]])
You can check distances above the `max_distance` are zeros:
from scipy.spatial.distance import cdist
✓cdist(points1, points2)
✗array([[0.38065, 0.78542, 0.44928, 0.39562, 0.5381 ],
[0.38275, 0.40985, 0.44793, 0.67419, 0.46706],
[0.78963, 0.99555, 0.57206, 0.30512, 0.64905],
[0.60485, 0.9141 , 0.51235, 0.31829, 0.6001 ],
[0.16705, 0.66419, 0.61616, 0.76776, 0.6628 ]])
Aliases
scipy.spatial.cKDTree.sparse_distance_matrix