#!/usr/bin/env python3
import importlib.util, json, math, statistics, pathlib, html, datetime, sys, hashlib
ROOT = pathlib.Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("noether_base", ROOT / "noether_x_independent_benchmark.py")
base = importlib.util.module_from_spec(spec); sys.modules[spec.name] = base; spec.loader.exec_module(base)
DT = base.DT * base.DOWNSAMPLE
MAX_K = 22
THEILER_SECONDS = [0.40, 0.80, 1.20]
FIT_WINDOWS = [(0.16,0.56),(0.16,0.72),(0.24,0.72),(0.24,0.88)]
START_STRIDE = 3

def line_fit(xs, ys):
    mx,my=statistics.mean(xs),statistics.mean(ys)
    den=sum((x-mx)**2 for x in xs)
    if den<1e-15: return {"slope":0.0,"intercept":my,"r2":0.0}
    slope=sum((x-mx)*(y-my) for x,y in zip(xs,ys))/den
    intercept=my-slope*mx
    sse=sum((y-intercept-slope*x)**2 for x,y in zip(xs,ys))
    sst=sum((y-my)**2 for y in ys)
    return {"slope":slope,"intercept":intercept,"r2":1-sse/sst if sst>1e-15 else 0.0}

def longest_run(samples):
    runs=[]; cur=[]
    for r in samples:
        if cur and abs((r["t"]-cur[-1]["t"])-DT)>1e-5:
            runs.append(cur); cur=[]
        cur.append(r)
    if cur:runs.append(cur)
    return max(runs,key=len),[len(x) for x in runs]

def normalize(rows):
    keys=["q1","q2","w1","w2"]
    means=[statistics.mean(r[k] for r in rows) for k in keys]
    stds=[statistics.pstdev(r[k] for r in rows) for k in keys]
    if any(x<1e-10 for x in stds): raise ValueError("degenerate state coordinate")
    X=[[ (r[k]-means[d])/stds[d] for d,k in enumerate(keys)] for r in rows]
    return X,stds

