"""Reproduce the integral-strain NN/PINN demonstration (NumPy + SciPy).

Both networks learn epsilon(x,a,T) and N(x,a,T). Displacement is the
Gauss-Legendre integral of the learned epsilon, so u(0)=0 by construction.
N(1)=T is imposed on both. Only the PINN sees equilibrium and constitutive
residuals. No reference strain/displacement fields enter optimization.

Run: OPENBLAS_NUM_THREADS=1 python3 scripts/generate-parametric-pinn.py
"""
import argparse, hashlib, importlib.util, json, time
from pathlib import Path
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy.integrate import cumulative_trapezoid

ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('learning', Path(__file__).with_name('generate-learning-replays.py'))
learning = importlib.util.module_from_spec(spec)
spec.loader.exec_module(learning)
Net = learning.Net
BETA = .6
DERIVATIVE_H = .001
QUADRATURE_ORDER = 64


def geometry(x, a):
    return .065*a*np.sin(4*np.pi*x)


def stiffness(x, a):
    slope = .065*a*4*np.pi*np.cos(4*np.pi*x)
    return (1-.42*np.exp(-((x-.62)/.09)**2))/(1+slope*slope)**1.5


def body(x, t):
    return .18*t*(1+.4*np.sin(2*np.pi*x))


def reference(x, a, t, n=4001):
    z = np.linspace(0, 1, n)
    force = t*(1+.18*(1-z)+.072*(np.cos(2*np.pi*z)-1)/(2*np.pi))
    k = stiffness(z, a)
    strain = force/k
    for _ in range(20):
        strain -= (strain+BETA*strain**3-force/k)/(1+3*BETA*strain**2)
    u = cumulative_trapezoid(strain, z, initial=0)
    return np.interp(x, z, u), np.interp(x, z, force), np.interp(x, z, strain)


def inputs(x, a, t):
    x, a, t = np.broadcast_arrays(x, a, t)
    fields = [2*x-1, (a-1)/.5, (t-.7)/.4]
    for frequency in [2, 4, 8]:
        fields.extend([np.sin(frequency*np.pi*x), np.cos(frequency*np.pi*x)])
    fields.append(np.exp(-((x-.62)/.09)**2))
    return np.stack(fields, -1)


def forward(net, x, a, t):
    raw, cache = net.forward(inputs(x, a, t))
    return np.stack((raw[:, 0], t+(1-x)*raw[:, 1]), -1), (cache, x)


def backward(net, dy, cache):
    inner, x = cache
    net.backward(dy*np.stack((np.ones_like(x), 1-x), -1), inner)


def integration_grid(x, a, t, order=QUADRATURE_ORDER):
    nodes, weights = leggauss(order)
    return ((x[:, None]*(nodes+1)/2).ravel(),
            np.broadcast_to(a[:, None], (len(x), order)).ravel(),
            np.broadcast_to(t[:, None], (len(x), order)).ravel(),
            x[:, None]*weights/2)


def displacement(net, x, a, t, order=QUADRATURE_ORDER):
    qx, qa, qt, weights = integration_grid(x, a, t, order)
    eps = forward(net, qx, qa, qt)[0][:, 0].reshape(weights.shape)
    return np.sum(weights*eps, axis=1)


def loss_grad(net, quadrature, targets, loads, xc, ac, tc, physics):
    net.zero()
    qx, qa, qt, weights = quadrature
    field, cache = forward(net, qx, qa, qt)
    prediction = np.sum(field[:, 0].reshape(weights.shape)*weights, axis=1)
    residual = (prediction-targets)/loads
    loss = float(np.mean(residual**2))
    grad = np.zeros_like(field)
    grad[:, 0] = (2*residual[:, None]*weights/(len(targets)*loads[:, None])).ravel()
    backward(net, grad, cache)
    terms = {'data': loss}
    if physics:
        center, cc = forward(net, xc, ac, tc)
        plus, cp = forward(net, xc+DERIVATIVE_H, ac, tc)
        minus, cm = forward(net, xc-DERIVATIVE_H, ac, tc)
        strain, force = center.T
        k = stiffness(xc, ac)
        rc = (k*(strain+BETA*strain**3)-force)/tc
        re = ((plus[:, 1]-minus[:, 1])/(2*DERIVATIVE_H)+body(xc, tc))/tc
        weight = .5
        terms.update(constitutive=float(np.mean(rc**2)), equilibrium=float(np.mean(re**2)))
        loss += weight*(terms['constitutive']+terms['equilibrium'])
        dc = 2*weight*rc/(len(xc)*tc)
        de = 2*weight*re/(len(xc)*tc)
        backward(net, np.stack((dc*k*(1+3*BETA*strain**2), -dc), -1), cc)
        gp = np.zeros_like(plus)
        gp[:, 1] = de/(2*DERIVATIVE_H)
        backward(net, gp, cp)
        backward(net, -gp, cm)
    return loss, terms


