Parameter estimation with Markov chain Monte Carlo

Data set download


[1]:
# Colab setup ------------------
import os, shutil, sys, subprocess, urllib.request
if "google.colab" in sys.modules:
    cmd = "pip install --upgrade iqplot colorcet datashader bebi103 arviz cmdstanpy watermark"
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    from cmdstanpy.install_cmdstan import latest_version
    cmdstan_version = latest_version()
    cmdstan_url = f"https://github.com/stan-dev/cmdstan/releases/download/v{cmdstan_version}/"
    fname = f"colab-cmdstan-{cmdstan_version}.tgz"
    urllib.request.urlretrieve(cmdstan_url + fname, fname)
    shutil.unpack_archive(fname)
    os.environ["CMDSTAN"] = f"./cmdstan-{cmdstan_version}"
    data_path = "https://s3.amazonaws.com/bebi103.caltech.edu/data/"
else:
    data_path = "../data/"
# ------------------------------
[2]:
import numpy as np
import scipy.stats as st
import pandas as pd

import cmdstanpy
import arviz as az

import iqplot
import bebi103

import bokeh.io
import bokeh.plotting
bokeh.io.output_notebook()
Loading BokehJS ...

In this lesson, we will learn how to use Markov chain Monte Carlo to do parameter estimation. To get the basic idea behind MCMC, imagine for a moment that we can draw samples out of the posterior distribution. This means that the probability of choosing given values of a set of parameters is proportional to the posterior probability of that set of values. If we drew many many such samples, we could reconstruct the posterior from the samples, e.g., by making histograms. That’s a big thing to imagine: that we can draw properly weighted samples. But, it turns out that we can! That is what MCMC allows us to do.

We discussed some theory behind this seemingly miraculous capability in lecture. For this lesson, we will just use the fact that we can do the sampling to learn about posterior distributions in the context of parameter estimation.

Stan: Our MCMC engine

We will use Stan as our main engine for performing MCMC, and will use one of its Python interfaces, CmdStanPy. Stan is the state of the art for MCMC. Importantly, it is also a probabilistic programming language, which allows us to more easily specify Bayesian generative models. The Stan documentation will be very useful for you.

The data set

The data come from the Elowitz lab, published in Singer et al., Dynamic Heterogeneity and DNA Methylation in Embryonic Stem Cells, Molec. Cell, 55, 319-331, 2014, available here. In the following paragraphs, I repeat the description of the data set and EDA from last term:

In this paper, the authors investigated cell populations of embryonic stem cells using RNA single molecule fluorescence in situ hybridization (smFISH), a technique that enables them to count the number of mRNA transcripts in a cell for a given gene. They were able to measure four different genes in the same cells. So, for one experiment, they get the counts of four different genes in a collection of cells.

The authors focused on genes that code for pluripotency-associated regulators to study cell differentiation. Indeed, differing gene expression levels are a hallmark of differentiated cells. The authors do not just look at counts in a given cell at a given time. The temporal nature of gene expression is also important. While the authors do not directly look at temporal data using smFISH (since the technique requires fixing the cells), they did look at time lapse fluorescence movies of other regulators. We will not focus on these experiments here, but will discuss how the distribution of mRNA counts acquired via smFISH can serve to provide some insight about the dynamics of gene expression.

The data set we are analyzing now comes from an experiment where smFISH was performed in 279 cells for the genes rex1, rest, nanog, and prdm14. The data set may be downloaded at https://s3.amazonaws.com/bebi103.caltech.edu/data/singer_transcript_counts.csv.

ECDFs of mRNA counts

We will do a quick EDA to get a feel for the data set by generating ECDFs for the mRNA counts for each of the four genes.

[3]:
%load_ext blackcellmagic
[4]:
df = pd.read_csv(os.path.join(data_path, "singer_transcript_counts.csv"), comment="#")

genes = ["Nanog", "Prdm14", "Rest", "Rex1"]

plots = [
    iqplot.ecdf(
        data=df[gene].values,
        q=gene,
        x_axis_label="mRNA count",
        title=gene,
        frame_height=150,
        frame_width=200,
    )
    for gene in genes
]

bokeh.io.show(
    bokeh.layouts.column(bokeh.layouts.row(*plots[:2]), bokeh.layouts.row(*plots[2:]))
)

Note the difference in the \(x\)-axis scales. Clearly, prdm14 has far fewer mRNA copies than the other genes. The presence of two inflection points in the Rex1 EDCF implies bimodality.

Building a generative model

As we discussed in a lesson last term, we can model the transcript counts, which result from bursty gene expression, as being Negative Binomially distributed. For a given gene, the likelihood for the counts is

\begin{align} n_i \mid \alpha, b \sim \text{NegBinom}(\alpha, 1/b) \;\forall i, \end{align}

