Beispiel #1
0
 def MCMCplot( self, M ):
     try:
         from pymc import Uniform, deterministic, Normal, MCMC, Matplot
     except ImportError as exc:
         sys.stderr.write("Warning: failed to import pymc module. ({})\n".format(exc))
         sys.stderr.write("If pymc is not installed, try installing:\n")
         sys.stderr.write("e.g. try using easy_install: easy_install pymc\n")
     Matplot.plot(M)
Beispiel #2
0
def fit_std_curve_by_pymc(i_vals, i_sds, dpx_concs):
    import pymc
    from pymc import Uniform, stochastic, deterministic, MCMC
    from pymc import Matplot
    # Define prior distributions for both Ka and Kd
    ka = Uniform('ka', lower=0, upper=1000)
    kd = Uniform('kd', lower=0, upper=1000)

    @stochastic(plot=True, observed=True)
    def quenching_model(ka=ka, kd=kd, value=i_vals):
        pred_i = quenching_func(ka, kd, dpx_concs)
        # The first concentration in dpx_concs should always be zero
        # (that is, the first point in the titration should be the
        # unquenched fluorescence), so we assert that here:
        assert dpx_concs[0] == 0
        # The reason this is necessary is that in the likelihood calculation
        # we skip the error for the first point, since (when the std. err
        # is calculated by well) the error is 0 (the I / I_0 ratio is
        # always 1 for each well, the the variance/SD across the wells is 0).
        # If we don't skip this first point, we get nan for the likelihood.
        # In addition, the model always predicts 1 for the I / I_0 ratio
        # when the DPX concentration is 0, so it contributes nothing to
        # the overall fit.
        return -np.sum((value[1:] - pred_i[1:])**2 / (2 * i_sds[1:]**2))

    pymc_model = pymc.Model([ka, kd, quenching_model])
    mcmc = MCMC(pymc_model)
    mcmc.sample(iter=155000, burn=5000, thin=150)
    Matplot.plot(mcmc)

    plt.figure()
    num_to_plot = 1000
    ka_vals = mcmc.trace('ka')[:]
    kd_vals = mcmc.trace('kd')[:]
    if num_to_plot > len(ka_vals):
        num_to_plot = len(ka_vals)
    for i in range(num_to_plot):
        plt.plot(dpx_concs, quenching_func(ka_vals[i], kd_vals[i], dpx_concs),
                 alpha=0.01, color='r')
    plt.errorbar(dpx_concs, i_vals, yerr=i_sds, linestyle='', marker='o',
            color='k', linewidth=2)

    return (ka_vals, kd_vals)
import pymc
import radon_varying_slope
from pylab import hist, show
from pymc import Matplot

M = pymc.MCMC(radon_varying_slope)
M.sample(iter=50e3, burn=10e3, thin=10)

fit = M.stats()
for k in fit.keys():
    print(k, fit[k]['mean'])

Matplot.plot(M)
import pymc
import radon_varying_intercept
from pylab import hist, show
from pymc import Matplot

M = pymc.MCMC(radon_varying_intercept)
M.sample(iter=50e3, burn=10e3, thin=5)

fit = M.stats()
for k in fit.keys():
     print(k,fit[k]['mean'])

Matplot.plot(M)
Beispiel #5
0
# PyMC implementation of Panel 6.4 from Royle & Dorazio (2008) pp. 217
# MA MacNeil - 04.03.14

import Mbht
import sys
import os
import pdb
from pymc import MCMC, BinaryMetropolis, Metropolis, AdaptiveMetropolis
from pymc import Matplot as mp
import pdb


M = MCMC(Mbht)
#M = MCMC(models,db='sqlite',dbname='xx_dbase')
xex = 6
M.isample(10**xex, 10**xex-10**(xex-1), thin=10**(xex-4), verbose=2)
#M.isample(100000, 80000, thin=10, verbose=2)

try:
    os.mkdir('Outputs')
except OSError:
    pass