def observed_data(seed=11):
    rng = np.random.default_rng(seed)
    x = np.linspace(0, 1, 161)
    obsx = np.array([.06, .15, .24, .33, .43, .54])
    train = [(a, t) for a in [.6, 1., 1.4] for t in [.45, .95]]
    test = [(a, t) for a in [.8, 1.2] for t in [.45, .7, .95]]
    specimens, xt, at, tt, yt = [], [], [], [], []
    for i, (a, t) in enumerate(train+test):
        u, n, strain = reference(x, a, t)
        obs = reference(obsx, a, t)[0]+rng.normal(0, .003, len(obsx)) if i < len(train) else np.array([])
        if len(obs):
            xt.extend(obsx); at.extend([a]*len(obs)); tt.extend([t]*len(obs)); yt.extend(obs)
        specimens.append({'id': f'G{i+1:02d}', 'split': 'train' if i < len(train) else 'test',
            'amplitude': a, 'load': t, 'geometry': learning.rounded(geometry(x, a)),
            'stiffness': learning.rounded(stiffness(x, a)), 'truth': learning.rounded(u),
            'force': learning.rounded(n), 'strain': learning.rounded(strain),
            'training_x': learning.rounded(obsx) if len(obs) else [], 'training_y': learning.rounded(obs)})
    return x, specimens, tuple(map(np.asarray, (xt, at, tt, yt))), rng


