"""emcee cheat sheet (Lecture 6) — tested with emcee 3.1. Toy model: straight line + intrinsic scatter."""
import numpy as np, emcee
from scipy import optimize

x = np.linspace(0, 10, 20); sig = 0.8
y = 0.5 * x + 1.0 + np.random.default_rng(1).normal(0, np.hypot(sig, 1.5), x.size)

# ===== 1. PRIORS: write them explicitly ===========================================
def log_prior(theta):
    m, b, ln_s = theta                       # scale parameter sampled in log: uniform in ln s = Jeffreys in s
    if not (-5 < m < 5 and np.log(0.01) < ln_s < np.log(10)):
        return -np.inf                       # hard bounds: -inf outside
    return -0.5 * ((b - 1.2) / 0.5)**2       # Gaussian prior on b from a previous measurement (1.2 +/- 0.5)
    # other common choices:
    #   log-uniform on A > 0 (if you sample A itself):  lp = -np.log(A)
    #   half-normal on A > 0:                           lp = -0.5*(A/sA)**2  (and -inf for A < 0)

def log_like(theta):
    m, b, ln_s = theta
    var = sig**2 + np.exp(2 * ln_s)          # measurement error + intrinsic scatter
    return -0.5 * np.sum((y - m * x - b)**2 / var + np.log(2 * np.pi * var))

def log_prob(theta):
    lp = log_prior(theta)
    if not np.isfinite(lp):
        return -np.inf, np.nan               # blobs must be returned even outside the prior
    return lp + log_like(theta), 5 * theta[0] + theta[1]   # blob = derived quantity, here y(x=5)

# ===== 2. START: optimise first, then a small ball inside the prior ================
ndim, nwalkers = 3, 32                       # nwalkers >= 2*ndim (better many more)
res = optimize.minimize(lambda t: -log_prob(t)[0], x0=[0.4, 1.0, 0.0], method="Nelder-Mead")
# multimodal? global search instead:  optimize.differential_evolution(lambda t: -log_prob(t)[0], bounds)
p0 = res.x + 1e-4 * np.random.default_rng(2).normal(size=(nwalkers, ndim))
assert all(np.isfinite(log_prob(p)[0]) for p in p0), "a walker starts outside the prior"

# ===== 3. MOVES (default: stretch, a = 2) ===========================================
moves = emcee.moves.StretchMove(a=2.0)                                        # default
moves = [(emcee.moves.DEMove(), 0.8), (emcee.moves.DESnookerMove(), 0.2)]     # differential evolution
moves = [(emcee.moves.StretchMove(), 0.8), (emcee.moves.DEMove(gamma0=1.0), 0.2)]  # + mode-hopping jumps
# moves = emcee.moves.GaussianMove(cov=np.array([0.05, 0.3, 0.2])**2)         # plain Metropolis per walker
#   cov: scalar (isotropic), 1-D array (one width per parameter) or full ndim x ndim matrix

# ===== 4. RUN: save to disk, stop when converged ====================================
backend = emcee.backends.HDFBackend("chain.h5"); backend.reset(nwalkers, ndim)   # needs h5py
sampler = emcee.EnsembleSampler(nwalkers, ndim, log_prob, moves=moves, backend=backend)
# parallel:  from multiprocessing import Pool
#            with Pool() as pool: sampler = emcee.EnsembleSampler(..., pool=pool); sampler.run_mcmc(...)
old_tau = np.inf
for _ in sampler.sample(p0, iterations=20000, progress=True):
    if sampler.iteration % 200: continue
    tau = sampler.get_autocorr_time(tol=0)
    if np.all(50 * tau < sampler.iteration) and np.all(np.abs(old_tau - tau) / tau < 0.01):
        break                                # N > 50 tau and tau stable to 1%
    old_tau = tau
# continue an old run later:  sampler.run_mcmc(None, 5000)   (same backend file)

# ===== 5. OUTPUT =====================================================================
print("acceptance:", np.mean(sampler.acceptance_fraction))     # aim for 0.2-0.5
burn, thin = int(5 * tau.max()), max(1, int(tau.min() / 2))
chain = sampler.get_chain(discard=burn, thin=thin, flat=True)  # (n_samples, ndim)
logp  = sampler.get_log_prob(discard=burn, thin=thin, flat=True)
y5    = sampler.get_blobs(discard=burn, thin=thin, flat=True)  # derived quantity, no error propagation needed
q16, q50, q84 = np.percentile(chain, [16, 50, 84], axis=0)
best = chain[np.argmax(logp)]                                  # ~MAP; use the optimiser result for the true maximum
# import corner; corner.corner(chain, labels=["m", "b", "ln s"])
print("m, b, ln s =", q50.round(3), "+", (q84 - q50).round(3), "-", (q50 - q16).round(3), "  y(5) =", np.median(y5).round(3))
