"""Independent reconstruction of Section 6 of Carmona & Laurière, SIAM Review (2026).

Run python reproduce.py --help for paths, independent repetitions, policy and seed.
Uses the same physical Brownian increments within every paired comparison.
"""
import argparse
import csv
import json
import platform
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np


HORIZON = 5.0
STEPS = tuple(10 * 2**k for k in range(8))
CONTROL = (0.01, 0.05, 0.10, 0.20)
NODES, WEIGHTS = np.polynomial.hermite.hermgauss(10)
NORMAL_WEIGHTS = WEIGHTS / np.sqrt(np.pi)
PUBLISHED_MEANS = {
    'linear': [0.577, 0.281, 0.144, 0.0747, 0.0386, 0.0198, 0.0101, 0.00512],
    'tanh': [0.342, 0.177, 0.0932, 0.0485, 0.0251, 0.0128, 0.00653, 0.00331],
    'mean_0.20': [0.430, 0.262, 0.177, 0.135, 0.114, 0.105, 0.101, 0.0982],
    'rms_0.20': [0.408, 0.237, 0.151, 0.108, 0.0871, 0.0772, 0.0728, 0.0708],
}
PUBLISHED_SLOPES = {
    'mean_0.01': -0.946, 'rms_0.01': -0.947, 'mean_0.05': -0.806, 'rms_0.05': -0.811,
    'mean_0.10': -0.588, 'rms_0.10': -0.612, 'mean_0.20': -0.290, 'rms_0.20': -0.350,
}


def tanh_gh10(mu, sd):
    """Ten-point Gauss–Hermite approximation to E[tanh(mu + sd Z)], Z standard normal."""
    average = np.zeros_like(mu)
    for node, weight in zip(NODES, NORMAL_WEIGHTS):
        average += weight * np.tanh(mu + np.sqrt(2) * sd * node)
    return average


def simulate_run(job):
    n, run, kind, c, paths, sd, init, seed = job
    rng_init, rng_action, rng_w = [np.random.default_rng(s) for s in
                                  np.random.SeedSequence([seed, n, run]).spawn(3)]
    h = HORIZON / n
    sqrt_h = np.sqrt(h)
    # In setting 1 the exact difference recursion eliminates X0 and W.
    if kind == 'linear':
        delta = np.zeros(paths)
        peak = np.zeros(paths)
        for _ in range(n):
            delta = (1 - h) * delta + h * sd * rng_action.standard_normal(paths)
            np.maximum(peak, np.abs(delta), out=peak)
        return n, run, {'linear': np.mean(peak**2)}
    if init == 'normal':
        sampled = rng_init.normal(1.0, np.sqrt(0.5), paths)
    elif init == 'uniform':
        sampled = rng_init.uniform(0.5, 1.5, paths)
    else:
        sampled = np.full(paths, float(init))
    relaxed_mean = sampled.copy()
    relaxed_rms = sampled.copy()
    peak_mean = np.zeros(paths)
    peak_rms = np.zeros(paths)
    for _ in range(n):
        a = 1 - sampled + sd * rng_action.standard_normal(paths)
        dw = sqrt_h * rng_w.standard_normal(paths)
        sampled += h * np.tanh(a) + (0.1 + c * a) * dw
        mu = 1 - relaxed_mean
        relaxed_mean += h * tanh_gh10(mu, sd) + (0.1 + c * mu) * dw
        np.maximum(peak_mean, np.abs(sampled - relaxed_mean), out=peak_mean)
        if kind == 'controlled':
            mu = 1 - relaxed_rms
            volatility = np.sqrt((0.1 + c * mu)**2 + (c * sd)**2)
            relaxed_rms += h * tanh_gh10(mu, sd) + volatility * dw
            np.maximum(peak_rms, np.abs(sampled - relaxed_rms), out=peak_rms)
    if kind == 'tanh':
        return n, run, {'tanh': np.mean(peak_mean**2)}
    return n, run, {f'mean_{c:.2f}': np.mean(peak_mean**2), f'rms_{c:.2f}': np.mean(peak_rms**2)}


def lines_plot():
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    return plt