def generate(steps=8000, out=None, model_seed=11):
    started = time.monotonic()
    x, specimens, (xt, at, tt, yt), rng = observed_data()
    q = integration_grid(xt, at, tt)
    models = [Net('mlp', inputs=10, outputs=2, width=48, seed=model_seed) for _ in range(2)]
    if model_seed != 11:
        rng = np.random.default_rng(model_seed)
    checkpoints = set([0, 1, 5, 10, 25, 50, 100, 200, 400]+list(range(600, steps+1, 200))+[steps])
    frames = []
    # Fixed independent physics-only validation grid; no reference labels.
    vrng = np.random.default_rng(271828)
    vx, va, vt = vrng.uniform(.002, .998, 1024), vrng.uniform(.6, 1.4, 1024), vrng.uniform(.45, .95, 1024)
    validation = []
    for step in range(steps+1):
        if step in checkpoints:
            predictions, scores, strains, strain_scores, train_scores = [], [], [], [], []
            for model in models:
                pp = [displacement(model, x, np.full_like(x, s['amplitude']), np.full_like(x, s['load'])) for s in specimens]
                ep = [forward(model, x, np.full_like(x, s['amplitude']), np.full_like(x, s['load']))[0][:, 0] for s in specimens]
                predictions.append(learning.rounded(pp)); strains.append(learning.rounded(ep))
                scores.append([learning.score(p, np.asarray(s['truth'])) for p, s in zip(pp, specimens)])
                strain_scores.append([learning.score(p, np.asarray(s['strain'])) for p, s in zip(ep, specimens)])
                train_scores.append(learning.score(displacement(model, xt, at, tt), yt))
            frames.append({'step': step, 'predictions': predictions, 'scores': scores,
                'strain_predictions': strains, 'strain_scores': strain_scores, 'train_scores': train_scores})
        if step % 500 == 0 or step == steps:
            _, terms = loss_grad(models[1], q, yt, tt, vx, va, vt, True)
            validation.append({'step': step, **terms})
            print(json.dumps({'step': step, 'physics_validation': terms, 'elapsed_s': round(time.monotonic()-started, 1)}), flush=True)
        if step == steps:
            break
        xc, ac, tc = rng.uniform(.002, .998, 384), rng.uniform(.6, 1.4, 384), rng.uniform(.45, .95, 384)
        for i, model in enumerate(models):
            loss_grad(model, q, yt, tt, xc, ac, tc, i == 1)
            model.step(.001 if step < 5000 else .0003)
    # Fresh audit parameters were fixed before this run and never enter training.
    audit = []
    for a in [.7, .9, 1.1, 1.3]:
        for t in [.55, .8]:
            u, force, strain = reference(x, a, t)
            aa, tt_audit = np.full_like(x, a), np.full_like(x, t)
            pred = forward(models[1], x, aa, tt_audit)[0][:, 0]
            up = displacement(models[1], x, aa, tt_audit)
            refined_u = displacement(models[1], x, aa, tt_audit, 128)
            audit.append({'amplitude': a, 'load': t, 'strain': learning.score(pred, strain),
                'displacement': learning.score(up, u), 'quadrature_64_128_max_error': float(np.max(np.abs(up-refined_u)))})
    result = {'schema_version': 1, 'kind': 'executed_parametric_corrugated_strip', 'seed': model_seed,
        'x': learning.rounded(x), 'specimens': specimens, 'frames': frames,
        'models': [{'id': 'nn', 'name': 'NN · observations + integral strain', 'parameters': models[0].count()},
                   {'id': 'pinn', 'name': 'PINN · observations + integral strain + physics', 'parameters': models[1].count()}],
        'protocol': {'steps': steps, 'widths': [10, 48, 48, 2], 'raw_inputs': ['position', 'amplitude', 'traction'],
            'features': 'scaled x,a,T; sin/cos(2πx,4πx,8πx); known soft-region Gaussian',
            'optimizer': 'Adam', 'learning_rate': [.001, .0003], 'switch_step': 5000,
            'training_observations': len(yt), 'training_specimens': 6, 'test_specimens': 6, 'noise_std': .003,
            'collocation_per_step': 384, 'physics_weight': .5, 'residual_normalization': 'divide displacement and force residuals by traction T',
            'strain_representation': 'direct network output; u is its Gauss-Legendre integral from0 to x',
            'quadrature_order': QUADRATURE_ORDER, 'derivative_h': DERIVATIVE_H,
            'derivative_scope': 'force equilibrium only; displayed strain is the learned field',
            'physics_domain': {'x': [0, 1], 'amplitude': [.6, 1.4], 'load': [.45, .95]},
            'selection': f'fixed {steps}-update budget; physics-only diagnostics; no reference labels used for optimizer or checkpoint selection',
            'development_boundary': 'The six original demonstration cases were inspected in an earlier release. Eight additional audit parameter pairs were fixed before the first integral-strain run. Quadrature was refined using integration consistency, without retuning against reference scores.',
            'observation_seed': 11,
            'units': 'dimensionless', 'beta': BETA, 'same_initial_weights': True,
            'boundary_conditions': 'u(0)=0, N(1)=T, imposed on both models',
            'equations': ['u(x)=integral_0^x epsilon(s)ds', 'N′ + b = 0', 'N = K(x,a) [epsilon + 0.6epsilon³]'],
            'reference': '4001-point independent quadrature and scalar Newton iteration',
            'scope': 'Synthetic reduced extensional strip, not full-board compression/FEM or experimental validation'},
        'physics_validation': validation, 'additional_audit': audit,
        'source_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
    target = out or ROOT/'public/learning-lab/pinn-parametric.json'
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(result, separators=(',', ':'), allow_nan=False))
    np.savez_compressed(target.with_suffix('.weights.npz'), **{f'{i}_{k}': v for i, m in enumerate(models) for k, v in m.p.items()})
    print(json.dumps({'saved': str(target), 'bytes': target.stat().st_size, 'final_strain_test_R2': [s['r2'] for s in frames[-1]['strain_scores'][1][6:]], 'audit': audit}), flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--steps', type=int, default=8000)
    parser.add_argument('--out', type=Path)
    parser.add_argument('--model-seed', type=int, default=11)
    args = parser.parse_args()
    generate(args.steps, args.out, args.model_seed)
