Multiprocess not recognizing defined function

280 Views Asked by At

I'm trying to fit a simple gaussian model to some data using the markov-chain monte carlo package EMCEE while utilizing parallel processing. I am using multiprocess instead of multiprocessing as I am working in Jupyter notebook where multiprocessing often runs into problems for some reason. Currently, the code is saying that one of my functions is not defined even though it was defined earlier. Not sure why it isn't being carried over once the parallelization starts. Specifically the error occurs on the very last line saying that "log_prior" is not defined. Any thoughts on how to fix this issue would be much appreciated.

import numpy as np
import emcee
from scipy.optimize import minimize
import matplotlib.pyplot as plt

np.random.seed(123)

# Choose the "true" parameters.
mu_true = 5
sig_true = 0.5
f_true = 0.534

# Generate some synthetic data from the model.
N = 500
x = np.sort(10 * np.random.rand(N))
yerr = 0.03 + 0.05 * np.random.rand(N)
y = np.exp(-np.power(x - mu_true, 2.) / (2 * np.power(sig_true, 2.)))
y+= 0.5*np.abs(f_true * y) * np.random.randn(N)
y += yerr * np.random.randn(N)


def log_likelihood(theta, x, y, yerr):
    mu, sig, log_f = theta
    model = np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
    sigma2 = yerr**2 + model**2 * np.exp(2 * log_f)
    return -0.5 * np.sum((y - model) ** 2 / sigma2 + np.log(sigma2))

np.random.seed(42)
nll = lambda *args: -log_likelihood(*args)
initial = np.array([mu_true, sig_true, np.log(f_true)]) + 0.1 * np.random.randn(3)
soln = minimize(nll, initial, args=(x, y, yerr))
mu_ml, sig_ml, log_f_ml = soln.x

def log_prior(theta):
    mu, sig, log_f  = theta
    if 2 < mu < 10 and 0.0 < sig < 5 and -10.0 < log_f < 1.0:
        return 0.0
    return -np.inf

def log_probability(theta, x, y, yerr):
    lp = log_prior(theta)
    if not np.isfinite(lp):
        return -np.inf
    return lp + log_likelihood(theta, x, y, yerr)

import time
import multiprocess
import numpy as np
from multiprocess import Pool



pos = soln.x + 0.2 * np.random.randn(32, 3)
nwalkers, ndim = pos.shape

nsteps = 10000
if __name__ == "__main__":
    with Pool() as pool:
        sampler = emcee.EnsembleSampler(
        nwalkers, ndim, log_probability, args=(x, y, yerr), pool=pool)
        sampler.run_mcmc(pos, 10000, progress=True);
0

There are 0 best solutions below