os.chdir('Outputs')
M.write_csv("zz_results.csv")
mp.plot(M)
                               ls_dmat.columns,
                               show_stats=True,
                               maxrow=3,
                               save_fig=True,
                               path=output_dir,
                               fname='ls_beta_posteriors.png')

    plots.plot_posterior_panel(M.trace('beta', chain=None)[:],
                               dmat.columns,
                               show_stats=True,
                               maxrow=3,
                               save_fig=True,
                               path=output_dir,
                               fname='beta_posteriors.png')

    Matplot.plot(M.eps_tau, path=output_dir)
    Matplot.plot(M.tau_car, path=output_dir)

    # plot maps
    w = M.trace('w', chain=None)[:].mean(axis=0)
    ls_beta = M.trace('ls_beta', chain=None)[:].mean(axis=0)
    ls_pred = np.exp(np.array(pred_dmat).dot(ls_beta) + w)  #/0.5**2

    layers = [ls_pred, w, pred_dmat.dsettm, pred_dmat.reserv]
    ls_pred_max = int(np.percentile(ls_pred, 95).round())
    lims = [(0, ls_pred_max), (-0.5, 0.5), (-2, 2), (-2, 2)]
    titles = [
        'Relative density surface', 'Spatial random effects',
        'Distance to major settlements', 'Density of protected areas'
    ]
    main = ' '.join(subdir.split('_'))
                      value=ydata,
                      plot=True)

if __name__ == '__main__':
    # Build a model
    # NOTE: Be careful to avoid namespace clashes with pysb.Model!
    pymc_model = pymc.Model([k, decay_model, timecourse])

    # Initialize an MCMC object from the model
    mcmc = MCMC(pymc_model)

    # Sample
    mcmc.sample(iter=10000, burn=5000)

    # Plot the posterior distribution of the parameter k
    plt.ion()
    Matplot.plot(mcmc)

    # Plot the original data (underlying and noisy)
    # along with the sampled trajectories
    plt.figure()
    plt.plot(tspan, ysim, color='r')
    plt.plot(tspan, ydata, color='g')
    num_timecourses = 1000
    num_iterations_sampled = mcmc.trace('decay_model')[:].shape[0]
    plt.plot(tspan,
             mcmc.trace('decay_model')[num_iterations_sampled -
                                       num_timecourses:, :].T,
             alpha=0.05,
             color='b')
Beispiel #8
0
import numpy as np
from scipy.stats import bernoulli


def model(data):
    theta_prior = pc.Beta('theta_prior', alpha=1.0, beta=1.0)
    coin = pc.Bernoulli('coin', p=theta_prior, value=data, observed=True)
    mod = pc.Model([theta_prior, coin])

    return mod


def generateSample(t, s):
    return bernoulli.rvs(t, size=s)


def mcmcTraces(data):
    mod = model(data)
    mc = pc.MCMC(mod)

    mc.sample(iter=5000, burn=1000)
    return mc.trace('theta_prior')[:]


sample = generateSample(0.7, 500)

trs = mcmcTraces(sample)
print(trs)
k = pt.histogram(trs, "theta prior; size=100", datarange=(0.2, 0.9))
pt.plot(k, name='ahoj')
Beispiel #9
0
    return -np.sum(((value - solver.yobs['A_obs'])**2) / (2 * variances))

if __name__ == '__main__':
    # Build a model
    # NOTE: Be careful to avoid namespace clashes with pysb.Model!
    pymc_model = pymc.Model([k, decay_model])

    # Initialize an MCMC object from the model
    mcmc = MCMC(pymc_model)

    # Sample
    mcmc.sample(iter=15000, burn=5000, thin=10)

    # Plot the posterior distribution of the parameter k
    plt.ion()
    Matplot.plot(mcmc)

    # Plot the original data (underlying and noisy)
    # along with the sampled trajectories
    plt.figure()
    plt.plot(tspan, ysim, color='r')
    plt.plot(tspan, ydata, color='g')
    num_to_plot = 1000
    k_vals = mcmc.trace('k')[:]
    if num_to_plot > len(k_vals):
        num_to_plot = len(k_vals)

    for i in range(num_to_plot):
        solver.run(np.array([A_0.value, k_vals[i], 1.0]))
        plt.plot(tspan, solver.yobs['A_obs'], alpha=0.05, color='b')
