#!/usr/bin/env python3
"""Numbers the reader's second check of Part 3 asked for. Writes find-film-extra-fix4.json, after every run, so a killed run leaves what it has.

free_stretch: the program with its free stretch simulate(q, f * T) for f other than 1, seeds 1-4 at noise 0.1, the rest of find_film unchanged. Is a whole period needed?
  periods is sweeps * (f + 2/3), the time simulated, the program's cost.
seed1_cos: on seed 1 as written, cos(lag, speed) at sweep 15, 20 and the last, and the ratio of rms(lag) from sweep to sweep over sweeps 18 to the last but two.
One core, about ten seconds a run: OMP_NUM_THREADS=1.
"""
import json
import os
import statistics
import sys

import numpy as np

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(HERE, 'src'))
from twisted_average import N, a, b, rate, simulate, slide, turn  # noqa: E402

OUT = os.path.join(HERE, 'results', 'find-film-extra-fix4.json')
T_STAR = 6.390159918584649
FRACS = [('1/4', 0.25), ('1/3', 1 / 3), ('1/2', 0.5), ('1', 1.0), ('3/2', 1.5)]
SEEDS = [1, 2, 3, 4]


def run(seed, frac, trace=None, cap=200):
    q = np.array([a, b / a])[:, None, None] + 0.1 * np.random.default_rng(seed).standard_normal((2, N, N))
    q = (q + turn(q) + turn(turn(q))) / 3
    T = 6.355
    for sweep in range(1, cap + 1):
        q = simulate(q, frac * T)
        third = simulate(q, T / 3)
        two_thirds = simulate(third, T / 3)
        lag = slide(third) - q
        e = float(np.sqrt(np.mean(lag * lag)))
        speed = rate(q)
        if trace is not None:
            trace.append({'sweep': sweep, 'rms': e, 'cos': float(np.sum(lag * speed) / np.sqrt(np.sum(lag * lag) * np.sum(speed * speed)))})
        if e < 1e-10:
            return {'status': 'returned', 'sweeps': sweep, 'T': float(T), 'std_u': float(np.std(q[0]))}
        T -= np.clip(3 * np.sum(lag * speed) / np.sum(speed * speed), -0.1, 0.1)
        q = (q + slide(third) + slide(slide(two_thirds))) / 3
    return {'status': 'cap', 'sweeps': cap, 'T': float(T), 'std_u': float(np.std(q[0]))}


out = {'about': __doc__, 'free_stretch': {'seeds': '1-4', 'rows': []}, 'seed1_cos': {}}


def save():
    with open(OUT + '.tmp', 'w') as f:
        json.dump(out, f, indent=1)
    os.replace(OUT + '.tmp', OUT)


trace = []
base = run(1, 1.0, trace)
rows = {r['sweep']: r for r in trace}
last = trace[-1]['sweep']
ratios = [rows[s]['rms'] / rows[s - 1]['rms'] for s in range(18, last - 1)]
out['seed1_cos'] = {'sweeps': last, 'cos_at_15': rows[15]['cos'], 'cos_at_20': rows[20]['cos'], 'cos_at_last': rows[last]['cos'], 'rms_ratio_median_18_to_last_but_two': statistics.median(ratios)}
save()
print(base, out['seed1_cos'], flush=True)

for name, frac in FRACS:
    per = [dict(seed=s, **run(s, frac)) for s in SEEDS]
    on_film = [p for p in per if p['status'] == 'returned' and abs(p['T'] - T_STAR) < 1e-6]
    sw = [p['sweeps'] for p in per]
    out['free_stretch']['rows'].append({'name': name, 'f': frac, 'on_film': len(on_film), 'n': len(per), 'sweeps_median': statistics.median(sw), 'sweeps_min': min(sw), 'sweeps_max': max(sw), 'periods_median': statistics.median(sw) * (frac + 2 / 3), 'runs': per})
    save()
    print(name, out['free_stretch']['rows'][-1], flush=True)
