Overview of tobler’s Interpolation Methods

import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
from libpysal.examples import load_example

from tobler.area_weighted import area_interpolate
from tobler.dasymetric import masked_area_interpolate
from tobler.model import glm

Let’s say we want to represent the poverty rate and male employment using zip code geographies, but the only data available is at the census-tract level. The tobler package provides several different ways to estimate data collected at one geography using the boundaries of a different geography.

Load Data

First we’ll grab two geodataframes representing chaleston, sc–one with census tracts and the other with zctas

c1 = load_example("Charleston1")
c2 = load_example("Charleston2")
Downloading Charleston1 to /home/runner/.local/share/pysal/Charleston1
Downloading Charleston2 to /home/runner/.local/share/pysal/Charleston2

Since areal interpolation uses spatial ovelays, we should make sure to use a reasonable projection. If a tobler detects that a user is performing an analysis on an unprojected geodataframe, it will do its best to reproject the data into the appropriate UTM zone to ensure accuracy. All the same, its best to set the local CRS explicitly.

crs = 6569  # https://spatialreference.org/ref/epsg/6569/
tracts = gpd.read_file(c1.get_path("sc_final_census2.shp")).to_crs(crs)
zip_codes = gpd.read_file(c2.get_path("CharlestonMSA2.shp")).to_crs(crs)
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

tracts.plot(ax=ax[0])
zip_codes.plot(ax=ax[1])

for _ax in ax:
    _ax.axis("off")
../_images/272472463d0ecda5b06c03ff0944443e8304a70ac766f2a6e8b49cf20872ff0d.png
tracts.columns
Index(['FIPS', 'MSA', 'TOT_POP', 'POP_16', 'POP_65', 'WHITE_', 'BLACK_',
       'ASIAN_', 'HISP_', 'MULTI_RA', 'MALES', 'FEMALES', 'MALE1664',
       'FEM1664', 'EMPL16', 'EMP_AWAY', 'EMP_HOME', 'EMP_29', 'EMP_30',
       'EMP16_2', 'EMP_MALE', 'EMP_FEM', 'OCC_MAN', 'OCC_OFF1', 'OCC_INFO',
       'HH_INC', 'POV_POP', 'POV_TOT', 'HSG_VAL', 'POLYID', 'geometry'],
      dtype='str')
tracts["pct_poverty"] = tracts.POV_POP / tracts.POV_TOT

Areal Interpolation

The simplest technique available in tobler is simple areal interpolation in which variables from the source data are weighted according to the overlap between source and target polygons, then reaggregated to fit the target polygon geometries

results = area_interpolate(
    source_df=tracts,
    target_df=zip_codes,
    intensive_variables=["pct_poverty"],
    extensive_variables=["EMP_MALE"],
)
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

results.plot("EMP_MALE", scheme="quantiles", ax=ax[0])
tracts.plot("EMP_MALE", scheme="quantiles", ax=ax[1])

ax[0].set_title("interpolated")
ax[1].set_title("original")
for _ax in ax:
    _ax.axis("off")
fig.suptitle("Male Employment (extensive)")
Text(0.5, 0.98, 'Male Employment (extensive)')
../_images/267b290b00c7575923170c82d63790a4ad22b0d9516809735cc180c8332edccf.png
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

results.plot("pct_poverty", scheme="quantiles", cmap="magma", ax=ax[0])
tracts.plot("pct_poverty", scheme="quantiles", cmap="magma", ax=ax[1])

ax[0].set_title("interpolated")
ax[1].set_title("original")
for _ax in ax:
    _ax.axis("off")
fig.suptitle("Poverty Rate (intensive)")
Text(0.5, 0.98, 'Poverty Rate (intensive)')
../_images/34a446e4acf36aa00cf8394e4c260461a7a9639ec5e663b01c5e5dee0992397d.png

Performance

By default, area_interpolate will run in a single process, which is typically good enough for small- to medium-sized GeoDataFrames. However, you can specify n_jobs to set the number of processes to be used to run the operation in parallel, where -1 represents all available. This can significantly speed-up the computation for large datasets. We can illustrate this using generated grids and interpolation of a random variable between two hexagonal grids with different orientation.

grid1 = tracts.make_grid(
    cell_size=100, grid_type="hexagon", flat_topped=False
).to_frame("geometry")
grid2 = tracts.make_grid(cell_size=100, grid_type="hexagon", flat_topped=True).to_frame(
    "geometry"
)
grid1["variable"] = np.random.default_rng(seed=9).random(len(grid1))
grid1.shape
(839044, 2)

When comparing the two following lines on a machine with 24 cores, the timing is as follows:

interpolated_grid = area_interpolate(grid1, grid2, extensive_variables=["variable"])
interpolated_grid = area_interpolate(
    grid1,
    grid2,
    extensive_variables=["variable"],
    n_jobs=-1,
)

