libpysal.weights.Queen

class libpysal.weights.Queen(polygons, **kw)[source]

Construct a weights object from a collection of pysal polygons that share at least one vertex.

Construct queen contiguity weights from polygon-like inputs.

Parameters:
polygons : list

A collection of shapes to build weights from.

**kw

Optional arguments for libpysal.weights.W, including ids to set custom names for the weights object.

Methods

asymmetry([intrinsic])

Asymmetry check.

from_WSP(WSP[, silence_warnings])

Create a pysal W from a pysal WSP object (thin weights matrix).

from_adjlist(adjlist[, focal_col, ...])

Return an adjacency list representation of a weights object.

from_dataframe(df[, geom_col, idVariable, ...])

Construct a weights object from a (geo)pandas dataframe with a geometry column.

from_file([path, format])

Read a weights file into a W object.

from_iterable(iterable[, sparse])

Construct a weights object from a collection of arbitrary polygons.

from_networkx(graph[, weight_col])

Convert a networkx graph to a PySAL W object.

from_shapefile(filepath[, idVariable, full])

Queen contiguity weights from a polygon shapefile.

from_sparse(sparse)

Convert a scipy.sparse array to a PySAL W object.

from_xarray(da[, z_value, coords_labels, k, ...])

Construct a weights object from a xarray.DataArray with an additional attribute index containing coordinate values of the raster in the form of Pandas.Index/MultiIndex.

full()

Generate a full numpy.ndarray.

get_transform()

Getter for transform property.

plot(gdf[, indexed_on, ax, color, node_kws, ...])

Plot spatial weights objects.

remap_ids(new_ids)

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

set_shapefile(shapefile[, idVariable, full])

Adding metadata for writing headers of .gal and .gwt files.

set_transform([value])

Transformations of weights.

symmetrize([inplace])

Construct a symmetric KNN weight.

to_WSP()

Generate a WSP object.

to_adjlist([remove_symmetric, drop_islands, ...])

Compute an adjacency list representation of a weights object.

to_file([path, format])

Write a weights to a file.

to_networkx()

Convert a weights object to a networkx graph.

to_sparse([fmt])

Generate a scipy.sparse array object from a pysal W.

Attributes

asymmetries

List of id pairs with asymmetric weights sorted in ascending index location order.

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[source]

List of id pairs with asymmetric weights sorted in ascending index location order.

asymmetry(intrinsic=True)[source]

Asymmetry check.

Parameters:
intrinsic : bool

Default is True. Intrinsic symmetry is defined as:

\[w_{i,j} == w_{j,i}\]

If intrinsic is False symmetry is defined as:

\[i \in N_j \ \& \ j \in N_i\]

where \(N_j\) is the set of neighbors for \(j\).

Returns:

asymmetries – Empty if no asymmetries are found. If there are asymmetries, then a list of (i,j) tuples is returned sorted in ascending index location order.

Return type:

list

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[source]

Number of neighbors for each observation.

property component_labels[source]

Store the graph component in which each observation falls.

property diagW2[source]

Diagonal of \(WW\).

See also

trcW2

property diagWtW[source]

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

See also

trcWtW

property diagWtW_WW[source]

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

classmethod from_WSP(WSP, silence_warnings=True)[source]

Create a pysal W from a pysal WSP object (thin weights matrix).

Parameters:
WSP : WSP

PySAL sparse weights object.

silence_warnings : bool

By default libpysal will print a warning if the dataset contains disconnected components or islands. Set to True to silence it.

Returns:

w – PySAL weights object

Return type:

W

Examples

>>> from libpysal.weights import lat2W, WSP, W

Build a 10x10 scipy.sparse matrix for a rectangular 2x5 region of cells (rook contiguity), then construct a PySAL sparse weights object (wsp).

>>> sp = lat2SW(2, 5)
>>> wsp = WSP(sp)
>>> wsp.n
10
>>> wsp.sparse[0].todense()
matrix([[0, 1, 0, 0, 0, 1, 0, 0, 0, 0]], dtype=int8)

Create a standard PySAL W from this sparse weights object.

>>> w = W.from_WSP(wsp)
>>> w.n
10
>>> print(w.full()[0][0])
[0 1 0 0 0 1 0 0 0 0]
classmethod from_adjlist(adjlist, focal_col='focal', neighbor_col='neighbor', weight_col=None)[source]

Return an adjacency list representation of a weights object.

Parameters:
adjlist : pandas.DataFrame

Adjacency list with a minimum of two columns.

focal_col : str

Name of the column with the “source” node ids.

neighbor_col : str

Name of the column with the “destination” node ids.

weight_col : str

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_dataframe(df, geom_col=None, idVariable=None, ids=None, id_order=None, use_index=None, **kwargs)[source]

Construct a weights object from a (geo)pandas dataframe with a geometry column. This will cast the polygons to PySAL polygons, then build the W using ids from the dataframe.

