SciPy

scipy.spatial.KDTree.sparse_distance_matrix

KDTree.sparse_distance_matrix(self, other, max_distance, p=2.0, output_type='dok_matrix')[source]

Compute a sparse distance matrix

Computes a distance matrix between two KDTrees, leaving as zero any distance greater than max_distance.

Parameters
otherKDTree
max_distancepositive float
pfloat, 1<=p<=infinity

Which Minkowski p-norm to use. A finite large p may cause a ValueError if overflow can occur.

output_typestring, optional

Which container to use for output data. Options: ‘dok_matrix’, ‘coo_matrix’, ‘dict’, or ‘ndarray’. Default: ‘dok_matrix’.

New in version 1.6.0.

Returns
resultdok_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
>>> np.random.seed(21701)
>>> points1 = np.random.random((5, 2))
>>> points2 = np.random.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.20220215, 0.14538496, 0.,         0.10257199, 0.        ],
    [0.13491385, 0.27251306, 0.,         0.18793787, 0.        ],
    [0.19262396, 0.,         0.,         0.25795122, 0.        ],
    [0.14859639, 0.07076002, 0.,         0.04065851, 0.        ],
    [0.17308768, 0.,         0.,         0.24823138, 0.        ]])

You can check distances above the max_distance are zeros:

>>> from scipy.spatial import distance_matrix
>>> distance_matrix(points1, points2)
array([[0.20220215, 0.14538496, 0.43588092, 0.10257199, 0.4555495 ],
    [0.13491385, 0.27251306, 0.65944131, 0.18793787, 0.68184154],
    [0.19262396, 0.34121593, 0.72176889, 0.25795122, 0.74538858],
    [0.14859639, 0.07076002, 0.48505773, 0.04065851, 0.50043591],
    [0.17308768, 0.32837991, 0.72760803, 0.24823138, 0.75017239]])

Previous topic

scipy.spatial.KDTree.query_pairs

Next topic

scipy.spatial.cKDTree