Beispiel #10
0
print 'input:'
print gpr.fil
x0,y0,z0,vz0,vb0,Mg0,PM0,comp0=np.genfromtxt(gpr.fil,skiprows=0,unpack=True,\
                                             usecols=(0,1,2,11,12,13,19,20),\
                                             dtype="d17",\
                                             converters={0:expDtofloat,  # x0  in pc \
                                                         1:expDtofloat,  # y0  in pc \
                                                         2:expDtofloat,  # z0  in pc \
                                                         11:expDtofloat, # vz0 in km/s\
                                                         12:expDtofloat, # vb0(LOS due binary), km/s\
                                                         13:expDtofloat, # Mg0 in Angstrom\
                                                         19:expDtofloat, # PM0 [1]\
                                                         20:expDtofloat}) # comp0 1,2,3(background)
data = Mg0

obs = Normal( "obs", mean, precision, value = data, observed = True)
model = Model( {"p":p, "precision": precision, "mean1": mean1, "mean2":mean2, "obs":obs} )

if __name__=="__main__":
    from pymc import MCMC, Matplot

    S = MCMC(locals(), db='pickle')
    S.sample(iter=10000, burn=8000, thin=2)
    import pylab
    Matplot.plot(S)
    pylab.ion()
    pylab.hist(data,100)
    pylab.savefig('data.png')
    pylab.ioff()
    pylab.show()
Beispiel #11
0
                               ls_dmat.columns,
                               show_stats=True,
                               maxrow=3,
                               save_fig=True,
                               path=output_dir,
                               fname='ls_beta_posteriors.png')

    plots.plot_posterior_panel(M.trace('beta', chain=None)[:],
                               dmat.columns,
                               show_stats=True,
                               maxrow=3,
                               save_fig=True,
                               path=output_dir,
                               fname='beta_posteriors.png')

    Matplot.plot(M.eps_sd, path=output_dir)
    Matplot.plot(M.tau_car, path=output_dir)
    Matplot.plot(M.disp, path=output_dir)

    # plot maps
    w = M.trace('w', chain=None)[:].mean(axis=0)
    ls_beta = M.trace('ls_beta', chain=None)[:].mean(axis=0)
    ls_pred = np.exp(np.array(pred_dmat).dot(ls_beta) + w)  #/0.5**2

    layers = [ls_pred, w, pred_dmat.wolf, pred_dmat.conif]
    ls_pred_max = int(np.percentile(ls_pred, 95).round())
    lims = [(0, ls_pred_max), (-0.5, 0.5), (-2, 2), (-2, 2)]
    titles = [
        'Relative density surface', 'Spatial random effects', 'Wolf space use',
        '% coniferous'
    ]
Beispiel #12
0
solu = solve([a/(a+b)-0.225, a*b/((a+b)**2*(a+b+1))-0.0011],[a,b])
alpha, beta = solu[1]
alpha = float(alpha)
beta = float(beta)
mcmc_dict = dict()
for i in range(len(MLE_april_se)):	
	player_se = april_df.ix[i,:]

	
	mu = pymc.Beta('mu', alpha, beta)
	xs = pymc.Binomial('xs', n=player_se['AB'], p=mu, value=player_se['H'], observed=True)
	mcmc_dict['mu'+str(i)] = pymc.MCMC([mu, xs])
	mcmc_dict['mu'+str(i)].sample(iter=4000, thin=2)

print '\t'
Matplot.plot(mcmc_dict['mu0'])
Matplot.plot(mcmc_dict['mu1'])
Matplot.plot(mcmc_dict['mu2'])
fall_in = 0
result_df = pd.concat([MLE_april_se, MLE_year_se], axis=1)
mean_post_list = []
ll_list = []
ul_list = []
in_list = []
for i, mui in enumerate(mcmc_dict.values()):
	
	mean_post = mui.stats()['mu']['mean']
	mean_post_list.append(mean_post)

	ll, ul = mui.stats()['mu']['95% HPD interval']
	ll_list.append(ll)
Beispiel #13
0
def main():
    # Run the model
    M = MCMC([p, z, theta_hat, t, counts])
    M.sample(110000, 10000, verbose=2)

    Matplot.plot(M)