pysal

Table Of Contents

Previous topic

pysal.weights — Spatial Weights

This Page

weights — Spatial weights matrices for PySAL: Python Spatial Analysis Library

The weights Spatial weights for PySAL

New in version 1.0.

weights — Spatial Weights

class pysal.weights.W(neighbors, weights=None, id_order=None)

Spatial weights

Parameters:

neighbors : dictionary

key is region ID, value is a list of neighbor IDS Example: {‘a’:[‘b’],’b’:[‘a’,’c’],’c’:[‘b’]}

weights = None : dictionary

key is region ID, value is a list of edge weights If not supplied all edge wegiths are assumed to have a weight of 1. Example: {‘a’:[0.5],’b’:[0.5,1.5],’c’:[1.5]}

id_order = None : list

An ordered list of ids, defines the order of observations when iterating over W if not set, lexicographical ordering is used to iterate and the id_order_set property will return False. This can be set after creation by setting the ‘id_order’ property.

Examples

>>> from pysal import W
>>> neighbors={0: [3, 1], 1: [0, 4, 2], 2: [1, 5], 3: [0, 6, 4], 4: [1, 3, 7, 5], 5: [2, 4, 8], 6: [3, 7], 7: [4, 6, 8], 8: [5, 7]}
>>> weights={0: [1, 1], 1: [1, 1, 1], 2: [1, 1], 3: [1, 1, 1], 4: [1, 1, 1, 1], 5: [1, 1, 1], 6: [1, 1], 7: [1, 1, 1], 8: [1, 1]}
>>> w=W(neighbors,weights)
>>> w.pct_nonzero
0.29629629629629628

Read from external gal file

>>> import pysal
>>> w=pysal.open("../examples/stl.gal").read()
>>> w.n
78
>>> w.pct_nonzero
0.065417488494411577

Set weights implicitly

>>> neighbors={0: [3, 1], 1: [0, 4, 2], 2: [1, 5], 3: [0, 6, 4], 4: [1, 3, 7, 5], 5: [2, 4, 8], 6: [3, 7], 7: [4, 6, 8], 8: [5, 7]}
>>> w=W(neighbors)
>>> w.pct_nonzero
0.29629629629629628
>>> w=lat2W(100,100)
>>> w.trcW2
39600.0
>>> w.trcWtW
39600.0
>>> w.transform='r'
>>> w.trcW2
2530.7222222222586
>>> w.trcWtW
2533.6666666666774

Cardinality Histogram

>>> w=pysal.rook_from_shapefile("../examples/sacramentot2.shp")
>>> w.histogram
[(1, 1), (2, 6), (3, 33), (4, 106), (5, 114), (6, 70), (7, 35), (8, 17), (9, 9), (10, 4), (11, 4), (12, 3), (13, 0), (14, 1)]

Attributes

asymmetries
cardinalities
diagW2
diagWtW
diagWtW_WW
histogram
id2i
id_order
id_order_set
islands
max_neighbors
mean_neighbors
min_neighbors
n
neighbor_offsets
nonzero
pct_nonzero
s0
s1
s2
s2array
sd
sparse
trcW2
trcWtW
trcWtW_WW
transform

Methods

asymmetry
full
get_transform
higher_order
order
set_transform
shimbel
asymmetries
list of id pairs with asymmetric weights
asymmetry()

Checks for w_{i,j} == w_{j,i} forall i,j

Returns:

asymmetries : list

empty if no asymmetries are found if asymmetries, first list is row indices, second list is column indices of asymmetric cells

Examples

>>> from pysal import lat2W
>>> w=lat2W(3,3)
>>> w.asymmetry()
[]
>>> w.transform='r'
>>> w.asymmetry()
(array([1, 3, 0, 2, 4, 1, 5, 0, 4, 6, 1, 3, 5, 7, 2, 4, 8, 3, 7, 4, 6, 8, 5,
       7]), array([0, 0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8,
       8]))
>>> neighbors={0:[1,2,3], 1:[1,2,3], 2:[0,1], 3:[0,1]}
>>> weights={0:[1,1,1], 1:[1,1,1], 2:[1,1], 3:[1,1]}
>>> w=W(neighbors,weights)
>>> w.asymmetry()
(array([1, 0]), array([0, 1]))
cardinalities
number of neighbors for each observation : dict
diagW2

Diagonal of WW : array

See also

trcW2

diagWtW