def error_figure(out, rows):
    plt = lines_plot()
    fig, axes = plt.subplots(1, 3, figsize=(12.6, 4.05), constrained_layout=True)
    panels = [
        ('(a) Action enters the drift', [('linear', 'Linear'), ('tanh', 'tanh')]),
        ('(b) Controlled volatility, c = 0.20', [('mean_0.20', 'Mean (7.1)'), ('rms_0.20', 'RMS (7.5)')]),
        ('(c) RMS (7.5) by control strength', [(f'rms_{c:.2f}', f'c = {c:.2f}') for c in CONTROL]),
    ]
    colors = ('#006e83', '#b44f20', '#69933f', '#7054a0')
    for p, (ax, (title, curves)) in enumerate(zip(axes, panels)):
        for (curve, label), color in zip(curves, colors):
            subset = [r for r in rows if r['curve'] == curve]
            ax.loglog(STEPS, [r['estimate'] for r in subset], '-o', ms=4, color=color, label=label)
            if curve in PUBLISHED_MEANS and p != 2:
                ax.loglog(STEPS, PUBLISHED_MEANS[curve], '--s', color=color, ms=5,
                          markerfacecolor='none', alpha=0.82)
        ax.set_title(title, fontsize=10, loc='left')
        ax.set_xlabel('Number of time steps N')
        ax.grid(True, which='major', alpha=.23)
        ax.legend(fontsize=8, frameon=False)
    axes[0].set_ylabel('Mean squared maximum grid discrepancy')
    fig.suptitle('Solid circles: independent simulation        Dashed squares: published tables',
                 fontsize=10)
    fig.savefig(out / 'errors.png', dpi=190)
    plt.close(fig)


def trajectory_figure(out, sd, seed):
    plt = lines_plot()
    fine_n = 1000
    initial = np.array([0.5, 0.8, 1.2, 1.5])
    rng_w, rng_z = [np.random.default_rng(s) for s in np.random.SeedSequence([seed, 9999]).spawn(2)]
    fine_dw = np.sqrt(HORIZON / fine_n) * rng_w.standard_normal((fine_n, len(initial)))
    fine_z = rng_z.standard_normal((fine_n, len(initial)))
    fig, axes = plt.subplots(1, 3, figsize=(12.6, 3.65), sharey=True, constrained_layout=True)
    for ax, n, linear in zip(axes, (100, 1000, 1000), (True, True, False)):
        stride = fine_n // n
        dw = fine_dw.reshape(n, stride, -1).sum(axis=1)
        # This choice correlates coarse/fine action seeds and preserves their standard normal marginals.
        z = fine_z.reshape(n, stride, -1).sum(axis=1) / np.sqrt(stride)
        sampled = np.empty((n + 1, 4))
        relaxed = np.empty_like(sampled)
        sampled[0] = relaxed[0] = initial
        for k in range(n):
            a = 1 - sampled[k] + sd * z[k]
            b = a if linear else np.tanh(a)
            mu = 1 - relaxed[k]
            avg = mu if linear else tanh_gh10(mu, sd)
            sampled[k+1] = sampled[k] + (HORIZON/n)*b + .1*dw[k]
            relaxed[k+1] = relaxed[k] + (HORIZON/n)*avg + .1*dw[k]
        time = np.linspace(0, HORIZON, n + 1)
        for i, color in enumerate(('#006e83', '#b44f20', '#69933f', '#7054a0')):
            ax.plot(time, sampled[:, i], color=color, lw=.95)
            ax.plot(time, relaxed[:, i], '--', color=color, lw=1.35)
        ax.set_title(f'{"Linear" if linear else "tanh"} drift, N = {n}',fontsize=10)
        ax.set_xlabel('Time')
        ax.grid(alpha=.18)
    axes[0].set_ylabel('State')
    fig.suptitle('Four paired paths per panel: sampled actions (solid), relaxed Euler (dashed)',fontsize=10)
    fig.savefig(out / 'trajectories.png', dpi=190)
    plt.close(fig)


def write_csv(path, rows):
    with path.open('w', encoding='utf-8', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)


