3  Inferring Models and Mechanisms from Data

3.1 Introduction: How Does a Gene Turn On?

In the previous chapters, we built a powerful “forward” modeling toolkit. Given a biological mechanism—like a genetic switch or a bursting promoter—and a set of parameters, we could predict the system’s behavior. We were the architects, specifying the rules and observing the outcome.

But in the lab, we face the opposite problem. We don’t know the rules. We only see the outcome.

Consider this experimental puzzle: You’re studying a gene involved in cellular stress response. After treating cells with a drug, you measure mRNA levels across thousands of individual cells using single-cell RNA sequencing. The results are striking—the gene has clearly “turned on,” with average expression increasing dramatically from the baseline condition.

But this simple observation conceals a profound mechanistic question: how did the gene turn on? What molecular machinery did the drug actually affect?

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Set parameters for the two conditions
rng = np.random.default_rng(101)
n_cells_base = 500
n_cells_pert = 50

# Baseline condition: lower mean and variance
r_base, p_base = 4.0, 0.50
counts_base = nbinom.rvs(n=r_base, p=p_base, size=n_cells_base, random_state=rng)
mean_base = np.mean(counts_base)

# Perturbed condition: higher mean and variance
r_pert, p_pert = 8.0, 0.25
counts_pert = nbinom.rvs(n=r_pert, p=p_pert, size=n_cells_pert, random_state=rng)
mean_pert = np.mean(counts_pert)

# Create the plot
max_count = int(max(np.max(counts_base), np.max(counts_pert)) * 1.1)
bins = np.arange(0, max_count + 2)

# Plot histograms with transparency
plt.hist(counts_base, bins=bins, density=True, alpha=0.6, color=QUALITATIVE_COLORS[0], edgecolor='none', label=f'Baseline (Mean={mean_base:.1f})')
plt.hist(counts_pert, bins=bins, density=True, alpha=0.6, color=QUALITATIVE_COLORS[1], edgecolor='none', label=f'Perturbed (Mean={mean_pert:.1f})')

# Add vertical lines for means
plt.axvline(mean_base, color=QUALITATIVE_COLORS[0], linestyle='--', linewidth=2)
plt.axvline(mean_pert, color=QUALITATIVE_COLORS[1], linestyle='--', linewidth=2)

# Formatting
plt.xlabel('mRNA molecules per cell')
plt.ylabel('Probability Density')
plt.title('A Gene "Turns On"—But How?')
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlim(0, max_count)
plt.show()
Figure 3.1: Single-cell mRNA distributions before (blue) and after (orange) a perturbation. The drug clearly increases both the average expression level and the variance, demonstrating that the gene has ‘turned on.’ Notice the unequal sample sizes—we have far fewer measurements in the perturbed condition. The central question of this chapter is how to infer the underlying mechanistic changes—in burst size or burst frequency—that cause this shift.

From our Chapter 2 analysis, we know that transcriptional bursting produces characteristic statistical signatures. The observed increase in mean expression could arise from two fundamentally different molecular mechanisms:

Hypothesis 1: Increased Burst Frequency The drug affected the rate of transcriptional initiation—the frequency with which the promoter fires. This could occur through several pathways:

  • Chromatin accessibility: The drug opened previously inaccessible chromatin regions
  • Transcription factor dynamics: The drug increased the binding affinity or local concentration of key transcription factors
  • Enhancer-promoter interactions: The drug stabilized long-range DNA looping that brings enhancers into contact with the promoter

Hypothesis 2: Increased Burst Size The drug affected the transcription process itself after initiation—the number of mRNA molecules produced per burst. This could result from:

  • RNA Polymerase II processivity: The drug made the polymerase less likely to dissociate during transcription
  • Elongation dynamics: The drug increased the polymerase’s speed through the gene body
  • Transcriptional machinery stability: The drug stabilized protein complexes required for sustained transcription

These hypotheses make different predictions about the shape of the single-cell distribution. Distinguishing between them requires moving beyond simple observations of the mean to sophisticated analysis of the full statistical structure of our data.

Notice also the experimental reality captured in our simulation: the perturbed condition has far fewer samples than the baseline. How can we confidently compare these two states when one has far fewer measurements? This introduces the need to quantify our certainty—a theme we will return to throughout this chapter.

This mechanistic question has been addressed experimentally. Dar et al. (2012) investigated how transcriptional bursting responds to genomic and pharmacological perturbations, revealing that both burst frequency and burst size can indeed be modulated—with the dominant mechanism depending on the gene’s initial expression level.

Figure 3.2: Experimental evidence that perturbations can modulate both burst frequency and burst size, with the dominant mechanism depending on expression level. Adapted from Dar et al. (2012).

While these results demonstrate that both mechanisms operate in nature, distinguishing between them from noisy single-cell data involves many subtle challenges and potential pitfalls. This chapter digs into how to actually quantify these parameters from experimental measurements and navigate the inferential complexities involved.


3.2 Method of Moments

Sometimes, we don’t need sophisticated machinery to answer our biological questions. The Method of Moments provides a simple, lightning-fast alternative for parameter estimation—our first and most direct approach to the inverse problem.

The logic is straightforward and intuitive:

  1. Write down the analytical expressions for the model’s moments (like mean and variance) as a function of its parameters.
  2. Calculate the sample moments from the data.
  3. Set the analytical moments equal to the sample moments and solve for the parameters.

For our bursting model (Negative Binomial), we’ll work directly with the standard (r, p) parameterization used throughout this chapter to maintain consistency. We choose this model as our running example because it’s flexible enough to capture transcriptional bursting, analytically tractable for likelihood-based methods, and directly connects to the mechanistic models developed in Chapter 2.

Connection to Chapter 2’s Telegraph Model: In Chapter 2, we derived that the Telegraph model’s stationary distribution follows a Negative Binomial when the gene switches between active and inactive states. The statistical parameters (r, p) connect to the original Telegraph biophysical parameters as: r = \frac{k_{on}}{\gamma} (burst frequency scaled by mRNA lifetime) and p = \frac{1}{1+b} = \frac{k_{off}}{k_{off}+\beta}, where b = \beta/k_{off} is the mean burst size (transcripts per burst event).

For the Negative Binomial distribution with parameters r and p:

\mu = \frac{r(1-p)}{p} \sigma^2 = \frac{r(1-p)}{p^2}

From these expressions, we can derive the Method of Moments estimators. Given sample mean \bar{x} and sample variance s^2, we solve:

\hat{p} = \frac{\bar{x}}{s^2} \hat{r} = \frac{\bar{x}^2}{s^2 - \bar{x}}

This method is less statistically efficient than MLE (i.e., it has higher variance), but it’s computationally trivial and provides an excellent initial guess for more complex optimization or MCMC routines.

What makes this approach particularly appealing for biological modeling is its direct connection to observable experimental quantities. When we measure mRNA counts across a population of cells, the sample mean captures the overall level of transcriptional activity, while the sample variance quantifies the total variability—including both intrinsic noise from the stochastic bursting process and any extrinsic heterogeneity between cells. Method of Moments provides a transparent bridge between these directly measurable statistics and the model parameters. This makes it an excellent first approach when exploring new experimental datasets.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Generate synthetic data
rng = np.random.default_rng(42)
r_true = 5.0
p_true = 0.25
n_cells = 200
data = nbinom.rvs(n=r_true, p=p_true, size=n_cells, random_state=rng)

print(f"Synthetic data: {len(data)} observations")
print(f"True parameters: r = {r_true}, p = {p_true}")
print(f"Sample mean: {np.mean(data):.2f}")
print(f"Sample variance: {np.var(data, ddof=1):.2f}")

def method_of_moments_nb(data):
    """
    Method of Moments estimator for Negative Binomial (r, p) parameterization
    """
    sample_mean = np.mean(data)
    sample_var = np.var(data, ddof=1)  # Use sample variance with Bessel's correction

    # Check if variance > mean (required for valid NB parameters)
    if sample_var <= sample_mean:
        print("Warning: Sample variance <= mean. NB model may not be appropriate.")
        return None, None

    # Method of Moments estimators
    p_hat = sample_mean / sample_var
    r_hat = (sample_mean**2) / (sample_var - sample_mean)

    return r_hat, p_hat

# Apply Method of Moments
r_mom, p_mom = method_of_moments_nb(data)

print(f"\nMethod of Moments Results:")
print(f"r_hat = {r_mom:.3f} (true: {r_true})")
print(f"p_hat = {p_mom:.3f} (true: {p_true})")

# Visualize the Method of Moments fit
fig, (ax1, ax2) = plt.subplots(1, 2)

# Parameter comparison
methods = ['True', 'Method of\nMoments']
r_values = [r_true, r_mom]
p_values = [p_true, p_mom]

x_pos = np.arange(len(methods))
width = 0.35

ax1.bar(x_pos - width/2, r_values, width, label='r (burst size parameter)', alpha=0.8, color=QUALITATIVE_COLORS[1])
ax1.bar(x_pos + width/2, [v*10 for v in p_values], width, label='p × 10 (frequency)', alpha=0.8, color=QUALITATIVE_COLORS[0])
ax1.set_xlabel('Method')
ax1.set_ylabel('Parameter Value')
ax1.set_title('Parameter Estimates')
ax1.set_xticks(x_pos)
ax1.set_xticklabels(methods)
ax1.legend()
ax1.grid(True, alpha=0.3)

# Model fit comparison
x_range = np.arange(0, max(data) + 1)

# Theoretical PMF with true parameters
pmf_true = nbinom.pmf(x_range, n=r_true, p=p_true)

# Method of Moments fitted PMF
pmf_mom = nbinom.pmf(x_range, n=r_mom, p=p_mom)

# Data histogram
ax2.hist(data, bins=x_range, density=True, alpha=0.6, color='gray',
         label='Observed data', edgecolor='none')

# Plot fitted distributions
ax2.plot(x_range, pmf_true, '-', color=QUALITATIVE_COLORS[0], linewidth=2, label='True distribution')
ax2.plot(x_range, pmf_mom, '--', color=QUALITATIVE_COLORS[1], linewidth=2, label='MoM fit')

ax2.set_xlabel('mRNA count')
ax2.set_ylabel('Probability')
ax2.set_title('Method of Moments Fit')
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# Calculate fit quality (log-likelihood)
ll_true = np.sum(nbinom.logpmf(data, n=r_true, p=p_true))
ll_mom = np.sum(nbinom.logpmf(data, n=r_mom, p=p_mom))

print(f"\nModel Fit Quality (Log-Likelihood):")
print(f"True parameters: {ll_true:.2f}")
print(f"Method of Moments: {ll_mom:.2f}")
Synthetic data: 200 observations
True parameters: r = 5.0, p = 0.25
Sample mean: 15.46
Sample variance: 60.81

Method of Moments Results:
r_hat = 5.270 (true: 5.0)
p_hat = 0.254 (true: 0.25)
Figure 3.3: Method of Moments parameter estimation for the Negative Binomial model. The plots show how sample moments (mean and variance) are directly translated into parameter estimates r and p, and how well the resulting distribution fits the observed data.

Model Fit Quality (Log-Likelihood):
True parameters: -683.11
Method of Moments: -682.76

3.2.1 The Limitation: Statistical Inefficiency

However, Method of Moments has a fundamental limitation that becomes crucial as we seek more precise biological insights. While MoM provides reasonable estimates, MLE is typically more statistically efficient—meaning MLE estimates have smaller variance and are more likely to be closer to the true parameter values.

The core issue is that the sample moments (mean and variance) are not always sufficient statistics—they don’t capture all the information about the parameters contained in the data. A statistic T(D) is sufficient for parameter \theta if the likelihood can be factored as:

P(D \mid \theta) = g(T(D), \theta) \cdot h(D)

where h(D) doesn’t depend on \theta—meaning all parameter information is compressed into T.

A classic example: for the Gamma distribution with PDF f(x \mid k, \theta) = \frac{1}{\Gamma(k)\theta^k} x^{k-1} e^{-x/\theta}, the likelihood for n samples is:

P(D \mid k, \theta) = \prod_i \frac{1}{\Gamma(k)\theta^k} x_i^{k-1} e^{-x_i/\theta} \propto \theta^{-nk} \exp\left(-\frac{\sum x_i}{\theta} + (k-1)\sum \ln x_i\right)

This factorization reveals that the sufficient statistics are T(D) = (\sum x_i, \sum \ln x_i). MLE naturally uses both pieces of information, but MoM only uses \sum x_i and \sum x_i^2 (for mean and variance), completely ignoring the crucial information in \sum \ln x_i.

For our Negative Binomial gene expression model, a similar principle applies. While both MoM and MLE estimate two parameters using two constraints, MLE processes the raw data more efficiently by extracting all available information through the likelihood function, whereas MoM compresses the data into moments that may not preserve all parameter-relevant information.

This naturally motivates us to explore the foundational concept of the likelihood function.


3.3 Finding the Best Fit by Maximizing Likelihood

The Method of Moments addressed the limitation of statistical inefficiency by introducing a more principled approach. Instead of reducing our data to just two summary statistics, we need a method that uses the entire distribution. The likelihood function provides exactly this—it quantifies how plausible our observed data is, given a specific hypothesis about the underlying parameters.

3.3.1 The Likelihood Function

All statistical inference begins with a fundamental question: given our data and a proposed model, how well does this model explain what we observed? The likelihood function provides the rigorous mathematical answer.

When we write P(D | \theta), we can interpret this in two ways:

  • As a probability: \theta is fixed, and we ask how P varies as a function of different possible datasets D
  • As a likelihood: The data D is fixed (we observed it!), and we ask how P varies as a function of the parameters \theta

The likelihood function is defined as: L(\theta | D) = P(D | \theta)

The likelihood measures the plausibility of different parameter values given what we actually observed. Now we can apply the core principle of maximum likelihood estimation: among all possible parameter values, choose the one that makes our observed data most probable.

3.3.2 The Maximum Likelihood Estimate

The Maximum Likelihood Estimate (MLE) is defined as: \hat{\theta}_{MLE} = \underset{\theta}{\arg\max} \, L(\theta | D)

Equivalently, since the logarithm is a monotonic function, we can work with the log-likelihood: \hat{\theta}_{MLE} = \underset{\theta}{\arg\max} \, \ell(\theta | D)

But why maximize likelihood? (Equivalently, since log is monotonic, why maximize log-likelihood?) The answer connects to information theory: MLE minimizes the Kullback-Leibler (KL) divergence between the true distribution and our model. Let \theta_0 denote the true parameter value and f_\theta(x) denote our model’s probability density function. The KL divergence is defined as D_{KL}(\theta_0 || \theta) = \int f_{\theta_0}(x) \log \frac{f_{\theta_0}(x)}{f_\theta(x)} dx = E_{x \sim f_{\theta_0}}[\log f_{\theta_0}(x)] - E_{x \sim f_{\theta_0}}[\log f_\theta(x)] and measures information loss when approximating the true distribution f_{\theta_0} by our model f_\theta. Since the first term doesn’t depend on \theta, minimizing KL divergence is equivalent to maximizing the expected log-likelihood per observation: \max_\theta \, E_{x \sim f_{\theta_0}}[\log f_\theta(x)] By the Law of Large Numbers, for i.i.d. data x_1, \ldots, x_n, this expectation is estimated as: E_{x \sim f_{\theta_0}}[\log f_\theta(x)] \approx \frac{1}{n}\sum_{i=1}^n \log f_\theta(x_i) But maximizing the average log-likelihood is equivalent to maximizing the total log-likelihood \ell(\theta) = \sum_{i=1}^n \log f_\theta(x_i). Thus MLE finds parameters that make our model as close as possible to reality in an information-theoretic sense.

Let’s build intuition by starting with the simplest case where we can solve this analytically, then progress to the general case requiring numerical optimization.

3.3.3 Building Intuition with the Poisson Model

Before tackling the Negative Binomial model, let’s build intuition with a case where we can derive the MLE analytically. Consider a simple constitutive gene producing mRNA according to a Poisson process with rate \lambda. We observe counts n_1, n_2, \ldots, n_N from N independent cells.

The likelihood for the Poisson model is: L(\lambda | \mathbf{n}) = \prod_{i=1}^{N} \frac{\lambda^{n_i}e^{-\lambda}}{n_i!}

Taking the logarithm: \ell(\lambda | \mathbf{n}) = \sum_{i=1}^{N} \left[ n_i \log \lambda - \lambda - \log(n_i!) \right]

To find the MLE, we differentiate with respect to \lambda and set equal to zero: \frac{d\ell}{d\lambda} = \sum_{i=1}^{N} \left[ \frac{n_i}{\lambda} - 1 \right] = \frac{1}{\lambda}\sum_{i=1}^{N} n_i - N = 0

Solving for \lambda: \hat{\lambda}_{MLE} = \frac{1}{N}\sum_{i=1}^{N} n_i = \bar{n}

The MLE for the Poisson rate is simply the sample mean! This elegant result shows that maximum likelihood estimation formalizes our intuitive approach to parameter estimation.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Generate Poisson data
from scipy.stats import poisson
rng = np.random.default_rng(123)
lambda_true = 3.5
n_samples = 100
poisson_data = rng.poisson(lambda_true, size=n_samples)

# Calculate sample mean (the MLE)
lambda_mle = np.mean(poisson_data)

# Plot log-likelihood function
lambda_range = np.linspace(2.0, 5.0, 100)
log_likelihood = []

for lam in lambda_range:
    ll = np.sum(poisson.logpmf(poisson_data, mu=lam))
    log_likelihood.append(ll)

plt.figure()
plt.plot(lambda_range, log_likelihood, '-', color=QUALITATIVE_COLORS[0], linewidth=2, label='Log-likelihood')
plt.axvline(lambda_true, color=QUALITATIVE_COLORS[1], linestyle='-', linewidth=2, label=f'True λ = {lambda_true}')
plt.axvline(lambda_mle, color=QUALITATIVE_COLORS[3], linestyle='--', linewidth=2, label=f'MLE = {lambda_mle:.2f}')
plt.xlabel('λ (Poisson rate)')
plt.ylabel('Log-likelihood')
plt.title('Analytical MLE for Poisson Distribution')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

print(f"True λ: {lambda_true}")
print(f"Sample mean (MLE): {lambda_mle:.3f}")
print(f"Sample size: {n_samples}")
Figure 3.4: Analytical MLE for the Poisson model. The log-likelihood function peaks exactly at the sample mean, demonstrating the analytical result. This simple case builds intuition before we tackle the more complex Negative Binomial model.
True λ: 3.5
Sample mean (MLE): 3.460
Sample size: 100

3.3.4 Numerical MLE for the Negative Binomial Model

Now let’s return to our main running example: the phenomenological bursting model that produces a Negative Binomial distribution. Unlike the Poisson case, we cannot solve for the MLE analytically and must use numerical optimization.

The Negative Binomial distribution has two parameters we’ll estimate via MLE:

  • r: the burst size parameter
  • p: the burst frequency parameter

For the NB distribution, the log-likelihood is:

\ell(r, p | \mathbf{n}) = \sum_{i=1}^{N} \left[ \log\binom{n_i + r - 1}{n_i} + r \log p + n_i \log(1-p) \right]

This expression involves the binomial coefficient, which makes analytical differentiation complex. Instead, we’ll use numerical optimization to find the MLE.

Let’s implement this approach and visualize the likelihood landscape:

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom
from scipy.optimize import minimize

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Generate synthetic negative binomial data
rng = np.random.default_rng(456)
r_true = 5.0  # burst size parameter
p_true = 0.25  # burst frequency parameter
n_samples = 200
nb_data = nbinom.rvs(n=r_true, p=p_true, size=n_samples, random_state=rng)

# Define negative log-likelihood function
def neg_log_likelihood_nb(params, data):
    r, p = params
    if r <= 0 or p <= 0 or p >= 1:
        return np.inf
    return -np.sum(nbinom.logpmf(data, n=r, p=p))

# Create contour plot of likelihood landscape
r_range = np.linspace(1, 10, 50)
p_range = np.linspace(0.1, 0.9, 50)
R, P = np.meshgrid(r_range, p_range)

# Calculate log-likelihood for each point
log_likelihoods = np.zeros_like(R)
for i in range(len(r_range)):
    for j in range(len(p_range)):
        log_likelihoods[j, i] = -neg_log_likelihood_nb([R[j, i], P[j, i]], nb_data)

# Plot contour
plt.figure()
plt.contourf(R, P, log_likelihoods, levels=20, alpha=0.6, cmap='plasma')
plt.colorbar(label='Log-likelihood')

# Find MLE using numerical optimization
initial_guess = [3.0, 0.5]
result = minimize(neg_log_likelihood_nb, initial_guess, args=(nb_data,),
                 bounds=[(0.1, 20), (0.01, 0.99)], method='L-BFGS-B')

r_mle, p_mle = result.x

# Mark true values and MLE
plt.plot(r_true, p_true, 'ko', markersize=8, label=f'True values (r={r_true}, p={p_true})')
plt.plot(r_mle, p_mle, '*', color=QUALITATIVE_COLORS[0], markersize=12, label=f'MLE (r={r_mle:.2f}, p={p_mle:.2f})')

plt.xlabel('r (burst size parameter)')
plt.ylabel('p (burst frequency parameter)')
plt.title('Negative Binomial MLE: Likelihood Landscape')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

print(f"True parameters: r={r_true}, p={p_true}")
print(f"MLE estimates: r={r_mle:.3f}, p={p_mle:.3f}")
print(f"Sample size: {n_samples}")
print(f"Sample mean: {np.mean(nb_data):.2f}")
print(f"Sample variance: {np.var(nb_data, ddof=1):.2f}")
Figure 3.5: Maximum likelihood estimation for the Negative Binomial model. The 2D contour plot shows the log-likelihood landscape, with the MLE marked by the red star. The black dot shows the true parameter values used to generate the data.
True parameters: r=5.0, p=0.25
MLE estimates: r=4.953, p=0.253
Sample size: 200
Sample mean: 14.63
Sample variance: 65.39
A Note on Optimizing Functions in Modern Times

How did minimize() actually find the peak in that likelihood landscape? Modern optimization methods come in two flavors.

Derivative-free optimizers like Nelder-Mead search the parameter space by evaluating the function at different points and following patterns in the values. They’re robust and require only the function itself—no derivatives needed. But they can be slow, especially in high dimensions, because they’re searching without directional information.

Gradient-based optimizers like L-BFGS-B use derivative information to march directly toward the peak. They’re typically much faster and more accurate because they know which direction is uphill.

The surprise: gradient-based optimization is now trivially easy with automatic differentiation (autograd). You write the function once, and autograd computes exact derivatives automatically. Libraries like JAX, PyTorch, and TensorFlow make this the new default.

This is not finite differences. Finite differences approximate derivatives numerically via \frac{\partial f}{\partial \theta} \approx \frac{f(\theta + h) - f(\theta)}{h}, which is noisy and expensive (requires n+1 function evaluations for n parameters). Autograd uses the chain rule to compute exact derivatives in a single forward and backward pass. For a composition f(g(h(\theta))), the chain rule gives:

\frac{\partial f}{\partial \theta} = \frac{\partial f}{\partial g} \cdot \frac{\partial g}{\partial h} \cdot \frac{\partial h}{\partial \theta}

Autograd builds a computational graph of your function’s operations and applies the chain rule automatically, yielding exact derivatives (up to floating-point precision) at essentially the cost of one function evaluation.

The syntax is remarkably simple:

# Define your function
grad_f = jax.grad(f)  # Get gradient function automatically

# Use it in optimization
minimize(f, x0, method='L-BFGS-B', jac=grad_f)

Let’s compare both approaches on our negative binomial likelihood, visualizing their paths through parameter space:

Code
import jax
import jax.numpy as jnp
from jax import grad
from scipy.optimize import minimize
from scipy.stats import nbinom
import numpy as np
import matplotlib.pyplot as plt

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Use the same synthetic data from the previous example
# (nb_data, r_true, p_true are already defined)

# Step 1: Define your likelihood function (using JAX operations)
def neg_ll_with_grad(params, data):
    r, p = params[0], params[1]
    from jax.scipy.special import gammaln
    k = jnp.array(data)
    log_lik = jnp.sum(
        gammaln(k + r) - gammaln(k + 1) - gammaln(r) +
        r * jnp.log(p) + k * jnp.log(1 - p)
    )
    return -log_lik

# Step 2: Get the gradient function for free with autograd
grad_neg_ll = jax.grad(neg_ll_with_grad)  # That's it!

# Starting point (intentionally far from optimum to show contrast)
x0 = np.array([2.0, 0.8])

# Storage for optimization paths (include initial point)
path_nelder_mead = [x0.copy()]
path_lbfgsb = [x0.copy()]

def callback_nm(xk):
    path_nelder_mead.append(xk.copy())

def callback_lbfgsb(xk):
    path_lbfgsb.append(xk.copy())

# Method 1: Nelder-Mead (derivative-free) - just needs the function
result_nm = minimize(
    lambda p: neg_ll_with_grad(p, nb_data),
    x0,
    method='Nelder-Mead',
    callback=callback_nm,
    options={'maxiter': 200}
)

# Method 2: L-BFGS-B (gradient-based) - just add the autograd gradient
result_lbfgsb = minimize(
    lambda p: neg_ll_with_grad(p, nb_data),
    x0,
    method='L-BFGS-B',
    jac=lambda p: np.array(grad_neg_ll(p, nb_data)),  # Pass the autograd gradient here
    bounds=[(0.1, 20), (0.01, 0.99)],
    callback=callback_lbfgsb,
    options={'maxiter': 200}
)

# Convert paths to arrays
path_nm = np.array(path_nelder_mead)
path_lb = np.array(path_lbfgsb)

# Create visualization on the likelihood landscape
plt.figure()
# Reuse the likelihood landscape from the previous figure
r_range = np.linspace(1, 12, 50)
p_range = np.linspace(0.1, 0.9, 50)
R, P = np.meshgrid(r_range, p_range)
log_likelihoods = np.zeros_like(R)
for i in range(len(r_range)):
    for j in range(len(p_range)):
        log_likelihoods[j, i] = -neg_ll_with_grad([R[j, i], P[j, i]], nb_data)

plt.contourf(R, P, log_likelihoods, levels=20, alpha=0.6, cmap='plasma')

# Plot optimization paths
if len(path_nm) > 0:
    plt.plot(path_nm[:, 0], path_nm[:, 1], 'o-', color=QUALITATIVE_COLORS[5],
             linewidth=2, markersize=4, alpha=0.7,
             label=f'Nelder-Mead ({len(path_nm)} steps)')
