libpysal.weights.Rook¶
- class libpysal.weights.Rook(polygons, **kw)[source]¶
Construct a weights object from a collection of pysal polygons that share at least one edge.
- Parameters:
See also
Methods
__init__(polygons, **kw)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
networkxgraph to a PySALWobject.from_shapefile(filepath[, idVariable, full])Rook contiguity weights from a polygon shapefile.
from_sparse(sparse)Convert a
scipy.sparsearray to a PySALWobject.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
Wof id values fromw.id_ordertonew_idsin all.set_shapefile(shapefile[, idVariable, full])Adding metadata for writing headers of
.galand.gwtfiles.set_transform([value])Transformations of weights.
symmetrize([inplace])Construct a symmetric KNN weight.
to_WSP()Generate a
WSPobject.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
networkxgraph.to_sparse([fmt])Generate a
scipy.sparsearray object from a pysal W.Attributes
asymmetriesList of id pairs with asymmetric weights sorted in ascending index location order.
cardinalitiesNumber of neighbors for each observation.
component_labelsStore the graph component in which each observation falls.
diagW2Diagonal of \(WW\).
diagWtWDiagonal of \(W^{'}W\).
diagWtW_WWDiagonal of \(W^{'}W + WW\).
histogramCardinality histogram as a dictionary where key is the id and value is the number of neighbors for that unit.
id2iDictionary where the key is an ID and the value is that ID's index in
W.id_order.id_orderReturns the ids for the observations in the order in which they would be encountered if iterating over the weights.
id_order_setReturns
Trueif user has setid_order,Falseif not.islandsList of ids without any neighbors.
max_neighborsLargest number of neighbors.
mean_neighborsAverage number of neighbors.
min_neighborsMinimum number of neighbors.
nNumber of units.
n_componentsStore whether the adjacency matrix is fully connected.
neighbor_offsetsGiven the current
id_order,neighbor_offsets[id]is the offsets of the id's neighbors inid_order.nonzeroNumber of nonzero weights.
pct_nonzeroPercentage of nonzero weights.
s0s0is defined ass1s1is defined ass2s2is defined ass2arrayIndividual elements comprising
s2.sdStandard deviation of number of neighbors.
sparseSparse matrix object.
transformGetter for transform property.
trcW2Trace of \(WW\).
trcWtWTrace of \(W^{'}W\).
trcWtW_WWTrace of \(W^{'}W + WW\).
- 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
str the name of the column in df that contains the geometries. Defaults to active geometry column.
- idVariable
str DEPRECATED - use ids instead. the name of the column to use as IDs. If nothing is provided, the dataframe index is used
- idslist-like,
str 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_indexbool
use index of df as ids to index the spatial weights object. Defaults to False but in future will default to True.
- df
- 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.
- classmethod from_shapefile(filepath, idVariable=None, full=False, **kwargs)[source]¶
Rook contiguity weights from a polygon shapefile.
- Parameters:
- Returns:
- w
W instance of spatial weights
- w
Notes
Rook contiguity defines as neighbors any pair of polygons that share a common edge in their polygon definitions.
Examples
>>> from libpysal.weights import Rook >>> import libpysal >>> wr=Rook.from_shapefile(libpysal.examples.get_path("columbus.shp"), "POLYID") >>> "%.3f"%wr.pct_nonzero '8.330' >>> wr=Rook.from_shapefile( ... libpysal.examples.get_path("columbus.shp"), sparse=True ... ) >>> pct_sp = wr.sparse.nnz *1. / wr.n**2 >>> "%.3f"%pct_sp '0.083'
- 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_valueint/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.
- sparsebool
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_nodatabool
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
keywordarguments optional arguments passed when sparse = False
- da
- Returns:
- wlibpysal.weights.W/libpysal.weights.WSP
instance of spatial weights class W or WSP with an index attribute
Notes
Lower order contiguities are also selected.
Returned object contains index attribute that includes a Pandas.MultiIndex object from the DataArray.