"""Michaelis-Menten fitting simulation for the ProteinIQ guide on Km, Vmax and kcat.

True parameters Km = 1 and Vmax = 1 (concentrations in units of Km, rates in units of Vmax).
Eight log-spaced substrate concentrations per design. Each rate gets Gaussian noise with
SD = sqrt((0.02 Vmax)^2 + (0.05 v)^2): a 2% of Vmax floor plus 5% proportional error.
Each replicate is fitted by nonlinear least squares (scipy curve_fit, bounds 0..1e4)
and by a Lineweaver-Burk straight line through 1/v against 1/[S].
Run: python fit-simulation.py   (numpy 2.2, scipy 1.16; seed 20261109)
"""
import json
import numpy as np
from scipy.optimize import curve_fit

rng = np.random.default_rng(20261109)
N = 10000
mm = lambda s, V, K: V * s / (K + s)
designs = {
    "below_km": np.geomspace(0.05, 0.5, 8),
    "wide": np.geomspace(0.2, 5, 8),
    "saturating": np.geomspace(2, 20, 8),
}
out = {}
examples = {}
for name, s in designs.items():
    v0 = mm(s, 1.0, 1.0)
    nl, lb = [], []
    for _ in range(N):
        v = v0 + np.sqrt(0.02**2 + (0.05 * v0) ** 2) * rng.standard_normal(len(s))
        v = np.maximum(v, 1e-4)
        p, _ = curve_fit(mm, s, v, p0=[v.max() * 1.5, np.median(s)], bounds=([0, 0], [1e4, 1e4]), maxfev=20000)
        nl.append(p)
        slope, icpt = np.polyfit(1 / s, 1 / v, 1)
        lb.append([1 / icpt if icpt > 0 else np.nan, slope / icpt if icpt > 0 else np.nan, 1 / slope])
    nl, lb = np.array(nl), np.array(lb)
    pct = lambda x: [round(float(y), 3) for y in np.nanpercentile(x, [5, 50, 95])]
    out[name] = {
        "substrate_range_in_Km": [float(s[0]), float(s[-1])],
        "nonlinear": {"Km_p5_p50_p95": pct(nl[:, 1]), "Vmax_p5_p50_p95": pct(nl[:, 0]),
                       "V_over_K_p5_p50_p95": pct(nl[:, 0] / nl[:, 1]),
                       "frac_Km_off_by_2x": round(float(np.mean((nl[:, 1] > 2) | (nl[:, 1] < 0.5))), 3)},
        "lineweaver_burk": {"frac_negative_intercept": round(float(np.mean(np.isnan(lb[:, 0]))), 3),
                             "Km_p5_p50_p95_valid": pct(lb[:, 1]), "V_over_K_p5_p50_p95": pct(lb[:, 2]),
                             "frac_Km_off_by_2x_or_invalid": round(float(np.mean(np.isnan(lb[:, 1]) | (lb[:, 1] > 2) | (lb[:, 1] < 0.5))), 3)},
    }
    if name == "below_km":
        order = np.argsort(nl[:, 1])
        examples = {k: [round(float(x), 3) for x in nl[order[int(q * (N - 1))]]] for k, q in (("p5", 0.05), ("p95", 0.95))}
out["below_km_example_fits_Vmax_Km"] = examples
print(json.dumps(out, indent=2))