if len(path_lb) > 0:
    plt.plot(path_lb[:, 0], path_lb[:, 1], 's-', color=QUALITATIVE_COLORS[2],
             linewidth=2, markersize=4, alpha=0.7,
             label=f'L-BFGS-B + autograd ({len(path_lb)} steps)')

# Mark key points
plt.plot(x0[0], x0[1], '*', color=QUALITATIVE_COLORS[1], markersize=15, label='Initial guess', zorder=5)
plt.plot(r_mle, p_mle, '*', color=QUALITATIVE_COLORS[0], markersize=15, label='MLE', zorder=5)

plt.xlabel('r (burst size parameter)')
plt.ylabel('p (burst frequency parameter)')
plt.title('Optimization Paths: Derivative-Free vs Gradient-Based')
plt.legend(loc='upper right')
plt.grid(True, alpha=0.3)
plt.show()

print(f"Nelder-Mead: {len(path_nm)} iterations, final LL = {-result_nm.fun:.2f}")
print(f"L-BFGS-B (autograd): {len(path_lb)} iterations, final LL = {-result_lbfgsb.fun:.2f}")
Figure 3.6: Comparing derivative-free and gradient-based optimization. The Nelder-Mead algorithm (derivative-free, orange) takes a wandering path with many function evaluations. The L-BFGS-B algorithm (gradient-based, blue) marches directly toward the optimum using gradient information from autograd. Both start from the same initial guess (green star) and find the MLE (red star), but the gradient-based method is dramatically more efficient.
Nelder-Mead: 65 iterations, final LL = -674.12
L-BFGS-B (autograd): 13 iterations, final LL = -674.12

Bottom line: with autograd, you supply only the likelihood function—the gradient comes for free. This combination of gradient-based optimization with automatic differentiation is the foundation of modern machine learning and should be your default approach for any non-trivial inference problem.

Notice how the MLE captures the true parameters reasonably well, but there’s inherent uncertainty due to finite sample size. How confident should we be in our estimates?

3.3.5 Quantifying Uncertainty: Confidence Intervals for the MLE

The MLE gives us a point estimate, but we need to quantify our uncertainty. There are two main approaches:

3.3.5.1 Method 1: Fisher Information and the Delta Method

The Fisher Information provides a classical approach to MLE uncertainty quantification.

To build intuition, think of the likelihood as a surface in parameter space. The MLE sits at the peak of this surface, where the first derivatives (the slope) are zero. But what tells us how sharp or flat this peak is? The answer lies in the second derivatives—the curvature of the likelihood surface. A sharp, needle-like peak (high curvature) means small changes in parameters cause large drops in likelihood, indicating high certainty in our estimates. A broad, flat peak (low curvature) suggests many parameter values fit the data nearly as well, reflecting high uncertainty.

Formal Definition: Fisher Information Matrix

For a parameter vector \theta = (\theta_1, \theta_2, \ldots, \theta_k), the Fisher Information matrix is defined as:

I(\theta) = -E\left[ \frac{\partial^2 \ell(\theta)}{\partial \theta \partial \theta^T} \right]

where the (i,j)-th element is:

I_{ij}(\theta) = -E\left[ \frac{\partial^2 \ell(\theta)}{\partial \theta_i \partial \theta_j} \right]

The Fisher Information quantifies the amount of information that observable data carries about the unknown parameters. Higher Fisher Information means the data provides more precise information about the parameter values.

Key Mathematical Properties:

For i.i.d. data with n observations, the total Fisher Information is additive: I_n(\theta) = n \cdot I_1(\theta), where I_1(\theta) is the Fisher Information from a single observation. This fundamental property underlies many asymptotic results and explains why estimation precision improves with \sqrt{n}.

Notational convention: In what follows, when we write \ell(\theta) inside an expectation E[\cdot] over a random variable x, we mean the log-likelihood for a single observation: \ell(\theta) = \log f(x \mid \theta). This is standard notation in theoretical statistics and allows us to write Fisher Information properties compactly.

First, we establish that the score (first derivative of log-likelihood) has zero expectation at the true parameter value. For a single observation with PDF f(x \mid \theta):

\begin{align} E\left[ \frac{\partial \ell(\theta)}{\partial \theta} \right] &= \int \frac{\partial \log f(x \mid \theta)}{\partial \theta} f(x \mid \theta) \, dx \\ &= \int \frac{1}{f(x \mid \theta)} \frac{\partial f(x \mid \theta)}{\partial \theta} f(x \mid \theta) \, dx \\ &= \int \frac{\partial f(x \mid \theta)}{\partial \theta} \, dx \\ &= \frac{\partial}{\partial \theta} \int f(x \mid \theta) \, dx = \frac{\partial}{\partial \theta} (1) = 0 \end{align}

where we used the chain rule for logarithms and exchanged integration and differentiation (valid under regularity conditions).

The Information Matrix Equality follows by differentiating the score’s zero-expectation property with respect to \theta. Writing the expectation as an integral makes the calculation transparent:

\begin{align} 0 &= \frac{\partial}{\partial \theta} E\left[ \frac{\partial \ell(\theta)}{\partial \theta} \right] \\ &= \frac{\partial}{\partial \theta} \int \frac{\partial \log f(x \mid \theta)}{\partial \theta} f(x \mid \theta) \, dx \\ &= \int \frac{\partial^2 \log f(x \mid \theta)}{\partial \theta^2} f(x \mid \theta) \, dx + \int \frac{\partial \log f(x \mid \theta)}{\partial \theta} \frac{\partial f(x \mid \theta)}{\partial \theta} \, dx \\ &= E\left[ \frac{\partial^2 \ell(\theta)}{\partial \theta^2} \right] + E\left[ \left(\frac{\partial \ell(\theta)}{\partial \theta}\right)^2 \right] \end{align}

where the second term arises from applying the product rule to \frac{\partial}{\partial \theta}[\text{score} \cdot f(x \mid \theta)], using the fact that \frac{\partial \log f}{\partial \theta} = \frac{1}{f}\frac{\partial f}{\partial \theta}.

Rearranging gives the two equivalent forms of Fisher Information:

I(\theta) = E\left[ \left(\frac{\partial \ell(\theta)}{\partial \theta}\right)^2 \right] = -E\left[ \frac{\partial^2 \ell(\theta)}{\partial \theta^2} \right]

This shows Fisher Information can be computed either from the variance of the score (since the score has zero mean) or the negative expectation of the Hessian.

The Cramér-Rao Lower Bound:

The Fisher Information has a profound consequence through the Cramér-Rao bound, which establishes a fundamental limit on estimation accuracy. For any unbiased estimator \hat{\theta} (meaning E[\hat{\theta}] = \theta):

\text{Var}(\hat{\theta}) \geq I(\theta)^{-1}

This inequality says no unbiased estimator can achieve lower variance than the inverse Fisher Information. High information (large I(\theta)) means high precision (small variance), and vice versa. The MLE is asymptotically efficient, meaning as n \to \infty, it achieves this bound: \text{Var}(\hat{\theta}_{MLE}) \to I(\theta)^{-1}. This directly answers why the variance equals 1/\text{FIM} and establishes MLE as achieving the best possible precision for burst parameter estimation from single-cell data.

In practice, we approximate this using the observed Hessian (second derivatives) at the MLE:

\hat{I}(\hat{\theta}) = -\left. \frac{\partial^2 \ell(\theta)}{\partial \theta^2} \right|_{\theta = \hat{\theta}}

The inverse of the Fisher Information gives us the asymptotic covariance matrix:

\text{Cov}(\hat{\theta}) \approx I(\hat{\theta})^{-1}

Constructing Confidence Intervals: The fundamental result underlying Fisher Information-based inference is the asymptotic normality of the MLE:

\hat{\theta} \xrightarrow{d} N\left(\theta_0, I(\theta_0)^{-1}\right)

where \theta_0 is the true parameter value and \xrightarrow{d} denotes convergence in distribution as sample size n \to \infty.

But where does this fundamental result come from? Let’s see the key steps.

Derivation Sketch: Asymptotic Normality of the MLE

The MLE \hat{\theta} satisfies the score equation s(\hat{\theta}) = 0, where s(\theta) = \partial\ell/\partial\theta is the score function. We can understand its asymptotic behavior through Taylor expansion around the true parameter \theta_0:

0 = s(\hat{\theta}) = s(\theta_0) + s'(\theta_0)(\hat{\theta} - \theta_0) + O_p(|\hat{\theta} - \theta_0|^2)

where s'(\theta) = \partial^2\ell/\partial\theta^2 is the Hessian. Rearranging and multiplying by \sqrt{n}:

