pyINLA · random effects

bym2

A spatial model for areas on a map with two parts, a spatial part shared with the neighbours and noise of each area, and one parameter for their split.

Idea

The effect of each area is a spatial part, a besag field, plus noise of its own (Riebler et al., 2016). $\tau$ is the precision of the total and $\phi$ the share of its variance that is spatial: with $\phi = 1$ it is besag, with $\phi = 0$ independent noise. fbym2 lets the smoothness of the spatial part differ between parts of the map.

Model

$$\mathbf b = \frac{1}{\sqrt\tau}\Big(\sqrt{1-\phi}\;\mathbf v + \sqrt{\phi}\;\mathbf u\Big), \qquad \mathbf v \sim \mathcal N(\mathbf 0, I),$$
meaning
$b_i$effect of area $i$
$\mathbf u$spatial part: a besag field, scaled so that the geometric mean of its marginal variances is 1
$\mathbf v$noise of each area
$\tau$precision of $b_i$
$\phi$share of the variance of $b_i$ that is spatial, between 0 and 1

The latent vector is $(\mathbf b, \mathbf u)$, of length $2n$; the first $n$ entries, $\mathbf b$, enter the predictor. $\mathbf u$ sums to zero in each connected part of two or more areas. pyinla reports $\tau$ and $\phi$ as Precision for idx and Phi for idx.

Priors

The priors are on $\theta_1 = \log\tau$ and $\theta_2 = \text{logit}\,\phi$, set with hyper, a list of two: [{...}, {...}].

defaultmeaning
$\tau${'prior': 'pc.prec', 'param': [1, 0.01]}$P(1/\sqrt\tau > 1) = 0.01$ (Simpson et al., 2017)
$\phi${'prior': 'pc', 'param': [0.5, 0.5]}$P(\phi < 0.5) = 0.5$

The PC prior of $\phi$ depends on the map; it is computed before the fit, at a cost of $O(n^3)$. Beyond $\text{logit}\,\phi = 12$ it is flat.

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}(E_i\, e^{\beta_0 + b_i})$. 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"

def fit(effect):
    return pyinla(model={"response": "Y", "fixed": ["1"], "random": [effect]},
                  family="poisson", data=areas, E=areas["E"].to_numpy())

fit_bym2  = fit({"id": "idx", "model": "bym2", "graph": graph})   # PC priors on tau and phi
fit_besag = fit({"id": "idx", "model": "besag", "graph": graph, "scale.model": True,
                 "hyper": [{"prior": "pc.prec", "param": [1, 0.01]}]})   # the same prior on tau
print(fit_bym2.summary_hyperpar[["mean", "0.025quant", "0.975quant"]].round(2))

# log Bayes factor against besag; INLA's log marginal likelihood of bym2 has an
# extra 0.5 (n - 1) log(2 pi) (n areas, one connected map), so remove it first
n = 558
print(fit_bym2.mlik.iloc[1] - fit_besag.mlik.iloc[1] - 0.5 * (n - 1) * np.log(2 * np.pi))
                   mean  0.025quant  0.975quant
Precision for idx  0.28        0.23        0.34
Phi for idx        0.95        0.85        0.99
-3.285714123870491

$\phi = 0.95$: almost all of the variation is spatial. The log Bayes factor against besag, with the same prior on $\tau$, is $-3.3$: the noise is not needed for these data.

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()

# the first 558 entries of the latent vector are b, the effect of each area
b       = fit_bym2.summary_random["idx"]["mean"].to_numpy()[:558]
x       = fit_besag.summary_random["idx"]["mean"].to_numpy()
overall = areas["Y"].sum() / areas["E"].sum()
rr      = np.exp(fit_bym2.summary_fixed["mean"].iloc[0] + b) / overall   # relative to the whole country
diff    = b - x
lim     = np.abs(diff).max()

fig, ax = plt.subplots(1, 2, figsize=(10, 5))
binned_map(ax[0], rr, "bym2: relative risk")
map_df.assign(diff=diff).plot("diff", ax=ax[1], cmap="RdBu_r", vmin=-lim, vmax=lim, linewidth=0,
                              legend=True, legend_kwds={"shrink": 0.6})
ax[1].set_title("bym2 minus besag")
ax[1].set_axis_off()

print(f"bym2 minus besag: mean |difference| {np.abs(diff).mean():.2f}, largest {lim:.2f}")
bym2 minus besag: mean |difference| 0.03, largest 0.58
Maps of Brazil: relative risk of dengue in April from bym2, and the difference from besag
Left: $e^{\beta_0 + b_i}$, posterior means, relative to the whole country. Right: posterior mean of $b_i$ minus that of $x_i$ from besag.

The two differ most in the far South, where there are almost no cases.

Comparing with besag

$$\log \text{BF} = \log \pi(\mathbf y \mid \text{bym2}) - \log \pi(\mathbf y \mid \text{besag}) - \tfrac{1}{2}(n - 1)\log(2\pi)$$

INLA's log marginal likelihood of bym2 has an extra $\frac{1}{2}(n-1)\log(2\pi)$ compared with besag's, on a connected map of $n$ areas. Here, with $\phi$ fixed close to 1, where the two models are the same, the difference of the log marginal likelihoods is 511.81, and $\frac{1}{2} \cdot 557 \log(2\pi) = 511.85$.

Reference

Options

entry, for exampledefaultmeaning
'id': 'idx'column with the area index, $1, \dots, n$
'model': 'bym2'
'graph': graphthe neighbours (below)
'scale.model': FalseTruescale $\mathbf u$ (above)
'constr': FalseTrue$\mathbf u$ sums to zero in each connected part; with False, remove the intercept: 'fixed': ['0', ...]
'adjust.for.con.comp': FalseTrueone constraint per connected part (below); False needs a prior on $\phi$ other than 'pc'
'hyper': [...]PC priorspriors of $\theta_1, \theta_2$ (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 on $(\mathbf b, \mathbf u)$; $A$ has $2n$ columns
'rankdef': 1from the graphrank deficiency
'diagonal': 1e-40constant added to the diagonal of the precision matrix

weights is not accepted by bym2. In the examples, graph is the graph file of the example above, and A, e and w are arrays you make.

Hyperparameters

priorparaminitialfixed
$\theta_1 = \log\tau$'pc.prec'[1, 0.01]4 ($\tau \approx 54.6$)False
$\theta_2 = \text{logit}\,\phi$'pc'[0.5, 0.5]$-3$ ($\phi \approx 0.047$)False

hyper is a list of two, $[\tau, \phi]$; {} keeps the default of its slot:

'hyper': [{}, {'prior': 'normal', 'param': [0, 1]}]   # only the prior of phi changes
'hyper': [{}, {'initial': 2, 'fixed': True}]          # logit(phi) fixed at 2

The PC prior of $\phi$ shrinks towards $\phi = 0$, no spatial part.

Priors tested with bym2. On $\theta_1$: pc.prec, loggamma, normal (or gaussian), laplace, pc.mgamma, jeffreystdf. On $\theta_2$: pc, normal (or gaussian), loggamma, flat, logtnormal. On both, 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 on $\mathbf u$; 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.

With adjust.for.con.comp=False, give $\phi$ a prior other than 'pc': INLA computes the PC prior of $\phi$ only with True.

References