In [1]:
%matplotlib inline

Combining contiguity with block structures in creating W objects

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.

In [9]:
import pysal as ps
import numpy as np
In [10]:
db ='columbus.dbf'))

The variable EW is a binary that differenciates eastern from westerd polygons.

In [11]:
ew = db.by_col('EW')
[1.0, 0.0, 1.0, 0.0, 1.0]
In [12]:
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:

In [13]:
block = ps.weights.regime_weights(ew)

Now we get the standard contiguity using the shapefile:

In [14]:
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 block and 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 PySAL:

In [15]:
from IPython.display import HTML
HTML('<iframe src= width=700 height=350></iframe>')
In [16]:
w = ps.weights.Wsets.w_intersection(cont, block)
<pysal.weights.weights.W at 0x4b25ad0>