Parameters:
df : DataFrame

a :class: pandas.DataFrame containing geometries to use for spatial weights

geom_col : string

the name of the column in df that contains the geometries. Defaults to active geometry column.

idVariable : string

DEPRECATED - use ids instead. the name of the column to use as IDs. If nothing is provided, the dataframe index is used

ids : list-like, string

a list-like of ids to use to index the spatial weights object or the name of the column to use as IDs. If nothing is provided, the dataframe index is used if use_index=True or a positional index is used if use_index=False. Order of the resulting W is not respected from this list.

id_order : list

DEPRECATED - argument is deprecated and will be removed. An ordered list of ids to use to index the spatial weights object. If used, the resulting weights object will iterate over results in the order of the names provided in this argument.

use_index : bool

use index of df as ids to index the spatial weights object. Defaults to False but in future will default to True.

classmethod from_file(path='', format=None)[source]

Read a weights file into a W object.

Parameters:
path : string

location to save the file

format : string

string denoting the format to write the weights to.

Return type:

W object

classmethod from_iterable(iterable, sparse=False, **kwargs)[source]

Construct a weights object from a collection of arbitrary polygons.

This will cast the polygons to PySAL polygons, then build the W.

Parameters:
iterable : iterable

a collection of of shapes to be cast to PySAL shapes. Must support iteration. Contents may either be a shapely or PySAL shape.

**kwargs : keyword arguments

Optional arguments for libpysal.weights.W.

See also

libpysal.weights.weights.W, libpysal.weights.contiguiyt.Queen

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

Convert a networkx graph to a PySAL W object.

Parameters:
graph : networkx.Graph

The graph to convert to a W.

weight_col : string

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

Returns:

w – A W object containing the same graph as the networkx graph.

Return type:

libpysal.weights.W

classmethod from_shapefile(filepath, idVariable=None, full=False, **kwargs)[source]

Queen contiguity weights from a polygon shapefile.

Parameters:
filepath : str

Name of polygon shapefile including suffix.

idVariable : str, optional

Name of a column in the shapefile’s DBF to use for ids.

full : bool, default False

Write out the entire path for a shapefile (True) or only the base of the shapefile without extension (False). Default is True.

kwargs : dict

Additional keyword arguments passed to libpysal.weights.W.

Returns:

w – instance of spatial weights

Return type:

W

Examples

>>> from libpysal.weights import Queen
>>> import libpysal
>>> wq=Queen.from_shapefile(libpysal.examples.get_path("columbus.shp"))
>>> "%.3f"%wq.pct_nonzero
'9.829'
>>> wq=Queen.from_shapefile(libpysal.examples.get_path("columbus.shp"),"POLYID")
>>> "%.3f"%wq.pct_nonzero
'9.829'
>>> wq=Queen.from_shapefile(
...     libpysal.examples.get_path("columbus.shp"), sparse=True
... )
>>> pct_sp = wq.sparse.nnz *1. / wq.n**2
>>> "%.3f"%pct_sp
'0.098'

Notes

Queen contiguity defines as neighbors any pair of polygons that share at least one vertex in their polygon definitions.

classmethod from_sparse(sparse)[source]

Convert a scipy.sparse array to a PySAL W object.

Parameters:
sparse : scipy.sparse array

Returns:

w – A W object containing the same graph as the scipy.sparse graph.

Return type:

libpysal.weights.W

Notes

When the sparse array has a zero in its data attribute, and the corresponding row and column values are equal, the value for the pysal weight will be 0 for the “loop”.

classmethod from_xarray(da, z_value=None, coords_labels={}, k=1, include_nodata=False, n_jobs=1, sparse=True, **kwargs)[source]

Construct a weights object from a xarray.DataArray with an additional attribute index containing coordinate values of the raster in the form of Pandas.Index/MultiIndex.

Parameters:
da : xarray.DataArray

Input 2D or 3D DataArray with shape=(z, y, x)

z_value : int/string/float

Select the z_value of 3D DataArray with multiple layers.

coords_labels : dictionary

Pass dimension labels for coordinates and layers if they do not belong to default dimensions, which are (band/time, y/lat, x/lon) e.g. coords_labels = {“y_label”: “latitude”, “x_label”: “longitude”, “z_label”: “year”} Default is {} empty dictionary.

sparse : boolean

type of weight object. Default is True. For libpysal.weights.W, sparse = False

k : int

Order of contiguity, this will select all neighbors upto kth order. Default is 1.

include_nodata : boolean

If True, missing values will be assumed as non-missing when selecting higher_order neighbors, Default is False

n_jobs : int

Number of cores to be used in the sparse weight construction. If -1, all available cores are used. Default is 1.

**kwargs : keyword arguments

optional arguments passed when sparse = False

Returns:

