pyINLA · random effects

besag

A spatial model for areas on a map: each area is pulled towards the mean of its neighbours, by the same amount everywhere.

Idea

Disease rates in small areas are noisy. The besag model (Besag et al., 1991) smooths them: each area borrows strength from its neighbours, with one precision $\tau$ for the whole map. It has no noise term of its own; bym2 adds one, and fbesag lets the precision differ between parts of the map.

Model

$$x_i \mid \mathbf x_{-i} \sim \mathcal N\Big(\frac{1}{n_i} \sum_{j \sim i} x_j,\ \frac{1}{n_i\, \tau}\Big),$$

where $n_i$ is the number of neighbours of area $i$ and $j \sim i$ means that $j$ is a neighbour of $i$. Together, $\mathbf x$ has precision matrix $Q = \tau R$, with $R_{ii} = n_i$, $R_{ij} = -1$ for neighbours and $0$ otherwise.

$R$ is singular, so $\mathbf x$ sums to zero in each connected part of two or more areas. With scale.model=True, $R$ is scaled so that the geometric mean of the marginal variances is 1 (Sørbye and Rue, 2014); then $1/\sqrt\tau$ is a typical sd of $x_i$, whatever the map. pyinla reports $\tau$ as Precision for idx.

Prior

The prior is on $\theta = \log\tau$, set with hyper.

hypermeaning
default[{'prior': 'loggamma', 'param': [1, 0.00005]}]$\tau \sim \text{Gamma}(1,\ 0.00005)$ (shape, rate)
PC prior[{'prior': 'pc.prec', 'param': [1, 0.01]}]$P(1/\sqrt\tau > 1) = 0.01$ (Simpson et al., 2017); use with scale.model=True

Example: dengue in Brazil

Dengue cases $y_i$ and expected cases $E_i$ in April in the 558 microregions of Brazil (Lowe et al., 2021):

$$y_i \sim \text{Poisson}\big(E_i\, e^{\beta_0 + x_i}\big).$$

Data: brazil_558_microregions.csv, brazil_558_microregions.graph, brazil_558_microregions.geojson.

import numpy as np
import pandas as pd
from pyinla import pyinla

areas = pd.read_csv("brazil_558_microregions.csv")   # idx, region, Y and E of April
graph = "brazil_558_microregions.graph"

besag = {"id": "idx", "model": "besag", "graph": graph, "scale.model": True,
         "hyper": [{"prior": "pc.prec", "param": [1, 0.01]}]}    # P(sd > 1) = 0.01
fit = pyinla(model={"response": "Y", "fixed": ["1"], "random": [besag]},
             family="poisson", data=areas, E=areas["E"].to_numpy())
print(fit.summary_hyperpar[["mean", "0.025quant", "0.975quant"]].round(2))
                   mean  0.025quant  0.975quant
Precision for idx  0.26        0.23         0.3

$1/\sqrt\tau \approx 2$: neighbouring areas can differ a lot on this map.

import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

map_df = gpd.read_file("brazil_558_microregions.geojson").sort_values("idx").reset_index(drop=True)
brks   = [0, 0.2, 0.5, 1, 2, 5, np.inf]
labels = ["< 0.2", "0.2-0.5", "0.5-1", "1-2", "2-5", "> 5"]
cols   = ListedColormap(["#2c7bb6", "#abd9e9", "#e0f3f8", "#fee090", "#fdae61", "#d7191c"])

def binned_map(ax, values, title):
    v = pd.Categorical(pd.cut(values, brks, right=False, labels=labels), categories=labels)
    map_df.assign(v=v).plot("v", ax=ax, cmap=cols, linewidth=0, legend=True,
                            legend_kwds={"loc": "lower left", "fontsize": 8, "frameon": False})
    ax.set_title(title)
    ax.set_axis_off()

# observed over expected, and the fitted relative risk e^{beta_0 + x_i} (posterior means),
# both relative to the whole country
overall = areas["Y"].sum() / areas["E"].sum()
beta0   = fit.summary_fixed["mean"].iloc[0]
x       = fit.summary_random["idx"]["mean"].to_numpy()
smr     = areas["Y"] / areas["E"] / overall
rr      = np.exp(beta0 + x) / overall

fig, ax = plt.subplots(1, 2, figsize=(10, 5))
binned_map(ax[0], smr, "observed / expected")
binned_map(ax[1], rr, "besag: relative risk")

# how much besag moves each area away from observed / expected, by quarter of E
pos    = areas["Y"] > 0                                    # areas with cases
change = np.abs(np.log(rr[pos]) - np.log(smr[pos]))
print(change.groupby(pd.qcut(areas["E"][pos], 4, labels=["smallest E", "2nd", "3rd", "largest E"]),
                     observed=True).mean().round(3).to_string())
E
smallest E    0.080
2nd           0.097
3rd           0.079
largest E     0.044
Maps of Brazil: observed over expected dengue cases in April, and the relative risk from besag
Left: observed over expected cases. Right: $e^{\beta_0 + x_i}$, posterior means. Both relative to the whole country.

With many cases in most areas, besag moves the observed ratios little: by 4% to 10% on average (on the log scale), least where the expected count is largest.

Reference

Options

entry, for exampledefaultmeaning
'id': 'idx'column with the area index, $1, \dots, n$
'model': 'besag'
'graph': graphthe neighbours (below)
'scale.model': TrueFalsescale $R$ (above)
'constr': FalseTruesum to zero in each connected part; with False, remove the intercept: 'fixed': ['0', ...]
'adjust.for.con.comp': FalseTrueone constraint per connected part (below)
'hyper': [...]loggammaprior of $\theta$ (examples below)
'n': 558from the graphnumber of areas
'values': list(range(1, 559))from the graphids of the areas
'extraconstr': {'A': A, 'e': e}Nonefurther constraints $A\mathbf x = \mathbf e$
'rankdef': 1from the graphrank deficiency of $R$
'diagonal': 1e-40constant added to the diagonal of $Q$
'weights': wNoneweight of $x_i$ in each observation, one per observation

In the examples, graph is the graph file of the example above, and A, e and w are arrays you make.

Hyperparameter

priorparaminitialfixed
$\theta = \log\tau$'loggamma'[1, 0.00005]4 ($\tau \approx 54.6$)False

To fix $\tau$, for example at 10 (then summary_hyperpar is None):

'hyper': [{'initial': np.log(10), 'fixed': True}]

Priors tested with besag: loggamma, pc.prec, flat, logtnormal, normal (or gaussian), laplace, pc.mgamma, jeffreystdf, and your own as 'expression: ...' or 'table: ...'.

Graph

graph is a dense or sparse adjacency matrix, an InlaGraph, or a graph file: line 1 is the number of areas $n$, then one line per area, i k nb_1 ... nb_k (the area, its number of neighbours, the neighbours). A file that numbers the areas from 0 is detected.

Disconnected maps

scale.modeladjust.for.con.compconstraintsscalingarea without neighbours
FalseFalseone for the whole mapnoneflat
TrueFalseone for the whole mapwhole mapstandard normal
FalseTrueone per connected partnoneflat
TrueTrueone per connected partper connected partstandard normal

Constraints are sum-to-zero; a connected part has two or more areas, and areas without neighbours are left out of the scaling. With adjust.for.con.comp=True, rankdef is the number of connected parts.

INLA leaves $\frac{1}{2}\log|R|^*$ out of the log marginal likelihood ($|R|^*$: the product of the non-zero eigenvalues of $R$). To compare with bym2, see bym2.

References