Diagonal of W^{'}W : array

See also

trcWtW

diagWtW_WW
diagonal of W^{'}W + WW
full()

Generate a full numpy array

Returns:

implicit : tuple

first element being the full numpy array and second element keys being the ids associated with each row in the array.

See also

full

Examples

>>> from pysal import W
>>> neighbors={'first':['second'],'second':['first','third'],'third':['second']}
>>> weights={'first':[1],'second':[1,1],'third':[1]}
>>> w=W(neighbors,weights)
>>> wf,ids=w.full()
>>> wf
array([[ 0.,  1.,  0.],
       [ 1.,  0.,  1.],
       [ 0.,  1.,  0.]])
>>> ids
['first', 'second', 'third']
get_transform()

Getter for transform property

Returns:transformation : string (or none)

Examples

>>> from pysal import lat2W
>>> w=lat2W()
>>> w.weights[0]
[1.0, 1.0]
>>> w.transform
'O'
>>> w.transform='r'
>>> w.weights[0]
[0.5, 0.5]
>>> w.transform='b'
>>> w.weights[0]
[1.0, 1.0]
>>> 
higher_order(k=3)

Contiguity weights object of order k

Parameters:

k : int

order of contiguity

Returns:

implicit : W

spatial weights object

See also

higher_order

Notes

Implements the algorithm in Anselin and Smirnov (1996) [R6]

References

[R6](1, 2) Anselin, L. and O. Smirnov (1996) “Efficient algorithms for constructing proper higher order spatial lag operators. Journal of Regional Science, 36, 67-89.

Examples

>>> from pysal import lat2W
>>> w5=lat2W()
>>> w5_shimbel=w5.shimbel()
>>> w5_shimbel[0][24]
8
>>> w5_shimbel[0][0:4]
[-1, 1, 2, 3]
>>> w5_8th_order=w5.higher_order(8)
>>> w5_8th_order.neighbors[0]
[24]
>>> from pysal import rook_from_shapefile as rfs
>>> w=rfs('../examples/10740.shp')
>>> w2=w.higher_order(2)
>>> w[1]
{0: 1.0, 2: 1.0, 83: 1.0, 4: 1.0}
>>> w2[1]
{3: 1.0, 5: 1.0, 6: 1.0, 10: 1.0, 82: 1.0, 85: 1.0, 91: 1.0, 92: 1.0, 101: 1.0}
>>> w[147]
{144: 1.0, 146: 1.0, 164: 1.0, 165: 1.0, 150: 1.0}
>>> w[85]
{0: 1.0, 101: 1.0, 83: 1.0, 84: 1.0, 90: 1.0, 91: 1.0, 93: 1.0}
>>> 
histogram
cardinality histogram as a dictionary, key is the id, value is the number of neighbors for that unit
id2i
Dictionary where the key is an ID and the value is that ID’s index in W.id_order.
id_order
returns the ids for the observations in the order in which they would be encountered if iterating over the weights.
id_order_set

returns True if user has set id_order, False if not.

Examples

>>> from pysal import lat2W
>>> w=lat2W()
>>> w.id_order_set
True
islands
list of ids without any neighbors
max_neighbors
largest number of neighbors
mean_neighbors
average number of neighbors
min_neighbors
minimum number of neighbors
n
number of units
neighbor_offsets

Given the current id_order, neighbor_offsets[id] is the offsets of the id’s neighrbors in id_order

Examples

>>> from pysal import W
>>> neighbors={'c': ['b'], 'b': ['c', 'a'], 'a': ['b']}
>>> weights ={'c': [1.0], 'b': [1.0, 1.0], 'a': [1.0]}
>>> w=W(neighbors,weights)
>>> w.id_order = ['a','b','c']
>>> w.neighbor_offsets['b']
[2, 0]
>>> w.id_order = ['b','a','c']
>>> w.neighbor_offsets['b']
[2, 1]
nonzero
number of nonzero weights
order(kmax=3)

Determine the non-redundant order of contiguity up to a specific order.

Parameters:

kmax : int

maximum order of contiguity

Returns:

implicit : dict

observation id is the key, value is a list of contiguity orders with a negative 1 in the ith position

See also

order

Notes

Implements the algorithm in Anselin and Smirnov (1996) [R7]

References

[R7](1, 2) Anselin, L. and O. Smirnov (1996) “Efficient algorithms for constructing proper higher order spatial lag operators. Journal of Regional Science, 36, 67-89.

Examples

>>> from pysal import rook_from_shapefile as rfs
>>> w=rfs('../examples/10740.shp')
>>> w3=w.order()
>>> w3[1][0:5]
[1, -1, 1, 2, 1]
pct_nonzero
percentage of nonzero weights
s0

float

s0=\sum_i \sum_j w_{i,j}

s1

float

s1=1/2 \sum_i \sum_j (w_{i,j} + w_{j,i})^2

s2

float

s2=\sum_j (\sum_i w_{i,j} + \sum_i w_{j,i})^2

s2array

individual elements comprising s2

See also

s2

sd
standard deviation of number of neighbors : float
set_transform(value='B')

Transformations of weights.

Parameters:

transform : string (not case sensitive)

B: Binary R: Row-standardization (global sum=n) D: Double-standardization (global sum=1) V: Variance stabilizing O: Restore original transformation (from instantiation)

Examples

>>> from pysal import lat2W
>>> w=lat2W()
>>> w.weights[0]
[1.0, 1.0]
>>> w.transform
'O'
>>> w.transform='r'
>>> w.weights[0]
[0.5, 0.5]
>>> w.transform='b'
>>> w.weights[0]
[1.0, 1.0]
>>> 
shimbel()

Find the Shmibel matrix for the first order contiguity matrix.

Returns:

implicit : list of lists

one list for each observation which stores the shortest order between it and each of the the other observations.

See also

shimbel

Examples

>>> from pysal import lat2W
>>> w5=lat2W()
>>> w5_shimbel=w5.shimbel()
>>> w5_shimbel[0][24]
8
>>> w5_shimbel[0][0:4]
[-1, 1, 2, 3]
>>>
sparse

Sparse matrix object

For any matrix manipulations required for w, w.sparse should be used. This is based on scipy.sparse.

transform

Getter for transform property

Returns:transformation : string (or none)

Examples

>>> from pysal import lat2W
>>> w=lat2W()
>>> w.weights[0]
[1.0, 1.0]
>>> w.transform
'O'
>>> w.transform='r'
>>> w.weights[0]
[0.5, 0.5]
>>> w.transform='b'
>>> w.weights[0]
[1.0, 1.0]
>>> 
trcW2

Trace of WW

See also

diagW2

trcWtW

Trace of W^{'}W : float

See also

diagWtW

trcWtW_WW
trace of W^{'}W + WW
pysal.weights.lat2W(nrows=5, ncols=5, rook=True, id_type='int')

Create a W object for a regular lattice.

Parameters:

nrows : int

number of rows

ncols : int

number of columns

rook : boolean

type of contiguity. Default is rook. For queen, rook =False

id_type : string

string defining the type of IDs to use in the final W object; options are ‘int’ (0, 1, 2 ...; default), ‘float’ (0.0, 1.0, 2.0, ...) and ‘string’ (‘id0’, ‘id1’, ‘id2’, ...)

Returns:

w : W

instance of spatial weights class W

Notes

Observations are row ordered: first k observations are in row 0, next k in row 1, and so on.

Examples

>>> from pysal import lat2W
>>> w9=lat2W(3,3)
>>> w9.pct_nonzero
0.29629629629629628
>>> w9[0]
{1: 1.0, 3: 1.0}
>>> w9[3]
{0: 1.0, 4: 1.0, 6: 1.0}
>>> 
pysal.weights.regime_weights(regimes)

Construct spatial weights for regime neighbors.

Block contiguity structures are relevant when defining neighbor relations based on membership in a regime. For example, all counties belonging to the same state could be defined as neighbors, in an analysis of all counties in the US.

Parameters:

regimes : list or array

ids of which regime an observation belongs to

Returns:

W : spatial weights instance

Examples

>>> from pysal import regime_weights 
>>> import numpy as np
>>> regimes=np.ones(25)
>>> regimes[range(10,20)]=2
>>> regimes[range(21,25)]=3
>>> regimes
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  2.,  2.,  2.,
        2.,  2.,  2.,  2.,  2.,  2.,  2.,  1.,  3.,  3.,  3.,  3.])
>>> w=regime_weights(regimes)
>>> w.weights[0]
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
>>> w.neighbors[0]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 20]
>>> regimes=['n','n','s','s','e','e','w','w','e']
>>> n=len(regimes)
>>> w=regime_weights(regimes)
>>> w.neighbors
{0: [1], 1: [0], 2: [3], 3: [2], 4: [5, 8], 5: [4, 8], 6: [7], 7: [6], 8: [4, 5]}
pysal.weights.comb(items, n=None)

Combinations of size n taken from items

Parameters:

items : sequence

n : integer

size of combinations to take from items

Returns:

implicit : generator

combinations of size n taken from items

Examples

>>> x=range(4)
>>> for c in comb(x,2):
...     print c
...     
[0, 1]
[0, 2]
[0, 3]
[1, 2]
[1, 3]
[2, 3]
pysal.weights.order(w, kmax=3)

Determine the non-redundant order of contiguity up to a specific order.

Parameters:

w : W

spatial weights object

kmax : int

maximum order of contiguity

Returns:

info : dictionary

observation id is the key, value is a list of contiguity orders with a negative 1 in the ith position

Notes

Implements the algorithm in Anselin and Smirnov (1996) [R8]

References

[R8](1, 2) Anselin, L. and O. Smirnov (1996) “Efficient algorithms for constructing proper higher order spatial lag operators. Journal of Regional Science, 36, 67-89.

Examples

>>> from pysal import rook_from_shapefile as rfs
>>> w=rfs('../examples/10740.shp')
>>> w3=order(w,kmax=3)
>>> w3[1][0:5]
[1, -1, 1, 2, 1]
pysal.weights.higher_order(w, order=2)

Contiguity weights object of order k

Parameters:

w : W

spatial weights object

order : int

order of contiguity

Returns:

implicit : W

spatial weights object

Notes

Implements the algorithm in Anselin and Smirnov (1996) [R9]

References

[R9](1, 2) Anselin, L. and O. Smirnov (1996) “Efficient algorithms for constructing proper higher order spatial lag operators. Journal of Regional Science, 36, 67-89.

Examples

>>> from pysal import lat2W, higher_order
>>> w10=lat2W(10,10)
>>> w10_2=higher_order(w10,2)
>>> w10_2[0]
{2: 1.0, 11: 1.0, 20: 1.0}
>>> w5=lat2W()
>>> w5[0]
{1: 1.0, 5: 1.0}
>>> w5[1]
{0: 1.0, 2: 1.0, 6: 1.0}
>>> w5_2=higher_order(w5,2)
>>> w5_2[0]
{2: 1.0, 10: 1.0, 6: 1.0}
pysal.weights.shimbel(w)

Find the Shmibel matrix for first order contiguity matrix.

Parameters:

w : W

spatial weights object

Returns :

——- :

info : list of lists

one list for each observation which stores the shortest order between it and each of the the other observations.

Examples

>>> from pysal import lat2W, shimbel
>>> w5=lat2W()
>>> w5_shimbel=shimbel(w5)
>>> w5_shimbel[0][24]
8
>>> w5_shimbel[0][0:4]
[-1, 1, 2, 3]
>>>
pysal.weights.remap_ids(w, old2new, id_order=[])

Remaps the IDs in a spatial weights object

Parameters:

w : W

Spatial weights object

old2new : dictionary

Dictionary where the keys are the IDs in w (i.e. “old IDs”) and the values are the IDs to replace them (i.e. “new IDs”)

id_order : list

An ordered list of new IDs, which defines the order of observations when iterating over W. If not set then the id_order in w will be used.

Returns:

implicit : W

Spatial weights object with new IDs

Examples

>>> from pysal import lat2W, remap_ids
>>> w = lat2W(3,2)
>>> w.id_order
[0, 1, 2, 3, 4, 5]
>>> w.neighbors[0]
[2, 1]
>>> old_to_new = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
>>> w_new = remap_ids(w, old_to_new)
>>> w_new.id_order
['a', 'b', 'c', 'd', 'e', 'f']
>>> w_new.neighbors['a']
['c', 'b']
pysal.weights.full(w)

Generate a full numpy array

Parameters:

w : W

spatial weights object

Returns:

implicit : tuple

first element being the full numpy array and second element keys being the ids associated with each row in the array.

Examples

>>> from pysal import W, full
>>> neighbors={'first':['second'],'second':['first','third'],'third':['second']}
>>> weights={'first':[1],'second':[1,1],'third':[1]}
>>> w=W(neighbors,weights)
>>> wf,ids=full(w)
>>> wf
array([[ 0.,  1.,  0.],
       [ 1.,  0.,  1.],
       [ 0.,  1.,  0.]])
>>> ids
['first', 'second', 'third']