w – instance of spatial weights class W or WSP with an index attribute

Return type:

libpysal.weights.W/libpysal.weights.WSP

Notes

  1. Lower order contiguities are also selected.

  2. Returned object contains index attribute that includes a Pandas.MultiIndex object from the DataArray.

full()[source]

Generate a full numpy.ndarray.

Returns:

(fullw, keys) – The first element being the full numpy.ndarray and second element keys being the ids associated with each row in the array.

Return type:

tuple

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()[source]

Getter for transform property.

Returns:

transformation – Valid transformation value. See the transform parameters in set_transform() for a detailed description.

Return type:

str, None

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]

See also

set_transform

property histogram[source]

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

property id2i[source]

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

property id_order[source]

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

property id_order_set[source]

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[source]

List of ids without any neighbors.

property max_neighbors[source]

Largest number of neighbors.

property mean_neighbors[source]

Average number of neighbors.

property min_neighbors[source]

Minimum number of neighbors.

property n[source]

Number of units.

property n_components[source]

Store whether the adjacency matrix is fully connected.

property neighbor_offsets[source]

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

Returns:

neighbor_list – Offsets of the id’s neighbors in id_order.

Return type:

list

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[source]

Number of nonzero weights.

property pct_nonzero[source]

Percentage of nonzero weights.

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

Plot spatial weights objects. Requires matplotlib, and implicitly requires a geopandas.GeoDataFrame as input.

Parameters:
gdf : geopandas.GeoDataFrame

The original shapes whose topological relations are modelled in W.

indexed_on : str

Column of geopandas.GeoDataFrame that the weights object uses as an index. Default is None, so the index of the geopandas.GeoDataFrame is used.

ax : matplotlib.axes.Axes

Axis on which to plot the weights. Default is None, so plots on the current figure.

color : str

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

node_kws : dict

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

edge_kws : dict

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

Returns:

  • f (matplotlib.figure.Figure) – Figure on which the plot is made.

  • ax (matplotlib.axes.Axes) – Axis on which the plot is made.

Notes

If you’d like to overlay the actual shapes from the geopandas.GeoDataFrame, call gdf.plot(ax=ax) after this. To plot underneath, adjust the z-order of the plot as follows: 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(new_ids)[source]

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

Parameters:
new_ids : list, numpy.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[source]

s0 is defined as

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

s1 is defined as

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

s2 is defined as

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

Individual elements comprising s2.

See also

s2

property sd[source]

Standard deviation of number of neighbors.

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

Adding metadata for writing headers of .gal and .gwt files.

Parameters:
shapefile : str

The shapefile name used to construct weights.

idVariable : str

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

full : bool

Write out the entire path for a shapefile (True) or only the base of the shapefile without extension (False). Default is True.

set_transform(value='B')[source]

Transformations of weights.

Parameters:
value : str

This parameter is not case sensitive. The following are valid transformations.

  • 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[source]

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

symmetrize(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()[source]

Generate a WSP object.

Returns:

implicit – Thin W class

Return type:

libpysal.weights.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

See also

WSP

to_adjlist(remove_symmetric=False, drop_islands=None, focal_col='focal', neighbor_col='neighbor', weight_col='weight', sort_joins=False)[source]

Compute an adjacency list representation of a weights object.

Parameters:
remove_symmetric : bool

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.

drop_islands : bool

Whether or not to preserve islands as entries in the adjacency list. By default, observations with no neighbors do not appear in the adjacency list. If islands are kept, they are coded as self-neighbors with zero weight.

focal_col : str

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

neighbor_col : str

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

weight_col : str

Name of the column in which to store weight information.

sort_joins : bool

Whether or not to lexicographically sort the adjacency list by (focal_col, neighbor_col). Default is False.

to_file(path='', format=None)[source]

Write a weights to a file. The format is guessed automatically from the path, but can be overridden with the format argument.

See libpysal.io.FileIO for more information.

Parameters:
path : string

location to save the file

format : string

string denoting the format to write the weights to.

Return type:

None

to_networkx()[source]

Convert a weights object to a networkx graph.

Return type:

A networkx graph representation of the W object.

to_sparse(fmt='coo')[source]

Generate a scipy.sparse array object from a pysal W.

Parameters:
fmt : {'bsr', 'coo', 'csc', 'csr'}

scipy.sparse format

Returns:

A scipy.sparse array with a format of fmt.

Return type:

scipy.sparse array

Notes

The keys of the w.neighbors are encoded to determine row,col in the sparse array.

property transform[source]

Getter for transform property.

Returns:

transformation – Valid transformation value. See the transform parameters in set_transform() for a detailed description.

Return type:

str, None

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]

See also

set_transform

property trcW2[source]

Trace of \(WW\).

See also

diagW2

property trcWtW[source]

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

See also

diagWtW

property trcWtW_WW[source]

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