libpysal.weights.W

class libpysal.weights.W(neighbors, weights=None, id_order=None, silence_warnings=False, ids=None)[source]

Spatial weights class.

Parameters
neighborsdictionary

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

weightsdictionary

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

id_orderlist

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.

silence_warningsboolean

By default libpysal will print a warning if the dataset contains any disconnected components or islands. To silence this warning set this parameter to True.

idslist

Values to use for keys of the neighbors and weights dicts.

Attributes (NOTE: these are described by their docstrings. to view, use the `help` function)
———-
asymmetries
cardinalities
component_labels
diagW2
diagWtW
diagWtW_WW
histogram
id2i
id_order
id_order_set
islands
max_neighbors
mean_neighbors
min_neighbors
n
n_components
neighbor_offsets
nonzero
pct_nonzero
s0
s1
s2
s2array
sd
sparse
trcW2
trcWtW
trcWtW_WW
transform

Examples

>>> from libpysal.weights 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)
>>> "%.3f"%w.pct_nonzero
'29.630'

Read from external gal file

>>> import libpysal
>>> w = libpysal.io.open(libpysal.examples.get_path("stl.gal")).read()
>>> w.n
78
>>> "%.3f"%w.pct_nonzero
'6.542'

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)
>>> round(w.pct_nonzero,3)
29.63
>>> from libpysal.weights import lat2W
>>> w = lat2W(100, 100)
>>> w.trcW2
39600.0
>>> w.trcWtW
39600.0
>>> w.transform='r'
>>> round(w.trcW2, 3)
2530.722
>>> round(w.trcWtW, 3)
2533.667

Cardinality Histogram >>> w.histogram [(2, 4), (3, 392), (4, 9604)]

Disconnected observations (islands)

>>> from libpysal.weights import W
>>> w = W({1:[0],0:[1],2:[], 3:[]})

UserWarning: The weights matrix is not fully connected: There are 3 disconnected components. There are 2 islands with ids: 2, 3.

__init__(self, neighbors, weights=None, id_order=None, silence_warnings=False, ids=None)[source]

Initialize self. See help(type(self)) for accurate signature.

Methods

__init__(self, neighbors[, weights, …])

Initialize self.

asymmetry(self[, intrinsic])

Asymmetry check.

from_WSP(WSP[, silence_warnings])

from_adjlist(adjlist[, focal_col, …])

Return an adjacency list representation of a weights object.

from_file([path, format])

from_networkx(graph[, weight_col])

Convert a networkx graph to a PySAL W object.

from_shapefile(\*args, \*\*kwargs)

full(self)

Generate a full numpy array.

get_transform(self)

Getter for transform property.

plot(self, gdf[, indexed_on, ax, color, …])

Plot spatial weights objects.

remap_ids(self, new_ids)

In place modification throughout W of id values from w.id_order to new_ids in all

set_shapefile(self, shapefile[, idVariable, …])

Adding meta data for writing headers of gal and gwt files.

set_transform(self[, value])

Transformations of weights.

symmetrize(self[, inplace])

Construct a symmetric KNN weight.

to_WSP(self)

Generate a WSP object.

to_adjlist(self[, remove_symmetric, …])

Compute an adjacency list representation of a weights object.

to_networkx(self)

Convert a weights object to a networkx graph

Attributes

asymmetries

List of id pairs with asymmetric weights.

cardinalities

Number of neighbors for each observation.

component_labels

Store the graph component in which each observation falls.

diagW2

Diagonal of \(WW\).

diagWtW

