pyINLA · Random Effects

Generic2 Model

Type 2 generic specification: hierarchical convolution of structured and unstructured random effects.

Overview

The generic2 model implements a hierarchical random effect structure that combines a structured component (governed by matrix C) with an unstructured IID component. This is similar to the BYM (Besag-York-Mollie) convolution model used in spatial statistics.

Key features:

Mathematical Formulation

The generic2 model defines a hierarchical structure:

\[\mathbf{v} \sim \mathcal{N}(\mathbf{0}, \tau_v^{-1} \mathbf{C}^{-1})\]

\[\mathbf{u} \mid \mathbf{v} \sim \mathcal{N}(\mathbf{v}, \tau_u^{-1} \mathbf{I})\]

The joint precision matrix for the augmented latent field \((\mathbf{u}, \mathbf{v})^\top\) is:

\[\mathbf{Q} = \begin{pmatrix} \tau_u \mathbf{I} & -\tau_u \mathbf{I} \\ -\tau_u \mathbf{I} & \tau_u \mathbf{I} + \tau_v \mathbf{C} \end{pmatrix}\]

where:

Interpretation

The model can be understood as: \(\mathbf{u} = \mathbf{v} + \boldsymbol{\epsilon}\), where \(\mathbf{v}\) captures structured variation (via C) and \(\boldsymbol{\epsilon}\) captures unstructured/IID variation.

When to Use Generic2

Spatial Convolution Models

When modeling areal data where you want to separate spatially structured effects from local overdispersion.

BYM-like Models

When implementing Besag-York-Mollie style models with custom spatial structure.

Mixed Structure Effects

When random effects have both a structured component (from domain knowledge) and unexplained heterogeneity.

Variance Decomposition

When you want to decompose total variance into structured and unstructured components.

Specification in pyINLA

Allowed Parameters

Parameter Required Description
id Yes Column name for the grouping/index variable
model Yes Must be 'generic2'
Cmatrix Yes The \(n \times n\) precision structure matrix for \(\mathbf{v}\)
hyper No List of two prior specifications: [prec (tau_v), prec.random (tau_u)]
constr No Sum-to-zero constraint on \(\mathbf{v}\) only. Default: False
extraconstr No Dict with keys 'A' and 'e' for custom linear constraints
n No Dimension of the random effect (auto-detected from Cmatrix if omitted)
diagonal No Small value added to precision diagonal for numerical stability (default: 1e-4)

Basic Syntax

Shared setup. Every snippet on this page assumes this block has been run first; it builds a small synthetic df with the columns the examples use.

# shared setup for every snippet on this page (run this first)
import numpy as np
import pandas as pd
from pyinla import pyinla, inla_surv

rng = np.random.default_rng(42)
n = 80
n_regions = 50
neighbors = [[(i - 1) % n_regions, (i + 1) % n_regions] for i in range(n_regions)]   # a ring

def build_adjacency_matrix(nb):
    W = np.zeros((len(nb), len(nb)))
    for i, js in enumerate(nb):
        for j in js:
            W[i, j] = W[j, i] = 1.0
    return W

n = 150
df = pd.DataFrame({'x': rng.standard_normal(n), 'idx': rng.integers(1, n_regions + 1, size=n)})
df['y'] = 0.5 * df['x'] + rng.normal(0, 0.5, n)
df['observed'] = rng.poisson(np.exp(0.3 + 0.4 * df['x']))
df['region'] = rng.integers(1, 11, size=len(df))     # index column used by a snippet below
import numpy as np
from pyinla import pyinla

# Create precision structure matrix
n = 30
C = np.eye(n)  # Identity for simple case

# Model specification (intercept included by default)
formula = {
    'response': 'y',
    'fixed': ['x'],
    'random': [
        {
            'id': 'idx',
            'model': 'generic2',
            'Cmatrix': C
        }
    ]
}

result = pyinla(formula=formula, family='gaussian', data=df)

Hyperparameters

The generic2 model has two hyperparameters:

Parameter Internal Scale Description
\(\tau_v\) \(\log(\tau_v)\) Precision for structured component (Cmatrix)
\(\tau_u\) \(\log(\tau_u)\) Precision for unstructured (IID) component

Output Hyperparameters

In the results, you'll also see h2 (heritability-like ratio), which measures the proportion of variance from the structured component: \(h^2 = \frac{1/\tau_u}{1/\tau_u + 1/\tau_v}\).

Prior Specification

'random': [{
    'id': 'idx',
    'model': 'generic2',
    'Cmatrix': C,
    'hyper': [
        {  # theta1: log(tau_v) - precision for Cmatrix
            'prior': 'pc.prec',
            'param': [1, 0.01],
            'initial': 4
        },
        {  # theta2: log(tau_u) - precision for random
            'prior': 'pc.prec',
            'param': [0.5, 0.01],
            'initial': 4
        }
    ]
}]

Fixed Hyperparameters

import math
'hyper': [
    {'initial': math.log(10), 'fixed': True},  # Fix tau_v = 10
    {'initial': math.log(25), 'fixed': True}   # Fix tau_u = 25
]

Latent Field Structure

The latent field for generic2 has dimension \(2n\):

Note on Constraints

When constr=True is specified, the sum-to-zero constraint is applied only to \(\mathbf{v}\) (the structured component), not to \(\mathbf{u}\).

Example: Disease Mapping

A typical application is disease mapping with spatial structure:

# Build ICAR-like precision matrix from adjacency
# D - diagonal matrix of neighbor counts
# W - adjacency matrix
# Q = D - W (graph Laplacian)

n_regions = 50
W = build_adjacency_matrix(neighbors)  # Your adjacency data
D = np.diag(W.sum(axis=1))
Q = D - W

# Add small diagonal for numerical stability (if Q is singular)
Q = Q + np.eye(n_regions) * 1e-6

formula = {
    'response': 'observed',
    # Intercept included by default
    'offset': 'log_expected',
    'random': [{
        'id': 'region',
        'model': 'generic2',
        'Cmatrix': Q
    }]
}

result = pyinla(formula=formula, family='poisson', data=df)

# Examine variance decomposition
print(result.summary_hyperpar)  # Includes h2 for variance ratio

Relationship to Other Models