def main():
    import scipy
    import matplotlib
    from scipy.stats import linregress, t
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--paths', type=int, default=10000, help='paths per independent run')
    parser.add_argument('--repeats', type=int, default=5, help='runs for settings 2 and 3')
    parser.add_argument('--linear-repeats', type=int, default=10, help='runs for setting 1')
    parser.add_argument('--sd', type=float, default=np.sqrt(0.5), help='action standard deviation')
    parser.add_argument('--initial', default='normal',
                        help="normal (mean 1, variance 0.5), uniform on [0.5,1.5], or a constant e.g. 1")
    parser.add_argument('--seed', type=int, default=1782856)
    parser.add_argument('--workers', type=int, default=4)
    parser.add_argument('--out', type=Path, default=Path(__file__).resolve().parent / 'results')
    args = parser.parse_args()
    if min(args.paths,args.workers)<1 or min(args.repeats,args.linear_repeats)<2 or args.sd<=0 or not np.isfinite(args.sd) or args.seed<0:
        parser.error('positive paths/workers/sd, nonnegative seed and at least two runs are required')
    if args.initial not in ('normal', 'uniform'):
        try:
            if not np.isfinite(float(args.initial)):
                raise ValueError
        except ValueError:
            parser.error('initial must be normal, uniform or a finite number')
    cases = [('linear', 0.0), ('tanh', 0.0)] + [('controlled', c) for c in CONTROL]
    jobs = [(n, r, kind, c, args.paths, args.sd, args.initial, args.seed)
            for n in STEPS for kind, c in cases
            for r in range(args.linear_repeats if kind=='linear' else args.repeats)]
    results = {}
    with ProcessPoolExecutor(max_workers=args.workers) as pool:
        for n, run, estimates in pool.map(simulate_run, jobs):
            for curve, estimate in estimates.items():
                results.setdefault((curve, n), []).append(float(estimate))
            if 'rms_0.20' in estimates and run == args.repeats-1:
                print(f'Completed N = {n}', flush=True)
    args.out.mkdir(parents=True, exist_ok=True)
    curves = ['linear', 'tanh'] + [f'{m}_{c:.2f}' for c in CONTROL for m in ('mean','rms')]
    rows, slopes = [], []
    for curve in curves:
        estimates = []
        for k, n in enumerate(STEPS):
            group = results[curve, n]
            estimate, std = float(np.mean(group)), float(np.std(group, ddof=1))
            estimates.append(estimate)
            reported = PUBLISHED_MEANS.get(curve, [None]*8)[k]
            rows.append(dict(curve=curve, steps=n, runs=len(group), paths_per_run=args.paths,
                             estimate=estimate, sd_across_run_means=std, mc_se=std/np.sqrt(len(group)),
                             published=reported, relative_difference=estimate/reported-1 if reported else None))
        fit = linregress(np.log(STEPS), np.log(estimates))
        halfwidth = t.ppf(.975, len(STEPS)-2) * fit.stderr
        tables_fit = None
        if curve in PUBLISHED_MEANS:
            tables_fit = linregress(np.log(STEPS), np.log(PUBLISHED_MEANS[curve])).slope
        slopes.append(dict(curve=curve, estimate=fit.slope, ci_low=fit.slope-halfwidth,
                           ci_high=fit.slope+halfwidth, published_table4=PUBLISHED_SLOPES.get(curve),
                           refit_rounded_published_means=tables_fit))
    write_csv(args.out / 'errors.csv', rows)
    write_csv(args.out / 'slopes.csv', slopes)
    error_figure(args.out, rows)
    trajectory_figure(args.out, args.sd, args.seed)
    config = dict(paths_per_run=args.paths, repeats_settings_2_3=args.repeats,
                  repeats_setting_1=args.linear_repeats, action_sd=args.sd, initial=args.initial,
                  seed=args.seed, workers=args.workers, quadrature='direct 10-point Gauss-Hermite',
                  T=HORIZON, steps=STEPS, controlled_volatility_strengths=CONTROL,
                  python=platform.python_version(), numpy=np.__version__, scipy=scipy.__version__,
                  matplotlib=matplotlib.__version__)
    (args.out / 'config.json').write_text(json.dumps(config, indent=2), encoding='utf-8')
    for row in slopes:
        print(f"{row['curve']:>10}  slope {row['estimate']:.4f}", flush=True)


if __name__ == '__main__':
    main()