def divergence(X,theiler):
    n=len(X); end=n-MAX_K
    starts=range(0,end,START_STRIDE); pairs=[]
    for i in starts:
        a=X[i]; best=-1; bestd=float("inf")
        for j in range(end):
            if abs(i-j)<=theiler: continue
            b=X[j]
            d=(a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2+(a[3]-b[3])**2
            if d<bestd: best,bestd=j,d
        if best>=0 and bestd>1e-18:pairs.append((i,best))
    if len(pairs)<100: raise ValueError("insufficient neighbor pairs: "+str(len(pairs)))
    curve=[]
    for k in range(MAX_K+1):
        vals=[]
        for i,j in pairs:
            a,b=X[i+k],X[j+k]
            d=math.sqrt(sum((a[c]-b[c])**2 for c in range(4)))
            vals.append(math.log(max(d,1e-12)))
        curve.append(statistics.mean(vals))
    fits={}
    for lo,hi in FIT_WINDOWS:
        ks=[k for k in range(MAX_K+1) if lo-1e-9<=k*DT<=hi+1e-9]
        f=line_fit([k*DT for k in ks],[curve[k] for k in ks])
        fits[f"{lo:.2f}-{hi:.2f}s"]={**f,"points":len(ks)}
    return {"theiler_samples":theiler,"theiler_seconds":theiler*DT,"neighbor_pairs":len(pairs),"curve_ln_distance":curve,"curve_time_s":[k*DT for k in range(MAX_K+1)],"fits":fits}

def main():
    trials={}
    for t in (1,2,3):
        samples,prep=base.prepare_trial(t)
        rows,runs=longest_run(samples)
        if len(rows)<500: raise ValueError("trial "+str(t)+" too few contiguous rows")
        X,stds=normalize(rows); sensitivity=[]; windows={}
        for sec in THEILER_SECONDS:
            res=divergence(X,round(sec/DT)); windows[f"{sec:.2f}s"]=res
            for wn,f in res["fits"].items():
                sensitivity.append({"theiler_s":sec,"fit_window":wn,"lambda_per_s":f["slope"],"r2":f["r2"]})
        primary=windows["0.80s"]["fits"]["0.16-0.72s"]
        slopes=[x["lambda_per_s"] for x in sensitivity]
        trials[str(t)]={
            "preparation":prep,"contiguous_run_lengths":runs,"longest_contiguous_samples":len(rows),
            "effective_duration_s":(len(rows)-1)*DT,"state_variables":["q1_rad","q2_rad","w1_rad_per_s","w2_rad_per_s"],
            "state_standard_deviations":dict(zip(["q1","q2","w1","w2"],stds)),
            "theiler_sensitivity":windows,
            "primary_estimate":{"theiler_window_s":0.8,"fit_window_s":"0.16-0.72s","lambda_max_per_s":primary["slope"],"r2":primary["r2"],"doubling_time_s":math.log(2)/primary["slope"] if primary["slope"]>0 else None},
            "sensitivity_range_lambda_per_s":[min(slopes),max(slopes)],
            "all_sensitivity_slopes_positive":all(x>0 for x in slopes),
            "median_sensitivity_r2":statistics.median(x["r2"] for x in sensitivity)
        }
    prim=[trials[str(t)]["primary_estimate"]["lambda_max_per_s"] for t in (1,2,3)]
    r2=[trials[str(t)]["primary_estimate"]["r2"] for t in (1,2,3)]
    robust=all(x>0 for x in prim) and all(x>=0.80 for x in r2) and all(trials[str(t)]["all_sensitivity_slopes_positive"] for t in (1,2,3))
    overall={"mean_primary_lambda_per_s":statistics.mean(prim),"median_primary_lambda_per_s":statistics.median(prim),
      "primary_lambda_range_per_s":[min(prim),max(prim)],"primary_r2_range":[min(r2),max(r2)],
      "all_trial_primary_estimates_positive":all(x>0 for x in prim),
      "all_theiler_and_fit_window_sensitivity_slopes_positive":all(trials[str(t)]["all_sensitivity_slopes_positive"] for t in (1,2,3)),
      "robust_positive_finite_time_divergence":robust,
      "interpretation":"positive finite-time divergence is supported across all three recordings and tested parameter windows; consistent with sensitive dependence, not a stand-alone proof of deterministic chaos" if robust else "estimate is not robust across recordings and parameter windows; no positive-chaos claim is justified"}
    result={"schema_version":"1.0.0","study":"noether-x-independent-double-pendulum","analysis":"finite-time largest Lyapunov estimate from measured 4D phase state",
      "date_utc":datetime.datetime.now(datetime.timezone.utc).isoformat(),
      "method":{"name":"Rosenstein-style nearest-neighbor divergence","reference":"Rosenstein, Collins & De Luca, Physica D 65 (1993), 117-134, DOI 10.1016/0167-2789(93)90009-P",
      "state":"q1, q2, w1, w2 from camera-angle measurements and local polynomial differentiation; standardized within trial",
      "sampling_interval_s":DT,"sampling_rate_hz":1/DT,"maximum_divergence_horizon_s":MAX_K*DT,
      "theiler_windows_s":THEILER_SECONDS,"fit_windows_s":FIT_WINDOWS,"reference_start_stride_samples":START_STRIDE,
      "gap_handling":"only the longest contiguous retained segment in each trial","cross_trial_pairing":False},
      "overall":overall,"trials":trials,
      "limitations":["Finite noisy recordings cannot by themselves establish deterministic chaos.",
      "Velocities are locally polynomial derivatives of processed camera angles.","Data are downsampled to 25 Hz; raw 6.77 GB high-speed video was not downloaded.",
      "Three recordings are analyzed separately, not treated as matched perturbed initial-condition pairs.",
      "No surrogate-data test or independent variational-equation Lyapunov calculation is included."]}
    out=ROOT/"results"/"lyapunov_analysis.json"; out.parent.mkdir(exist_ok=True)
    md=["# Finite-time Lyapunov analysis — independent double-pendulum data","",f"Run date UTC: {result['date_utc']}","","## Result", "",overall["interpretation"],"",
      f"- Mean primary estimate: **{overall['mean_primary_lambda_per_s']:.4f} s⁻¹**",
      f"- Trial range: **{overall['primary_lambda_range_per_s'][0]:.4f}–{overall['primary_lambda_range_per_s'][1]:.4f} s⁻¹**",
      f"- Primary-fit R² range: **{overall['primary_r2_range'][0]:.3f}–{overall['primary_r2_range'][1]:.3f}**",
      f"- Robust positive result across tested parameter combinations: **{str(robust).upper()}**","","## Per-trial results",
      "| Trial | λmax (s⁻¹) | Doubling time (s) | R² | Contiguous points | Sensitivity range (s⁻¹) |","|---:|---:|---:|---:|---:|---:|"]
    for t in (1,2,3):
        x=trials[str(t)]; p=x["primary_estimate"]; d=f"{p['doubling_time_s']:.3f}" if p["doubling_time_s"] else "not positive"
        md.append(f"| {t} | {p['lambda_max_per_s']:.4f} | {d} | {p['r2']:.3f} | {x['longest_contiguous_samples']} | {x['sensitivity_range_lambda_per_s'][0]:.4f} to {x['sensitivity_range_lambda_per_s'][1]:.4f} |")
    md += ["","## Protocol","",
      "The measured phase state is (q1, q2, w1, w2). Coordinates are standardized within each trial. For each reference point, the nearest state-space neighbor is selected while excluding temporal neighbors within a Theiler window. Mean log-distance is tracked forward in time; its local linear slope estimates finite-time largest Lyapunov divergence. The method follows the experimental-time-series approach of Rosenstein, Collins and De Luca (1993).","",
      f"Sampling interval: {DT:.3f} s (25 Hz). Theiler windows: 0.40, 0.80 and 1.20 s. Linear-fit windows: 0.16–0.56, 0.16–0.72, 0.24–0.72 and 0.24–0.88 s. Only each recording's longest contiguous retained segment is used. No neighbor pairs are formed across trials.","",
      "## Interpretation boundary","",
      "Positive, approximately linear early-time divergence is consistent with sensitive dependence on initial conditions. It is not, by itself, proof that the observed finite recordings are generated by a deterministic chaotic attractor. Estimates are sensitive to measurement noise, derivative smoothing, sampling rate, neighbor exclusion and the selected linear-fit interval. Surrogate-data and variational-equation tests are not included.","",
      "The raw high-speed video (6.77 GB) was not downloaded because the production server's root filesystem was critically full. Processed camera-angle streams and previously validated encoder calibration were reused.","",
      "## Sources","",
      "- Dataset: [Mendeley Data, Double Pendulum Design and Data Repository, v2](https://data.mendeley.com/datasets/z4hvxjgtbz/2)",
      "- Experimental apparatus: [HardwareX article](https://pmc.ncbi.nlm.nih.gov/articles/PMC9041261/)",
      "- Estimator: [Rosenstein, Collins & De Luca (1993), DOI](https://doi.org/10.1016/0167-2789(93)90009-P)",
      "- Parent benchmark: [Noether-X independent double-pendulum report](report.html)","","Reproducibility: see lyapunov_analysis.json and lyapunov_analysis.py."]
    markdown="\n".join(md)+"\n"
    out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+"\n")
    (out.parent/"lyapunov_analysis.md").write_text(markdown)
    print(json.dumps({"status":"COMPUTED","overall":overall,"trials":{k:{"lambda":v["primary_estimate"]["lambda_max_per_s"],"r2":v["primary_estimate"]["r2"],"n":v["longest_contiguous_samples"],"sensitivity_range":v["sensitivity_range_lambda_per_s"],"all_positive":v["all_sensitivity_slopes_positive"]} for k,v in trials.items()}},ensure_ascii=False))
    site=pathlib.Path("/opt/darkoza/science-site/reports/noether-x-independent-double-pendulum"); site.mkdir(parents=True,exist_ok=True)
    (site/"lyapunov_analysis.json").write_text(json.dumps(result,ensure_ascii=False,indent=2)+"\n")
    (site/"lyapunov_analysis.md").write_text(markdown)
    (site/"lyapunov_analysis.py").write_text(pathlib.Path(__file__).read_text())
    rows="".join("<tr><td>{}</td><td>{:.4f}</td><td>{}</td><td>{:.3f}</td><td>{}</td></tr>".format(t,trials[str(t)]["primary_estimate"]["lambda_max_per_s"],("{:.3f}".format(trials[str(t)]["primary_estimate"]["doubling_time_s"]) if trials[str(t)]["primary_estimate"]["doubling_time_s"] else "—"),trials[str(t)]["primary_estimate"]["r2"],trials[str(t)]["longest_contiguous_samples"]) for t in (1,2,3))
    label="Positive finite-time divergence supported" if robust else "Inconclusive / not robust enough"
    page="""<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Lyapunov Analysis — Noether-X</title><style>body{font:16px/1.65 system-ui,sans-serif;max-width:920px;margin:40px auto;padding:0 20px;color:#18202a;background:#fafbfc}h1,h2{line-height:1.2}table{border-collapse:collapse;width:100%;margin:18px 0}th,td{padding:10px;border-bottom:1px solid #d9dee5;text-align:left}a{color:#145da0}.note{padding:14px;border-left:3px solid #64748b;background:#f0f3f6}</style><p><a href="report.html">← Parent benchmark report</a></p><h1>Finite-time Lyapunov analysis</h1><p>Independent real-data double-pendulum study · 15 November 2026</p><h2>Result</h2><p><strong>"""+html.escape(label)+"""</strong></p><p>Mean primary estimate: <strong>"""+f"{overall['mean_primary_lambda_per_s']:.4f}"+""" s⁻¹</strong>; trial range: <strong>"""+f"{overall['primary_lambda_range_per_s'][0]:.4f}–{overall['primary_lambda_range_per_s'][1]:.4f}"+""" s⁻¹</strong>; primary-fit R² range: <strong>"""+f"{overall['primary_r2_range'][0]:.3f}–{overall['primary_r2_range'][1]:.3f}"+"""</strong>.</p><table><thead><tr><th>Trial</th><th>λmax (s⁻¹)</th><th>Doubling time (s)</th><th>R²</th><th>Points</th></tr></thead><tbody>"""+rows+"""</tbody></table><h2>Method</h2><p>Rosenstein-style nearest-neighbor divergence in each recording's measured four-dimensional phase state (q1, q2, w1, w2). States are standardized within trial; temporal neighbors are excluded using Theiler windows of 0.40, 0.80 and 1.20 s. Mean log separation is followed over 0.88 s; slopes are evaluated over four early-time windows. Sampling interval is 0.040 s (25 Hz). Each trial is analyzed independently using its longest contiguous retained segment.</p><div class="note"><strong>Interpretation boundary:</strong> positive finite-time divergence is consistent with sensitivity to initial conditions, but finite noisy recordings alone do not prove a deterministic chaotic attractor. Measurement noise, derivative smoothing, sampling and fit-window choice remain limitations. No surrogate-data or independent variational-equation test was performed in this pass.</div><h2>Reproducibility and sources</h2><p><a href="lyapunov_analysis.json">Machine-readable results</a> · <a href="lyapunov_analysis.md">Full protocol and report</a> · <a href="lyapunov_analysis.py">Analysis source</a></p><p><a href="https://data.mendeley.com/datasets/z4hvxjgtbz/2">Mendeley dataset</a> · <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC9041261/">HardwareX paper</a> · <a href="https://doi.org/10.1016/0167-2789(93)90009-P">Rosenstein et al. (1993)</a></p></html>"""
    (site/"lyapunov_analysis.html").write_text(page)
    parent=site/"report.html"
    if parent.exists():
        old=parent.read_text()
        if 'href="lyapunov_analysis.html"' not in old:
            link='<p><a href="lyapunov_analysis.html">Finite-time Lyapunov / sensitivity analysis addendum</a></p>'
            old=old.replace("</body>",link+"</body>",1) if "</body>" in old else old+link
            parent.write_text(old)
    for root in [pathlib.Path("/opt/darkoza/science-site"),pathlib.Path("/opt/darkoza/science-api-site/v1")]:
        manifest=root/"SHA256SUMS.txt"
        files=sorted(p for p in root.rglob("*") if p.is_file() and p!=manifest)
        manifest.write_text("".join(hashlib.sha256(p.read_bytes()).hexdigest()+"  "+str(p.relative_to(root))+"\n" for p in files))
    print("PUBLISHED_FILES_AND_MANIFESTS_OK")
    print("PUBLIC_URL=https://darkoza.com/science/reports/noether-x-independent-double-pendulum/lyapunov_analysis.html")
if __name__=="__main__": main()
