This is a pre-release version (2.0.0.dev0+git20260907.41eeb59).Go to latest (1.18.0)
{ } Raw JSON

bundles / scipy 2.0.0.dev0+git20260907.41eeb59 / 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 : cKDTree

The other KDTree to compute distances against.

max_distance : positive float

Maximum distance within which neighbors are returned. Distances above this value are returned as zero.

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 : str, optional

Which 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 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 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.11603, 0.     , 0.     ],
       [0.     , 0.     , 0.     , 0.     , 0.     ],
       [0.24287, 0.26248, 0.     , 0.     , 0.     ],
       [0.     , 0.     , 0.13636, 0.     , 0.     ],
       [0.     , 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.9595 , 0.8948 , 0.11603, 0.66051, 0.35869],
       [0.42885, 0.56871, 0.71481, 0.68005, 0.40827],
       [0.24287, 0.26248, 0.71725, 0.43233, 0.605  ],
       [0.94969, 0.81421, 0.13636, 0.50014, 0.56379],
       [1.06841, 0.87597, 0.38201, 0.50638, 0.8128 ]])

Aliases

  • scipy.spatial.cKDTree.sparse_distance_matrix