where \(\alpha\) is the burst frequency (higher \(\alpha\) means gene expression comes on more frequently) and \(b\) is the burst size, i.e., the typical number of transcripts made per burst. We have therefore identified the two parameters we need to estimate, \(\alpha\) and \(b\).

Because the Negative Binomial distribution is often parametrized in terms of \(\alpha\) and \(\beta= 1/b\), we can alternatively state our likelihood as

\begin{align} &\beta = 1/b,\\[1em] &n_i \mid \alpha, \beta \sim \text{NegBinom}(\alpha, \beta)\;\; \forall i. \end{align}

Given that we have a Negative Binomial likelihood, we are left to specify priors the burst size \(b\) and the burst frequency \(\alpha\).

Priors for burst size and inter-burst time

We will apply the bet-the-farm technique to get our priors for the burst size and inter-burst times. I would expect the time between bursts to be longer than a second, since it takes time for the transcriptional machinery to assemble. I would expect it to be shorter than a few hours, since an organism would need to adapt its gene expression based on environmental changes on that time scale or faster. The time between bursts needs to be in units of RNA lifetimes, and bacterial RNA lifetimes are of order minutes. So, the range of values of \(\alpha\) is \(10^{-2}\) to \(10^2\), leading to a prior of

\begin{align} \log_{10} \alpha \sim \text{Norm}(0, 1). \end{align}

I would expect the burst size to depend on promoter strength and/or strength of transcriptional activators. I could imagine anywhere from a few to a few thousand transcripts per burst, giving a range of \(10^0\) to \(10^4\), and a prior of

\begin{align} \log_{10} b \sim \text{Norm}(2, 1). \end{align}

We then have the following model.

\begin{align} &\log_{10} \alpha \sim \text{Norm}(0, 1),\\[1em] &\log_{10} b \sim \text{Norm}(2, 1),\\[1em] &\beta = 1/b,\\[1em] &n_i \sim \text{NegBinom}(\alpha, \beta) \;\forall i. \end{align}

Sampling the posterior

To draw samples out of the posterior, we need to use some new Stan syntax. Here is the Stan code we will use with some notes about Stan syntax.

data {
  int<lower=0> N;
  array[N] int<lower=0> n;
}


parameters {
  real log10_alpha;
  real log10_b;
}


transformed parameters {
  real alpha = 10^log10_alpha;
  real b = 10^log10_b;
  real beta_ = 1.0 / b;
}


model {
  // Priors
  log10_alpha ~ normal(0, 1);
  log10_b ~ normal(2, 1);

  // Likelihood
  n ~ neg_binomial(alpha, beta_);
}
  • Note that the raise-to-power operator is ^, not ** as in Python.

  • The data block contains the counts \(n\) of the mRNA transcripts. There are \(N\) cells that are measured. Most data blocks look like this. There is an integer parameter that specifies the size of the data set, and then the data set is given as an array. The declaration that n is an array of length N is array [N], followed by the type of data, is integer. We specified a lower bound on the data (as we will do on the parameters) using the <lower=0> syntax.

  • The parameters block tells us what the parameters of the posterior are. In this case, we wish to sample out of the posterior \(g(\alpha, b \mid \mathbf{n})\), where \(\mathbf{n}\) is the set of transcript counts for the gene. So, the two parameters are \(\alpha\) and \(b\). However, since defining the prior was more easily defined in terms of logarithms, we specify \(\log_{10} \alpha\) and \(\log_{10} b\) as the parameters.

  • The transformed parameters block allows you to do any transformation of the parameters you are sampling for convenience. In this case, Stan’s Negative Binomial distribution is parametrized by \(\beta = 1/b\), so we make the transformation of the b to beta_. Notice that I have called this variable beta_ and not beta. I did this because beta is one of Stan’s distributions, and you should avoid naming a variable after a word that is already in the Stan language. The other transformations we need to make involve converting the logarithms to the actual parameter values.

  • Finally, the model block is where the model is specified. The syntax of the model block is almost identical to that of the hand-written model.

Now that we have specified our model, we can compile it.

[5]:
sm = cmdstanpy.CmdStanModel(stan_file='smfish.stan')
23:05:53 - cmdstanpy - INFO - compiling stan file /Users/bois/Dropbox/git/bebi103_course/2024/b/content/lessons/08/smfish.stan to exe file /Users/bois/Dropbox/git/bebi103_course/2024/b/content/lessons/08/smfish
23:06:06 - cmdstanpy - INFO - compiled model executable: /Users/bois/Dropbox/git/bebi103_course/2024/b/content/lessons/08/smfish

With our compiled model, we just need to specify the data and let Stan’s sampler do the work! When using CmdStanPy, the data has to be passed in as a dictionary with keys corresponding to the variable names declared in the data block of the Stan program and values as Numpy arrays with the appropriate data type. For this calculation, we will use the data set for the rest gene.

