From: Bayesian Models for Astrophysical Data, Cambridge Univ. Press

(c) 2017,  Joseph M. Hilbe, Rafael S. de Souza and Emille E. O. Ishida 

 

you are kindly asked to include the complete citation if you used this material in a publication

Code 10.9 Lognormal model in Python using Stan to describe the initial mass function (IMF)

======================================================================

import numpy as np
import pandas as pd
import pylab as plt
import pystan 
import statsmodels.api as sm

# Data
path_to_data = 'https://raw.githubusercontent.com/astrobayes/BMAD/master/data/Section_10p4/NGC6611.csv'

# read data
data_frame = dict(pd.read_csv(path_to_data))

# prepare data for Stan
data = {}
data['X'] = data_frame['Mass']
data['nobs'] = data['X'].shape[0]

# Fit
stan_code="""
data{
    int<lower=0> nobs;                        # number of data points
    vector[nobs] X;                              # stellar mass
}
parameters{
    real mu;                                          # mean 
    real<lower=0> sigma;                   # scatter
}
model{
    # priors and likelihood
    sigma ~ normal(0, 100);
    mu ~ normal(0, 100);

    X ~ lognormal(mu, sigma);
}
"""

# Run mcmc
fit = pystan.stan(model_code=stan_code, data=data, iter=5000, chains=3,
                           warmup=2500, thin=1, n_jobs=3)

 

# Output
print(fit)

# plot chains and posteriors
fit.traceplot()
plt.show()

======================================================================

Output on screen:

Inference for Stan model: anon_model_ccdb5e21e66f2da8adbf43d171c7e454.
3 chains, each with iter=5000; warmup=2500; thin=1; 
post-warmup draws per chain=2500, total post-warmup draws=7500.

               mean     se_mean        sd       2.5%        25%        50%         75%       97.5%      n_eff      Rhat
mu          -1.25         1.0e-3     0.07      -1.39        -1.3        -1.25         -1.21         -1.12      4804        1.0
sigma      1.04          7.6e-4     0.05       0.94          1.0         1.03          1.07          1.14       4612        1.0
lp__     -110.3             0.02     1.01    -113.1     -110.7      -110.0       -109.6      -109.3       3776        1.0

Samples were drawn using NUTS at Wed May  3 18:03:22 2017.
For each parameter, n_eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor on split chains (at 
convergence, Rhat=1).