libpysal.weights.fill_diagonal

libpysal.weights.fill_diagonal(w, val=1.0, wsp=False)[source]

Returns a new weights object with values inserted along the main diagonal.

Parameters:
wW

Spatial weights object

diagonalfloat, int or array

Defines the value(s) to which the weights matrix diagonal should be set. If a constant is passed then each element along the diagonal will get this value (default is 1.0). An array of length w.n can be passed to set explicit values to each element along the diagonal (assumed to be in the same order as w.id_order).

wspbool

If True return a thin weights object of the type WSP, if False return the standard W object.

Returns:
wW

Spatial weights object

Examples

>>> from libpysal.weights import lat2W
>>> import numpy as np

Build a basic rook weights matrix, which has zeros on the diagonal, then insert ones along the diagonal.

>>> w = lat2W(5, 5, id_type='string')
>>> w_const = insert_diagonal(w)
>>> w['id0'] ==  {'id5': 1.0, 'id1': 1.0}
True
>>> w_const['id0'] == {'id5': 1.0, 'id0': 1.0, 'id1': 1.0}
True

Insert different values along the main diagonal.

>>> diag = np.arange(100, 125)
>>> w_var = insert_diagonal(w, diag)
>>> w_var['id0'] == {'id5': 1.0, 'id0': 100.0, 'id1': 1.0}
True