"""Jaylab teaching examples. Python 3 standard library; no commercial solver.
Run: python3 numerics.py --out results
Units: N, m, kg, s except the explicitly labeled nonlinear N/mm example.
"""
import argparse, csv, json, math
from pathlib import Path

def oscillator(h, steps, method):
    # m=1 kg, k=10000 N/m, c=0, u0=0.001 m, v0=0; no external force.
    u, v, a = .001, 0., -10.
    vm = v - .5*h*a  # velocity at -h/2 for central differences
    rows=[]
    for n in range(steps+1):
        t=n*h
        rows.append([t,u,v,.001*math.cos(100*t),(.5*v*v+5000*u*u)/.005])
        if method=='cdm':
            vp=vm+h*a
            u+=h*vp
            a=-10000*u
            vm=vp
            v=vm+.5*h*a  # synchronized velocity at the new full step
        elif method=='newmark':
            predictor=u+h*v+.25*h*h*a
            an=-10000*predictor/(1+2500*h*h)
            u=predictor+.25*h*h*an
            v+=.5*h*(a+an)
            a=an
        else: raise ValueError(method)
    return rows

def newton():
    u=0.; rows=[]
    for i in range(5):
        f=100*u+10*u**3; r=110-f; kt=100+30*u*u
        rows.append([i,u,f,r,kt,r/kt]);u+=r/kt
    return rows

def ramp(t,T):
    # Force grows linearly from 0 to F0=10 N, then holds; m=1, k=10000.
    if t<=T:return .001*(t/T-math.sin(100*t)/(100*T))
    uT=.001*(1-math.sin(100*T)/(100*T))
    vT=.001/T*(1-math.cos(100*T))
    return .001+(uT-.001)*math.cos(100*(t-T))+vT/100*math.sin(100*(t-T))

def verify():
    # Independent closed-form discrete phase solution, not just step refinement.
    for h in [.019,.005,.001]:
        for method in ['cdm','newmark']:
            theta=2*(math.asin(50*h) if method=='cdm' else math.atan(50*h))
            rows=oscillator(h,100,method)
            assert max(abs(row[1]-.001*math.cos(i*theta)) for i,row in enumerate(rows))<1e-14
            if method=='newmark':assert max(abs(row[4]-1) for row in rows)<1e-11
    # Global displacement error decreases with dt on the same 0.5 s interval.
    for method in ['cdm','newmark']:
        err=[max(abs(r[1]-r[3]) for r in oscillator(h,round(.5/h),method)) for h in [.005,.0025,.00125]]
        assert err[0]>err[1]>err[2]
        assert 3.5<err[1]/err[2]<4.5
    assert abs(newton()[-1][1]-1)<1e-10
    # Exact ramp solution checked against an independent RK4 time integration.
    for T in [.02,.1,.5]:
        h=.00001;u=v=0.
        def acc(t,x):return 10*min(t/T,1)-10000*x
        maximum=0.
        for n in range(round((T+.1)/h)):
            t=n*h
            a1=acc(t,u); k1=v
            a2=acc(t+h/2,u+h*k1/2);k2=v+h*a1/2
            a3=acc(t+h/2,u+h*k2/2);k3=v+h*a2/2
            a4=acc(t+h,u+h*k3);k4=v+h*a3
            u+=h*(k1+2*k2+2*k3+k4)/6;v+=h*(a1+2*a2+2*a3+a4)/6
            maximum=max(maximum,abs(u-ramp(t+h,T)))
        assert maximum<1e-10,(T,maximum)
    return True

def export(out):
    out.mkdir(parents=True,exist_ok=True)
    def save(name,head,rows):
        with (out/name).open('w',newline='') as f:
            w=csv.writer(f);w.writerow(head);w.writerows(rows)
    save('newton.csv',['iteration','u_mm','internal_force_N','residual_N','tangent_N_per_mm','correction_mm'],newton())
    for h in [.019,.005,.001]:
        for method in ['cdm','newmark']:
            save(f'{method}-{h}.csv',['time_s','u_m','v_m_per_s','exact_u_m','physical_energy_over_initial'],oscillator(h,math.floor(.5/h),method))
    phases=[[h,2*math.asin(50*h)/h,2*math.atan(50*h)/h] for h in [.019,.005,.001]]
    save('phase.csv',['dt_s','cdm_omega_rad_s','newmark_omega_rad_s'],phases)
    save('ramp.csv',['time_s','u_T002_m','u_T01_m','u_T05_m'],[[i*.0002]+[ramp(i*.0002,T) for T in [.02,.1,.5]] for i in range(3501)])
    (out/'verification.json').write_text(json.dumps({'passed':verify(),'scope':'Analytical teaching cases only: discrete-phase identities, Newmark energy, second-order time refinement, Newton root, ramp versus independent RK4.'},indent=2))


def dynamic_newton():
    m,k,alpha,h,u0=1.,10000.,1e9,.005,.001
    a0=-(k*u0+alpha*u0**3)/m
    predictor=u0+.25*h*h*a0
    u=predictor;rows=[]
    for i in range(12):
        residual=4*m*predictor/h**2-(4*m/h**2+k)*u-alpha*u**3
        tangent=4*m/h**2+k+3*alpha*u*u
        correction=residual/tangent
        rows.append([i,u*1000,residual,tangent,correction*1000])
        if abs(residual)<1e-8 and abs(correction)<1e-12:break
        u+=correction
    else:raise AssertionError('Newton did not converge')
    # Independent bracketed root of end-state dynamic balance.
    lo,hi=0.,.001
    for _ in range(80):
        mid=(lo+hi)/2
        f=4*m*(mid-predictor)/h**2+k*mid+alpha*mid**3
        if f>0:hi=mid
        else:lo=mid
    assert abs(u-(lo+hi)/2)<1e-13
    assert abs(4*m*(u-predictor)/h**2+k*u+alpha*u**3)<1e-8
    return rows

def narrative_export(out):
    export(out)
    rows=dynamic_newton()
    with (out/'newton-dynamic.csv').open('w',newline='') as f:
        writer=csv.writer(f)
        writer.writerow(['iteration','u_mm','residual_N','effective_tangent_N_per_m','correction_mm'])
        writer.writerows(rows)
    (out/'narrative-verification.json').write_text(json.dumps({'passed':True,'nonlinear_root_mm':rows[-1][1],'scope':'Linear discrete phase, energy and refinement checks; nonlinear end equilibrium checked against bisection. Not solver or physical validation.'},indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--out',default='results');a=p.parse_args();narrative_export(Path(a.out))
