In this notebook, we will work through an example on how to combine to rules to build spatial weights. This is inspired by a note by Yamil Velez to the
openspace list on May 10th. 2014. His question was:
I have read the relevant documentation and I still have not found a way to solve this problem. Basically, my goal is to compute the average value in contiguous cells for each cell in a raster file but only for valid contiguous cells. My raster file is made up of both land and water cells but I only want to work with the land cells. When I compute spatial lags, however, values from water cells are introduced. Is there any way to modify the weights so that water cells are automatically given a zero and not factored into the spatial lag calculation? Thanks so much!
Here I present a potential answer with an example using PySAL data examples.
import pysal as ps import numpy as np
db = ps.open(ps.examples.get_path('columbus.dbf')) db.header
['AREA', 'PERIMETER', 'COLUMBUS_', 'COLUMBUS_I', 'POLYID', 'NEIG', 'HOVAL', 'INC', 'CRIME', 'OPEN', 'PLUMB', 'DISCBD', 'X', 'Y', 'NSA', 'NSB', 'EW', 'CP', 'THOUS', 'NEIGNO']
EW is a binary that differenciates eastern from westerd polygons.
ew = db.by_col('EW') ew[:5]
[1.0, 0.0, 1.0, 0.0, 1.0]
from pysal.contrib.viz import mapping as maps maps.plot_choropleth(ps.examples.get_path('columbus.shp'), np.array(ew), 'unique_values')
We're gonna use this to build block weights:
block = ps.weights.regime_weights(ew)
Now we get the standard contiguity using the shapefile:
cont = ps.queen_from_shapefile(ps.examples.get_path('columbus.shp'))
And the combination will give the desired structure, one that uses contiguous values, but only "valid" ones (here we're assuming "valid" means the surrounding observations are also in the same
EW group). This is basically the intersection of
cont, where $j$ is neighbor of $i$ if $j$ is contiguous and in the same
EW group as $i$. This is encoded in the
w_intersection method of
from IPython.display import HTML HTML('<iframe src=http://pysal.readthedocs.org/en/v1.7/library/weights/Wsets.html#pysal.weights.Wsets.w_intersection width=700 height=350></iframe>')
w = ps.weights.Wsets.w_intersection(cont, block) w
<pysal.weights.weights.W at 0x4b25ad0>