[6]:
# Construct data dict, making sure data are ints
data = dict(N=len(df), n=df["Rest"].values.astype(int))

# Sample using Stan
samples = sm.sample(
    data=data,
    chains=4,
    iter_sampling=1000,
)

# Convert to ArviZ InferenceData instance
samples = az.from_cmdstanpy(posterior=samples)
23:06:06 - cmdstanpy - INFO - CmdStan start processing

23:06:07 - cmdstanpy - INFO - CmdStan done processing.
23:06:07 - cmdstanpy - WARNING - Non-fatal error during sampling:
Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
Exception: neg_binomial_lpmf: Shape parameter is inf, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is inf, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Inverse scale parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Inverse scale parameter is 0, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is inf, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
        Exception: neg_binomial_lpmf: Shape parameter is inf, but must be positive finite! (in 'smfish.stan', line 26, column 2 to column 33)
Consider re-running with show_console=True if the above output is unclear!

We got lots of warnings! In particular, we get warnings that some of the parameters fed into the Negative Binomial distribution are invalid, being either zero or infinite. These warnings are arising during Stan’s warm-up phase as it is assessing optimal settings for sampling, and should not be of concern. It is generally a bad idea to silence warnings, but if you are sure that the warnings that the sampler will throw are of no concern, you can silence logging using the bebi103.stan.disable_logging context. In most notebooks in these notes, to avoid clutter for pedagogical purposes, we will disable the warnings.

[7]:
with bebi103.stan.disable_logging():
    samples = sm.sample(
        data=data,
        chains=4,
        iter_sampling=1000,
    )

# Convert to ArviZ InferenceData instance
samples = az.from_cmdstanpy(posterior=samples)

Now, let’s take a quick look at the samples.

[8]:
samples.posterior
[8]:
<xarray.Dataset>
Dimensions:      (chain: 4, draw: 1000)
Coordinates:
  * chain        (chain) int64 0 1 2 3
  * draw         (draw) int64 0 1 2 3 4 5 6 7 ... 993 994 995 996 997 998 999
Data variables:
    log10_alpha  (chain, draw) float64 0.6647 0.6297 0.6401 ... 0.7576 0.5949
    log10_b      (chain, draw) float64 1.199 1.231 1.242 ... 1.117 1.12 1.271
    alpha        (chain, draw) float64 4.621 4.263 4.366 ... 5.784 5.723 3.935
    b            (chain, draw) float64 15.83 17.03 17.44 ... 13.08 13.18 18.66
    beta_        (chain, draw) float64 0.06317 0.05872 ... 0.07587 0.0536
Attributes:
    created_at:                 2024-01-07T07:06:08.580717
    arviz_version:              0.17.0
    inference_library:          cmdstanpy
    inference_library_version:  1.2.0

As we have already seen, the samples are indexed by chain and draw. Parameters represented in the parameters and transformed parameters blocks are reported.

Plots of the samples

There are many ways of looking at the samples. In this case, since we have two parameters of interest, the pulse frequency and pulse size, we can plot the samples as a scatter plot to get the approximate density.

[9]:
def plot_scatter(samples, title=None):
    p = bokeh.plotting.figure(
        frame_width=200,
        frame_height=200,
        x_axis_label='α',
        y_axis_label='b',
        title=title,
    )

    p.circle(
        samples.posterior['alpha'].values.ravel(),
        samples.posterior['b'].values.ravel(),
        size=2,
        alpha=0.2,
    )

    return p

bokeh.io.show(plot_scatter(samples))

We see very strong correlation between \(\alpha\) and \(b\). This does not necessarily mean that they depend on each other. Rather, it means that our degree of belief about their values depends on both in a correlated way. The measurements we made cannot effectively separate the effects of \(\alpha\) and \(b\) on the transcript counts.

Marginalizing the posterior

We can also plot the marginalized posterior distributions. Remember that the marginalized distributions properly take into account the effects of the other variable, including the strong correlation I just mentioned. To obtain the marginalized distribution, we simply ignore the samples of the parameters we are marginalizing out. It is convenient to look at the marginalized distributions as ECDFs.

[10]:
plots = [
    iqplot.ecdf(
        samples.posterior[param].values.ravel(),
        q=param,
        frame_height=200,
        frame_width=250,
    )
    for param in ["alpha", "b"]
]

bokeh.io.show(bokeh.layouts.gridplot(plots, ncols=2))

Alternatively, we can visualize the marginalized posterior PDFs as histograms. Because we have such a large number of samples, binning bias from histograms is less of a concern.

[11]:
plots = [
    iqplot.histogram(
        samples.posterior[param].values.ravel(),
        q=param,
        rug=False,
        frame_height=200,
        frame_width=250,
    )
    for param in ["alpha", "b"]
]