Single-threaded:

CPU times: user 26.2 s, sys: 67.9 ms, total: 26.3 s
Wall time: 26.3 s

Parallel:

CPU times: user 11.5 s, sys: 1.62 s, total: 13.1 s
Wall time: 15.5 s

You can see that it nearly halved the computation time. Interpolation is not an embarrassingly parallel algorithm so not all parts of the process can be parallelised, but you can expect about double the performance in most cases. However, the exact case is heavily dependent on the nature of the data and relations between polygons in source and destination.

The same case above, with grid1 using cell_size of 50 and grid2 using 500, would yield:

Single-threaded:

CPU times: user 23.1 s, sys: 0 ns, total: 23.1 s
Wall time: 23.1 s

Parallel:

CPU times: user 5.71 s, sys: 530 ms, total: 6.24 s
Wall time: 7.39 s

That is about 3x faster. The most difference would be in situations when one of the GeoDataFrames contains non-compact geometries that do not fit nicely to the structure of an STRtree spatial index.


Dasymetric Interpolation

To help improve accuracy in interpolation we can use axiliary information to mask out areas we know aren’t inhabited. For example we can use raster data like https://www.mrlc.gov/national-land-cover-database-nlcd-2016 to mask out uninhabited land uses. To do so, we need to provide a path to the raster and a list of pixel values that are considered developed. Default values are taken from NLCD.

tobler can accept any kind of raster data that can be read by rasterio, so you can provide your own, or download directly from NLCD linked above. Alternatively, you can download a compressed version of the NLCD we host in the spatialucr quilt bucket using three short lines of code:

import rasterio

with rasterio.Env(AWS_NO_SIGN_REQUEST="YES"):
    results = masked_area_interpolate(
        raster="s3://spatial-ucr/nlcd/landcover/nlcd_landcover_2011.tif",
        source_df=tracts,
        target_df=zip_codes,
        intensive_variables=["pct_poverty"],
        extensive_variables=["EMP_MALE"],
        pixel_values=[22, 23, 24],
    )
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

results.plot("EMP_MALE", scheme="quantiles", ax=ax[0])
tracts.plot("EMP_MALE", scheme="quantiles", ax=ax[1])

ax[0].set_title("interpolated")
ax[1].set_title("original")
for _ax in ax:
    _ax.axis("off")
fig.suptitle("Male Employment (extensive)")
Text(0.5, 0.98, 'Male Employment (extensive)')
../_images/86c1ddff25cfc37dd1802b3473d2f9906b55cc6f860ef0c7bf099370407e8956.png
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

results.plot("pct_poverty", scheme="quantiles", cmap="magma", ax=ax[0])
tracts.plot("pct_poverty", scheme="quantiles", cmap="magma", ax=ax[1])

ax[0].set_title("interpolated")
ax[1].set_title("original")
for _ax in ax:
    _ax.axis("off")
fig.suptitle("Poverty Rate (intensive)")
Text(0.5, 0.98, 'Poverty Rate (intensive)')
../_images/5006503ac094f212b739e052cf06dc44d5c1b798a825ce72e886bed9ebd27f43.png

Model-Based Interpolation

Rather than assume that extensive and intensive variables are distributed uniformly throughout developed land, tobler can also use a model-based approach to assign weights to different cell types, e.g. if we assume that “high intensity development” raster cells are likely to contain more people than “low intensity development”, even though we definitely want to allocate population to both types. In these cases, tobler consumes a raster layer as additional input and a patsy-style model formula string. A default formula string is provided but results can be improved by fitting a model more appropriate for local settings.

Unlike area weighted and dasymetric techniques, model-based interpolation estimates only a single variable at a time

with rasterio.Env(AWS_NO_SIGN_REQUEST="YES"):
    emp_results = glm(
        raster="s3://spatial-ucr/nlcd/landcover/nlcd_landcover_2011.tif",
        source_df=tracts,
        target_df=zip_codes,
        extensive_variable="EMP_MALE",
    )
fig, ax = plt.subplots(1, 2, figsize=(14, 7))

emp_results.plot("EMP_MALE", scheme="quantiles", ax=ax[0])
tracts.plot("EMP_MALE", scheme="quantiles", ax=ax[1])

ax[0].set_title("interpolated")
ax[1].set_title("original")
for _ax in ax:
    _ax.axis("off")
fig.suptitle("Male Employment (extensive)")
Text(0.5, 0.98, 'Male Employment (extensive)')
../_images/b85cfd5a6e99774cbacca4fb6414c56fc12881b10d1af3b3d265833322ad79a6.png

From the map, you can inspect the model-based approach for the extensive variable (male employment).