Diagonal of \(W^{'}W\).

diagWtW_WW

Diagonal of \(W^{'}W + WW\).

histogram

Cardinality histogram as a dictionary where key is the id and 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.

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.

n_components

Store whether the adjacency matrix is fully connected.

neighbor_offsets

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

nonzero

Number of nonzero weights.

pct_nonzero

Percentage of nonzero weights.

s0

s0 is defined as

s1

s1 is defined as

s2

s2 is defined as

s2array

Individual elements comprising s2.

sd

Standard deviation of number of neighbors.

sparse

Sparse matrix object.

transform

Getter for transform property.

trcW2

Trace of \(WW\).

trcWtW

Trace of \(W^{'}W\).

trcWtW_WW

Trace of \(W^{'}W + WW\).

property asymmetries

List of id pairs with asymmetric weights.

asymmetry(self, intrinsic=True)[source]

Asymmetry check.

Parameters
intrinsicboolean

default=True

intrinsic symmetry:

\(w_{i,j} == w_{j,i}\)

if intrisic is False:

symmetry is defined as \(i \in N_j \ AND \ j \in N_i\) where \(N_j\) is the set of neighbors for j.

Returns
asymmetrieslist

empty if no asymmetries are found if asymmetries, then a list of (i,j) tuples is returned

Examples

>>> from libpysal.weights import lat2W
>>> w=lat2W(3,3)
>>> w.asymmetry()
[]
>>> w.transform='r'
>>> w.asymmetry()
[(0, 1), (0, 3), (1, 0), (1, 2), (1, 4), (2, 1), (2, 5), (3, 0), (3, 4), (3, 6), (4, 1), (4, 3), (4, 5), (4, 7), (5, 2), (5, 4), (5, 8), (6, 3), (6, 7), (7, 4), (7, 6), (7, 8), (8, 5), (8, 7)]
>>> result = w.asymmetry(intrinsic=False)
>>> result
[]
>>> 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()
[(0, 1), (1, 0)]
property cardinalities

Number of neighbors for each observation.

property component_labels

Store the graph component in which each observation falls.

property diagW2

Diagonal of \(WW\).

See also

trcW2
property diagWtW

Diagonal of \(W^{'}W\).

See also

trcWtW
property diagWtW_WW

Diagonal of \(W^{'}W + WW\).

classmethod from_adjlist(adjlist, focal_col='focal', neighbor_col='neighbor', weight_col=None)[source]

Return an adjacency list representation of a weights object.

Parameters
adjlistpandas DataFrame

adjacency list with a minimum of two columns

focal_colstring

name of the column with the “source” node ids

neighbor_colstring

name of the column with the “destination” node ids

weight_colstring

name of the column with the weight information. If not provided and the dataframe has no column named “weight” then all weights are assumed to be 1.

classmethod from_networkx(graph, weight_col='weight')[source]

Convert a networkx graph to a PySAL W object.

Parameters
graphnetworkx graph

the graph to convert to a W

weight_colstring

if the graph is labeled, this should be the name of the field to use as the weight for the W.

Returns
——–
a pysal.weights.W object containing the same graph
as the networkx graph
full(self)[source]

Generate a full numpy array.

Parameters
selfW

spatial weights object

Returns
(fullw, keys)tuple

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

Examples

>>> from libpysal.weights 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']
get_transform(self)[source]

Getter for transform property.

Returns
transformationstring (or none)

See also

set_transform

Examples

>>> from libpysal.weights 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]
property histogram

Cardinality histogram as a dictionary where key is the id and value is the number of neighbors for that unit.

property id2i

Dictionary where the key is an ID and the value is that ID’s index in W.id_order.

property id_order

Returns the ids for the observations in the order in which they would be encountered if iterating over the weights.

property id_order_set

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

Examples

>>> from libpysal.weights import lat2W
>>> w=lat2W()
>>> w.id_order_set
True
property islands

List of ids without any neighbors.

property max_neighbors

Largest number of neighbors.

property mean_neighbors

Average number of neighbors.

property min_neighbors

Minimum number of neighbors.

property n

Number of units.

property n_components

Store whether the adjacency matrix is fully connected.

property neighbor_offsets

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

Returns
list

offsets of the id’s neighbors in id_order

Examples

>>> from libpysal.weights 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]
property nonzero

Number of nonzero weights.

property pct_nonzero

Percentage of nonzero weights.

plot(self, gdf, indexed_on=None, ax=None, color='k', node_kws=None, edge_kws=None)[source]

Plot spatial weights objects. NOTE: Requires matplotlib, and implicitly requires geopandas dataframe as input.

Parameters
gdfgeopandas geodataframe

the original shapes whose topological relations are modelled in W.

indexed_onstr

column of gdf which the weights object uses as an index. (Default: None, so the geodataframe’s index is used)

axmatplotlib axis

axis on which to plot the weights. (Default: None, so plots on the current figure)

colorstring

matplotlib color string, will color both nodes and edges the same by default.

node_kwskeyword argument dictionary

dictionary of keyword arguments to send to pyplot.scatter, which provide fine-grained control over the aesthetics of the nodes in the plot

edge_kwskeyword argument dictionary

dictionary of keyword arguments to send to pyplot.plot, which provide fine-grained control over the aesthetics of the edges in the plot

Returns
f,axmatplotlib figure,axis on which the plot is made.
NOTE: if you’d like to overlay the actual shapes from the

geodataframe, call gdf.plot(ax=ax) after this. To plot underneath, adjust the z-order of the geopandas plot: gdf.plot(ax=ax,zorder=0)

Examples

>>> from libpysal.weights import Queen
>>> import libpysal as lp
>>> import geopandas
>>> gdf = geopandas.read_file(lp.examples.get_path("columbus.shp"))
>>> weights = Queen.from_dataframe(gdf)
>>> tmp = weights.plot(gdf, color='firebrickred', node_kws=dict(marker='*', color='k'))
remap_ids(self, new_ids)[source]

In place modification throughout W of id values from w.id_order to new_ids in all

Parameters
new_idslist

/ndarray Aligned list of new ids to be inserted. Note that first element of new_ids will replace first element of w.id_order, second element of new_ids replaces second element of w.id_order and so on.

Examples

>>> from libpysal.weights import lat2W
>>> w = lat2W(3, 3)
>>> w.id_order
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> w.neighbors[0]
[3, 1]
>>> new_ids = ['id%i'%id for id in w.id_order]
>>> _ = w.remap_ids(new_ids)
>>> w.id_order
['id0', 'id1', 'id2', 'id3', 'id4', 'id5', 'id6', 'id7', 'id8']
>>> w.neighbors['id0']
['id3', 'id1']
property s0

s0 is defined as

\[s0=\sum_i \sum_j w_{i,j}\]
property s1

s1 is defined as

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

s2 is defined as

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

Individual elements comprising s2.

See also

s2
property sd

Standard deviation of number of neighbors.

set_shapefile(self, shapefile, idVariable=None, full=False)[source]

Adding meta data for writing headers of gal and gwt files.

Parameters
shapefilestring

shapefile name used to construct weights

idVariablestring

name of attribute in shapefile to associate with ids in the weights

fullboolean

True - write out entire path for shapefile, False (default) only base of shapefile without extension

set_transform(self, value='B')[source]

Transformations of weights.

Parameters
transformstring

not case sensitive)

.. table::
widths

auto

transform string

value

B

Binary

R

Row-standardization (global sum=n)

D

Double-standardization (global sum=1)

V

Variance stabilizing

O

Restore original transformation (from instantiation)

Notes

Transformations are applied only to the value of the weights at instantiation. Chaining of transformations cannot be done on a W instance.

Examples

>>> from libpysal.weights 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]
property sparse

Sparse matrix object.

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

symmetrize(self, inplace=False)[source]

Construct a symmetric KNN weight.

This ensures that the neighbors of each focal observation consider the focal observation itself as a neighbor.

This returns a generic W object, since the object is no longer guaranteed to have k neighbors for each observation.

to_WSP(self)[source]

Generate a WSP object.

Returns
implicitlibpysal.weights.WSP

Thin W class

See also

WSP

Examples

>>> from libpysal.weights import W, WSP
>>> neighbors={'first':['second'],'second':['first','third'],'third':['second']}
>>> weights={'first':[1],'second':[1,1],'third':[1]}
>>> w=W(neighbors,weights)
>>> wsp=w.to_WSP()
>>> isinstance(wsp, WSP)
True
>>> wsp.n
3
>>> wsp.s0
4
to_adjlist(self, remove_symmetric=False, focal_col='focal', neighbor_col='neighbor', weight_col='weight')[source]

Compute an adjacency list representation of a weights object.

Parameters
remove_symmetricbool

whether or not to remove symmetric entries. If the W is symmetric, a standard directed adjacency list will contain both the forward and backward links by default because adjacency lists are a directed graph representation. If this is True, a W created from this adjacency list MAY NOT BE THE SAME as the original W. If you would like to consider (1,2) and (2,1) as distinct links, leave this as “False”.

focal_colstring

name of the column in which to store “source” node ids.

neighbor_colstring

name of the column in which to store “destination” node ids.

weight_colstring

name of the column in which to store weight information.

to_networkx(self)[source]

Convert a weights object to a networkx graph

Parameters
None
Returns
a networkx graph representation of the W object
property transform

Getter for transform property.

Returns
transformationstring (or none)

See also

set_transform

Examples

>>> from libpysal.weights 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]
property trcW2

Trace of \(WW\).

See also

diagW2
property trcWtW

Trace of \(W^{'}W\).

See also

diagWtW
property trcWtW_WW

Trace of \(W^{'}W + WW\).