bokeh.io.show(bokeh.layouts.gridplot(plots, ncols=2))

Analysis for all genes

We can do the same analysis for all genes. To do so, we input the data sets for each gene into the sampler and make our plot of the posterior. When we do the sampling, to avoid clutter on our screen, we can disable the logging that CmdStanPy sends by using the bebi103.stan.disable_logging() context manager, and we will use the show_progress=False kwarg when calling sm.sample().

[12]:
plots = []

for gene in df.columns:
    data = dict(N=len(df), n=df[gene].values.astype(int))

    with bebi103.stan.disable_logging():
        samples = sm.sample(
            data=data, chains=4, iter_sampling=1000, show_progress=False
        )

    samples = az.from_cmdstanpy(posterior=samples)
    plots.append(plot_scatter(samples, title=gene))

bokeh.io.show(
    bokeh.layouts.column(bokeh.layouts.row(*plots[:2]), bokeh.layouts.row(*plots[2:]))
)

Note that this single Negative Binomial model probably does not describe the Rex1 data, as can be seen from the ECDF of the measurements. Nonetheless, we can still (foolishly) assume the model is true and compute (i.e., sample) the posterior as if the model were true. This is always what we are doing when we perform parameter estimations. That said, we should seek a more apt model for Rex1.

Display of “best fit”

After performing an MCMC calculation to access the posterior, we often want to visualize, for example, the ECDF of the measurements along with ECDFs predicted from the model. We will discuss methods for doing this in coming lessons when we discuss posterior predictive checks. For now, we will plot theoretical CDFs for parameter sets drawn from the posterior. First, we’ll grab the posterior samples again.

[13]:
# Re-obtain samples for rest
data = dict(N=len(df), n=df["Rest"].values.astype(int))

with bebi103.stan.disable_logging():
    samples = sm.sample(
        data=data,
        chains=4,
        iter_sampling=1000,
        show_progress=False,
    )

samples = az.from_cmdstanpy(posterior=samples)

And now we’ll get a plot of the ECDF.

[14]:
p = iqplot.ecdf(data=df['Rest'].values, x_axis_label='mRNA count')

We’ll generate a new CDFs for 100 sets of parameter values.

[15]:
# x-values and samples to use in plot
x = np.arange(251)
alphas = samples.posterior["alpha"].values.flatten()[::40]
betas = samples.posterior["beta_"].values.flatten()[::40]

for alpha, beta in zip(alphas, betas):
    y = st.nbinom.cdf(x, alpha, beta / (1 + beta))
    x_plot, y_plot = bebi103.viz.cdf_to_staircase(x, y)
    p.line(x_plot, y_plot, line_width=0.5, color="orange", level="underlay")

bokeh.io.show(p)

The measured CDF seems to be within reason given the model. This is not true for the Rex1 gene, however.

[16]:
# Re-obtain samples for rest
data = dict(N=len(df), n=df["Rex1"].values.astype(int))

with bebi103.stan.disable_logging():
    samples = sm.sample(
        data=data,
        chains=4,
        iter_sampling=1000,
        show_progress=False,
    )

samples = az.from_cmdstanpy(posterior=samples)

# Make ECDF
p = iqplot.ecdf(data=df["Rex1"].values, x_axis_label="mRNA count", x_range=[-20, 425])

# x-values and samples to use in plot
x = np.arange(426)
alphas = samples.posterior["alpha"].values.flatten()[::40]
betas = samples.posterior["beta_"].values.flatten()[::40]

for alpha, beta in zip(alphas, betas):
    y = st.nbinom.cdf(x, alpha, beta / (1 + beta))
    x_plot, y_plot = bebi103.viz.cdf_to_staircase(x, y)
    p.line(x_plot, y_plot, line_width=0.5, color="orange", level="underlay")

bokeh.io.show(p)

The lesson here is that getting nicely identifiable parameter estimates does not mean that the model is good. As I mentioned before, we will do more careful assessment of this when we do posterior predictive checks.

[17]:
bebi103.stan.clean_cmdstan()

Computing environment

[18]:
%load_ext watermark
%watermark -v -p numpy,scipy,pandas,cmdstanpy,arviz,bokeh,iqplot,bebi103,jupyterlab
print("cmdstan   :", bebi103.stan.cmdstan_version())
Python implementation: CPython
Python version       : 3.11.5
IPython version      : 8.15.0

numpy     : 1.26.2
scipy     : 1.11.4
pandas    : 2.1.4
cmdstanpy : 1.2.0
arviz     : 0.17.0
bokeh     : 3.3.0
iqplot    : 0.3.5
bebi103   : 0.1.19
jupyterlab: 4.0.10

cmdstan   : 2.33.1