libpysal.cg.distance_matrix

libpysal.cg.distance_matrix(X, p=2.0, threshold=50000000.0)[source]

Calculate a distance matrix.

Parameters:
Xnumpy.ndarray

An \(n \\times k\) array where \(n\) is the number of observations and \(k\) is the number of dimensions (2 for \(x,y\)).

pfloat

Minkowski p-norm distance metric parameter where \(1<=\mathtt{p}<=\infty\). 2 is Euclidean distance and 1 is Manhattan distance. Default is 2.0.

thresholdint

If \((\mathtt{n}**2)*32 > \mathtt{threshold}\) use scipy.spatial.distance_matrix instead of working in RAM, this is roughly the amount of RAM (in bytes) that will be used. Must be positive. Default is 5e7.

Returns:
dnumpy.ndarray

An n by \(m\) \(p\)-norm distance matrix.

Raises:
TypeError

Raised when an invalid dimensional array is passed in.

Notes

Needs optimization/integration with other weights in PySAL.

Examples

>>> x, y = [r.flatten() for r in np.indices((3, 3))]
>>> data = np.array([x, y]).T
>>> d = distance_matrix(data)
>>> np.array(d)
array([[0.        , 1.        , 2.        , 1.        , 1.41421356,
        2.23606798, 2.        , 2.23606798, 2.82842712],
       [1.        , 0.        , 1.        , 1.41421356, 1.        ,
        1.41421356, 2.23606798, 2.        , 2.23606798],
       [2.        , 1.        , 0.        , 2.23606798, 1.41421356,
        1.        , 2.82842712, 2.23606798, 2.        ],
       [1.        , 1.41421356, 2.23606798, 0.        , 1.        ,
        2.        , 1.        , 1.41421356, 2.23606798],
       [1.41421356, 1.        , 1.41421356, 1.        , 0.        ,
        1.        , 1.41421356, 1.        , 1.41421356],
       [2.23606798, 1.41421356, 1.        , 2.        , 1.        ,
        0.        , 2.23606798, 1.41421356, 1.        ],
       [2.        , 2.23606798, 2.82842712, 1.        , 1.41421356,
        2.23606798, 0.        , 1.        , 2.        ],
       [2.23606798, 2.        , 2.23606798, 1.41421356, 1.        ,
        1.41421356, 1.        , 0.        , 1.        ],
       [2.82842712, 2.23606798, 2.        , 2.23606798, 1.41421356,
        1.        , 2.        , 1.        , 0.        ]])