\sqrt{n}(\hat{\theta} - \theta_0) = -\left(\frac{1}{n}s'(\theta_0)\right)^{-1} \frac{1}{\sqrt{n}}s(\theta_0) + o_p(1)

Now the magic: the score at the true parameter is a sum of i.i.d. terms with mean zero (from our earlier calculation) and variance equal to the Fisher Information per observation. By the Central Limit Theorem:

\frac{1}{\sqrt{n}}s(\theta_0) \xrightarrow{d} N(0, I_1(\theta_0))

Meanwhile, by the Law of Large Numbers, the normalized Hessian converges to its expectation:

-\frac{1}{n}s'(\theta_0) \xrightarrow{p} I_1(\theta_0)

Combining these via Slutsky’s theorem:

\sqrt{n}(\hat{\theta} - \theta_0) \xrightarrow{d} I_1(\theta_0)^{-1} \cdot N(0, I_1(\theta_0)) = N(0, I_1(\theta_0)^{-1})

For n observations with total Fisher Information I_n(\theta_0) = n \cdot I_1(\theta_0), this gives \hat{\theta} \xrightarrow{d} N(\theta_0, I_n(\theta_0)^{-1}).

This derivation reveals the deep connections: the score function (first derivative) determines the MLE location, the Fisher Information (second derivative curvature) determines uncertainty, and classical limit theorems (CLT, LLN) provide asymptotic normality. The variance inversely proportional to Fisher Information emerges naturally, confirming the Cramér-Rao bound. The connection to information theory runs even deeper: MLE minimizes the empirical KL divergence between the true distribution and our model, making it information-theoretically optimal.

For a single parameter \theta, a (1-\alpha) confidence interval is:

\text{CI}_{1-\alpha}(\theta) = \left[\hat{\theta} - z_{\alpha/2} \sqrt{I(\hat{\theta})^{-1}}, \, \hat{\theta} + z_{\alpha/2} \sqrt{I(\hat{\theta})^{-1}}\right]

where z_{\alpha/2} is the critical value from the standard normal distribution (e.g., z_{0.025} = 1.96 for a 95% CI).

For multiple parameters \theta = (\theta_1, \ldots, \theta_k), the confidence region is an ellipse defined by:

(\theta - \hat{\theta})^T I(\hat{\theta}) (\theta - \hat{\theta}) \le \chi^2_{k, 1-\alpha}

where \chi^2_{k, 1-\alpha} is the (1-\alpha) quantile of the chi-squared distribution with k degrees of freedom. The \chi^2_k distribution arises because this quadratic form is the squared Mahalanobis distance: when \hat{\theta} \sim N(\theta_0, I^{-1}), the standardized distance (\theta_0 - \hat{\theta})^T I (\theta_0 - \hat{\theta}) follows a \chi^2_k distribution (the multivariate generalization of squaring a standard normal). This inequality defines the set of parameter values \theta that are “consistent” with the data at level 1-\alpha. Geometrically, the covariance matrix \Sigma = I(\hat{\theta})^{-1} determines the confidence ellipse: the eigenvectors define the ellipse’s orientation (its major and minor axes), while the eigenvalues scaled by \chi^2_{k, 1-\alpha} determine the squared lengths of those axes.

Let’s construct these confidence intervals:

Code
import numpy as np
from scipy.optimize import minimize
from scipy.stats import nbinom, chi2
import matplotlib.pyplot as plt

# Use the same data from previous example
# Calculate numerical Hessian at MLE
# Note: This numerical Hessian implementation is for demonstration. For production use,
# consider libraries like `numdifftools` or the Hessian returned by some optimization
# packages for better robustness to step size choice and floating-point errors.
def hessian_2d(func, x, h=1e-5):
    """Calculate numerical Hessian matrix"""
    n = len(x)
    H = np.zeros((n, n))

    for i in range(n):
        for j in range(n):
            if i == j:
                # Second derivative
                H[i, j] = (func(x + h*np.eye(n)[i]) - 2*func(x) + func(x - h*np.eye(n)[i])) / h**2
            else:
                # Mixed derivative
                H[i, j] = (func(x + h*np.eye(n)[i] + h*np.eye(n)[j]) - func(x + h*np.eye(n)[i] - h*np.eye(n)[j]) -
                          func(x - h*np.eye(n)[i] + h*np.eye(n)[j]) + func(x - h*np.eye(n)[i] - h*np.eye(n)[j])) / (4*h**2)
    return H

# Calculate Fisher Information
# Note: Since we computed the Hessian of the negative log-likelihood,
# the Fisher Information is simply the Hessian (not its negative)

# Use a lambda function to create a new function of one variable (p)
# that calls the original function with the required nb_data.
hessian = hessian_2d(lambda p: neg_log_likelihood_nb(p, nb_data), [r_mle, p_mle])
fisher_info = hessian
covariance_matrix = np.linalg.inv(fisher_info)

# Extract standard errors
se_r = np.sqrt(covariance_matrix[0, 0])
se_p = np.sqrt(covariance_matrix[1, 1])

print("Fisher Information Analysis:")
print(f"SE(r) = {se_r:.4f}")
print(f"SE(p) = {se_p:.4f}")
print(f"95% CI for r: [{r_mle - 1.96*se_r:.3f}, {r_mle + 1.96*se_r:.3f}]")
print(f"95% CI for p: [{p_mle - 1.96*se_p:.3f}, {p_mle + 1.96*se_p:.3f}]")

# Plot confidence ellipse
def confidence_ellipse(mean, cov, alpha=0.05):
    """Generate points for a confidence ellipse"""
    # Chi-square quantile for 2 parameters
    chi2_val = chi2.ppf(1 - alpha, df=2)

    # Eigendecomposition
    eigenvals, eigenvecs = np.linalg.eig(cov)

    # Angle of rotation
    angle = np.arctan2(eigenvecs[1, 0], eigenvecs[0, 0])

    # Semi-axes lengths
    a = np.sqrt(chi2_val * eigenvals[0])
    b = np.sqrt(chi2_val * eigenvals[1])

    # Generate ellipse points
    t = np.linspace(0, 2*np.pi, 100)
    ellipse = np.array([a * np.cos(t), b * np.sin(t)])

    # Rotate and translate
    R = np.array([[np.cos(angle), -np.sin(angle)],
                  [np.sin(angle), np.cos(angle)]])
    ellipse = R @ ellipse + mean.reshape(-1, 1)

    return ellipse[0], ellipse[1]

# Plot with confidence ellipse
plt.figure()
contourf = plt.contourf(R, P, log_likelihoods, levels=20, cmap='plasma', alpha=0.6)

plt.colorbar(contourf, label='Log-likelihood')

# Add confidence ellipse
ellipse_r, ellipse_p = confidence_ellipse(np.array([r_mle, p_mle]), covariance_matrix)
plt.plot(ellipse_r, ellipse_p, color=QUALITATIVE_COLORS[0], linewidth=2, label='95% Confidence Ellipse')

# Mark points
plt.plot(r_true, p_true, 'ko', markersize=10, label='True values')
plt.plot(r_mle, p_mle, '*', color=QUALITATIVE_COLORS[0], markersize=15, label='MLE')

plt.xlabel('r (burst size parameter)')
plt.ylabel('p (burst frequency parameter)')
plt.title('Fisher Information Confidence Region')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
Fisher Information Analysis:
SE(r) = 0.6596
SE(p) = 0.0261
95% CI for r: [3.660, 6.246]
95% CI for p: [0.202, 0.304]
Figure 3.7: Fisher Information-based confidence intervals for the Negative Binomial MLE. The ellipse shows the approximate 95% confidence region based on the asymptotic normality of the MLE.

3.3.5.2 Method 2: Bootstrap Confidence Intervals

While the Fisher Information provides an elegant analytical approach, calculating the Hessian matrix can be difficult or numerically unstable for complex models. The bootstrap offers a powerful, simulation-based alternative that bypasses these challenges.

Figure 3.8: Schematic illustration of the bootstrap resampling procedure.

The bootstrap provides a more robust, non-parametric approach to uncertainty quantification. The algorithm is beautifully simple:

  1. Resample: Create many new datasets by sampling from the original data with replacement
  2. Re-estimate: Calculate the MLE for each bootstrap dataset
  3. Analyze: The distribution of bootstrap MLEs gives us empirical confidence intervals
Code
# Bootstrap analysis
rng = np.random.default_rng(42) # for reproducibility of bootstrap samples
n_bootstrap = 1000
bootstrap_estimates = []

print(f"Running {n_bootstrap} bootstrap iterations...")

for i in range(n_bootstrap):
    # Resample data with replacement
    bootstrap_data = rng.choice(nb_data, size=len(nb_data), replace=True)

    # Define negative log-likelihood for bootstrap data
    def neg_ll_bootstrap(params):
        r, p = params
        if r <= 0 or p <= 0 or p >= 1:
            return np.inf
        return -np.sum(nbinom.logpmf(bootstrap_data, n=r, p=p))

    # Optimize
    try:
        result = minimize(neg_ll_bootstrap, [r_mle, p_mle], method='L-BFGS-B',
                         bounds=[(0.1, 20), (0.01, 0.99)])
        if result.success:
            bootstrap_estimates.append(result.x)
    except:
        continue

bootstrap_estimates = np.array(bootstrap_estimates)
bootstrap_r = bootstrap_estimates[:, 0]
bootstrap_p = bootstrap_estimates[:, 1]

# Calculate bootstrap confidence intervals
r_ci = np.percentile(bootstrap_r, [2.5, 97.5])
p_ci = np.percentile(bootstrap_p, [2.5, 97.5])

print(f"\nBootstrap Results ({len(bootstrap_estimates)} successful iterations):")
print(f"Bootstrap SE(r) = {np.std(bootstrap_r):.4f}")
print(f"Bootstrap SE(p) = {np.std(bootstrap_p):.4f}")
print(f"Bootstrap 95% CI for r: [{r_ci[0]:.3f}, {r_ci[1]:.3f}]")
print(f"Bootstrap 95% CI for p: [{p_ci[0]:.3f}, {p_ci[1]:.3f}]")

# Create comprehensive plot
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

# Bootstrap distribution of r
ax1.hist(bootstrap_r, bins=30, alpha=0.7, color='gray', edgecolor='none', density=True)
ax1.axvline(r_mle, color=QUALITATIVE_COLORS[0], linestyle='--', label=f'MLE = {r_mle:.3f}')
ax1.axvline(r_true, color=QUALITATIVE_COLORS[1], linestyle='-', label=f'True = {r_true}')
ax1.axvline(r_ci[0], color=QUALITATIVE_COLORS[5], linestyle=':', label='95% CI')
ax1.axvline(r_ci[1], color=QUALITATIVE_COLORS[5], linestyle=':')
ax1.set_xlabel('r (burst size parameter)')
ax1.set_ylabel('Bootstrap density')
ax1.set_title('Bootstrap Distribution of r')
ax1.legend()
ax1.grid(True, alpha=0.3)

# Bootstrap distribution of p
ax2.hist(bootstrap_p, bins=30, alpha=0.7, color='gray', edgecolor='none', density=True)
ax2.axvline(p_mle, color=QUALITATIVE_COLORS[0], linestyle='--', label=f'MLE = {p_mle:.3f}')
ax2.axvline(p_true, color=QUALITATIVE_COLORS[1], linestyle='-', label=f'True = {p_true}')
ax2.axvline(p_ci[0], color=QUALITATIVE_COLORS[5], linestyle=':', label='95% CI')
ax2.axvline(p_ci[1], color=QUALITATIVE_COLORS[5], linestyle=':')
ax2.set_xlabel('p (burst frequency parameter)')
ax2.set_ylabel('Bootstrap density')
ax2.set_title('Bootstrap Distribution of p')
ax2.legend()
ax2.grid(True, alpha=0.3)

# 2D scatter of bootstrap estimates
ax3.scatter(bootstrap_r, bootstrap_p, alpha=0.5, s=10, color='gray')
ax3.plot(r_mle, p_mle, '*', color=QUALITATIVE_COLORS[0], markersize=15, label='MLE')
ax3.plot(r_true, p_true, 'ko', markersize=10, label='True values')
ax3.set_xlabel('r (burst size parameter)')
ax3.set_ylabel('p (burst frequency parameter)')
ax3.set_title('Bootstrap Parameter Estimates')
ax3.legend()
ax3.grid(True, alpha=0.3)

# Comparison of methods - grouped by parameter
parameters = ['r', 'p']
fisher_errors = [se_r, se_p]
bootstrap_errors = [np.std(bootstrap_r), np.std(bootstrap_p)]

x = np.arange(len(parameters))
width = 0.35

ax4.bar(x - width/2, fisher_errors, width, label='Fisher Info SE', alpha=0.7, color=QUALITATIVE_COLORS[0], edgecolor='none')
ax4.bar(x + width/2, bootstrap_errors, width, label='Bootstrap SE', alpha=0.7, color=QUALITATIVE_COLORS[1], edgecolor='none')
ax4.set_xlabel('Parameter')
ax4.set_ylabel('Standard Error')
ax4.set_title('Comparison of Uncertainty Methods')
ax4.set_xticks(x)
ax4.set_xticklabels(parameters)
ax4.legend()
ax4.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()
Running 1000 bootstrap iterations...

Bootstrap Results (1000 successful iterations):
Bootstrap SE(r) = 0.8296
Bootstrap SE(p) = 0.0333
Bootstrap 95% CI for r: [3.782, 6.962]
Bootstrap 95% CI for p: [0.199, 0.332]
Figure 3.9: Bootstrap confidence intervals for the Negative Binomial MLE. The left panels show histograms of bootstrap parameter estimates, while the right panel shows the 2D distribution of bootstrap estimates with confidence regions.

MLE is the workhorse of inference for good reason. It gives us the single “best” parameter values and comes with strong theoretical guarantees: it’s consistent (gets the right answer with enough data) and asymptotically efficient (achieves the lowest possible uncertainty for large datasets). We can also quantify our confidence through methods like Fisher Information or Bootstrap resampling.

But a single answer, even one with a confidence interval, comes with a philosophical catch. The 95% confidence interval is a statement about our procedure, not a direct statement of belief about the parameter itself. What if we want to ask, ‘Given my data, what is the probability the burst size is between 10 and 20?’ For that, we must change our framework entirely.

We have now used the full power of the likelihood to find the single “best” parameter set and have even drawn confidence intervals around it. It is tempting to declare victory. But a crucial question remains: can we truly trust this result? What if the peak we found is not a sharp, well-defined mountain top, but a long, flat ridge where many different parameter combinations fit the data almost equally well? Before we can make any biological claims, we must confront this sobering possibility.


3.4 Identifiability: What Can We Actually Learn?

We’ve just learned how to find the “best” parameters through maximum likelihood estimation. The algorithm converged, the fit looks good, and we have our answer. Our work is done, right?

Not quite. Let’s pose a critical question: What if the peak of our likelihood mountain is not a sharp, well-defined summit, but a long, flat ridge where many different parameter combinations fit the data almost equally well? Our “best-fit” parameters might be just one point along an entire curve of equally plausible solutions.

The concept of identifiability addresses exactly this question: can our model’s parameters be uniquely determined from our data? This isn’t merely a statistical concern—it determines what biological mechanisms we can actually infer from our experiments.

3.4.1 The Two Faces of Identifiability

Identifiability manifests in two distinct forms:

Structural Identifiability: A fundamental property of the model itself. Even with infinite, perfect data of a given type, can we uniquely determine all parameters? This depends on the mathematical structure of our equations and what we choose to measure.

Practical Identifiability: A property of our actual, finite, noisy dataset. The model might be structurally sound, but our specific experimental data may be too poor to pin down the parameters with confidence.

We’ll explore both using a single, simple running example—the constitutive gene—to build intuition before moving to more complex cases.

3.4.2 Structural Non-Identifiability: The Constitutive Gene Example

Let’s return to the simplest gene expression model from Chapter 1: the constitutive gene. The ODE model is:

\frac{dx}{dt} = \beta - \gamma x

with steady-state solution x_{ss} = \beta/\gamma.

Now suppose we collect steady-state data: a set of protein concentrations from many cells. Each measurement follows a Poisson distribution around the mean steady-state level:

P(n | \beta, \gamma) = \text{Poisson}(n | \beta/\gamma)

Here’s the problem: the likelihood depends only on the ratio \lambda = \beta/\gamma. We can never identify \beta and \gamma individually from steady-state data alone. The model is structurally non-identifiable.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson

# 1. Simulate steady-state data
rng = np.random.default_rng(123)
beta_true, gamma_true = 6.0, 2.0
ratio_true = beta_true / gamma_true  # This is all the data can see
data = rng.poisson(ratio_true, size=500)

# 2. Define the log-likelihood function
def log_likelihood_steady_state(beta, gamma, data):
    if beta <= 0 or gamma <= 0:
        return -np.inf
    ratio = beta / gamma
    return np.sum(poisson.logpmf(data, mu=ratio))

# 3. Create grid and compute likelihood surface
beta_grid = np.linspace(2, 10, 80)
gamma_grid = np.linspace(0.5, 5, 80)
B, G = np.meshgrid(beta_grid, gamma_grid)
log_likelihood_surface = np.zeros_like(B)

for i in range(len(beta_grid)):
    for j in range(len(gamma_grid)):
        log_likelihood_surface[j, i] = log_likelihood_steady_state(B[j, i], G[j, i], data)

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# 4. Plot the contour map
plt.figure()
plt.contourf(B, G, log_likelihood_surface, levels=30, cmap='plasma',alpha=0.6)

plt.colorbar(label='Log-Likelihood')

# Highlight the ridge
beta_line = np.linspace(2, 10, 100)
gamma_line = beta_line / ratio_true
plt.plot(beta_line, gamma_line, '--', color=QUALITATIVE_COLORS[0], lw=2, label=f'Ridge where β/γ = {ratio_true:.1f}')

# Mark true values
plt.plot(beta_true, gamma_true, 'o', color=QUALITATIVE_COLORS[0], markersize=8, label='True parameters')

plt.xlabel('β (production rate)')
plt.ylabel('γ (degradation rate)')
plt.title('The Likelihood Ridge: Structural Non-Identifiability')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

print(f"Key insight: Only the ratio β/γ = {ratio_true:.1f} is identifiable from steady-state data")
print(f"Sample mean: {np.mean(data):.3f} ≈ {ratio_true:.1f} (expected steady-state)")
Figure 3.10: Structural non-identifiability in the constitutive gene model. When only steady-state data is available, the likelihood surface forms a perfect ridge. Any parameter combination (β,γ) along this ridge produces an identical fit, making it impossible to identify the parameters individually.
Key insight: Only the ratio β/γ = 3.0 is identifiable from steady-state data
Sample mean: 2.972 ≈ 3.0 (expected steady-state)
Mathematical Diagnosis: The Hessian Matrix

The Hessian matrix provides a precise mathematical diagnostic for identifiability. Let’s see how it reveals the structural problem in our steady-state example, then understand how to use it as a practical tool.

We can derive the analytical Hessian for the steady-state Poisson model. The log-likelihood depends only on the ratio \lambda = \beta/\gamma: \ell(\beta, \gamma) = \sum_{i=1}^N \left[ n_i \log\left(\frac{\beta}{\gamma}\right) - \frac{\beta}{\gamma} - \log(n_i!) \right]

The Hessian matrix of the negative log-likelihood is: H = \begin{pmatrix} \frac{N}{\beta^2} & -\frac{N}{\beta \gamma} \\ -\frac{N}{\beta \gamma} & \frac{N}{\gamma^2} \end{pmatrix}

Since \det(H) = 0, this matrix is singular with a zero eigenvalue, mathematically proving the unidentifiable direction along \beta/\gamma = \text{constant}.

Code
from scipy.optimize import minimize

# Pick a point on the ridge for analysis
beta_test, gamma_test = 4.0, 4.0/3.0  # Ratio = 3.0, on the ridge

# Define negative log-likelihood for optimization
def neg_log_likelihood_2d(params):
    beta, gamma = params
    if beta <= 0 or gamma <= 0:
        return np.inf
    return -log_likelihood_steady_state(beta, gamma, data)

# Compute Hessian numerically using finite differences
def compute_hessian(func, params, h=1e-5):
    """Compute Hessian matrix numerically using finite differences"""
    x, y = params

    # Second partial derivatives using finite differences
    fxx = (func([x+h, y]) - 2*func([x, y]) + func([x-h, y])) / h**2
    fyy = (func([x, y+h]) - 2*func([x, y]) + func([x, y-h])) / h**2
    fxy = (func([x+h, y+h]) - func([x+h, y-h]) - func([x-h, y+h]) + func([x-h, y-h])) / (4*h**2)

    return np.array([[fxx, fxy],
                     [fxy, fyy]])

# Compute Hessian at test point
hessian = compute_hessian(neg_log_likelihood_2d, [beta_test, gamma_test])
eigenvals, eigenvecs = np.linalg.eigh(hessian)

print(f"Analysis at point (β={beta_test:.1f}, γ={gamma_test:.2f}) on the ridge:")
print(f"Eigenvalues: {eigenvals[0]:.3f}, {eigenvals[1]:.3f}")
print(f"Ratio of eigenvalues: {eigenvals[1]/eigenvals[0]:.1f}")
print(f"The small eigenvalue (~{eigenvals[0]:.3f}) indicates the flat direction along the ridge")
print(f"The large eigenvalue (~{eigenvals[1]:.1f}) indicates curvature perpendicular to the ridge")
Analysis at point (β=4.0, γ=1.33) on the ridge:
Eigenvalues: -0.008, 944.510
Ratio of eigenvalues: -123568.4
The small eigenvalue (~-0.008) indicates the flat direction along the ridge
The large eigenvalue (~944.5) indicates curvature perpendicular to the ridge

The numerical Hessian gives eigenvalues ~0.003 and ~75 rather than exact zero due to finite difference errors—this is the practical diagnostic. For complex models without analytical solutions, we compute the Hessian numerically and look for near-zero eigenvalues as the signature of identifiability problems. The eigenvalue ratio (here ~25,000:1) quantifies the severity.

The eigenvectors reveal which parameter combinations are constrained versus unidentifiable. Large eigenvalues indicate sharp curvature where data strongly constrains parameters. The eigenvector for the near-zero eigenvalue points along \beta/\gamma = \text{constant}, showing exactly which combination is unresolved. This guides experimental design: we need measurements with information perpendicular to this flat direction.

3.4.3 The Fix: Changing the Experiment

Structural non-identifiability is not a mathematical limitation—it’s a statement about information content. The solution is to change the experiment to collect data with more information.

For the constitutive gene, we can solve the identifiability problem by collecting temporal data: measurements of how the protein distribution approaches steady state over time.

The time-dependent solution to our ODE is: x(t) = \frac{\beta}{\gamma}(1 - e^{-\gamma t}) + x_0 e^{-\gamma t}

From time-course data, we can separately identify both \beta and \gamma: the steady-state level determines \beta/\gamma, while the rate of approach to steady state determines \gamma.

Now let’s see how changing our experimental design transforms identifiability. By collecting time-course data that captures the system’s approach to steady state, we gain crucial information about both the equilibrium level (\beta/\gamma) and the dynamics (\gamma).

Code
from scipy.integrate import solve_ivp

# Simulate rich time-course dataset
def constitutive_gene_ode(t, x, beta, gamma):
    return [beta - gamma * x[0]]

beta_true, gamma_true = 6.0, 2.0
x0 = [0.0]
t_span = (0, 5)
t_full = np.linspace(0, 5, 50)

# Solve ODE and add noise
sol = solve_ivp(constitutive_gene_ode, t_span, x0, t_eval=t_full, args=(beta_true, gamma_true))
x_true = sol.y[0]
rng = np.random.default_rng(42)
noise_std = 0.3
x_full = x_true + rng.normal(0, noise_std, len(t_full))

# Create "impatient" dataset - last 50% only
n_total = len(t_full)
n_impatient = int(0.5 * n_total)
start_idx = n_total - n_impatient
t_impatient = t_full[start_idx:]
x_impatient = x_full[start_idx:]

# Define temporal log-likelihood
def temporal_log_likelihood(params, t_data, x_data):
    beta, gamma = params
    if beta <= 0 or gamma <= 0:
        return -np.inf
    try:
        # Always solve from t=0 with initial condition x0=[0.0],
        # but only evaluate at the time points in t_data
        sol = solve_ivp(constitutive_gene_ode, (0, t_data[-1]), x0,
                       t_eval=t_data, args=(beta, gamma))
        x_pred = sol.y[0]
        return -0.5 * np.sum(((x_data - x_pred) / noise_std)**2)
    except:
        return -np.inf

# Create parameter grid with wider ranges for better context
beta_range = np.linspace(2, 12, 50)
gamma_range = np.linspace(0.5, 4, 50)
B, G = np.meshgrid(beta_range, gamma_range)

# Compute likelihood surfaces
ll_full = np.zeros_like(B)
ll_impatient = np.zeros_like(B)

for i in range(len(beta_range)):
    for j in range(len(gamma_range)):
        ll_full[j, i] = temporal_log_likelihood([B[j, i], G[j, i]], t_full, x_full)
        ll_impatient[j, i] = temporal_log_likelihood([B[j, i], G[j, i]], t_impatient, x_impatient)

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Create 3-panel figure stacked back to horizontally
# Panel A (time series) 
fig, (ax1, ax2, ax3) = plt.subplots(1, 3)

# Panel A: The data
ax1.plot(t_full, x_full, 'o-', color=QUALITATIVE_COLORS[0], alpha=0.7, label='Full Data')
ax1.plot(t_impatient, x_impatient, 'o-', color=QUALITATIVE_COLORS[1], markersize=6, linewidth=3,
         label='Impatient Data (Final 50%)')
ax1.plot(t_full, x_true, 'k--', alpha=0.8, linewidth=2, label='True Trajectory')
ax1.axhline(beta_true/gamma_true, color=QUALITATIVE_COLORS[0], linestyle=':', alpha=0.7,
           label=f'Steady State = {beta_true/gamma_true:.1f}')
ax1.set_xlabel('Time')
ax1.set_ylabel('Concentration x')
ax1.set_title('A: Experimental Data Collection')
ax1.legend(loc='lower right', fontsize=9)
ax1.grid(True, alpha=0.3)

# Convert to relative likelihood (exp scale) for better visualization
from matplotlib.colors import LogNorm
ll_full_rel = np.exp(ll_full - np.max(ll_full))
ll_impatient_rel = np.exp(ll_impatient - np.max(ll_impatient))

# Clip to avoid underflow to exact zero (which gets masked in LogNorm)
ll_full_rel = np.clip(ll_full_rel, 1e-10, 1)
ll_impatient_rel = np.clip(ll_impatient_rel, 1e-10, 1)

# Panel B: Full data likelihood (fewer levels = looser contours)
ax2.contourf(B, G, ll_full_rel, levels=np.logspace(-10, 0, 8), cmap='plasma', norm=LogNorm(vmin=1e-10, vmax=1),alpha=0.6)

ax2.plot(beta_true, gamma_true, 'ko', markersize=8, label='True Values')
ax2.set_xlabel('β (production rate)')
ax2.set_ylabel('γ (degradation rate)')
ax2.set_title('B: Likelihood (Full Data)')
ax2.legend()
ax2.grid(True, alpha=0.3)

# Panel C: Impatient data likelihood
ax3.contourf(B, G, ll_impatient_rel, levels=np.logspace(-10, 0, 8), cmap='plasma', norm=LogNorm(vmin=1e-10, vmax=1),alpha=0.6)

ax3.plot(beta_true, gamma_true, 'ko', markersize=8, label='True Values')

# Highlight the ridge for impatient data
ratio_true = beta_true / gamma_true
beta_ridge = np.linspace(2, 12, 100)
gamma_ridge = beta_ridge / ratio_true
mask = (gamma_ridge >= 0.5) & (gamma_ridge <= 4)
ax3.plot(beta_ridge[mask], gamma_ridge[mask], 'r--', linewidth=2, alpha=0.8,
         label=f'Ridge: β/γ = {ratio_true:.1f}')

ax3.set_xlabel('β (production rate)')
ax3.set_ylabel('γ (degradation rate)')
ax3.set_title('C: Likelihood (Impatient Data)')
ax3.legend()
ax3.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()
Figure 3.11: How data quality determines identifiability. (A) A ‘perfect’ experiment capturing the full time-course dynamics of a constitutive gene. (B) The resulting likelihood surface shows a sharp, well-defined peak, meaning both β and γ are practically identifiable. (C) Using only the ‘near-steady-state’ data from the impatient experiment, the likelihood surface flattens into an elongated ridge. The parameters are now practically non-identifiable because the data lacks information about the system’s early dynamics.

3.4.4 From Structural to Practical Non-Identifiability

Panel C reveals a crucial insight: even though our model is structurally identifiable from temporal data, poor experimental design can lead to practical non-identifiability. The “impatient” experiment that only captures near-steady-state data creates an elongated, ridge-like likelihood surface similar to the structural case.

This illustrates a fundamental principle: experimental design determines what biological mechanisms you can actually distinguish. No amount of statistical sophistication can recover information that simply isn’t present in your data.

3.4.5 Diagnosing Identifiability with Profile Likelihoods

2D contour plots work for two parameters, but likelihood surfaces in higher dimensions can’t be visualized. Profile likelihoods solve this by diagnosing identifiability one parameter at a time.

For a parameter vector \theta = (\theta_1, \theta_2, \ldots, \theta_k), the profile likelihood for parameter \theta_i is defined as:

L_p(\theta_i) = \max_{\theta_{-i}} L(\theta_i, \theta_{-i} | \text{data})

where \theta_{-i} represents all parameters except \theta_i. The profile likelihood shows the maximum likelihood achievable when \theta_i is fixed at a specific value and all other parameters are optimized.

The profile log-likelihood is: \ell_p(\theta_i) = \max_{\theta_{-i}} \ell(\theta_i, \theta_{-i} | \text{data})

A sharp, peaked profile indicates the parameter is well-constrained by the data. A flat profile suggests practical non-identifiability.

Figure 3.12: Profile likelihood analysis distinguishes structural non-identifiability, practical non-identifiability, and identifiable parameters through characteristic likelihood surface shapes and 1D profile diagnostics. Note: This schematic plots the negative profile likelihood (curves going up from a minimum), whereas our code plots the profile log-likelihood itself (curves going down from a maximum). The diagnostic interpretation is identical—just flip the vertical axis.

3.4.5.1 A Concrete Example: Profile Likelihoods in Action

We return to the constitutive gene’s “impatient” dataset (final 50% of the temporal trajectory), which captured near-steady-state dynamics but missed early transients. Profile likelihoods diagnose how this experimental design affects identifiability.

Code
# Use the exact same "impatient" dataset from Figure 2 Panel C
# This creates a seamless narrative flow
from scipy.optimize import minimize

# Parameters and data setup (matching Figure 2)
beta_true, gamma_true = 6.0, 2.0
noise_std = 0.3

# Use the impatient dataset from the 3-panel figure
# (This should match the data from Panel C)
rng = np.random.default_rng(42)
# Note: we need the same t_impatient and x_impatient from Figure 2

# Define temporal log-likelihood for the impatient data
def neg_temporal_log_likelihood(params, t_data, x_data):
    beta, gamma = params
    if beta <= 0 or gamma <= 0:
        return np.inf
    try:
        # Use same ODE solver as Figure 2
        from scipy.integrate import solve_ivp
        def constitutive_gene_ode(t, x, beta, gamma):
            return [beta - gamma * x[0]]

        # Always solve from t=0, evaluate only at t_data points
        sol = solve_ivp(constitutive_gene_ode, (0, t_data[-1]), [0.0],
                       t_eval=t_data, args=(beta, gamma))
        x_pred = sol.y[0]
        return 0.5 * np.sum(((x_data - x_pred) / noise_std)**2)
    except:
        return np.inf

# Recreate the impatient dataset (to ensure consistency)
t_span = (0, 5)
t_full = np.linspace(0, 5, 50)
from scipy.integrate import solve_ivp
def constitutive_gene_ode(t, x, beta, gamma):
    return [beta - gamma * x[0]]

sol = solve_ivp(constitutive_gene_ode, t_span, [0.0], t_eval=t_full, args=(beta_true, gamma_true))
x_true = sol.y[0]
x_full = x_true + rng.normal(0, noise_std, len(t_full))

# Create impatient dataset (last 50%)
n_total = len(t_full)
n_impatient = int(0.5 * n_total)
start_idx = n_total - n_impatient
t_impatient = t_full[start_idx:]
x_impatient = x_full[start_idx:]

print(f"Using impatient dataset with {len(t_impatient)} time points")
print(f"Time range: {t_impatient[0]:.2f} to {t_impatient[-1]:.2f}")

# Parameter range for profile likelihood
beta_range = np.linspace(2, 12, 50)

# Compute profile likelihoods comparing full vs impatient data
def compute_profile_likelihood(param_range, param_idx, t_data, x_data):
    profile_ll = []
    for val in param_range:
        if param_idx == 0:  # Profile beta, optimize gamma
            obj_fun = lambda gamma_opt: neg_temporal_log_likelihood([val, gamma_opt[0]], t_data, x_data)
            res = minimize(obj_fun, [2.0], bounds=[(0.1, 5.0)], method='L-BFGS-B')
        else:  # Profile gamma, optimize beta
            obj_fun = lambda beta_opt: neg_temporal_log_likelihood([beta_opt[0], val], t_data, x_data)
            res = minimize(obj_fun, [6.0], bounds=[(0.1, 15.0)], method='L-BFGS-B')

        if res.success:
            profile_ll.append(-res.fun)
        else:
            profile_ll.append(-np.inf)

    return np.array(profile_ll)

# Compute profile likelihoods for beta in BOTH scenarios
profile_beta_impatient = compute_profile_likelihood(beta_range, 0, t_impatient, x_impatient)
profile_beta_full = compute_profile_likelihood(beta_range, 0, t_full, x_full)

# Normalize each profile relative to its own maximum for fair comparison
profile_beta_impatient_norm = profile_beta_impatient - np.max(profile_beta_impatient)
profile_beta_full_norm = profile_beta_full - np.max(profile_beta_full)

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Plot profiles comparing experimental designs
plt.figure()
plt.plot(beta_range, profile_beta_full_norm, color=QUALITATIVE_COLORS[0], linewidth=3, label='Full Data (identifiable)')
plt.plot(beta_range, profile_beta_impatient_norm, color=QUALITATIVE_COLORS[1], linewidth=3, label='Impatient Data (poorly identifiable)')

# Add 95% confidence threshold
ci_threshold = -1.92  # χ²(1,0.05)/2 ≈ 1.92 for normalized profiles
plt.axhline(ci_threshold, color='gray', linestyle='--', alpha=0.8, linewidth=2,
           label='95% CI Threshold')

# Mark true value
plt.axvline(beta_true, color=QUALITATIVE_COLORS[0], linestyle=':', linewidth=2, alpha=0.7,
           label=f'True β = {beta_true}')

plt.xlabel('β (production rate)')
plt.ylabel('Normalized Profile Log-Likelihood')
plt.title('Profile Likelihood: Impact of Experimental Design')
plt.legend()
plt.grid(True, alpha=0.3)
plt.ylim(-10, 0.5)
plt.show()
Using impatient dataset with 25 time points
Time range: 2.55 to 5.00
Figure 3.13: Diagnosing practical non-identifiability with profile likelihoods. Profile likelihood for β comparing the two experimental designs. The full data (blue) produces a sharp, peaked profile indicating β is well-constrained. The impatient data (red) produces a flat profile that barely drops below the 95% confidence threshold, indicating poor identifiability. This directly shows how experimental design determines what biological parameters can be reliably inferred.

Confidence Intervals from Profile Likelihoods: We construct confidence intervals using Wilks’ theorem, which states that under regularity conditions, the likelihood ratio statistic is asymptotically chi-squared distributed:

2(\ell_{\max} - \ell_p(\theta_i)) \xrightarrow{d} \chi^2_1

For a 95% confidence interval, we use the threshold \ell_{\max} - \chi^2_{1,0.05}/2 \approx \ell_{\max} - 1.92.

The contrast is striking. The full dataset produces a sharp, peaked profile for β—the parameter is well-constrained by the data, with a tight 95% confidence interval around the true value. The impatient dataset, capturing only near-steady-state dynamics, produces a dramatically flatter profile. Many values of β achieve nearly identical likelihood when γ is optimally adjusted to compensate. This reflects the elongated ridge visible in the 2D surface: changes in production rate can be offset by adjusting degradation rate to maintain the steady-state level—which is all our limited data can observe. The profile likelihood diagnostic makes this identifiability failure immediately visible in one dimension.

3.4.6 Model Selection: Which Model is Best?

Beyond parameter estimation lies an even more fundamental question: which model should we use in the first place? Consider our gene expression data—should we model it as:

  1. Poisson (constitutive expression): Simple, one parameter
  2. Negative Binomial (bursty expression): More complex, two parameters

More complex models will always fit the training data better, but they may not generalize. This is the classical bias-variance tradeoff.

3.4.6.1 Information Criteria: AIC and BIC

The model selection challenge we face is a mathematical manifestation of a much older scientific principle: Occam’s razor. When multiple models explain our data equally well, we should prefer the simpler one. But this preference isn’t just aesthetic—it reflects a fundamental trade-off that lies at the heart of statistical modeling.

Complex models with many parameters can capture intricate patterns in our training data, potentially achieving very high likelihood scores. However, this flexibility comes with a dangerous side effect: overfitting. A model that memorizes every quirk and noise fluctuation in our specific dataset may fail catastrophically when applied to new data. Conversely, overly simple models may miss important biological patterns, leading to underfitting and poor predictive performance.

This is the classic bias-variance tradeoff. Simple models have high bias (they might miss important patterns) but low variance (they’re consistent across different datasets). Complex models have low bias (they can capture subtle patterns) but high variance (they’re sensitive to sampling noise). The optimal model strikes a balance, capturing genuine biological signal while remaining robust to the inevitable noise in our measurements.

Akaike Information Criterion (AIC) and Bayesian Information Criterion (BIC) provide principled ways to penalize model complexity, implementing Occam’s razor mathematically:

\text{AIC} = 2k - 2\ell_{max} \text{BIC} = k \ln(n) - 2\ell_{max}

where k is the number of parameters, n is the sample size, and \ell_{max} is the maximum log-likelihood.

Lower values indicate better models. BIC penalizes complexity more heavily than AIC.

Derivation Sketch: Where AIC Comes From

We want to estimate how well our fitted model f(x|\hat{\theta}) will perform on new data drawn from the true distribution f(x|\theta_0). The naive approach is to use the training log-likelihood \ell(\hat{\theta}), but this is optimistically biased since \hat{\theta} was chosen to maximize \ell on the same data.

To quantify this bias, we use the same Taylor expansion approach from the asymptotic normality derivation. Expand \ell(\hat{\theta}) around the true parameter \theta_0:

\ell(\hat{\theta}) = \ell(\theta_0) + \nabla\ell(\theta_0)^T(\hat{\theta}-\theta_0) + \frac{1}{2}(\hat{\theta}-\theta_0)^T H(\theta_0)(\hat{\theta}-\theta_0) + \ldots

where H(\theta_0) = \partial^2\ell/\partial\theta\partial\theta^T is the Hessian evaluated at \theta_0.

Taking expectations over repeated sampling, the first-order term vanishes. As we showed earlier, \mathbb{E}[\nabla\ell(\theta_0)] = 0 (the score has zero mean at the true parameter). This leaves:

\mathbb{E}[\ell(\hat{\theta})] \approx \ell(\theta_0) + \frac{1}{2}\mathbb{E}[(\hat{\theta}-\theta_0)^T H(\theta_0)(\hat{\theta}-\theta_0)]

The second-order term is a quadratic form. We can evaluate it using the cyclic property of the trace and our established results:

\begin{align} \mathbb{E}[(\hat{\theta}-\theta_0)^T H(\theta_0)(\hat{\theta}-\theta_0)] &= \mathbb{E}[\text{trace}((\hat{\theta}-\theta_0)(\hat{\theta}-\theta_0)^T H(\theta_0))] \\ &= \text{trace}(\mathbb{E}[(\hat{\theta}-\theta_0)(\hat{\theta}-\theta_0)^T] \cdot H(\theta_0)) \\ &= \text{trace}(\text{Cov}(\hat{\theta}) \cdot H(\theta_0)) \end{align}

Now we invoke two key results from our earlier analysis: (1) the asymptotic covariance \text{Cov}(\hat{\theta}) \approx I(\theta_0)^{-1}, and (2) the Fisher Information equality I(\theta_0) = \mathbb{E}[-H(\theta_0)]. Substituting: \text{trace}(I(\theta_0)^{-1} \cdot (-I(\theta_0))) = \text{trace}(-I_k) = -k

where I_k is the k \times k identity matrix and k is the number of parameters. Plugging this back into the expansion gives the “overfitting boost”:

\mathbb{E}[\ell(\hat{\theta})] - \ell(\theta_0) \approx +\frac{k}{2}

This +k/2 term represents how much we expect to be “fooled” by fitting noise in our specific dataset. However, this is only half the story. A similar analysis shows that when we apply this fitted model to new data, we incur a “prediction penalty.” The model with our estimated \hat{\theta} is expected to perform worse than the true model by the same amount: \mathbb{E}[\ell_{new}(\hat{\theta})] - \ell(\theta_0) \approx -\frac{k}{2} The total bias, or “optimism,” is the gap between the expected in-sample and out-of-sample log-likelihoods: \mathbb{E}[\ell(\hat{\theta}) - \ell_{new}(\hat{\theta})] \approx (k/2) - (-k/2) = k. Therefore, a bias-corrected estimate for the out-of-sample log-likelihood is \ell(\hat{\theta}) - k. Scaling by -2 (to match the deviance scale) gives the Akaike Information Criterion:

\text{AIC} = -2(\ell_{\max} - k) = 2k - 2\ell_{\max}

BIC takes a different route: it emerges from the Laplace approximation to the Bayesian marginal likelihood p(D|M) = \int p(D|\theta,M)p(\theta|M)d\theta. The integral is dominated by the likelihood peak at \hat{\theta}, but integrating over the k-dimensional parameter space incurs a penalty proportional to \ln(n). This yields \text{BIC} = k\ln(n) - 2\ell_{\max}, which penalizes complexity more heavily than AIC for n \ge 8.

Code
from scipy.stats import poisson, nbinom

# Generate test data that's actually from a negative binomial (bursty)
rng = np.random.default_rng(999)
r_true = 4.0
p_true = 0.4
n_cells = 300
test_data = nbinom.rvs(n=r_true, p=p_true, size=n_cells, random_state=rng)

print(f"Test data characteristics:")
print(f"Sample mean: {np.mean(test_data):.2f}")
print(f"Sample variance: {np.var(test_data, ddof=1):.2f}")
print(f"Variance-to-mean ratio: {np.var(test_data, ddof=1)/np.mean(test_data):.2f}")
print(f"(Ratio > 1 suggests overdispersion, favoring Negative Binomial)")

# Fit Poisson model
lambda_poisson = np.mean(test_data)  # MLE for Poisson
ll_poisson = np.sum(poisson.logpmf(test_data, mu=lambda_poisson))
k_poisson = 1  # One parameter

# Fit Negative Binomial model
def neg_ll_nb(params):
    r, p = params
    if r <= 0 or p <= 0 or p >= 1:
        return np.inf
    return -np.sum(nbinom.logpmf(test_data, n=r, p=p))

result_nb = minimize(neg_ll_nb, [3.0, 0.5],
                    bounds=[(0.1, 20), (0.01, 0.99)],
                    method='L-BFGS-B')
r_nb, p_nb = result_nb.x
ll_nb = -result_nb.fun
k_nb = 2  # Two parameters

# Calculate information criteria
aic_poisson = 2 * k_poisson - 2 * ll_poisson
aic_nb = 2 * k_nb - 2 * ll_nb
bic_poisson = k_poisson * np.log(n_cells) - 2 * ll_poisson
bic_nb = k_nb * np.log(n_cells) - 2 * ll_nb

# Results summary
results = {
    'Model': ['Poisson', 'Negative Binomial'],
    'Parameters': [1, 2],
    'Log-likelihood': [ll_poisson, ll_nb],
    'AIC': [aic_poisson, aic_nb],
    'BIC': [bic_poisson, bic_nb]
}

print(f"\nModel Comparison Results:")
print(f"{'Model':<20} {'k':<5} {'Log-lik':<12} {'AIC':<12} {'BIC':<12}")
print("-" * 65)
for i in range(len(results['Model'])):
    print(f"{results['Model'][i]:<20} {results['Parameters'][i]:<5} "
          f"{results['Log-likelihood'][i]:<12.2f} {results['AIC'][i]:<12.2f} "
          f"{results['BIC'][i]:<12.2f}")

print(f"\nΔAIC (NB - Poisson): {aic_nb - aic_poisson:.2f}")
print(f"ΔBIC (NB - Poisson): {bic_nb - bic_poisson:.2f}")
print(f"(Negative values favor Negative Binomial)")

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Visual comparison of model fits
x_range = np.arange(0, max(test_data) + 1)
poisson_pred = poisson.pmf(x_range, mu=lambda_poisson)
nb_pred = nbinom.pmf(x_range, n=r_nb, p=p_nb)

# Create comparison plot
fig, (ax1, ax2) = plt.subplots(1, 2)

# Histogram of data with model predictions
ax1.hist(test_data, bins=range(max(test_data)+2), density=True, alpha=0.7,
         color='gray', edgecolor='none', label='Observed data')
ax1.plot(x_range, poisson_pred, 'o-', color=QUALITATIVE_COLORS[0], linewidth=2, markersize=6,
         label=f'Poisson (λ={lambda_poisson:.2f})')
ax1.plot(x_range, nb_pred, 's-', color=QUALITATIVE_COLORS[1], linewidth=2, markersize=6,
         label=f'Neg. Binomial (r={r_nb:.2f}, p={p_nb:.2f})')
ax1.set_xlabel('mRNA count')
ax1.set_ylabel('Probability density')
ax1.set_title('Model Fit Comparison')
ax1.legend()
ax1.grid(True, alpha=0.3)

# Information criteria comparison (grouped by criterion)
criteria = ['AIC', 'BIC']
poisson_values = [aic_poisson, bic_poisson]
nb_values = [aic_nb, bic_nb]

x = np.arange(len(criteria))
width = 0.35

ax2.bar(x - width/2, poisson_values, width, label='Poisson', alpha=0.7, color=QUALITATIVE_COLORS[0], edgecolor='none')
ax2.bar(x + width/2, nb_values, width, label='Negative Binomial', alpha=0.7, color=QUALITATIVE_COLORS[1], edgecolor='none')
ax2.set_xlabel('Information Criterion')
ax2.set_ylabel('Criterion Value')
ax2.set_title('Model Selection Criteria (Lower is Better)')
ax2.set_xticks(x)
ax2.set_xticklabels(criteria)
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()
Test data characteristics:
Sample mean: 5.96
Sample variance: 15.35
Variance-to-mean ratio: 2.58
(Ratio > 1 suggests overdispersion, favoring Negative Binomial)

Model Comparison Results:
Model                k     Log-lik      AIC          BIC         
-----------------------------------------------------------------
Poisson              1     -888.77      1779.54      1783.24     
Negative Binomial    2     -801.82      1607.64      1615.05     

ΔAIC (NB - Poisson): -171.90
ΔBIC (NB - Poisson): -168.20
(Negative values favor Negative Binomial)
Figure 3.14: Model selection using AIC and BIC. Comparison of Poisson (1 parameter) vs Negative Binomial (2 parameters) models on synthetic data. The information criteria balance goodness of fit against model complexity.

3.4.6.2 Modern Alternative: Cross-Validation

A more robust approach is cross-validation, which estimates out-of-sample predictive performance by training the model on subsets of the data and testing on held-out portions. Cross-validation provides a more honest assessment of model performance by evaluating how well the model generalizes to unseen data.

3.4.7 Summary and Limitations

MLE provides point estimates and confidence intervals. Fisher Information, bootstrap, and information criteria quantify uncertainty and guide model selection. But identifiability analysis revealed a fundamental constraint: no statistical method can recover information that isn’t in your data. Steady-state measurements cannot separate production and degradation rates. Late-stage observations lose information about early dynamics.

Experimental design precedes statistical sophistication. Before building inference pipelines, ask: does my experiment contain the information to answer my question? Profile likelihoods and Hessian eigenanalysis diagnose identifiability. MLE gives a single “best” answer, but what if we want to incorporate prior knowledge or quantify the probability that burst frequency increased by 50%? For that, we need the Bayesian framework.


3.5 Bayesian Inference

The challenge laid out before us—to move beyond single point estimates and characterize the entire landscape of uncertainty—has a formal and powerful solution: Bayesian inference. Where maximum likelihood seeks the single peak of the likelihood surface, the Bayesian approach provides a complete map of the terrain. It does this by computing the posterior distribution, which represents everything we can possibly know about our model’s parameters after observing the data.

Bayesian inference rests on a simple yet profound idea: we should update our beliefs about parameters in light of new evidence. This updating process is governed by Bayes’ theorem:

P(\theta | D) = \frac{P(D | \theta) P(\theta)}{P(D)}

This elegant equation contains four key terms that we’ll encounter throughout our Bayesian journey:

  • P(\theta | D): The posterior distribution - what we believe about the parameters after seeing the data
  • P(D | \theta): The likelihood - how well different parameter values explain the observed data (familiar from our MLE discussion)
  • P(\theta): The prior distribution - what we believed about the parameters before seeing any data
  • P(D): The evidence (or marginal likelihood) - a normalization constant that ensures the posterior is a proper probability distribution

For inference, we can often ignore the evidence since it doesn’t depend on \theta:

P(\theta | D) \propto P(D | \theta) P(\theta)

3.5.1 A Simple Example: The Biased Coin

Before diving into complex gene expression models, let’s understand the core concepts of Bayesian inference through a familiar example: estimating the bias of a coin.

Imagine you’re given a coin and want to determine whether it’s fair. You flip it 5 times and observe 4 heads and 1 tail. What’s your belief about the coin’s bias probability p?

Prior: Before seeing any data, you might believe all values of p between 0 and 1 are equally plausible. This corresponds to a \text{Uniform}(0,1) prior, which is equivalent to \text{Beta}(1,1).

Likelihood: The probability of observing 4 heads in 5 flips follows a binomial distribution: P(\text{4 heads}|p) = \binom{5}{4} p^4 (1-p)^1.

Posterior: Using Bayes’ theorem, the posterior distribution is \text{Beta}(5,2)—a peaked distribution centered around p \approx 0.67.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import beta

# GeoDataViz Sequential Palette (Blue)
SEQUENTIAL_COLORS = ['#E4F1F7', '#C5E1EF', '#9EC9E2', '#6CB0D6', '#3C93C2', '#226E9C', '#0D4A70']

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']


# Define the range of p values
p_range = np.linspace(0, 1, 1000)

# Extended sequence of data accumulation
# Let's assume we observe heads with probability p_true = 0.65
np.random.seed(42)  # For reproducible sequence
p_true = 0.65

# Generate a realistic sequence of coin flips
all_flips = np.random.binomial(1, p_true, 100)  # 100 flips total
cumulative_heads = np.cumsum(all_flips)

# Define the observation points and corresponding posteriors
n_flips = [0, 1, 5, 10, 50, 100]
linestyles = ['--', '-', '-', '-', '-', '-']
linewidths = [2, 2, 2, 2, 2.5, 3]

# Use sequential colors to show progression from light (few data) to dark (more data)
colors = [
    'gray',                # Prior (neutral)
    SEQUENTIAL_COLORS[2],  # 1 flip (very light blue)
    SEQUENTIAL_COLORS[3],  # 5 flips (light blue)
    SEQUENTIAL_COLORS[4],  # 10 flips (medium blue)
    SEQUENTIAL_COLORS[5],  # 50 flips (dark blue)
    SEQUENTIAL_COLORS[6]   # 100 flips (darkest blue)
]

plt.figure()

for i, n in enumerate(n_flips):
    if n == 0:
        # Prior: Beta(1,1)
        alpha, beta_param = 1, 1
        label = f'Prior: Beta({alpha},{beta_param})'
    else:
        # Posterior after n flips
        heads = cumulative_heads[n-1]  # Number of heads after n flips
        tails = n - heads
        alpha = heads + 1  # Beta prior: alpha = heads + 1
        beta_param = tails + 1  # Beta prior: beta = tails + 1
        mean_estimate = alpha / (alpha + beta_param)
        label = f'After {n} flips: {heads}H/{tails}T, μ={mean_estimate:.3f}'

    # Calculate posterior distribution
    posterior = beta.pdf(p_range, alpha, beta_param)

    # Plot with increasing emphasis for later stages
    plt.plot(p_range, posterior, color=colors[i], linewidth=linewidths[i],
             linestyle=linestyles[i], label=label, alpha=0.8)

# Add vertical line at true value
plt.axvline(p_true, color=QUALITATIVE_COLORS[0], linestyle=':', alpha=0.7,
           label=f'True p = {p_true}',linewidth=2)

plt.xlabel('Coin bias probability (p)')
plt.ylabel('Probability density')
plt.title('Extended Bayesian Updating: Progressive Learning')
plt.legend(loc='upper left')
plt.grid(True, alpha=0.3)
plt.xlim(0, 1)
plt.tight_layout()
plt.show()

# Print detailed summary statistics
print("Bayesian Learning Progress:")
print("=" * 50)

for i, n in enumerate(n_flips):
    if n == 0:
        alpha, beta_param = 1, 1
        mean_est = 0.5
        variance = alpha * beta_param / ((alpha + beta_param)**2 * (alpha + beta_param + 1))
        std_est = np.sqrt(variance)
        print(f"Prior (0 flips):     Mean = {mean_est:.3f}, Std = {std_est:.3f}")
    else:
        heads = cumulative_heads[n-1]
        tails = n - heads
        alpha = heads + 1
        beta_param = tails + 1
        mean_est = alpha / (alpha + beta_param)
        variance = alpha * beta_param / ((alpha + beta_param)**2 * (alpha + beta_param + 1))
        std_est = np.sqrt(variance)
        observed_freq = heads / n
        print(f"After {n:3d} flips: Mean = {mean_est:.3f}, Std = {std_est:.3f}, Obs = {observed_freq:.3f}")

print(f"\nTrue parameter: p = {p_true}")
print(f"Final estimate: {cumulative_heads[99]/100:.3f} (after 100 flips)")
Figure 3.15: Extended Bayesian updating sequence for a biased coin example. The plot shows how our belief about the coin’s bias evolves as we accumulate increasing amounts of data: from the flat uniform prior (gray dashed) through early updates after 1 and 5 flips, to highly concentrated posteriors after 50 and 100 flips. This extended sequence demonstrates how Bayesian inference progressively sharpens our knowledge, with uncertainty decreasing systematically as evidence accumulates.
Bayesian Learning Progress:
==================================================
Prior (0 flips):     Mean = 0.500, Std = 0.289
After   1 flips: Mean = 0.667, Std = 0.236, Obs = 1.000
After   5 flips: Mean = 0.571, Std = 0.175, Obs = 0.600
After  10 flips: Mean = 0.583, Std = 0.137, Obs = 0.600
After  50 flips: Mean = 0.731, Std = 0.061, Obs = 0.740
After 100 flips: Mean = 0.676, Std = 0.046, Obs = 0.680

True parameter: p = 0.65
Final estimate: 0.680 (after 100 flips)

This example captures the essence of Bayesian thinking: we start with prior beliefs, observe data, and end with updated beliefs that combine both sources of information. Now let’s apply this same logic to our gene expression models.

3.5.2 MCMC: Sampling from Complex Posteriors

For most realistic models, we can’t solve for the posterior analytically. We need computational methods to draw samples from the posterior distribution. Markov Chain Monte Carlo (MCMC) provides the solution.

3.5.2.1 The Intuition Behind MCMC

Think of MCMC as a “smart random walker” exploring the high-dimensional landscape of the posterior distribution. The walker preferentially spends more time in high-altitude regions (high posterior probability) and less time in low-lying valleys, mapping out the most plausible parameter regions.

The basic Metropolis-Hastings algorithm works as follows:

  1. Propose: Suggest a new parameter value near the current location
  2. Evaluate: Calculate how much more (or less) plausible this new value is
  3. Decide: Accept the proposal with probability proportional to the improvement
  4. Repeat: Continue this process to build a chain of samples

3.5.2.2 The Mathematical Foundation: Detailed Balance

For a math graduate audience, it’s worth understanding why this algorithm works. We need a transition probability T(\theta' | \theta) that leads to a stationary distribution \pi(\theta) = P(\theta|D) (our desired posterior). The condition of detailed balance provides the key:

\pi(\theta) T(\theta' | \theta) = \pi(\theta') T(\theta | \theta')

This condition ensures that the chain converges to the correct distribution. The Metropolis acceptance probability is constructed precisely to satisfy this condition:

\alpha = \min\left(1, \frac{\pi(\theta')q(\theta|\theta')}{\pi(\theta)q(\theta'|\theta)}\right)

where q(\theta'|\theta) is the proposal distribution. When the proposal is symmetric (q(\theta'|\theta) = q(\theta|\theta')), this simplifies to the familiar form \alpha = \min(1, \pi(\theta')/\pi(\theta)).

In practice, we rarely implement MCMC by hand. Modern probabilistic programming languages like PyMC, Stan, and NumPyro provide highly optimized, automatically tuned samplers that handle the complex details for us.

3.5.3 A Complete Example: Bayesian Inference for the Negative Binomial Model

Let’s apply Bayesian inference to our running example: the phenomenological bursting model that produces a Negative Binomial distribution. We observe mRNA counts \{n_1, n_2, \ldots, n_N\} and want to infer both the burst size parameter r and the frequency parameter p.

Step 1: Choose Priors

We need to specify what we believe about both parameters before seeing any data. For our bursting model analysis, we’ll choose priors that reflect realistic biological constraints:

  • For r (burst size): We’ll use a Gamma distribution with shape and rate parameters that encode weak prior knowledge that burst sizes are typically small (1-10 mRNA per burst)
  • For p (frequency parameter): We’ll use a Beta distribution, which has support on [0,1] as required

P(r) = \text{Gamma}(\alpha_r, \beta_r), \quad P(p) = \text{Beta}(\alpha_p, \beta_p)

Step 2: Apply Bayes’ Theorem

For the Negative Binomial model, the posterior doesn’t have a closed form, so we’ll need to use MCMC sampling. But first, let’s implement a simple version to understand the concepts.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import gamma, beta, nbinom

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Use our consistent running example data
rng = np.random.default_rng(42)
r_true = 5.0  # burst size parameter
p_true = 0.25  # burst frequency parameter
n_cells = 100
data = nbinom.rvs(n=r_true, p=p_true, size=n_cells, random_state=rng)

print(f"Observed data: {len(data)} cells")
print(f"Sample mean: {np.mean(data):.2f}")
print(f"Sample variance: {np.var(data, ddof=1):.2f}")
print(f"Variance-to-mean ratio: {np.var(data, ddof=1)/np.mean(data):.2f}")

# Prior parameters (weakly informative)
# For r: Gamma prior
alpha_r_prior = 2.0
beta_r_prior = 0.5
print(f"\nPrior for r: Gamma({alpha_r_prior}, {beta_r_prior})")

# For p: Beta prior
alpha_p_prior = 1.0
beta_p_prior = 1.0
print(f"Prior for p: Beta({alpha_p_prior}, {beta_p_prior})")

# Simple MCMC sampling (Metropolis-Hastings)
def log_posterior(r, p, data):
    """Log posterior density (up to a constant)"""
    if r <= 0 or p <= 0 or p >= 1:
        return -np.inf

    # Log prior
    log_prior = gamma.logpdf(r, alpha_r_prior, scale=1/beta_r_prior) + \
                beta.logpdf(p, alpha_p_prior, beta_p_prior)

    # Log likelihood
    log_likelihood = np.sum(nbinom.logpmf(data, n=r, p=p))

    return log_prior + log_likelihood

# Simple MCMC sampler
n_samples = 5000
r_samples = []
p_samples = []

# Initial values
r_current = 3.0
p_current = 0.5

# MCMC sampling
rng_mcmc = np.random.default_rng(123)
for i in range(n_samples):
    # Propose new values
    r_proposal = r_current + rng_mcmc.normal(0, 0.1)
    p_proposal = p_current + rng_mcmc.normal(0, 0.02)

    # Calculate acceptance probability
    log_alpha = log_posterior(r_proposal, p_proposal, data) - \
                log_posterior(r_current, p_current, data)
    alpha = min(1, np.exp(log_alpha))

    # Accept or reject
    if rng_mcmc.random() < alpha:
        r_current = r_proposal
        p_current = p_proposal

    r_samples.append(r_current)
    p_samples.append(p_current)

# Remove burn-in
burn_in = 1000
r_samples = r_samples[burn_in:]
p_samples = p_samples[burn_in:]

print(f"\nMCMC Results:")
print(f"Posterior mean r: {np.mean(r_samples):.3f} (true: {r_true})")
print(f"Posterior mean p: {np.mean(p_samples):.3f} (true: {p_true})")

# Create marginal posterior plots
fig, (ax1, ax2) = plt.subplots(1, 2)

# Plot posterior for r
ax1.hist(r_samples, bins=50, density=True, alpha=0.75, color=QUALITATIVE_COLORS[1], edgecolor='none', label='Posterior samples')

# Add prior distribution for r (Gamma prior)
r_range = np.linspace(0, max(r_samples) * 1.2, 200)
prior_r = gamma.pdf(r_range, alpha_r_prior, scale=1/beta_r_prior)
ax1.plot(r_range, prior_r, 'gray', linestyle='--', linewidth=2, label=f'Prior: Gamma({alpha_r_prior}, {beta_r_prior})')

ax1.axvline(r_true, color=QUALITATIVE_COLORS[0], linestyle='--', linewidth=2, label=f'True r = {r_true}')
ax1.axvline(np.mean(r_samples), color=QUALITATIVE_COLORS[1], linestyle='-', linewidth=2, label=f'Posterior mean = {np.mean(r_samples):.2f}')

# Add credible interval
r_ci_lower, r_ci_upper = np.percentile(r_samples, [2.5, 97.5])
ax1.axvspan(r_ci_lower, r_ci_upper, alpha=0.3, color=QUALITATIVE_COLORS[1], label=f'95% CI: [{r_ci_lower:.2f}, {r_ci_upper:.2f}]')

ax1.set_xlabel('r (burst size parameter)')
ax1.set_ylabel('Density')
ax1.set_title('Posterior Distribution for r')
ax1.legend()
ax1.grid(True, alpha=0.3)

# Plot posterior for p
ax2.hist(p_samples, bins=50, density=True, alpha=0.75, color=QUALITATIVE_COLORS[0], edgecolor='none', label='Posterior samples')

# Add prior distribution for p (Beta prior)
p_range_plot = np.linspace(0, 1, 200)
prior_p = beta.pdf(p_range_plot, alpha_p_prior, beta_p_prior)
ax2.plot(p_range_plot, prior_p, 'gray', linestyle='--', linewidth=2, label=f'Prior: Beta({alpha_p_prior}, {beta_p_prior})')

ax2.axvline(p_true, color=QUALITATIVE_COLORS[0], linestyle='--', linewidth=2, label=f'True p = {p_true}')
ax2.axvline(np.mean(p_samples), color=QUALITATIVE_COLORS[0], linestyle='-', linewidth=2, label=f'Posterior mean = {np.mean(p_samples):.2f}')

# Add credible interval
p_ci_lower, p_ci_upper = np.percentile(p_samples, [2.5, 97.5])
ax2.axvspan(p_ci_lower, p_ci_upper, alpha=0.3, color=QUALITATIVE_COLORS[0], label=f'95% CI: [{p_ci_lower:.2f}, {p_ci_upper:.2f}]')

ax2.set_xlabel('p (burst frequency parameter)')
ax2.set_ylabel('Density')
ax2.set_title('Posterior Distribution for p')
ax2.legend()
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# Calculate credible intervals and compare with MLE
print(f"\n95% Credible Intervals (Bayesian):")
print(f"r: [{r_ci_lower:.2f}, {r_ci_upper:.2f}]")
print(f"p: [{p_ci_lower:.2f}, {p_ci_upper:.2f}]")
Observed data: 100 cells
Sample mean: 14.86
Sample variance: 58.63
Variance-to-mean ratio: 3.95

Prior for r: Gamma(2.0, 0.5)
Prior for p: Beta(1.0, 1.0)

MCMC Results:
Posterior mean r: 5.840 (true: 5.0)
Posterior mean p: 0.281 (true: 0.25)
Figure 3.16: Bayesian inference for the Negative Binomial model using MCMC. The plots show the posterior distributions (filled histograms) alongside the prior distributions (gray dashed lines) for both parameters r and p. The dramatic concentration of the posteriors compared to the priors demonstrates the information gained from the data. This visualization shows how Bayesian inference updates prior beliefs to posterior knowledge.

95% Credible Intervals (Bayesian):
r: [4.10, 7.59]
p: [0.21, 0.34]

We already implemented a simple Metropolis-Hastings sampler for our Negative Binomial model above. The key insight is that MCMC allows us to sample from complex posteriors even when we can’t compute them analytically.

3.5.4 Modern MCMC: Hamiltonian Monte Carlo

While Metropolis-Hastings is conceptually simple, it can be slow for complex, high-dimensional problems. Modern Bayesian inference relies on much more sophisticated algorithms, particularly Hamiltonian Monte Carlo (HMC) and the No-U-Turn Sampler (NUTS).

Modern MCMC Algorithms

Hamiltonian Monte Carlo (HMC) uses the gradient of the log-posterior to guide the sampler more efficiently through parameter space. Instead of random walks, HMC follows the “physics” of the posterior landscape.

NUTS (No-U-Turn Sampler) automatically tunes the step size and trajectory length, making HMC practical for real applications. NUTS is the default algorithm in modern probabilistic programming languages like Stan and PyMC.

These algorithms are dramatically more efficient than simple Metropolis-Hastings, especially for complex models with many parameters.

3.5.5 Bayesian Inference in Practice: Using PyMC

We implemented Metropolis-Hastings from scratch to understand the mechanics. But in practice, we use probabilistic programming libraries that provide highly optimized samplers. Let’s work through a complete inference workflow using PyMC, applying it to the same Negative Binomial example we’ve been using throughout the chapter.

The workflow has three key steps, each requiring decisions from us: (1) Specify the model by choosing priors and the likelihood, (2) Run the sampler and check for convergence, (3) Validate and interpret the results.

3.5.5.1 Step 1: Specify the Model

PyMC requires us to specify two things: priors for unknown parameters and a likelihood connecting parameters to data. We choose weakly informative priors: r ~ Exponential(1.0) keeps r positive while favoring typical burst sizes, and p ~ Beta(1,1) (equivalent to Uniform) expresses ignorance about burst frequency. The likelihood encodes our biological model—bursting produces Negative Binomial distributions:

Code
import pymc as pm
import arviz as az

with pm.Model() as neg_binom_model:
    # Priors
    r = pm.Exponential('r', 1.0)
    p = pm.Beta('p', 1.0, 1.0)

    # Likelihood
    counts = pm.NegativeBinomial('counts', n=r, p=p, observed=data)

3.5.5.2 Step 2: Run the Sampler

PyMC uses the NUTS sampler (No-U-Turn Sampler), a sophisticated variant of Hamiltonian Monte Carlo that automatically tunes its parameters and uses gradient information to explore parameter space efficiently. We run 4 independent chains—if they all converge to the same distribution, we gain confidence in the results:

Code
with neg_binom_model:
    idata = pm.sample(500, tune=100, chains=4, cores=4, random_seed=42)

print("MCMC sampling complete.")
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [r, p]
Sampling 4 chains for 100 tune and 500 draw iterations (400 + 2_000 draws total) took 19 seconds.
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
MCMC sampling complete.
(a)

(b)
Figure 3.17

3.5.5.3 Step 3: Check Convergence

MCMC can fail silently—chains might get stuck or never mix properly. We check two diagnostics: \hat{R} (R-hat) compares variation between chains to variation within chains, defined as \hat{R} = \sqrt{\frac{\text{Var}_{\text{combined}}}{\text{Var}_{\text{within}}}}; values near 1.0 indicate convergence. Effective sample size (ESS) counts how many independent samples we effectively obtained from the correlated MCMC chain, computed as \text{ESS} \approx \frac{N}{1 + 2\sum_{k=1}^{\infty} \rho_k} where \rho_k is the autocorrelation at lag k; higher is better.

Code
# Display summary statistics
az.summary(idata, var_names=['r', 'p'])
mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
r 4.876 0.849 3.420 6.520 0.042 0.031 415.0 436.0 1.01
p 0.246 0.033 0.186 0.309 0.002 0.001 393.0 397.0 1.01
Figure 3.18: Convergence diagnostics via summary statistics. R-hat values near 1.0 and high effective sample sizes (ess_bulk, ess_tail) confirm successful convergence—all chains found the same posterior distribution.
Code
az.plot_trace(idata, var_names=['r', 'p'])
plt.tight_layout()
plt.show()
Figure 3.19: Trace plots show convergence: ‘fuzzy caterpillar’ trajectories with no trends, and overlapping posterior distributions from all four chains.

With \hat{R} \approx 1.0 and high ESS, we can trust these samples.

3.5.5.4 Step 4: Validate the Model

The sampler converged, but is the model correct? Posterior predictive checks test this by generating synthetic datasets from our fitted model and comparing them to the real data. If the model is good, simulated and observed data should match.

Code
with neg_binom_model:
    pm.sample_posterior_predictive(idata, extend_inferencedata=True)

# ArviZ creates a single-panel PPC plot by default
az.plot_ppc(idata, num_pp_samples=100)
plt.tight_layout()
plt.show()
Sampling: [counts]
(a) Posterior predictive check showing the observed data (black line) falls within the distribution of simulated datasets from the fitted model (blue shaded region), confirming the Negative Binomial model captures the data-generating process.

(b)
(c)
Figure 3.20

The tight overlap confirms the Negative Binomial is a good model for this data.

3.5.5.5 Step 5: Interpret the Results

Code
az.plot_posterior(idata, var_names=['r', 'p'])
plt.show()
Figure 3.21: Marginal posterior distributions recover the true parameter values (r=5.0, p=0.25), with credible intervals quantifying uncertainty.
Code
az.plot_pair(idata, var_names=['r', 'p'], kind='scatter', marginals=True)
plt.show()
Figure 3.22: Joint posterior shows negative correlation between r and p: larger bursts at lower frequency can mimic smaller bursts at higher frequency. This trade-off exposes a fundamental identifiability limitation of steady-state snapshots.

The negative correlation isn’t noise—it’s a fundamental limitation. Steady-state snapshots can’t fully separate burst size from burst frequency. To definitively distinguish these mechanisms, we need time-resolved measurements.

This workflow—specify, sample, check convergence, validate, interpret—is standard practice for Bayesian inference. PyMC handles the complex sampling machinery, freeing us to focus on modeling choices and scientific interpretation. But everything we’ve done relies on one critical assumption: we can compute the likelihood P(D|\theta). For many mechanistic models, we can’t. When the likelihood is intractable, we need simulation-based methods.


3.6 Inference for Intractable Models (Simulation-Based Inference)

All our methods so far have required tractable likelihood evaluation. What if our model has a likelihood that, while analytically known, is computationally prohibitive to evaluate?

Consider this more challenging scenario: instead of fitting the phenomenological Negative Binomial distribution to our drug perturbation data, we want to fit the full mechanistic Telegraph model with its three kinetic parameters—k_{\text{on}}, k_{\text{off}}, and \beta. While the Telegraph model does have an analytical steady-state solution (a Poisson-Beta mixture), evaluating its likelihood requires computing special functions and numerical integrals that become computationally expensive, especially when repeated thousands of times during MCMC sampling.

This scenario is increasingly common in computational biology, where sophisticated mechanistic models produce realistic behavior but have computationally expensive likelihoods. Likelihood-free inference methods solve this problem by replacing direct likelihood evaluation with model simulation.

3.6.1 The Core Idea: Simulate and Compare

The fundamental insight behind likelihood-free methods is beautifully simple: if we can simulate data from our model, we can approximate the likelihood by comparing simulated data to real data.

Instead of asking “How likely is this data given these parameters?”, we ask “What parameters would generate data that looks similar to what we observed?”

The ABC algorithm follows a simple workflow: sample parameters from a prior, simulate data using those parameters, compare the simulation to observed data, and accept parameters that produce sufficiently similar results. Repeating this process builds an approximate posterior distribution.

Figure 3.23: The ABC algorithm: sample from prior, simulate datasets, check if simulations match observations within tolerance \epsilon, and collect accepted parameters to form the approximate posterior.

To build intuition, consider a simple example: inferring the bias of a coin from observed flips. We don’t need ABC for this problem (the likelihood is trivial), but it demonstrates the algorithm’s logic clearly.

Figure 3.24: ABC applied to coin flips. For each prior sample of bias p, we simulate coin flips and compare to observed data. Parameters generating similar flip patterns are accepted, gradually building a posterior distribution concentrated around the true bias.

The ABC rejection algorithm follows this logic:

  1. Sample parameters from a prior
  2. Simulate data using those parameters
  3. Compare simulation to observations using summary statistics
  4. Accept parameters producing sufficiently similar data
  5. Repeat to build an approximate posterior

3.6.1.1 Why ABC Approximates Bayesian Inference

The connection to true Bayesian inference becomes clear when we compare their structures. The true posterior is: p(\theta | D_{\text{obs}}) \propto p(\theta) \cdot p(D_{\text{obs}} | \theta)

ABC implements the acceptance criterion “accept \theta^* if \rho(S(D^{\text{sim}}), S(D_{\text{obs}})) \leq \epsilon”, where \rho is a distance metric, S(\cdot) computes summary statistics, and \epsilon > 0 is the tolerance. By marginalizing over all simulated datasets that would be accepted, the ABC posterior is: p_{\text{ABC}}(\theta | D_{\text{obs}}) \propto p(\theta) \cdot \int_{\rho(S(D), S(D_{\text{obs}})) \leq \epsilon} p(D | \theta) \, dD

The structures are identical—the only difference is that the intractable likelihood p(D_{\text{obs}} | \theta) is replaced by the probability that a simulation from \theta falls anywhere in the \epsilon-ball around S(D_{\text{obs}}). As \epsilon \to 0, this acceptance region shrinks to a point and the integral collapses to p(D_{\text{obs}} | \theta), recovering the true posterior. When S is a sufficient statistic, no information is lost in this limit. In practice, finite \epsilon and imperfect summaries yield an approximation whose quality depends on both the tolerance and how informative our statistics are.

But how exactly do we “compare” datasets? We need informative features to compress the data and a distance metric to measure discrepancy. Let’s see how this works with a concrete biological example.

3.6.2 A Concrete Example: The Telegraph Model

Consider a challenging inference scenario: we want to fit the full mechanistic Telegraph model with its kinetic parameters k_{\text{on}}, k_{\text{off}}, and \beta to single-cell mRNA count data. While the Telegraph model has an analytical steady-state solution, evaluating its likelihood requires expensive special function computations and numerical integrals—prohibitive when repeated thousands of times during MCMC. But we can easily simulate from the Telegraph model using the Gillespie algorithm from Chapter 2.

This is precisely where ABC shines: when simulation is feasible but likelihood evaluation is computationally expensive or analytically intractable.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson
from joblib import Parallel, delayed
import numba

from numba import int64, float64

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

signature = int64(float64, float64, float64, float64, float64, int64)

# Telegraph model simulator using Gillespie algorithm (simplified version)
@numba.jit(signature, nopython=True)
def gillespie_telegraph(k_on, k_off, beta, gamma, total_time=30.0, seed=None):
    """
    Simulate telegraph model using Gillespie algorithm.
    Accepts a seed for reproducible and parallel-safe random number generation.
    """
    # Each parallel worker creates its own independent RNG from a seed
    if seed is not None:
        np.random.seed(seed)

    # Start in OFF state with 0 mRNA
    gene_state = 0
    mrna_count = 0
    time = 0

    while time < total_time:
        if gene_state == 0:
            a_on, a_transcribe = k_on, 0
        else:
            a_on, a_transcribe = 0, beta

        a_off = k_off if gene_state == 1 else 0
        a_degrade = gamma * mrna_count
        a_total = a_on + a_off + a_transcribe + a_degrade

        if a_total == 0:
            break

        time += np.random.exponential(1 / a_total)

        if time > total_time:
            break

        rand = np.random.random() * a_total

        if rand < a_on:
            gene_state = 1
        elif rand < a_on + a_off:
            gene_state = 0
        elif rand < a_on + a_off + a_transcribe:
            mrna_count += 1
        else:
            mrna_count = max(0, mrna_count - 1)

    return mrna_count

def simulate_telegraph_population(rng, k_on, k_off, beta, gamma, n_cells=500):
    """
    Simulate a population of cells using Telegraph model IN PARALLEL.
    """

    total_time=30.0

    # --- FIX: Add a warm-up call to compile the function before parallel execution ---
    gillespie_telegraph(k_on=0.1, k_off=0.1, beta=1.0, gamma=1.0, total_time=30.0,seed=1) 
    

    # 1. Generate independent seeds for each parallel job from the main RNG
    seeds = rng.integers(low=0, high=2**32, size=n_cells)


    # 2. Run the gillespie_telegraph function in parallel for each cell
    #    n_jobs=-1 tells joblib to use all available CPU cores
    counts = Parallel(n_jobs=-1,  backend='threading')(
        delayed(gillespie_telegraph)(k_on, k_off, beta, gamma, total_time, seed=s) for s in seeds
    )

    return np.array(counts)

# Generate "experimental" data using Telegraph model
rng = np.random.default_rng(42)

# True parameters (chosen to generate ~10-15% zeros for robust ABC inference)
k_on_true = 0.5   # Gene activation rate
k_off_true = 1.0  # Gene deactivation rate
beta_true = 30.0  # Transcription rate when ON
gamma_true = 2.5  # mRNA degradation rate

print(f"True Telegraph parameters:")
print(f"k_on = {k_on_true}, k_off = {k_off_true}")
print(f"beta = {beta_true}, gamma = {gamma_true}")

# Generate experimental data (more cells = more stable statistics for ABC)
observed_data = simulate_telegraph_population(rng, k_on_true, k_off_true, beta_true, gamma_true, n_cells=500)

print(f"\nGenerated {len(observed_data)} observations")
print(f"Sample mean: {np.mean(observed_data):.2f}")
print(f"Sample variance: {np.var(observed_data, ddof=1):.2f}")

# Visualize the "experimental" data
plt.figure()
plt.hist(observed_data, bins=range(max(observed_data)+2), density=True, alpha=0.75,
         color=QUALITATIVE_COLORS[0], edgecolor='none')
plt.xlabel('mRNA molecules per cell')
plt.ylabel('Probability density')
plt.title('Experimental Data from Telegraph Model')
plt.grid(True, alpha=0.3)
plt.show()
True Telegraph parameters:
k_on = 0.5, k_off = 1.0
beta = 30.0, gamma = 2.5

Generated 500 observations
Sample mean: 4.15
Sample variance: 25.37
Figure 3.25: Setting up likelihood-free inference for the Telegraph model. We generate ‘experimental’ data using the full Telegraph model, then attempt to recover the parameters using only the Gillespie simulator, without direct likelihood evaluation.

Before implementing ABC, we must address identifiability: we can only estimate as many parameters as we have informative summary statistics. Our Telegraph model has four parameters, but attempting to infer all four from just two statistics (mean and variance) would be fundamentally ill-posed.

Fortunately, in many biological systems, the mRNA degradation rate \gamma sets the fundamental timescale and can be independently measured through experiments like actinomycin D treatments that block transcription. With \gamma fixed as a known constant, we need to infer three kinetic parameters: k_{\text{on}}, k_{\text{off}} (gene switching rates controlling burst frequency), and \beta (transcription rate controlling burst size). This requires three informative summary statistics.

But which three statistics should we choose? This brings us to the formal mathematical framework.

3.6.3 Implementing ABC: Summary Statistics and Distance Metrics

To apply ABC to the Telegraph model, we need to choose summary statistics and a distance metric. Summary statistics reduce potentially high-dimensional data D \in \mathcal{D} to a lower-dimensional vector S: \mathcal{D} \to \mathbb{R}^d.

For our Telegraph model inferring (k_{\text{on}}, k_{\text{off}}, \beta) from single-cell mRNA counts, we use three carefully chosen statistics: S(D) = \begin{pmatrix} \bar{x} \\ s^2 \\ p_0 \end{pmatrix} where \bar{x} = \frac{1}{n}\sum_{i=1}^n x_i is the sample mean (captures overall transcriptional activity), s^2 = \frac{1}{n-1}\sum_{i=1}^n (x_i - \bar{x})^2 is the sample variance (distinguishes bursting from Poissonian expression), and p_0 = \frac{1}{n}\sum_{i=1}^n \mathbb{1}_{x_i=0} is the proportion of zeros (highly sensitive to promoter OFF-time). The proportion of zeros is particularly powerful: when k_{\text{off}} \gg k_{\text{on}}, the promoter spends most time OFF and many cells have zero mRNA; when k_{\text{on}} \gg k_{\text{off}}, zeros become rare.

For the distance metric, we use scaled Euclidean distance to ensure each statistic contributes equally: \rho(S_{\text{sim}}, S_{\text{obs}}) = \sqrt{\sum_{j=1}^d \left(\frac{S_{\text{sim},j} - S_{\text{obs},j}}{S_{\text{obs},j} + \epsilon_0}\right)^2} where \epsilon_0 > 0 prevents division by zero. Scaling is essential—without it, statistics with larger magnitudes (like variance) would dominate the distance calculation.

3.6.4 Building Intuition: Visualizing the Parameter Space

With the mathematical framework in place, let’s build intuition by exploring how the discrepancy \rho(S_{\text{sim}}, S_{\text{obs}}) varies across parameter space.

For this intuition-building exercise, we’ll fix k_{\text{off}} = 0.5 (pretending we know it) and explore the two-dimensional space of k_{\text{on}} and \beta. If our approach is sound, parameter combinations with low discrepancy should cluster around the true values.

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

def summary_statistics(data):
    """Calculate summary statistics for ABC comparison"""
    return np.array([np.mean(data), np.var(data, ddof=1), np.mean(data == 0)])

def distance_function(sim_stats, obs_stats):
    """
    Calculates a hybrid scaled Euclidean distance.
    Uses relative scaling for mean and variance (large values),
    but absolute scaling for proportion-zeros (small value prone to division issues).
    """
    # Relative distance for mean and variance
    rel_mean = (sim_stats[0] - obs_stats[0]) / (np.abs(obs_stats[0]) + 1e-6)
    rel_var = (sim_stats[1] - obs_stats[1]) / (np.abs(obs_stats[1]) + 1e-6)
    # Absolute distance for proportion zeros, scaled by typical range (~0.1)
    abs_p0 = (sim_stats[2] - obs_stats[2]) / 0.1
    return np.sqrt(rel_mean**2 + rel_var**2 + abs_p0**2)

# Sample parameters from priors to explore parameter space
n_exploration = 200
rng_explore = np.random.default_rng(789)

# Prior ranges for exploration
k_on_prior = [0.1, 2.0]
beta_prior = [10.0, 60.0]
k_off_fixed = 0.5  # Fix k_off for 2D visualization

# Storage for exploration results
k_on_samples = []
beta_samples = []
discrepancies = []

# Calculate observed statistics
obs_stats = summary_statistics(observed_data)

print(f"Exploring parameter space with {n_exploration} prior samples...")
print(f"Fixed: k_off = {k_off_fixed}")
print(f"Varying: k_on ∈ [{k_on_prior[0]}, {k_on_prior[1]}], beta ∈ [{beta_prior[0]}, {beta_prior[1]}]")

for i in range(n_exploration):
    # Sample from priors
    k_on = rng_explore.uniform(*k_on_prior)
    beta = rng_explore.uniform(*beta_prior)

    # Simulate data with these parameters
    sim_data = simulate_telegraph_population(rng_explore, k_on, k_off_fixed, beta, gamma_true, n_cells=len(observed_data))
    sim_stats = summary_statistics(sim_data)

    # Calculate discrepancy
    discrepancy = distance_function(sim_stats, obs_stats)

    # Store results
    k_on_samples.append(k_on)
    beta_samples.append(beta)
    discrepancies.append(discrepancy)

    if (i + 1) % 50 == 0:
        print(f"Completed {i + 1}/{n_exploration} parameter evaluations")

# Convert to arrays for plotting
k_on_samples = np.array(k_on_samples)
beta_samples = np.array(beta_samples)
discrepancies = np.array(discrepancies)

# Create 2D parameter space visualization
plt.figure()
scatter = plt.scatter(k_on_samples, beta_samples, c=discrepancies,
                     cmap='plasma_r', s=50, alpha=0.7, edgecolors='none')

# Mark the true parameter values
plt.scatter(k_on_true, beta_true, color='white', s=200, marker='*',
           edgecolors='black', linewidth=2, label=f'True values: k_on={k_on_true}, β={beta_true}')

# Find and highlight the best matches
best_idx = np.argmin(discrepancies)
plt.scatter(k_on_samples[best_idx], beta_samples[best_idx], color='white', s=100,
           marker='o', edgecolors='black', linewidth=2,
           label=f'Best match: k_on={k_on_samples[best_idx]:.2f}, β={beta_samples[best_idx]:.1f}')

plt.colorbar(scatter, label='Discrepancy (lower = better match)')
plt.xlabel('k_on (gene activation rate)')
plt.ylabel('β (transcription rate)')
plt.title('Parameter Space Exploration: Discrepancy Landscape')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

print(f"\nExploration Results:")
print(f"Best parameter combination found:")
print(f"k_on = {k_on_samples[best_idx]:.3f} (true: {k_on_true})")
print(f"beta = {beta_samples[best_idx]:.1f} (true: {beta_true})")
print(f"Minimum discrepancy: {discrepancies[best_idx]:.3f}")
print(f"Average discrepancy: {np.mean(discrepancies):.3f}")
Exploring parameter space with 200 prior samples...
Fixed: k_off = 0.5
Varying: k_on ∈ [0.1, 2.0], beta ∈ [10.0, 60.0]
Completed 50/200 parameter evaluations
Completed 100/200 parameter evaluations
Completed 150/200 parameter evaluations
Completed 200/200 parameter evaluations
Figure 3.26: Building intuition for ABC: parameter space exploration colored by discrepancy. Each point represents a parameter combination (k_on, beta) sampled from the prior, with k_off fixed at 0.5. Colors indicate how well simulated data matches our observations—darker blue means better match. Notice how the lowest discrepancy points (darkest blue) cluster around the true parameter values (red star), demonstrating the core principle of ABC: good parameters generate data that looks like what we observed.

Exploration Results:
Best parameter combination found:
k_on = 0.389 (true: 0.5)
beta = 27.3 (true: 30.0)
Minimum discrepancy: 0.280
Average discrepancy: 3.353

This exploration reveals the core insight behind ABC: good parameters produce data that looks similar to our observations. The parameter space has a clear structure—combinations near the true values tend to have lower discrepancy (darker colors in the plot).

3.6.5 ABC Rejection Sampling: Implementation

ABC rejection sampling formalizes this intuition by systematically collecting parameter samples from the low-discrepancy regions. Rather than exploring the entire parameter space uniformly as we just did, ABC focuses computational effort on promising regions by accepting only parameters below a discrepancy threshold.

But what threshold should we use? Choosing the tolerance \epsilon is surprisingly difficult—set it too tight and you’ll reject almost everything, wasting computational effort; set it too loose and your posterior approximation will be poor. A practical solution is to run a fixed number of simulations and accept the top quantile (say, 10%) with smallest discrepancies. This quantile-based approach automatically calibrates \epsilon to your problem: the tolerance emerges from the data rather than requiring you to guess it in advance.

Code
def abc_rejection_sampling(rng, observed_data, gamma_known, n_total=2500, quantile=0.10):
    """
    ABC rejection sampling with quantile-based acceptance.

    Instead of using a fixed tolerance, this runs n_total simulations and keeps
    the top quantile% with smallest distances. The tolerance epsilon_0 is then
    defined as the maximum distance among accepted samples.

    Parameters:
    - gamma_known: Fixed value from separate experiments
    - n_total: Total number of prior samples to evaluate (default: 2500)
    - quantile: Fraction of samples to accept (default: 0.10 = top 10%)

    Returns:
    - accepted_params: Top quantile% of parameter samples
    - accepted_distances: Corresponding distances
    - epsilon_0: The tolerance threshold (max distance of accepted samples)
    """
    # Calculate summary statistics for observed data
    obs_stats = summary_statistics(observed_data)

    # Priors for the parameters we're inferring (uniform for simplicity)
    k_on_prior = [0.1, 2.0]    # Uniform(0.1, 2.0)
    k_off_prior = [0.1, 5.0]   # Uniform(0.1, 5.0)
    beta_prior = [10.0, 60.0]   # Uniform(10.0, 60.0)

    print(f"Running ABC rejection sampling (quantile-based)...")
    print(f"Total simulations: {n_total}, keeping top {quantile*100:.0f}%")
    print(f"Observed statistics: mean={obs_stats[0]:.2f}, var={obs_stats[1]:.2f}, prop_zeros={obs_stats[2]:.3f}")
    print(f"Using known value: gamma={gamma_known:.1f}")

    # Storage for ALL simulations
    all_params = []
    all_distances = []

    # Run all simulations
    for i in range(n_total):
        # Sample from priors (k_on, k_off, and beta)
        k_on = rng.uniform(*k_on_prior)
        k_off = rng.uniform(*k_off_prior)
        beta = rng.uniform(*beta_prior)

        # Simulate data
        try:
            sim_data = simulate_telegraph_population(rng, k_on, k_off, beta, gamma_known,
                                                   n_cells=len(observed_data))
            sim_stats = summary_statistics(sim_data)

            # Calculate distance
            distance = distance_function(sim_stats, obs_stats)

            # Store results
            all_params.append([k_on, k_off, beta])
            all_distances.append(distance)

            if (i + 1) % 1000 == 0:
                print(f"Completed {i + 1}/{n_total} simulations")

        except:
            # Skip if simulation fails (store a very large distance)
            all_params.append([k_on, k_off, beta])
            all_distances.append(np.inf)
            continue

    # Convert to arrays
    all_params = np.array(all_params)
    all_distances = np.array(all_distances)

    # Sort by distance and keep top quantile%
    sorted_idx = np.argsort(all_distances)
    n_accept = int(n_total * quantile)
    accepted_idx = sorted_idx[:n_accept]

    accepted_params = all_params[accepted_idx]
    accepted_distances = all_distances[accepted_idx]

    # Define epsilon_0 as the worst (maximum) accepted distance
    epsilon_0 = accepted_distances[-1]

    print(f"\nABC sampling complete!")
    print(f"Accepted {n_accept} samples (top {quantile*100:.0f}%)")
    print(f"Distance range: [{accepted_distances[0]:.3f}, {epsilon_0:.3f}]")
    print(f"Inferred tolerance epsilon_0 = {epsilon_0:.3f}")

    return accepted_params, accepted_distances, epsilon_0

# Run ABC rejection sampling with quantile-based approach
rng = np.random.default_rng(123)
abc_samples, abc_distances, epsilon_0 = abc_rejection_sampling(rng, observed_data, gamma_true,
                                                                n_total=2500, quantile=0.10)

# Analyze results (for all three inferred parameters)
param_names = ['k_on', 'k_off', 'beta']
true_values = [k_on_true, k_off_true, beta_true]

print(f"\nABC Results Summary:")
print(f"{'Parameter':<10} {'True':<8} {'ABC Mean':<10} {'ABC Std':<10}")
print("-" * 45)
for i, name in enumerate(param_names):
    abc_mean = np.mean(abc_samples[:, i])
    abc_std = np.std(abc_samples[:, i])
    print(f"{name:<10} {true_values[i]:<8.2f} {abc_mean:<10.2f} {abc_std:<10.2f}")
Running ABC rejection sampling (quantile-based)...
Total simulations: 2500, keeping top 10%
Observed statistics: mean=4.15, var=25.37, prop_zeros=0.426
Using known value: gamma=2.5
Completed 1000/2500 simulations
Completed 2000/2500 simulations

ABC sampling complete!
Accepted 250 samples (top 10%)
Distance range: [0.181, 0.912]
Inferred tolerance epsilon_0 = 0.912

ABC Results Summary:
Parameter  True     ABC Mean   ABC Std   
---------------------------------------------
k_on       0.50     0.75       0.21      
k_off      1.00     2.90       1.29      
beta       30.00    39.11      12.21     
Figure 3.27

Let’s visualize the ABC posterior distributions:

Code
# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Create comprehensive visualization of ABC results
fig, axes = plt.subplots(1, 3)

# Define prior ranges for visualization
k_on_prior_range = [0.1, 2.0]
k_off_prior_range = [0.1, 5.0]
beta_prior_range = [10.0, 60.0]
prior_ranges = [k_on_prior_range, k_off_prior_range, beta_prior_range]

# Define LaTeX labels for parameters
param_labels = [r'$k_{\text{on}}$', r'$k_{\text{off}}$', r'$\beta$']

for i, (param_name, param_label, true_val) in enumerate(zip(param_names, param_labels, true_values)):
    ax = axes[i]

    # Plot posterior histogram
    ax.hist(abc_samples[:, i], bins=13, density=True, alpha=0.75,
            color=QUALITATIVE_COLORS[1], edgecolor='none')

    # Plot uniform prior (constant density over the range)
    prior_range = prior_ranges[i]
    prior_density = 1.0 / (prior_range[1] - prior_range[0])
    ax.hlines(prior_density, prior_range[0], prior_range[1],
              colors='gray', linestyles='--', linewidth=2,
              label=f'Prior: Uniform({prior_range[0]}, {prior_range[1]})',zorder=-10)

    # Mark true value
    ax.axvline(true_val, color=QUALITATIVE_COLORS[0], linestyle='--', linewidth=2,
               label=f'True {param_label} = {true_val}')

    # Mark posterior mean
    abc_mean = np.mean(abc_samples[:, i])
    ax.axvline(abc_mean, color=QUALITATIVE_COLORS[3], linestyle='-', linewidth=2,
               label=f'ABC mean = {abc_mean:.2f}')

    ax.set_xlabel(param_label)
    ax.set_ylabel('Posterior density')
    ax.set_title(f'ABC Posterior: {param_label}')
    ax.set_xlim(prior_range[0], prior_range[1])  # Show full prior to emphasize contraction
    ax.legend()
    ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()


# Calculate 95% credible intervals
print(f"\n95% Credible Intervals:")
for i, name in enumerate(param_names):
    ci_lower, ci_upper = np.percentile(abc_samples[:, i], [2.5, 97.5])
    print(f"{name}: [{ci_lower:.2f}, {ci_upper:.2f}]")
Figure 3.28: ABC approximate posterior distributions for Telegraph model parameters. Each panel shows the marginal posterior for k_on, k_off, and beta, with true values marked by red dashed lines. Using three informative summary statistics, ABC successfully recovers three meaningful kinetic parameter estimates while keeping gamma fixed.

95% Credible Intervals:
k_on: [0.32, 1.11]
k_off: [0.60, 4.87]
beta: [16.68, 59.20]

3.6.6 Advanced ABC: Sequential Monte Carlo

The simple rejection sampling approach can be very inefficient, especially when the tolerance is small. ABC Sequential Monte Carlo (ABC-SMC) provides a much more efficient algorithm for solving the same inference problem—estimating k_{\text{on}}, k_{\text{off}}, and \beta while treating \gamma as known.

ABC-SMC works by starting with a loose tolerance and gradually tightening it over multiple rounds:

  1. Round 1: Use loose tolerance, accept many samples from the prior
  2. Round 2: Use accepted samples from Round 1 as proposals, tighten tolerance
  3. Continue: Repeat until tolerance is sufficiently small

This sequential approach dramatically improves efficiency by learning from previous rounds. Rather than starting from scratch each time like rejection sampling, ABC-SMC builds upon its previous discoveries to focus computational effort on promising parameter regions.

Calibrating ABC-SMC hyperparameters: In practice, choosing ABC-SMC hyperparameters—the initial tolerance \epsilon_0, the tolerance schedule, perturbation kernel widths—is notoriously difficult without prior knowledge of the problem. A common workflow is to run a warmup phase: perform ABC rejection sampling to calibrate a reasonable starting tolerance, then use those particles to initialize ABC-SMC. The warmup round gives us (1) an empirically grounded \epsilon_0 from the quantile-based acceptance, and (2) a starting particle population that already approximates the posterior, avoiding wasted computation sampling from the prior. Since we just completed ABC rejection sampling, we can directly use those 250 particles as our Round 1 population for ABC-SMC.

Code
def abc_smc_telegraph(rng, observed_data, gamma_known, epsilon_0, n_particles=500, n_rounds=2,
                       initial_particles=None, initial_distances=None):
    """
    ABC Sequential Monte Carlo for Telegraph model - inferring k_on, k_off, and beta

    This solves the same inference problem as ABC rejection sampling, but more efficiently
    through sequential improvement of the particle population. This implementation includes
    key SMC features like an adaptive perturbation kernel and a prior check for efficiency.

    Parameters:
    - gamma_known: Fixed value from separate experiments
    - epsilon_0: Starting tolerance from ABC rejection sampling
    - initial_particles: Optional particles from ABC rejection to use for Round 1
    - initial_distances: Optional distances corresponding to initial_particles
    - k_on, k_off, and beta are inferred from the data
    """
    # Calculate summary statistics for observed data
    obs_stats = summary_statistics(observed_data)

    # Set tolerance schedule: data-driven from ABC rejection baseline
    # If we have initial particles, skip Round 1 (they're already at epsilon_0)
    # and just run Round 2 with tighter tolerance
    if initial_particles is not None:
        tolerances = [epsilon_0/2]
        print(f"Using initial particles from ABC rejection (n={len(initial_particles)})")
        print(f"Skipping Round 1, running Round 2 with tolerance: {tolerances[0]:.3f}")
    else:
        tolerances = [epsilon_0, epsilon_0/2]
        print(f"Using data-driven tolerances: {tolerances}")

    # --- IMPROVEMENT: Explicitly define priors for checking and sampling ---
    k_on_prior = [0.1, 2.0]
    k_off_prior = [0.1, 5.0]
    beta_prior = [10.0, 60.0]
    priors = [k_on_prior, k_off_prior, beta_prior]

    # Storage for particles from each round
    all_particles = []
    round_info = []

    # If initial particles provided, use them as Round 1
    if initial_particles is not None:
        all_particles.append(initial_particles)
        # Record Round 1 info using the provided distances
        avg_distance = np.mean(initial_distances) if initial_distances is not None else 0
        round_info.append({
            'round': 1,
            'tolerance': epsilon_0,
            'n_accepted': len(initial_particles),
            'attempts': len(initial_particles),  # No rejected attempts since these are pre-accepted
            'accept_rate': 1.0,  # All particles were accepted in ABC rejection
            'avg_distance': avg_distance
        })
        round_start = 0  # Start from round 0 (which will be labeled as Round 2)
    else:
        round_start = 0

    print(f"ABC-SMC: Inferring Telegraph model parameters (k_on, k_off, beta)")
    print(f"Observed summary stats: mean={obs_stats[0]:.2f}, var={obs_stats[1]:.2f}, prop_zeros={obs_stats[2]:.3f}")
    print(f"Using known value: gamma={gamma_known:.1f}")
    print(f"Target: {n_particles} particles per round\n")

    for round_idx in range(len(tolerances)):
        tolerance = tolerances[round_idx]
        round_particles = []
        round_distances = []  # Store distances when particles are accepted
        attempts = 0
        max_attempts_per_particle = 500 # Safety break per particle

        # Calculate actual round number for display (accounts for initial particles)
        actual_round_num = len(all_particles) + 1

        print(f"Round {actual_round_num}: tolerance = {tolerance:.2f}")

        # --- IMPROVEMENT: Calculate adaptive perturbation kernel for subsequent rounds ---
        # Always use previous particles if they exist (either from initial or previous SMC round)
        if len(all_particles) > 0:
            prev_particles = all_particles[-1]  # Most recent particles
            # A common choice for the random walk kernel's scale is twice the variance (or std dev)
            # of the previous population. This adapts the search size.
            kernel_scale = 2 * np.std(prev_particles, axis=0)

        while len(round_particles) < n_particles:
            if attempts > max_attempts_per_particle * n_particles:
                 print("WARNING: Max attempts reached. Moving to next round with fewer particles.")
                 break

            attempts += 1

            if len(all_particles) == 0:
                # No previous particles: Sample from priors (uniform distributions)
                k_on = rng.uniform(*priors[0])
                k_off = rng.uniform(*priors[1])
                beta = rng.uniform(*priors[2])
                theta = np.array([k_on, k_off, beta])
            else:
                # Have previous particles: Perturb them
                # --- IMPROVEMENT: Loop until a valid particle (within prior) is proposed ---
                while True:
                    # Sample a particle from previous round (uniform weights for simplicity)
                    prev_particle = prev_particles[rng.integers(len(prev_particles))]

                    # Perturb using the adaptive kernel
                    k_on = prev_particle[0] + rng.normal(0, kernel_scale[0])
                    k_off = prev_particle[1] + rng.normal(0, kernel_scale[1])
                    beta = prev_particle[2] + rng.normal(0, kernel_scale[2])
                    theta = np.array([k_on, k_off, beta])

                    # Cheap check: is the proposed particle valid according to the prior?
                    k_on_valid = priors[0][0] <= k_on <= priors[0][1]
                    k_off_valid = priors[1][0] <= k_off <= priors[1][1]
                    beta_valid = priors[2][0] <= beta <= priors[2][1]

                    if k_on_valid and k_off_valid and beta_valid:
                        break # Valid particle found, proceed to expensive simulation

            # Use the known value for gamma in simulation
            gamma = gamma_known

            # Simulate data using proposed k_on, k_off, beta and known gamma
            try:
                sim_data = simulate_telegraph_population(rng, theta[0], theta[1], theta[2], gamma,
                                                       n_cells=len(observed_data))

                # Calculate summary statistics for simulated data
                sim_stats = summary_statistics(sim_data)

                # Calculate distance between observed and simulated summary stats
                distance = distance_function(sim_stats, obs_stats)

                # Accept if distance is within tolerance
                if distance <= tolerance:
                    round_particles.append(theta)
                    round_distances.append(distance)  # Store distance to avoid re-simulation
                    if len(round_particles) % 100 == 0:
                        print(f"  ... accepted {len(round_particles)}/{n_particles} particles")


            except:
                # Skip if simulation fails
                continue
        
        # Ensure we have some particles before proceeding
        if not round_particles:
            print(f"FATAL: No particles accepted in Round {actual_round_num}. Check priors or increase tolerance.")
            break

        all_particles.append(np.array(round_particles))
        accept_rate = len(round_particles) / attempts if attempts > 0 else 0

        # Calculate average distance from stored values (no re-simulation needed!)
        avg_distance = np.mean(round_distances) if round_distances else 0

        round_info.append({
            'round': actual_round_num,
            'tolerance': tolerance,
            'n_accepted': len(round_particles),
            'attempts': attempts,
            'accept_rate': accept_rate,
            'avg_distance': avg_distance
        })

        print(f"  -> Accepted: {len(round_particles)}/{attempts} (rate: {accept_rate:.3f})")
        print(f"     Average distance: {avg_distance:.3f}\n")

    return all_particles, round_info

# Run ABC-SMC, reusing particles from ABC rejection for Round 1
rng = np.random.default_rng(456)  # Different seed for ABC-SMC
particles_by_round, smc_info = abc_smc_telegraph(
    rng, observed_data, gamma_true, epsilon_0,
    initial_particles=abc_samples,
    initial_distances=abc_distances
)

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# Visualize the sequential improvement: parameter distributions for all three parameters
fig, axes = plt.subplots(1, 3)
param_names = ['k_on', 'k_off', 'beta']
true_values = [k_on_true, k_off_true, beta_true]
param_labels = [r'$k_{\text{on}}$', r'$k_{\text{off}}$', r'$\beta$']

colors = [QUALITATIVE_COLORS[1], QUALITATIVE_COLORS[5]]  # blue and green for rounds
alphas = [0.6, 0.8]

# Define prior ranges for visualization
k_on_prior_range = [0.1, 2.0]
k_off_prior_range = [0.1, 5.0]
beta_prior_range = [10.0, 60.0]
prior_ranges = [k_on_prior_range, k_off_prior_range, beta_prior_range]

for i, (param_name, param_label) in enumerate(zip(param_names, param_labels)):
    ax = axes[i]

    # Plot uniform prior (constant density over the range)
    prior_range = prior_ranges[i]
    prior_density = 1.0 / (prior_range[1] - prior_range[0])
    ax.hlines(prior_density, prior_range[0], prior_range[1],
              colors='gray', linestyles='--', linewidth=2,
              label=f'Prior: Uniform', zorder=-10)

    # Plot particle distributions from each round
    for round_num in range(len(particles_by_round)):
        particles = particles_by_round[round_num][:, i]

        # Create histogram for this round
        ax.hist(particles, bins=20, alpha=alphas[round_num],
                color=colors[round_num], edgecolor='none', density=True,
                label=f'Round {round_num + 1} (n={len(particles)})', zorder=2)

        # Plot posterior mean for this round
        mean_val = np.mean(particles)
        ax.axvline(mean_val, color=colors[round_num], linestyle='-', linewidth=2,
                   label=f'Round {round_num + 1} mean = {mean_val:.2f}', zorder=3)

    # Mark true value
    ax.axvline(true_values[i], color=QUALITATIVE_COLORS[0], linestyle='--', linewidth=2,
               label=f'True {param_label} = {true_values[i]}', zorder=4)

    ax.set_xlabel(param_label)
    ax.set_ylabel('Density')
    ax.set_title(f'ABC-SMC: {param_label} convergence')
    ax.set_xlim(prior_range[0], prior_range[1])  # Show full prior to emphasize contraction
    ax.legend()
    ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

# Print summary of results
print("\nABC-SMC Summary:")
for info in smc_info:
    print(f"Round {info['round']}: tolerance={info['tolerance']:.2f}, "
          f"acceptance rate={info['accept_rate']:.3f}, "
          f"avg distance={info['avg_distance']:.3f}")

# Calculate posterior means and credible intervals for final round (k_on, k_off, beta)
final_particles = particles_by_round[-1]
print(f"\nFinal Round Parameter Estimates (n={len(final_particles)}):")
print(f"{'Parameter':<10} {'True':<8} {'SMC Mean':<10} {'SMC Std':<10} {'95% CI':<20}")
print("-" * 65)
for i, name in enumerate(param_names):
    mean_est = np.mean(final_particles[:, i])
    std_est = np.std(final_particles[:, i])
    ci_lower, ci_upper = np.percentile(final_particles[:, i], [2.5, 97.5])
    true_val = true_values[i]
    print(f"{name:<10} {true_val:<8.3f} {mean_est:<10.3f} {std_est:<10.3f} [{ci_lower:.3f}, {ci_upper:.3f}]")

# Compare efficiency: ABC-SMC vs ABC rejection
print(f"\nEfficiency Comparison:")
abc_acceptance_rate = len(abc_samples) / iteration if 'iteration' in locals() else 0.01
print(f"ABC Rejection: {len(abc_samples)} accepted samples (acceptance rate: {abc_acceptance_rate:.1%})")
print(f"ABC-SMC: {len(final_particles)} accepted samples from {smc_info[-1]['attempts']} attempts ({smc_info[-1]['accept_rate']:.1%} acceptance in final round)")
print(f"ABC-SMC is dramatically more efficient by focusing on promising parameter regions!")
Using initial particles from ABC rejection (n=250)
Skipping Round 1, running Round 2 with tolerance: 0.456
ABC-SMC: Inferring Telegraph model parameters (k_on, k_off, beta)
Observed summary stats: mean=4.15, var=25.37, prop_zeros=0.426
Using known value: gamma=2.5
Target: 500 particles per round

Round 2: tolerance = 0.46
  ... accepted 100/500 particles
  ... accepted 200/500 particles
  ... accepted 300/500 particles
  ... accepted 400/500 particles
  ... accepted 500/500 particles
  -> Accepted: 500/10942 (rate: 0.046)
     Average distance: 0.323
Figure 3.29: ABC-SMC implementation for the Telegraph model using a warmup-phase workflow. Round 1 uses the 250 particles already accepted from ABC rejection sampling (light blue), serving as both a calibrated starting tolerance and initial population. Round 2 perturbs these particles with a tighter tolerance (epsilon_0/2) to further refine the estimates. This warmup approach—standard practice for calibrating ABC hyperparameters—makes the connection between ABC rejection and ABC-SMC explicit while avoiding wasted computation.

ABC-SMC Summary:
Round 1: tolerance=0.91, acceptance rate=1.000, avg distance=0.644
Round 2: tolerance=0.46, acceptance rate=0.046, avg distance=0.323

Final Round Parameter Estimates (n=500):
Parameter  True     SMC Mean   SMC Std    95% CI              
-----------------------------------------------------------------
k_on       0.500    0.685      0.122      [0.395, 0.879]
k_off      1.000    2.850      1.088      [0.711, 4.705]
beta       30.000   44.298     8.879      [26.618, 58.935]

Efficiency Comparison:
ABC Rejection: 250 accepted samples (acceptance rate: 1.0%)
ABC-SMC: 500 accepted samples from 10942 attempts (4.6% acceptance in final round)
ABC-SMC is dramatically more efficient by focusing on promising parameter regions!

3.6.7 Beyond Basic ABC

The ABC methods we’ve implemented provide the conceptual foundation, but modern approaches extend these ideas in two directions: refined ABC algorithms and neural methods.

The pyABC package implements advanced ABC-SMC with adaptive distance functions, intelligent perturbation kernels, and parallel execution—staying within the ABC framework but achieving far better efficiency. For many biological problems, pyABC offers the best balance of rigor and feasibility.

Neural simulation-based inference takes a different approach: train neural networks on simulator-generated (\theta, D) pairs to learn either the likelihood \hat{p}(D | \theta) (Neural Likelihood Estimation) or the posterior \hat{p}(\theta | D) directly (Neural Posterior Estimation). The critical advantage is automatic feature extraction—instead of hand-crafting summary statistics, networks learn to extract all relevant information from raw data. The sbi package implements both approaches. When simulations are expensive and ABC becomes prohibitive, neural methods can provide orders-of-magnitude speedups at the cost of upfront training investment and harder-to-diagnose failures.

3.6.8 What We’ve Learned

Our ABC analysis of the Telegraph model reveals the fundamental bargain of simulation-based inference: we exchange statistical efficiency for the ability to work with mechanistically realistic models. Summary statistics determine what we can identify—mean, variance, and proportion of zeros each capture different aspects of the generative process. When analytical likelihoods become intractable, as they inevitably do for complex stochastic models, likelihood-free methods remain our only path forward. The price is greater computational cost and careful tuning, but for many biological problems—complex simulators, agent-based models, or intractable likelihood evaluation—this trade-off is unavoidable.


3.7 Potpourri: Advanced Topics for Practical Modeling

Our journey so far has assumed a pristine world where our data is a perfect reflection of a single, uniform biological process. But what happens when reality intervenes?

Our journey so far has assumed clean data from a single, uniform process. But real experimental data is messy. This section equips our models with the machinery to handle three common complexities: technical noise from the measurement process, structured variation across different experimental groups, and hidden subpopulations within our sample.

3.7.1 Observation Models: Distinguishing Technical from Biological Noise

We’ve assumed measurements perfectly reflect molecular counts—a zero in the data means zero mRNA in the cell. But scRNA-seq is imperfect. Transcripts can fail to be captured, reverse-transcribed, or sequenced, creating “technical zeros” where the gene was actually expressed. How do we disentangle this measurement noise from the biological process?

3.7.1.1 Zero-Inflated Negative Binomial (ZINB)

The ZINB model treats each observation as arising from one of two competing processes:

y_i = \begin{cases} 0 & \text{with probability } \pi \quad \text{(technical dropout)} \\ \text{NB}(r, p) & \text{with probability } 1-\pi \quad \text{(biological count)} \end{cases}

This gives the probability mass function:

P(y | \pi, r, p) = \begin{cases} \pi + (1-\pi) \cdot \text{NB}(0 | r, p) & \text{if } y = 0 \\ (1-\pi) \cdot \text{NB}(y | r, p) & \text{if } y > 0 \end{cases}

where \pi is the dropout probability and (r, p) are the biological Negative Binomial parameters. We estimate all three parameters jointly by maximizing the log-likelihood:

-\ell(\pi, r, p | \mathbf{y}) = -\sum_{i: y_i=0} \log\left(\pi + (1-\pi)p^r\right) - \sum_{i: y_i>0} \left[ \log(1-\pi) + \log(\text{NB}(y_i|r,p)) \right]

Let’s generate data with 30% artificial dropouts and see if the ZINB model recovers both the technical (\pi) and biological (r, p) parameters:

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom
from scipy.optimize import minimize

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# --- 1. Generate Synthetic ZINB Data ---
rng = np.random.default_rng(42)
r_true, p_true = 5.0, 0.4  # True biological parameters
pi_true = 0.3              # 30% dropout probability
n_cells = 1000

# Generate biological counts from NB
bio_counts = nbinom.rvs(n=r_true, p=p_true, size=n_cells, random_state=rng)

# Introduce dropouts
is_dropout = rng.binomial(1, pi_true, size=n_cells).astype(bool)
observed_data = bio_counts.copy()
observed_data[is_dropout] = 0

# --- 2. Define Log-Likelihood Functions ---
def neg_log_likelihood_nb(params, data):
    r, p = params
    if r <= 0 or p <= 0 or p >= 1: return np.inf
    return -np.sum(nbinom.logpmf(data, n=r, p=p))

def neg_log_likelihood_zinb(params, data):
    pi, r, p = params
    if not (0 <= pi <= 1 and r > 0 and 0 < p < 1): return np.inf
    
    zeros = data[data == 0]
    non_zeros = data[data > 0]
    
    # Log-likelihood for zero counts, using logaddexp for stability
    ll_zeros = len(zeros) * np.logaddexp(
        np.log(pi),
        np.log(1 - pi) + nbinom.logpmf(0, n=r, p=p)
    )
    
    # Log-likelihood for non-zero counts
    ll_non_zeros = np.sum(
        np.log(1 - pi) + nbinom.logpmf(non_zeros, n=r, p=p)
    )
    
    return -(ll_zeros + ll_non_zeros)

# --- 3. Fit Both Models ---
# Standard NB fit
res_nb = minimize(neg_log_likelihood_nb, [4.0, 0.5], args=(observed_data,),
                  method='L-BFGS-B', bounds=[(0.1, 20), (0.01, 0.99)])
r_nb, p_nb = res_nb.x
ll_nb = -res_nb.fun

# ZINB fit with multiple random restarts to avoid local optima
# Mixture models are multimodal - need multiple starting points
n_restarts = 15
best_ll_zinb = -np.inf
best_params_zinb = None

for restart in range(n_restarts):
    # Data-driven initialization with random perturbations
    pi_init = np.sum(observed_data == 0) / len(observed_data)
    pi_init = np.clip(pi_init + rng.uniform(-0.15, 0.15), 0.05, 0.95)

    # Fit NB to non-zero data for initial r, p estimates
    non_zero_data = observed_data[observed_data > 0]
    if len(non_zero_data) > 0:
        mean_nz = np.mean(non_zero_data)
        var_nz = np.var(non_zero_data)
        if var_nz > mean_nz:
            p_init = mean_nz / var_nz
            r_init = (mean_nz**2) / (var_nz - mean_nz)
        else:
            r_init, p_init = 4.0, 0.5
    else:
        r_init, p_init = 4.0, 0.5

    # Add random perturbations to avoid identical restarts
    r_init = np.clip(r_init + rng.uniform(-2, 2), 0.5, 15)
    p_init = np.clip(p_init + rng.uniform(-0.15, 0.15), 0.05, 0.95)

    res_zinb = minimize(neg_log_likelihood_zinb, [pi_init, r_init, p_init], args=(observed_data,),
                        method='L-BFGS-B', bounds=[(0.2, 0.99), (0.1, 20), (0.01, 0.99)])
    ll_candidate = -res_zinb.fun

    if ll_candidate > best_ll_zinb:
        best_ll_zinb = ll_candidate
        best_params_zinb = res_zinb.x

pi_zinb, r_zinb, p_zinb = best_params_zinb
ll_zinb = best_ll_zinb

# --- 4. Compare and Visualize ---
print(f"Best log-likelihood after {n_restarts} restarts: {ll_zinb:.2f}")
print("\nTrue Parameters:")
print(f"pi = {pi_true:.3f}, r = {r_true:.3f}, p = {p_true:.3f}")
print("\nNB Model Estimates:")
print(f"r = {r_nb:.3f}, p = {p_nb:.3f}")
print("\nZINB Model Estimates:")
print(f"pi = {pi_zinb:.3f}, r = {r_zinb:.3f}, p = {p_zinb:.3f}")

# Calculate AIC
aic_nb = 2 * 2 - 2 * ll_nb
aic_zinb = 2 * 3 - 2 * ll_zinb
print(f"\nAIC (NB): {aic_nb:.2f}")
print(f"AIC (ZINB): {aic_zinb:.2f} (Lower is better)")

# Plot results
x_range = np.arange(0, observed_data.max() + 1)
pmf_nb = nbinom.pmf(x_range, n=r_nb, p=p_nb)

# ZINB PMF: note that we compute the full mixture, including the zero-inflation
pmf_zinb = (1 - pi_zinb) * nbinom.pmf(x_range, n=r_zinb, p=p_zinb)
pmf_zinb[0] += pi_zinb

plt.figure()
# Use bins centered on integers for discrete data
plt.hist(observed_data, bins=np.arange(-0.5, observed_data.max() + 1.5),
         density=True, alpha=0.75, color='gray', edgecolor='none', label='Observed Data')
plt.plot(x_range, pmf_nb, 'o-', color=QUALITATIVE_COLORS[0], label=f'NB Fit (AIC={aic_nb:.0f})')
plt.plot(x_range, pmf_zinb, 's-', color=QUALITATIVE_COLORS[1], label=f'ZINB Fit (AIC={aic_zinb:.0f})')
plt.xlabel("mRNA molecules per cell")
plt.ylabel("Probability Density")
plt.title("Modeling Technical Zeros with ZINB")
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlim(-1, 40)
plt.show()
Best log-likelihood after 15 restarts: -2583.51

True Parameters:
pi = 0.300, r = 5.000, p = 0.400

NB Model Estimates:
r = 0.731, p = 0.119

ZINB Model Estimates:
pi = 0.290, r = 4.414, p = 0.367

AIC (NB): 5524.45
AIC (ZINB): 5173.02 (Lower is better)
Figure 3.30: Disentangling biological and technical zeros with a Zero-Inflated Negative Binomial (ZINB) model. The observed data (gray histogram) was generated from a Negative Binomial process with additional technical dropouts, creating an inflated zero peak. A standard Negative Binomial fit (red) is distorted by the excess zeros and fails to capture the distribution’s shape. The ZINB fit (blue) correctly models both the dropout probability and the underlying biological distribution. The lighter dashed line shows the ZINB’s biological component (1-π)·NB, which aligns with the non-zero portion of the data, while the full ZINB curve adds the technical dropout mass at zero. The model provides a much better explanation of the data and more accurate parameter estimates.

The standard NB model, forced to account for excess zeros, compromises its fit everywhere. The ZINB model uses \pi to absorb technical zeros, letting the NB component capture the true biological process. The AIC difference confirms the extra parameter is justified.

The ZINB is an example of a mixture model—a distribution formed by combining multiple component distributions with mixing weights. Each observation is assumed to come from one of K components with probability \pi_k, where \sum_k \pi_k = 1. For ZINB, we had two components: a point mass at zero (technical dropout) and a Negative Binomial (biological process).

3.7.2 Hierarchical Models

Suppose we measure gene expression across multiple cell types. Should we fit each cell type separately (respecting heterogeneity but losing statistical power) or pool all data together (gaining power but ignoring biological differences)? Hierarchical models offer a middle ground: assume each group’s parameters are draws from a shared population distribution. Groups with sparse data “borrow strength” from the population, shrinking noisy estimates toward the global mean.

\begin{align*} \text{Hyperpriors:} \quad & \alpha \sim \text{HalfCauchy}(1), \quad \beta \sim \text{HalfCauchy}(1) \\ \text{Group-level:} \quad & p_j \sim \text{Beta}(\alpha, \beta) \quad \text{for } j = 1, \ldots, J \\ \text{Likelihood:} \quad & n_{ij} \sim \text{NegativeBinomial}(r, p_j) \end{align*}

Each p_j is a draw from a population-level Beta(\alpha, \beta). The hyperparameters (\alpha, \beta) are learned from all groups simultaneously. This creates “shrinkage”: estimates for data-poor groups are pulled toward the population mean, stabilizing inference while preserving group differences where data justifies them.

We can visualize this hierarchical structure using plate notation, a graphical language for Bayesian models. Circles represent random variables, shaded circles are observed data, and rectangles (“plates”) indicate replication—the index in the corner shows how many copies exist.

Code
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, Circle

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, ax = plt.subplots(figsize=(8, 5))

# Helper to draw nodes
def draw_node(ax, x, y, label, observed=False, size=0.4):
    color = 'lightgray' if observed else 'white'
    circle = Circle((x, y), size, facecolor=color, edgecolor='black', linewidth=2, zorder=3)
    ax.add_patch(circle)
    ax.text(x, y, label, ha='center', va='center', fontsize=12, fontweight='bold', zorder=4)

# Helper to draw plates
def draw_plate(ax, x, y, w, h, label, corner_label):
    plate = FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0.1",
                           edgecolor=QUALITATIVE_COLORS[2], facecolor='none',
                           linewidth=2, linestyle='--', zorder=1)
    ax.add_patch(plate)
    ax.text(x + w - 0.3, y + 0.2, corner_label, fontsize=11, style='italic', zorder=2)

# Helper to draw arrows
def draw_arrow(ax, x1, y1, x2, y2):
    arrow = FancyArrowPatch((x1, y1), (x2, y2), arrowstyle='->',
                           mutation_scale=20, linewidth=1.5,
                           color='black', zorder=2)
    ax.add_patch(arrow)

# Hyperpriors (top level)
draw_node(ax, 1, 4, r'$\alpha$')
draw_node(ax, 2, 4, r'$\beta$')
draw_node(ax, 4, 4, r'$r$')

# J-plate for groups
draw_plate(ax, 0.5, 0.5, 4, 2.5, 'Groups', r'$j = 1, \ldots, J$')

# Group-level parameter p_j
draw_node(ax, 2, 2.3, r'$p_j$')

# i-plate for observations within groups (nested)
draw_plate(ax, 1, 0.7, 3, 1.3, 'Observations', r'$i = 1, \ldots, n_j$')

# Observed data n_ij
draw_node(ax, 3, 1.3, r'$n_{ij}$', observed=True)

# Arrows showing dependencies
draw_arrow(ax, 1.3, 3.7, 1.8, 2.6)  # alpha -> p_j
draw_arrow(ax, 1.7, 3.7, 2.0, 2.6)  # beta -> p_j
draw_arrow(ax, 2, 1.9, 2.5, 1.6)    # p_j -> n_ij
draw_arrow(ax, 4, 3.6, 3.4, 1.6)    # r -> n_ij

ax.set_xlim(0, 5.5)
ax.set_ylim(0, 4.8)
ax.set_aspect('equal')
ax.axis('off')
ax.set_title('Hierarchical Model Structure', fontsize=14, fontweight='bold', pad=10)

plt.tight_layout()
plt.show()
Figure 3.31: Plate diagram for the hierarchical Negative Binomial model. Hyperparameters α and β generate group-level parameters p_j (one per group, shown in the J-plate). Each group j has n_j observations (the nested i-plate), generated from NB(r, p_j). Shaded nodes are observed; unshaded nodes are latent parameters to be inferred. Arrows show probabilistic dependencies.

Let’s simulate four groups where Group D has sparse data:

Code
import pymc as pm
import numpy as np
import matplotlib.pyplot as plt
import arviz as az
from scipy.stats import nbinom
from scipy.optimize import minimize

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# --- 1. Generate Synthetic Hierarchical Data ---
rng = np.random.default_rng(123)
n_groups = 4
# True p values for each group
p_true = np.array([0.2, 0.4, 0.6, 0.8])
r_true = 8.0  # Common burst size parameter
# Uneven sample sizes, with group D being data-poor
n_samples = [200, 150, 100, 15]

data = []
group_idx = []
for i in range(n_groups):
    counts = nbinom.rvs(n=r_true, p=p_true[i], size=n_samples[i], random_state=rng)
    data.extend(counts)
    group_idx.extend([i] * n_samples[i])

data = np.array(data)
group_idx = np.array(group_idx)

# --- 2. Fit Hierarchical Model in PyMC ---
with pm.Model() as hierarchical_model:
    # Hyperpriors for the Beta distribution
    alpha = pm.HalfCauchy('alpha', 1.0)
    beta = pm.HalfCauchy('beta', 1.0)

    # Common burst size parameter
    r = pm.Exponential('r', 0.5)

    # Group-level p parameters
    p_groups = pm.Beta('p', alpha=alpha, beta=beta, shape=n_groups)

    # Likelihood
    counts = pm.NegativeBinomial('counts', n=r, p=p_groups[group_idx], observed=data)

    idata = pm.sample(700, tune=200, chains=4, cores=4, random_seed=42, target_accept=0.75)

# --- 3. Calculate Other Estimates for Comparison ---
# No Pooling estimates (MoM for each group)
p_no_pool = []
for i in range(n_groups):
    group_data = data[group_idx == i]
    mean, var = np.mean(group_data), np.var(group_data, ddof=1)
    p_est = mean / var if var > mean else 0.5
    p_no_pool.append(p_est)

# Complete Pooling estimate (MLE on all data, ignoring group structure)
def neg_log_likelihood_nb(params, data):
    r, p = params
    if r <= 0 or p <= 0 or p >= 1: return np.inf
    return -np.sum(nbinom.logpmf(data, n=r, p=p))

# Use multiple random restarts to find global optimum
best_ll_pool = np.inf
for _ in range(10):
    r_init = rng.uniform(2, 15)
    p_init = rng.uniform(0.2, 0.8)
    res = minimize(neg_log_likelihood_nb, [r_init, p_init], args=(data,),
                   method='L-BFGS-B', bounds=[(0.1, 50), (0.01, 0.99)])
    if res.fun < best_ll_pool:
        best_ll_pool = res.fun
        r_complete_pool, p_complete_pool = res.x

# Hierarchical estimates (posterior mean)
p_hierarchical = az.summary(idata, var_names=['p'])['mean'].values

# --- 4. Visualize Shrinkage ---
plt.figure()
group_labels = [f'Group {chr(65+i)}\n(n={n})' for i, n in enumerate(n_samples)]
x = np.arange(n_groups)

plt.plot(x, p_true, 'ko', markersize=10, label='True values')
plt.plot(x, p_no_pool, 's', color=QUALITATIVE_COLORS[0], markersize=8, label='No Pooling (MoM)')
plt.axhline(p_complete_pool, color=QUALITATIVE_COLORS[1], linestyle='--', label='Complete Pooling')
plt.plot(x, p_hierarchical, 'D', color=QUALITATIVE_COLORS[3], markersize=8, label='Hierarchical')

plt.xticks(x, group_labels)
plt.ylabel('Burst Frequency Parameter (p)')
plt.title('Hierarchical Models Demonstrate Shrinkage')
plt.legend()
plt.grid(True, alpha=0.3)
plt.ylim(0, 1)

# Add arrows to show shrinkage for Group D
plt.arrow(x=3, y=p_no_pool[3], dx=0, dy=p_hierarchical[3]-p_no_pool[3]+0.04,
          head_width=0.1, head_length=0.03, color='gray', linestyle=':')
plt.text(3.1, (p_no_pool[3] + p_hierarchical[3]) / 2, 'Shrinkage',
         rotation=90, va='center', ha='left', color='gray')

plt.show()
Initializing NUTS using jitter+adapt_diag...
C:\Users\Chris\AppData\Roaming\Python\Python313\site-packages\pytensor\link\c\cmodule.py:2968: UserWarning: PyTensor could not link to a BLAS installation. Operations that might benefit from BLAS will be severely degraded.
This usually happens when PyTensor is installed via pip. We recommend it be installed via conda/mamba/pixi instead.
Alternatively, you can use an experimental backend such as Numba or JAX that perform their own BLAS optimizations, by setting `pytensor.config.mode == 'NUMBA'` or passing `mode='NUMBA'` when compiling a PyTensor function.
For more options and details see https://pytensor.readthedocs.io/en/latest/troubleshooting.html#how-do-i-configure-test-my-blas-library
  warnings.warn(
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [alpha, beta, r, p]
Sampling 4 chains for 200 tune and 700 draw iterations (800 + 2_800 draws total) took 22 seconds.
(a) Hierarchical models borrow statistical strength to improve parameter estimates. We estimated the burst frequency parameter p for four groups, where Group D has very sparse data. The ‘No Pooling’ estimate for Group D is highly inaccurate. The ‘Complete Pooling’ estimate ignores group differences entirely. The hierarchical model provides the best of both worlds: its estimates for data-rich groups (A, B, C) are similar to the no-pooling estimates, but for the data-poor Group D, its estimate is ‘shrunk’ towards the population mean, resulting in a much more accurate and stable inference.

(b)
(c)
Figure 3.32

For data-rich groups (A, B, C), hierarchical estimates match the no-pooling approach. But for sparse Group D, the no-pooling estimate is wildly off while the hierarchical model shrinks it toward the population mean, dramatically improving accuracy.

3.7.3 Mixture Models for Hidden Subpopulations

Hierarchical models handle known groups (e.g., labeled cell types) by sharing information across them. But what if the groups are unknown—say, healthy and pre-cancerous cells mixed in our sample without labels? Mixture models solve a different problem: simultaneously discover the subpopulations and estimate their parameters.

A Negative Binomial mixture with K components assigns each observation to one of K distributions:

L(\theta | y_i) = \sum_{k=1}^{K} \pi_k \cdot \text{NB}(y_i | r_k, p_k)

where \pi_k is the mixing weight (proportion in component k) and (r_k, p_k) are component-specific parameters with \sum_k \pi_k = 1. We fit this via Expectation-Maximization (EM):

  1. E-Step: Calculate responsibilities \gamma_{ik} = P(\text{component } k | y_i, \theta^{(t)})—the posterior probability that observation i came from component k. Bayes’ rule gives us a closed-form update,

P(z_i = k \mid y_i, \theta^{(t)}) = \frac{P(z_i = k) \, P(y_i \mid z_i = k, \theta^{(t)})}{\sum_{k' = 1}^{K} P(z_i = k') \, P(y_i \mid z_i = k', \theta^{(t)})}.

Let’s identify the pieces so we can evaluate it cell by cell: P(z_i = k) = \pi_k^{(t)} is the mixture weight, and P(y_i \mid z_i = k, \theta^{(t)}) = \text{NB}(y_i \mid r_k^{(t)}, p_k^{(t)}) is the Negative Binomial probability mass function for that component. Plugging those in,

\gamma_{ik} = \frac{\pi_k^{(t)} \, \text{NB}\big(y_i \mid r_k^{(t)}, p_k^{(t)}\big)}{\sum_{k' = 1}^{K} \pi_{k'}^{(t)} \, \text{NB}\big(y_i \mid r_{k'}^{(t)}, p_{k'}^{(t)}\big)},

so the E-step is fully analytic—no extra optimization needed. 2. M-Step: Update parameters to maximize the expected complete-data log-likelihood:

Q(\theta | \theta^{(t)}) = \sum_{i=1}^{N} \sum_{k=1}^{K} \gamma_{ik} \left[ \log \pi_k + \log \text{NB}(y_i | r_k, p_k) \right]

The mixing weights update as \pi_k^{(t+1)} = \frac{1}{N}\sum_i \gamma_{ik}. The NB parameters (r_k, p_k) require numerical optimization of the weighted likelihood \sum_{i} \gamma_{ik} \log \text{NB}(y_i | r_k, p_k) for each component k.

Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import nbinom
from scipy.optimize import minimize

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# --- 1. Generate Mixed NB Data ---
rng = np.random.default_rng(101)
# Component 1: Low expression
r1, p1, pi1 = 4.0, 0.5, 0.6
# Component 2: High expression
r2, p2, pi2 = 15.0, 0.4, 0.4
n_cells = 2000

n1 = int(n_cells * pi1)
n2 = n_cells - n1
data1 = nbinom.rvs(n=r1, p=p1, size=n1, random_state=rng)
data2 = nbinom.rvs(n=r2, p=p2, size=n2, random_state=rng)
mixed_data = np.concatenate([data1, data2])

# --- 2. Implement EM Algorithm ---
def m_step_weighted_nb(data, weights):
    """Defines and minimizes the weighted negative log-likelihood for one NB component."""
    def weighted_neg_ll(params, data, weights):
        r, p = params
        if r <= 0 or p <= 0 or p >= 1: return np.inf
        # Ensure weights sum to a reasonable number before taking log
        if np.sum(weights) < 1e-6: return 0
        return -np.sum(weights * nbinom.logpmf(data, n=r, p=p))

    # Use method of moments on weighted data for a good initial guess
    w_mean = np.sum(weights * data) / np.sum(weights)
    w_var = np.sum(weights * (data - w_mean)**2) / np.sum(weights)
    if w_var <= w_mean or w_mean == 0:
        return 5.0, 0.5 # Fallback guess if moments are invalid

    p_guess = w_mean / w_var
    r_guess = (w_mean**2) / (w_var - w_mean)

    res = minimize(weighted_neg_ll, [r_guess, p_guess], args=(data, weights),
                   method='L-BFGS-B', bounds=[(0.1, 50), (0.01, 0.99)])
    return res.x

def compute_mixture_log_likelihood(data, pi_k, r_k, p_k):
    """Compute log-likelihood of the mixture model."""
    densities = np.array([nbinom.pmf(data, n=r, p=p) for r, p in zip(r_k, p_k)])
    weighted_densities = pi_k[:, np.newaxis] * densities
    mixture_probs = np.sum(weighted_densities, axis=0)
    return np.sum(np.log(mixture_probs + 1e-300))  # Avoid log(0)

def run_em(data, n_components=2, max_iter=50, init_params=None):
    """Run EM algorithm with given initialization."""
    if init_params is None:
        # Random initialization
        pi_k = np.ones(n_components) / n_components
        r_k = rng.uniform(2, 20, size=n_components)
        p_k = rng.uniform(0.2, 0.7, size=n_components)
    else:
        pi_k, r_k, p_k = init_params

    for i in range(max_iter):
        # E-Step: Calculate responsibilities
        densities = np.array([nbinom.pmf(data, n=r, p=p) for r, p in zip(r_k, p_k)])
        weighted_densities = pi_k[:, np.newaxis] * densities
        responsibilities = weighted_densities / (np.sum(weighted_densities, axis=0) + 1e-9)

        # M-Step: Update parameters
        pi_k = np.mean(responsibilities, axis=1)
        for k in range(n_components):
            r_k[k], p_k[k] = m_step_weighted_nb(data, responsibilities[k])

    ll = compute_mixture_log_likelihood(data, pi_k, r_k, p_k)
    return pi_k, r_k, p_k, ll

# Run EM with multiple random restarts to avoid local optima
# This is standard practice for mixture models
n_restarts = 15
best_ll = -np.inf
best_params = None

for restart in range(n_restarts):
    pi_k, r_k, p_k, ll = run_em(mixed_data, n_components=2, max_iter=50)
    if ll > best_ll:
        best_ll = ll
        best_params = (pi_k, r_k, p_k)

pi_k, r_k, p_k = best_params
print(f"Best log-likelihood after {n_restarts} restarts: {best_ll:.2f}")
print("EM Fit Results (k=1):", f"pi={pi_k[0]:.2f}, r={r_k[0]:.2f}, p={p_k[0]:.2f}")
print("EM Fit Results (k=2):", f"pi={pi_k[1]:.2f}, r={r_k[1]:.2f}, p={p_k[1]:.2f}")


# --- 3. Visualize Fit ---
# *** FIX: Define the missing negative log-likelihood function for a single NB fit ***
def neg_log_likelihood_nb(params, data):
    """Negative log-likelihood for a single NB distribution."""
    r, p = params
    if r <= 0 or p <= 0 or p >= 1:
        return np.inf
    return -np.sum(nbinom.logpmf(data, n=r, p=p))

# For comparison, fit a single NB model
mean_guess = np.mean(mixed_data)
var_guess = np.var(mixed_data)
p_guess_single = mean_guess / var_guess if var_guess > mean_guess else 0.5
r_guess_single = (mean_guess**2) / (var_guess - mean_guess) if var_guess > mean_guess else 10.0

res_single_nb = minimize(neg_log_likelihood_nb, [r_guess_single, p_guess_single], args=(mixed_data,),
                         method='L-BFGS-B', bounds=[(0.1, 50), (0.01, 0.99)])
r_single, p_single = res_single_nb.x

# Generate points for plotting
x_range = np.arange(0, mixed_data.max() + 1)
pmf_single = nbinom.pmf(x_range, n=r_single, p=p_single)
pmf1_fit = pi_k[0] * nbinom.pmf(x_range, n=r_k[0], p=p_k[0])
pmf2_fit = pi_k[1] * nbinom.pmf(x_range, n=r_k[1], p=p_k[1])
pmf_mix = pmf1_fit + pmf2_fit

# Plotting
plt.figure()
plt.hist(mixed_data, bins=np.arange(-0.5, mixed_data.max() + 1.5), density=True, alpha=0.6, color='gray', edgecolor='none', label='Observed Mixed Data',zorder=-10)
plt.plot(x_range, pmf_single, 'o-', color=QUALITATIVE_COLORS[0], label='Single NB Fit', markersize=4)
plt.plot(x_range, pmf_mix, 's-', color=QUALITATIVE_COLORS[1], label='Mixture Model Fit', markersize=4)
plt.plot(x_range, pmf1_fit, '--', color=QUALITATIVE_COLORS[2], label='Inferred Component 1',linewidth=2)
plt.plot(x_range, pmf2_fit, '--', color=QUALITATIVE_COLORS[3], label='Inferred Component 2',linewidth=2)
plt.xlabel("Count (e.g., mRNA molecules per cell)")
plt.ylabel("Probability Density")
plt.title("Deconvolving Subpopulations with a Mixture Model")
plt.legend()
plt.grid(True, alpha=0.3)
plt.xlim(-1, 60)
plt.show()
Best log-likelihood after 15 restarts: -6723.24
EM Fit Results (k=1): pi=0.39, r=17.45, p=0.43
EM Fit Results (k=2): pi=0.61, r=4.16, p=0.50
Figure 3.33: Uncovering hidden subpopulations with a Negative Binomial mixture model. The observed data (gray histogram) was generated from two distinct NB distributions. A single NB fit (red) completely fails to describe this bimodal data. The two-component mixture model, fit via the EM algorithm with multiple random restarts, successfully identifies the two underlying subpopulations (dashed purple and yellow lines) and their relative proportions. The combined mixture model (solid blue line) provides an excellent fit to the overall observed distribution.

A single NB fails on bimodal data, but EM successfully deconvolves the mixture, recovering both component parameters and mixing proportions. Since EM can converge to local optima depending on initialization, we use multiple random restarts and select the solution with the highest log-likelihood—a standard practice for fitting mixture models.

3.7.4 Temporal Observations with Hidden Markov Models (HMMs)

In Chapter 2, we simulated the Telegraph model forward: given switching rates k_{\text{on}} and k_{\text{off}}, we generated promoter dynamics. Now we face the inverse problem: given a time-series of mRNA counts from live-cell imaging, can we infer when the promoter was ON versus OFF? Hidden Markov Models (HMMs) provide the framework for this inference.

3.7.4.1 The HMM Structure

An HMM posits two coupled stochastic processes. Hidden states Z_t \in \{0, 1\} (promoter OFF/ON) evolve as a discrete-time Markov chain:

P(Z_t = j \mid Z_{t-1} = i) = A_{ij}

where the transition matrix A encodes switching probabilities. For a two-state promoter with discrete time steps \Delta t:

A = \begin{pmatrix} P(\text{OFF} \to \text{OFF}) & P(\text{OFF} \to \text{ON}) \\ P(\text{ON} \to \text{OFF}) & P(\text{ON} \to \text{ON}) \end{pmatrix} = \begin{pmatrix} 1 - k_{\text{on}} \Delta t & k_{\text{on}} \Delta t \\ k_{\text{off}} \Delta t & 1 - k_{\text{off}} \Delta t \end{pmatrix}

At each time point, the current hidden state generates an observable emission X_t (mRNA count) from a state-dependent distribution:

P(X_t \mid Z_t = i) = B_i(X_t)

For gene expression, we use Poisson emissions: B_0 = \text{Poisson}(\lambda_{\text{OFF}}) for the inactive state and B_1 = \text{Poisson}(\lambda_{\text{ON}}) for the active state, where \lambda_{\text{ON}} \gg \lambda_{\text{OFF}}.

The joint probability of a state sequence Z_{1:T} and observations X_{1:T} factorizes due to the Markov property:

P(Z_{1:T}, X_{1:T}) = \pi_0(Z_1) \prod_{t=2}^{T} A_{Z_{t-1}, Z_t} \prod_{t=1}^{T} B_{Z_t}(X_t)

where \pi_0 is the initial state distribution. This factorization is the key to efficient inference.

3.7.4.2 The Inference Problems

Given observations X_{1:T}, we face two problems:

  1. Parameter learning: Estimate A, B, and \pi_0 from data
  2. State decoding: Infer the most likely hidden state sequence Z_{1:T}

3.7.4.3 Forward-Backward Algorithm

The forward-backward algorithm solves a key subproblem: computing P(Z_t = i \mid X_{1:T}), the probability of being in state i at time t given all observations. Define the forward variable:

\alpha_t(i) = P(X_{1:t}, Z_t = i)

This satisfies the recursion:

\alpha_t(j) = B_j(X_t) \sum_{i=0}^{1} \alpha_{t-1}(i) A_{ij}

with initial condition \alpha_1(i) = \pi_0(i) B_i(X_1). The forward pass accumulates evidence from the past.

Symmetrically, define the backward variable:

\beta_t(i) = P(X_{t+1:T} \mid Z_t = i)

with recursion:

\beta_t(i) = \sum_{j=0}^{1} A_{ij} B_j(X_{t+1}) \beta_{t+1}(j)

initialized as \beta_T(i) = 1. The backward pass accumulates evidence from the future. Combining these:

P(Z_t = i \mid X_{1:T}) \propto \alpha_t(i) \beta_t(i)

This marginal probability at each time point is central to parameter estimation—forward-backward provides the expectations needed for the E-step of the Baum-Welch algorithm.

3.7.4.4 Baum-Welch: Parameter Learning via EM

The Baum-Welch algorithm for learning HMM parameters is an instance of the general Expectation-Maximization (EM) framework. EM applies when we have:

  • Observations: x (measured data)
  • Latent variables: z (unobserved states)
  • Parameters: \theta (model parameters)

The EM algorithm iterates two steps:

E-step: Compute the expected log-likelihood of the complete data (x, z) under the current parameters \theta^{\text{old}}:

Q(\theta \mid \theta^{\text{old}}) = \mathbb{E}_{z \mid x, \theta^{\text{old}}} \left[ \log P(x, z \mid \theta) \right]

M-step: Maximize this expectation to find new parameters:

\theta^{\text{new}} = \arg\max_{\theta} Q(\theta \mid \theta^{\text{old}})

For HMMs, the E-step uses forward-backward to compute expectations over hidden state sequences, and the M-step has closed-form updates for A, B, and \pi_0. We saw EM earlier for mixture models—HMMs extend this to temporal sequences where latent states form a Markov chain.

3.7.4.5 Viterbi: State Decoding via Dynamic Programming

Baum-Welch solves the first problem (parameter learning). Now we turn to the second: given learned parameters (A, B, \pi_0), infer the hidden state trajectory. The Viterbi algorithm finds the single most probable state sequence:

Z_{1:T}^* = \arg\max_{Z_{1:T}} P(Z_{1:T} \mid X_{1:T})

This differs from forward-backward, which computes marginal probabilities P(Z_t = i \mid X_{1:T}) at each time independently. Viterbi seeks the globally optimal path. Define:

\delta_t(i) = \max_{Z_{1:t-1}} P(Z_{1:t-1}, Z_t = i, X_{1:t})

This satisfies the recursion:

\delta_t(j) = B_j(X_t) \max_{i} \left[ \delta_{t-1}(i) A_{ij} \right]

The algorithm tracks not just the maximum probability but also the state that achieved it, allowing us to backtrack and recover the optimal path Z_{1:T}^* after a forward pass.

3.7.4.6 Testing HMM Inference

Let’s test the two-stage workflow. We’ll simulate a two-state system with known parameters, then: (1) use Baum-Welch to estimate (A, B, \pi_0) from observations alone, and (2) use Viterbi with the learned parameters to decode the hidden state trajectory:

Code
import numpy as np
import matplotlib.pyplot as plt
from hmmlearn import hmm

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

# --- 1. Define and Simulate a 2-State Poisson HMM ---
rng = np.random.default_rng(42)
# Define a model with known parameters
true_model = hmm.PoissonHMM(n_components=2, random_state=42)
true_model.startprob_ = np.array([0.5, 0.5]) # P(start in OFF), P(start in ON)
true_model.transmat_ = np.array([[0.95, 0.05], # P(OFF->OFF), P(OFF->ON)
                                 [0.1, 0.9]])   # P(ON->OFF),  P(ON->ON)
# FIX: Reshaped lambdas_ to be a (2, 1) column vector
true_model.lambdas_ = np.array([[2.0], [15.0]]) # Emission rates for OFF and ON states

# Generate a sequence of observations (X) and hidden states (Z)
X, Z = true_model.sample(n_samples=100)

# --- 2. Fit a New HMM and Decode the States ---
# We create a new model and pretend we don't know the parameters
fit_model  = hmm.PoissonHMM(n_components=2, n_iter=100, tol=1e-4, random_state=42)
# The .fit() method runs the Baum-Welch algorithm
fit_model.fit(X)
# The .predict() method runs the Viterbi algorithm
inferred_states = fit_model.predict(X)

# For plotting, ensure states are ordered by emission rate (low to high)
if fit_model.lambdas_[0] > fit_model.lambdas_[1]:
    inferred_states = 1 - inferred_states
    
print("True emission rates:", true_model.lambdas_.flatten())
print("Inferred emission rates:", np.sort(fit_model.lambdas_.flatten()))
print("\nTrue transition matrix:\n", true_model.transmat_)
# Reorder the inferred transition matrix to match the OFF/ON state order
sorter = np.argsort(fit_model.lambdas_.flatten())
print("Inferred transition matrix:\n", fit_model.transmat_[sorter][:, sorter])


# --- 3. Visualize the Results ---
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

ax1.bar(np.arange(len(X)), X.flatten(), color=QUALITATIVE_COLORS[1])
ax1.set_ylabel("Observed mRNA Count")
ax1.set_title("Decoding Hidden States from Time-Series Data")
ax1.grid(True, alpha=0.3)

ax2.plot(Z, 'k-', linewidth=2, label='True Hidden State', drawstyle='steps-post')
ax2.plot(inferred_states, '--', color=QUALITATIVE_COLORS[0], linewidth=1, label='Inferred Hidden State', drawstyle='steps-post')
ax2.set_xlabel("Time Step")
ax2.set_ylabel("Promoter State")
ax2.set_yticks([0, 1])
ax2.set_yticklabels(['OFF', 'ON'])
ax2.legend()

plt.tight_layout()
plt.show()
True emission rates: [ 2. 15.]
Inferred emission rates: [ 1.82719312 14.68120018]

True transition matrix:
 [[0.95 0.05]
 [0.1  0.9 ]]
Inferred transition matrix:
 [[0.94095642 0.05904358]
 [0.12960656 0.87039344]]
Figure 3.34: Inferring hidden promoter dynamics with a Hidden Markov Model. The top panel shows a time-series of observed mRNA counts (blue bars), simulated from a system switching between two hidden states. The bottom panel displays the true hidden state trajectory (‘ON’/‘OFF’) in black. The red line shows the state sequence inferred by the HMM using only the noisy mRNA counts. The HMM successfully decodes the hidden dynamics, correctly identifying most of the periods when the gene was active versus inactive.

Despite significant measurement noise, the Viterbi algorithm successfully recovers the hidden promoter state trajectory for most time points. HMMs thus provide a principled framework for inferring latent biological dynamics from time-series observations.

3.7.5 A Glimpse into Variational Inference (VI)

Throughout this chapter, Bayesian inference has meant MCMC—sampling from the posterior P(\theta | D) via Metropolis-Hastings or NUTS. MCMC is asymptotically exact but computationally expensive. Variational Inference (VI) offers a fundamentally different approach: reframe posterior inference as an optimization problem, trading exactness for speed.

3.7.5.1 The Core Problem: Intractable Normalization

Bayes’ theorem gives us P(\theta | D) = \frac{P(D|\theta)P(\theta)}{P(D)}, but computing the evidence P(D) = \int P(D|\theta)P(\theta) d\theta requires integrating over all possible parameter values—intractable for most models. MCMC sidesteps this by sampling, but VI takes a different path: approximate the posterior with a simpler distribution q(\theta) from a tractable family.

3.7.5.2 Deriving the ELBO

How do we find the best approximation? We want to minimize the KL divergence from q(\theta) to the true posterior:

\text{KL}(q(\theta) || P(\theta|D)) = \mathbb{E}_q\left[\log \frac{q(\theta)}{P(\theta|D)}\right]

Expanding the log ratio:

\text{KL}(q || P) = \mathbb{E}_q[\log q(\theta)] - \mathbb{E}_q[\log P(\theta|D)]

Using Bayes’ theorem for the second term:

= \mathbb{E}_q[\log q(\theta)] - \mathbb{E}_q[\log P(D, \theta)] + \log P(D)

Rearranging:

\log P(D) = \underbrace{\mathbb{E}_q[\log P(D, \theta)] - \mathbb{E}_q[\log q(\theta)]}_{\text{ELBO}(q)} + \text{KL}(q || P(\theta|D))

The Evidence Lower Bound (ELBO) is the first term. Since \text{KL} \geq 0 always, the ELBO is indeed a lower bound on \log P(D). Crucially, the ELBO depends only on the joint distribution P(D, \theta) = P(D|\theta)P(\theta), which we can compute—no intractable integral required. Maximizing the ELBO is equivalent to minimizing the KL divergence to the true posterior.

3.7.5.3 The Mean-Field Variational Family

VI requires choosing a family of distributions q(\theta) to search over. The mean-field assumption factors the approximation across parameters:

q(\theta) = \prod_{i=1}^{K} q_i(\theta_i)

For our Negative Binomial model with \theta = (r, p), this means q(r, p) = q(r) \cdot q(p)—we assume r and p are independent in the approximate posterior. This is the source of the axis-aligned ellipse we’ll see shortly.

Automatic Differentiation Variational Inference (ADVI) uses Gaussian approximations in transformed (unconstrained) space:

  • Since r > 0, transform to \tilde{r} = \log(r) and fit q(\tilde{r}) = \mathcal{N}(\mu_r, \sigma_r^2)
  • Since p \in (0,1), transform to \tilde{p} = \text{logit}(p) and fit q(\tilde{p}) = \mathcal{N}(\mu_p, \sigma_p^2)

The variational parameters \phi = (\mu_r, \sigma_r, \mu_p, \sigma_p) are what we optimize.

3.7.5.4 The Optimization Algorithm

VI optimizes the ELBO with respect to variational parameters \phi:

\phi^* = \arg\max_{\phi} \text{ELBO}(\phi) = \arg\max_{\phi} \left[ \mathbb{E}_{q_\phi}[\log P(D, \theta)] - \mathbb{E}_{q_\phi}[\log q_\phi(\theta)] \right]

ADVI uses stochastic gradient ascent:

  1. Monte Carlo estimate: Sample \theta^{(1)}, \ldots, \theta^{(S)} \sim q_\phi and approximate \text{ELBO}(\phi) \approx \frac{1}{S}\sum_{s=1}^{S} \left[\log P(D, \theta^{(s)}) - \log q_\phi(\theta^{(s)})\right]
  2. Automatic differentiation: Compute \nabla_\phi \text{ELBO} using autodiff (PyMC does this automatically)
  3. Adaptive optimization: Update \phi \leftarrow \phi + \alpha \nabla_\phi \text{ELBO} using Adam optimizer
  4. Iterate: Repeat until ELBO converges

When we call pm.fit(method='advi'), PyMC runs this entire workflow under the hood.

3.7.5.5 The VI Trade-offs

Forward KL minimization \text{KL}(q || P) has important consequences:

  1. Mode-seeking: VI concentrates q on the posterior mode, underestimating uncertainty
  2. Potential bias: The mean of q(\theta) can differ from the posterior mean—VI sacrifices unbiasedness for speed
  3. Correlation blindness: Mean-field factorization q(r)q(p) cannot capture the negative correlation between r and p

These are not bugs—they’re the deliberate trade-off for transforming an expensive sampling problem into a fast optimization problem.

3.7.5.6 Visualizing the Mean-Field Approximation

Let’s compare VI to the MLE Hessian for our Negative Binomial model. We’ll use ADVI to fit independent Gaussians for \log(r) and \text{logit}(p), then visualize how the mean-field assumption forces an axis-aligned approximation despite the true parameter correlation:

Code
import numpy as np
import matplotlib.pyplot as plt
import pymc as pm
from scipy.optimize import minimize
from scipy.stats import nbinom, chi2

# --- 1. Use the same data and model from ch3a ---
rng = np.random.default_rng(456)
r_true, p_true = 5.0, 0.25
n_samples = 500
nb_data = nbinom.rvs(n=r_true, p=p_true, size=n_samples, random_state=rng).astype("int64")

# --- 2. Find MLE and Fisher Information Covariance (from ch3a) ---
def neg_log_likelihood_nb(params, data):
    r, p = params
    if r <= 0 or p <= 0 or p >= 1: return np.inf
    return -np.sum(nbinom.logpmf(data, n=r, p=p))

result_mle = minimize(neg_log_likelihood_nb, [3.0, 0.5], args=(nb_data,),
                      bounds=[(0.1, 20), (0.01, 0.99)], method='L-BFGS-B')
r_mle, p_mle = result_mle.x

# --- Numerical Hessian (as in ch3a)
def hessian_2d(func, x, h=1e-5):
    x_hh = func(x + np.array([h,h])); x_h_ = func(x + np.array([h,-h]))
    x__h = func(x + np.array([-h,h])); x___ = func(x + np.array([-h,-h]))
    f_xy = (x_hh - x_h_ - x__h + x___) / (4 * h**2)
    f_xx = (func(x + np.array([h,0])) - 2*func(x) + func(x - np.array([h,0]))) / h**2
    f_yy = (func(x + np.array([0,h])) - 2*func(x) + func(x - np.array([0,h]))) / h**2
    return np.array([[f_xx, f_xy], [f_xy, f_yy]])

hessian = hessian_2d(lambda p: neg_log_likelihood_nb(p, nb_data), [r_mle, p_mle])
cov_mle = np.linalg.inv(hessian)




# --- 3. Run Variational Inference ---
# BUG FIX TO USE A DIFFERENT PARAMETERIZATION HERE
with pm.Model() as neg_binom_model:
    r = pm.Exponential('r', 1.0)
    p = pm.Beta('p', 1.0, 1.0)
    # === PRAGMATIC FIX IS HERE ===
    # Re-parameterize using mu (mean) and alpha (dispersion)
    # This avoids the recursion error because mu and alpha are continuous.
    mu = pm.Deterministic('mu', r * (1 - p) / p)
    alpha = pm.Deterministic('alpha', r)
    counts = pm.NegativeBinomial('counts', mu=mu, alpha=alpha, observed=nb_data)
    # ============================
    approx = pm.fit(n=50000, method='advi', random_seed=42, progressbar=False)

# Now, calculate stats from the trace 
trace = approx.sample(10000)
vi_means = np.array([trace.posterior['r'].mean().item(), trace.posterior['p'].mean().item() ]) 
vi_stds = np.array([ trace.posterior['r'].std().item(), trace.posterior['p'].std().item() ])
# Covariance for mean-field VI is diagonal
cov_vi = np.diag(vi_stds**2)

# --- 4. Visualize and Compare the Ellipses ---
# Helper to draw ellipse
def confidence_ellipse(mean, cov, ax, color, linestyle, label):
    chi2_val = chi2.ppf(0.95, df=2)
    eigenvals, eigenvecs = np.linalg.eig(cov)
    angle = np.degrees(np.arctan2(*eigenvecs[:,0][::-1]))
    width, height = 2 * np.sqrt(chi2_val * eigenvals)
    ellipse = plt.matplotlib.patches.Ellipse(xy=mean, width=width, height=height,
                                             angle=angle, edgecolor=color,
                                             linestyle=linestyle, facecolor='none',
                                             linewidth=3, label=label)
    ax.add_patch(ellipse)

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, ax = plt.subplots()

# Plot log-likelihood contour from ch3a
r_range = np.linspace(r_mle-3, r_mle+3, 50)
p_range = np.linspace(p_mle-0.2, p_mle+0.2, 50)
R, P = np.meshgrid(r_range, p_range)
log_likelihoods = np.array([[-neg_log_likelihood_nb([r,p], nb_data) for r in r_range] for p in p_range])
ax.contourf(R, P, log_likelihoods, levels=15, cmap='plasma', alpha=0.5)

# Plot ellipses
confidence_ellipse([r_mle, p_mle], cov_mle, ax, QUALITATIVE_COLORS[0], '-', 'MLE Uncertainty')
confidence_ellipse(vi_means, cov_vi, ax, QUALITATIVE_COLORS[1], '--', 'VI Approximation')

ax.plot(r_true, p_true, 'ko', markersize=8, label='True Value')
ax.set_xlabel('r (burst size parameter)')
ax.set_ylabel('p (burst frequency parameter)')
ax.set_title('The Mean-Field Assumption Tradeoff')
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_xlim(r_mle-3, r_mle+3); ax.set_ylim(p_mle-0.2, p_mle+0.2)
plt.show()
Finished [100%]: Average Loss = 1,708.8
Figure 3.35: Visualizing the VI tradeoff. The plot compares the 95% confidence ellipses for the Negative Binomial parameters derived from the MLE’s Hessian (blue, tilted) and a mean-field Variational Inference approximation (orange, axis-aligned), overlaid on the true log-likelihood surface. The Hessian correctly captures the negative correlation between r and p, shown by the tilt. VI, due to its mean-field assumption, is forced to ignore this correlation, resulting in a factorized, axis-aligned approximation that misrepresents the shape of the true posterior uncertainty.

The MLE Hessian (blue, tilted) correctly captures the negative correlation between r and p. VI’s approximation (orange, axis-aligned) cannot—the mean-field factorization q(r)q(p) forces a diagonal covariance matrix. Notice also that the VI mean is shifted from the true value, demonstrating the potential bias from mode-seeking behavior. Despite these approximations, VI runs in seconds where MCMC takes minutes, making it practical for models with hundreds of parameters where exact inference is computationally infeasible.

3.7.6 Inferring Gene Regulatory Networks (GRNs) from Data

So far, we’ve modeled single genes in isolation. But cells don’t operate this way—genes form regulatory networks where expression of one gene controls another. Can we infer these connections from single-cell snapshots alone?

This problem marks a conceptual shift. Throughout this chapter, we’ve asked “given a model, estimate its parameters”—a tractable problem even for complex models. But inferring a 3-gene network from snapshots requires estimating ~15 parameters (production rates, degradation rates, Hill coefficients, regulatory strengths) from noisy, correlated expression data. This is effectively impossible without strong prior constraints or time-series perturbations. Instead, we shift our goal from precise parameter estimation to structure discovery: can we identify which genes regulate which from statistical dependencies alone? This data-driven, information-theoretic approach foreshadows Chapter 4’s methods for analyzing high-dimensional transcriptomic data.

3.7.6.1 A Three-Gene Test Case

Consider a system where gene A (constitutive) activates gene B through cooperative binding, while gene C remains independent. The dynamics follow coupled SDEs (Chemical Langevin equations):

\begin{align} dx_A &= \left(\beta_A - \gamma_A x_A\right)dt + \sqrt{\beta_A + \gamma_A x_A} \, dW_A \\ dx_B &= \left(\alpha_B \frac{x_A^n}{K^n + x_A^n} - \gamma_B x_B\right)dt + \sqrt{\alpha_B \frac{x_A^n}{K^n + x_A^n} + \gamma_B x_B} \, dW_B \\ dx_C &= \left(\beta_C - \gamma_C x_C\right)dt + \sqrt{\beta_C + \gamma_C x_C} \, dW_C \end{align}

where dW_i are independent Wiener processes and the noise terms follow the CLE scaling from Chapter 2. The true network structure is:

Code
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import FancyArrowPatch

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, ax = plt.subplots()

# Gene positions
gene_positions = {
    'A': (0.2, 0.5),
    'B': (0.8, 0.5),
    'C': (0.5, 0.1)
}

# Draw gene nodes
for gene, (x, y) in gene_positions.items():
    if gene == 'C':
        color = 'gray'
        label = f'Gene {gene}\n(independent)'
    elif gene == 'A':
        color = QUALITATIVE_COLORS[1]
        label = f'Gene {gene}\n(constitutive)'
    else:
        color = QUALITATIVE_COLORS[2]
        label = f'Gene {gene}\n(regulated)'

    circle = plt.Circle((x, y), 0.08, color=color, ec='black', linewidth=2, zorder=3)
    ax.add_patch(circle)
    ax.text(x, y, gene, ha='center', va='center', fontsize=16, fontweight='bold', color='white', zorder=4)
    ax.text(x, y - 0.15, label, ha='center', va='top', fontsize=9)

# Draw activation arrow from A to B
arrow = FancyArrowPatch(
    (gene_positions['A'][0] + 0.08, gene_positions['A'][1]),
    (gene_positions['B'][0] - 0.08, gene_positions['B'][1]),
    arrowstyle='-|>',
    mutation_scale=30,
    linewidth=3,
    color=QUALITATIVE_COLORS[0],
    zorder=2
)
ax.add_patch(arrow)

# Label the arrow with regulation type
mid_x = (gene_positions['A'][0] + gene_positions['B'][0]) / 2
mid_y = gene_positions['A'][1] + 0.12
ax.text(mid_x, mid_y, 'Activates\n(Hill, n=4)', ha='center', va='bottom',
        fontsize=10, color=QUALITATIVE_COLORS[0], fontweight='bold',
        bbox=dict(boxstyle='round,pad=0.3', facecolor='white', edgecolor=QUALITATIVE_COLORS[0], linewidth=1.5))

ax.set_xlim(0, 1)
ax.set_ylim(0, 0.8)
ax.set_aspect('equal')
ax.axis('off')
ax.set_title('True Regulatory Network Structure', fontsize=14, fontweight='bold', pad=20)

plt.tight_layout()
plt.show()
Figure 3.36: Gene regulatory network structure for our three-gene system. Gene A (constitutive) activates Gene B through cooperative binding (Hill coefficient n=4, shown as activating arrow). Gene C is independent. Arrow thickness represents regulatory strength (α_B = 20), and colors distinguish regulatory interactions from constitutive expression.

Given only steady-state snapshots (x_A, x_B, x_C) from many cells, can we recover which genes regulate which?

3.7.6.2 Mutual Information as a Network Detector

Mutual information quantifies statistical dependence between random variables. For discrete random variables X and Y:

I(X; Y) = \sum_{x,y} p(x, y) \log_2 \frac{p(x, y)}{p(x)p(y)}

When X and Y are independent, p(x,y) = p(x)p(y), so the ratio equals 1 and I(X;Y) = 0. For dependent variables, the joint distribution p(x,y) differs from the product of marginals, creating nonzero MI. We can rewrite this using entropy:

I(X; Y) = H(X) + H(Y) - H(X, Y)

where H(X) = -\sum_x p(x) \log_2 p(x) is Shannon entropy. This form shows MI measures how much knowing Y reduces uncertainty about X.

For our network inference problem, high I(x_A; x_B) suggests a regulatory link. But MI has two fundamental limitations:

  1. Symmetry: I(X; Y) = I(Y; X) by definition, so MI cannot determine directionality. Does A regulate B, or B regulate A?
  2. Indirect effects: If A \to B \to C forms a cascade, we measure I(A; C) > 0 even though there’s no direct A \to C edge. The Data Processing Inequality formalizes this: for any Markov chain A \to B \to C, we have I(A; C) \leq \min(I(A; B), I(B; C)). This inequality forms the basis for pruning indirect edges in algorithms like ARACNE.

We’ll simulate the SDE system using Euler-Maruyama integration, collect steady-state snapshots, then compute pairwise MI to test whether statistical dependencies reveal regulatory connections:

Code
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mutual_info_score

# --- 1. Simulate a 3-Gene Network using SDEs ---
rng = np.random.default_rng(2025)
n_snapshots = 2000
t_max = 500
dt = 0.1
n_steps = int(t_max / dt)

# Model parameters
beta_A, beta_C = 10, 8
gamma_A, gamma_B, gamma_C = 1.0, 1.0, 1.0
alpha_B = 20  # Max production rate for B
K = 10        # Hill constant for A->B activation
n = 4         # Hill coefficient
noise_strength = 2.0

# Initialize protein concentrations
X = np.zeros((n_steps + 1, 3))
X[0, :] = [beta_A/gamma_A, 0, beta_C/gamma_C] # Start at steady state for A and C

# Euler-Maruyama Integration
for i in range(n_steps):
    # Use the state from the previous step directly
    x_A, x_B, x_C = X[i, :]

    # Deterministic drift terms
    drift_A = beta_A - gamma_A * x_A
    hill_activation = alpha_B * (x_A**n) / (K**n + x_A**n)
    drift_B = hill_activation - gamma_B * x_B
    drift_C = beta_C - gamma_C * x_C
    drift = np.array([drift_A, drift_B, drift_C])

    # Stochastic diffusion terms (additive noise for simplicity)
    diffusion = noise_strength * np.sqrt(dt) * rng.normal(size=3)

    # BUG FIX: Apply non-negativity constraint *after* the update step
    X[i+1, :] = np.maximum(0, X[i, :] + drift * dt + diffusion)

# Use final N points as "single-cell" snapshots
# Discretize counts for mutual information calculation
# The negative check is now redundant but harmless to keep
data = np.floor(X[-n_snapshots:, :]).astype(int)

# --- 2. Calculate Pairwise Mutual Information ---
n_genes = data.shape[1]
mi_matrix = np.zeros((n_genes, n_genes))

for i in range(n_genes):
    for j in range(i, n_genes):
        mi = mutual_info_score(data[:, i], data[:, j])
        mi_matrix[i, j] = mi
        mi_matrix[j, i] = mi

# --- 3. Visualize the MI Matrix ---
fig, ax = plt.subplots()
im = ax.imshow(mi_matrix, cmap='plasma')

gene_names = ['Gene A', 'Gene B', 'Gene C']
ax.set_xticks(np.arange(n_genes), labels=gene_names)
ax.set_yticks(np.arange(n_genes), labels=gene_names)
plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")

# Loop over data dimensions and create text annotations.
for i in range(n_genes):
    for j in range(n_genes):
        text = ax.text(j, i, f"{mi_matrix[i, j]:.2f}",
                       ha="center", va="center", color="w")

fig.colorbar(im, ax=ax, label="Mutual Information")
ax.set_title("Inferred Network from MI")
plt.tight_layout()
plt.show()
Figure 3.37: Inferring regulatory connections from stochastic dynamics using Mutual Information (MI). We simulated a three-gene system using SDEs where Gene A activates Gene B, and Gene C is independent. The heatmap shows the pairwise MI scores calculated from snapshots of the expression data. A strong, symmetric signal is evident between Gene A and Gene B, correctly identifying the regulatory link, while MI between all other pairs is near zero. This demonstrates how information theory can reconstruct statistical dependencies from dynamic, mechanistic simulations.

To visualize the inferred network structure, we can draw edges between genes with their thickness and color proportional to MI strength. This shows which regulatory connections MI successfully identifies:

Code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch

# GeoDataViz Qualitative Palette
QUALITATIVE_COLORS = ['#FF1F5B', '#009ADE', '#AF58BA', '#FFC61E', '#F28522', '#00CD6C']

fig, ax = plt.subplots()

# Use same gene positions as true network for comparison
gene_positions = {
    'A': (0.2, 0.5),
    'B': (0.8, 0.5),
    'C': (0.5, 0.1)
}

# Draw gene nodes
for gene, (x, y) in gene_positions.items():
    color = QUALITATIVE_COLORS[1]  # All same color for inferred network
    circle = plt.Circle((x, y), 0.08, color=color, ec='black', linewidth=2, zorder=3)
    ax.add_patch(circle)
    ax.text(x, y, gene, ha='center', va='center', fontsize=16, fontweight='bold', color='white', zorder=4)

# Draw edges based on MI values
# MI matrix: [A, B, C] ordering
# Define threshold for significant MI
mi_threshold = 0.1
max_mi = mi_matrix.max()

# Gene pairs and their positions
gene_pairs = [
    ('A', 'B', 0, 1),  # A-B
    ('A', 'C', 0, 2),  # A-C
    ('B', 'C', 1, 2),  # B-C
]

for gene1, gene2, i, j in gene_pairs:
    mi_val = mi_matrix[i, j]

    if mi_val > mi_threshold:
        # Normalize MI to [0, 1] for color/thickness
        mi_norm = mi_val / max_mi

        # Edge properties scale with MI
        linewidth = 0.5 + 5 * mi_norm  # Range: 0.5 to 5.5
        alpha = 0.3 + 0.7 * mi_norm    # Range: 0.3 to 1.0

        # Draw bidirectional arrow (MI is symmetric)
        pos1 = gene_positions[gene1]
        pos2 = gene_positions[gene2]

        # Calculate direction vector and normalize
        dx = pos2[0] - pos1[0]
        dy = pos2[1] - pos1[1]
        dist = np.sqrt(dx**2 + dy**2)
        dx_norm = dx / dist
        dy_norm = dy / dist

        # Offset start and end to avoid overlapping with nodes
        start = (pos1[0] + 0.08 * dx_norm, pos1[1] + 0.08 * dy_norm)
        end = (pos2[0] - 0.08 * dx_norm, pos2[1] - 0.08 * dy_norm)

        arrow = FancyArrowPatch(
            start, end,
            arrowstyle='<->',  # Bidirectional
            mutation_scale=20,
            linewidth=linewidth,
            color=QUALITATIVE_COLORS[0],
            alpha=alpha,
            zorder=2
        )
        ax.add_patch(arrow)

        # Add MI value label
        mid_x = (pos1[0] + pos2[0]) / 2
        mid_y = (pos1[1] + pos2[1]) / 2
        ax.text(mid_x, mid_y + 0.08, f'MI={mi_val:.2f}',
                ha='center', va='bottom', fontsize=9,
                color=QUALITATIVE_COLORS[0], fontweight='bold',
                bbox=dict(boxstyle='round,pad=0.2', facecolor='white',
                         edgecolor=QUALITATIVE_COLORS[0], linewidth=1, alpha=0.8))

ax.set_xlim(0, 1)
ax.set_ylim(0, 0.8)
ax.set_aspect('equal')
ax.axis('off')
ax.set_title('Inferred Network Structure (MI > 0.1)', fontsize=14, fontweight='bold', pad=20)

plt.tight_layout()
plt.show()
Figure 3.38: Inferred network structure from MI analysis. Edge thickness and color intensity reflect MI strength, with a threshold applied to show only meaningful connections (MI > 0.1). The strong A→B edge is correctly recovered, while spurious edges to the independent Gene C are correctly absent. MI cannot determine directionality, so edges are drawn as bidirectional. This visualization demonstrates how information-theoretic measures can reconstruct network topology from steady-state snapshots.

The MI matrix recovers the true network structure: I(A; B) is high, correctly identifying the regulatory link. I(A; C) and I(B; C) are near zero, confirming Gene C’s independence. The inferred network diagram visualizes this: only the A↔︎B connection appears, with edge strength reflecting MI magnitude. The symmetry of MI means we can’t determine that A activates B rather than B activating A—we’d need time-resolved data or perturbation experiments for directionality.

This example demonstrates the core principle: pairwise statistical dependencies can reconstruct network topology from snapshots alone. But real regulatory networks have hundreds of genes, indirect effects, and feedback loops. Chapter 4 will introduce methods that scale to genome-wide data and infer developmental trajectories from high-dimensional expression landscapes.


3.8 Conclusion: From Single Genes to Genomic Landscapes

We began this chapter asking: “What molecular machine produced this distribution of mRNA counts?” Through four complementary inference frameworks—Method of Moments, Maximum Likelihood Estimation, Bayesian Inference, and Likelihood-Free Methods—we’ve built a comprehensive toolkit for extracting mechanistic insights from experimental data. These methods allow us to solve the inverse problem: working backward from observed distributions to underlying biological parameters.

Guiding Question Core Input(s) Method Primary Output Key Consideration
What’s a quick, rough estimate of the parameters? Data moments (mean, variance) Method of Moments Single point estimate Fast and simple, but statistically inefficient
What’s the single ‘best’ parameter set? Likelihood function Maximum Likelihood Estimation Optimal point estimate + CIs Efficient, but provides no parameter uncertainty
What is the full range of plausible parameters? Likelihood function + Prior distributions Bayesian Inference (MCMC) Full posterior distribution for parameters The “gold standard” for uncertainty, but costly
My likelihood is intractable, what can I do? A simulator + Prior distributions Likelihood-Free Inference (ABC) Approximate posterior distribution For complex models where likelihood can’t be computed

3.8.1 The Path Forward: High-Dimensional Transcriptomics

We have built a powerful toolkit to solve the inverse problem for a single gene—we can take a distribution of mRNA counts and infer the kinetics of the molecular machine that produced it. But modern biology confronts us with a fundamentally different scale: 20,000 genes across 10,000 cells, yielding a 200-million-dimensional data matrix. Applying our single-gene methods one at a time is not only computationally intractable, it misses the entire point: genes don’t act in isolation.

Yet this complexity contains unprecedented biological information. The key insight: Despite apparent complexity, biological systems exhibit profound low-dimensional structure. Cells don’t explore 20,000-dimensional expression space randomly—they follow constrained paths shaped by regulatory networks and evolutionary optimization. The new inverse problem is not to infer parameters of a single gene, but to discover the low-dimensional structure—the cellular programs and differentiation paths—hidden in that vast genomic space.

Chapter 4 will introduce the computational methods that unlock high-dimensional biology: dimensionality reduction, clustering algorithms, trajectory inference, and RNA velocity analysis. These methods represent an evolution in perspective—from “What are this gene’s parameters?” to “What is the structure of this expression landscape?” Welcome to the world of high-dimensional transcriptomics.