"""Blind Kickoff 10. Reads only frozen predictions and unchanged knot12d.py.

Run: ../.venv-knot12d-blind/bin/python ideal3d.py
Optional --only-static or --spin-test r coupling Omega steps for diagnostics.
All times use the absolute reference edge coupling as the unit.
"""
import os
os.environ.setdefault('OPENBLAS_NUM_THREADS','1')
os.environ.setdefault('OMP_NUM_THREADS','1')
os.environ.setdefault('VECLIB_MAXIMUM_THREADS','1')
import argparse
from datetime import datetime, timezone
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import platform
import resource
import sys
import time
import numpy as np
import scipy
from scipy.linalg import eigh, schur
from scipy.optimize import minimize_scalar
from scipy.fft import fft, fftfreq
from scipy.integrate import solve_ivp

HERE=Path(__file__).resolve().parent
SOURCE=HERE.parent/'knot12d/knot12d.py'
SOURCE_SHA='0747da40871a4135ee0e29507609d09edf8b5737722c690514ac9a63576813f6'
SQ=np.array([0,27,54,81])
INIT=np.zeros((108,2),complex)
INIT[0,0]=1
INIT[[0,54],1]=1/math.sqrt(2)
STATIONS=np.arange(108)%27
THETA=2*np.pi*STATIONS/27
W1=.78451361047755726381949763
W2=.23557321335935813368479318
W3=-1.17767998417887100694641568
COMPOSE=[W1,W2,W3,1-2*(W1+W2+W3),W3,W2,W1]

def sha(p):
    return hashlib.sha256(Path(p).read_bytes()).hexdigest()

def load_inputs():
    assert sha(SOURCE)==SOURCE_SHA
    pred_hash=(HERE/'predictions.sha256').read_text().split()[0]
    assert sha(HERE/'predictions.json')==pred_hash
    spec=importlib.util.spec_from_file_location('unchanged_knot12d',SOURCE)
    source=importlib.util.module_from_spec(spec)
    spec.loader.exec_module(source)
    return source,json.loads((HERE/'predictions.json').read_text()),pred_hash

def coupling(source,r,kind):
    X=source.torus3d(r)
    D=source.dist(X)
    axis=None
    if kind=='a':
        J=source.couplings(D,6)
        angular=None
    else:
        axis=np.array([0.,0.,1.]) if kind=='b' else np.ones(3)/math.sqrt(3)
        diff=X[None,:,:]-X[:,None,:]
        safe=np.where(D==0,1,D)
        angular=1-3*((diff@axis)/safe)**2
        raw=angular/safe**3
        np.fill_diagonal(raw,0)
        J=raw/abs(raw[0,27])
    assert np.max(abs(J-J.T))<1e-12
    assert abs(abs(J[0,27])-1)<1e-12
    others=np.where(STATIONS!=0)[0]
    j=int(others[np.argmax(abs(J[0,others]))])
    mask=STATIONS[:,None]!=STATIONS[None,:]
    ij=np.unravel_index(np.argmax(np.where(mask,abs(J),-1)),J.shape)
    diag=[]
    for i,jj in [(0,54),(27,81)]:
        diag.append({'indices':[i,jj],'angular_factor':None if angular is None else float(angular[i,jj]),'normalized_J':float(J[i,jj])})
    station_diags=[]
    for s in range(27):
        inds=np.where(STATIONS==s)[0]
        pairs=[(int(inds[0]),int(inds[2])),(int(inds[1]),int(inds[3]))]
        station_diags.append({'station':s,'diagonal_J':[float(J[i,j]) for i,j in pairs]})
    # Plane normal from the actual source coordinates, not a substituted geometry.
    plane=np.cross(X[27]-X[0],X[81]-X[0]);plane/=np.linalg.norm(plane)
    meta={'r':r,'coupling':kind,'axis':None if axis is None else axis.tolist(),
          'reference_edge_J':float(J[0,27]),'reference_square_J':J[np.ix_(SQ,SQ)].tolist(),
          'reference_diagonals':diag,'J_max_from_bead0_other_station':float(abs(J[0,j])),
          'J_max_from_bead0_partner_index':j,'global_interstation_J_max':float(abs(J[ij])),
          'global_interstation_J_max_indices':list(map(int,ij)),
          'reference_coplanarity_residual':float(abs((X[54]-X[0])@plane)),
          'all_station_diagonals':station_diags}
    return J,meta

def metrics_from_amplitudes(a):
    return np.column_stack((abs(a[:,2,0])**2,np.sum(abs(a[:,:,1])**2,axis=1),np.sum(abs(a[:,:,0])**2,axis=1)))

def extrema(ts,values,state):
    """Grid extrema plus local refinements of the 24 strongest local extrema.

    Not a rigorous continuous-time enclosure. Both the sample grid and local
    refinement convention are recorded, and temporal sampling is halved.
    """
    result={}
    for name,col,maximize,limit in [('first_pass',0,True,2.5),('long_transfer',0,True,40),('square_qubit_stay',1,False,40),('single_corner_stay',2,False,40)]:
        sel=np.where(ts<=limit+1e-12)[0]
        t,v=ts[sel],values[sel,col]
        sign=-1 if maximize else 1
        y=sign*v
        ids=np.where((y[1:-1]<=y[:-2])&(y[1:-1]<=y[2:]))[0]+1
        ids=ids[np.argsort(y[ids])[:24]]
        ix=int(np.argmin(y));best=float(v[ix]);when=float(t[ix])
        def value(x):
            z=state(float(x))[SQ]
            if col==0:return float(abs(z[2,0])**2)
            return float(np.sum(abs(z[:,1 if col==1 else 0])**2))
        for k in ids:
            res=minimize_scalar(lambda x:sign*value(x),bounds=(float(t[k-1]),float(t[k+1])),method='bounded',options={'xatol':1e-11})
            val=sign*float(res.fun)
            if sign*val < sign*best:best,when=val,float(res.x)
        for endpoint in [0.,limit]:
            val=value(endpoint)
            if sign*val<sign*best:best,when=val,endpoint
        result[name]=best
        result[name+'_time']=when
        result[name+'_grid_only']=float(v[ix])
    return result

def stationary(J,delta,sample_dt=.002):
    H=-J+np.diag(delta*STATIONS)
    w,V=eigh(H,driver='evd')
    if delta>=1000:
        # Local Rayleigh-Ritz refinement avoids losing origin-square accuracy
        # when LAPACK scales the full matrix by offsets as large as 2.6e8.
        for s in range(27):
            block=slice(4*s,4*s+4)
            B=V[:,block]
            HB=H@B-(delta*s)*B
            wb,R=eigh((B.T@HB+HB.T@B)/2,driver='evd')
            V[:,block]=B@R
            w[block]=wb+delta*s
    C=V.conj().T@INIT
    def state(t):return V@(np.exp(-1j*w*t)[:,None]*C)
    ts=np.linspace(0,40,round(40/sample_dt)+1)
    vals=[]
    B=V[SQ]
    for start in range(0,len(ts),4096):
        phases=np.exp(-1j*ts[start:start+4096,None]*w)
        amp=np.einsum('ij,bja->bia',B,phases[:,:,None]*C[None,:,:],optimize=True)
        vals.append(metrics_from_amplitudes(amp))
    vals=np.concatenate(vals)
    result=extrema(ts,vals,state)
    coarse=extrema(ts[::2],vals[::2],state)
    keys=['first_pass','long_transfer','square_qubit_stay','single_corner_stay']
    result['sample_dt']=sample_dt
    result['sample_halving_changes']={k:abs(result[k]-coarse[k]) for k in keys}
    normerr=energyerr=0.
    E0=np.real(np.sum(INIT.conj()*(H@INIT),axis=0))
    for t in np.linspace(0,40,81):
        psi=state(t)
        normerr=max(normerr,float(np.max(abs(np.sum(abs(psi)**2,axis=0)-1))))
        energy=np.real(np.sum(psi.conj()*(H@psi),axis=0))
        energyerr=max(energyerr,float(np.max(abs(energy-E0))))
    result['norm_max_error']=normerr
    result['energy_max_absolute_error']=energyerr
    result['energy_check_times']=81
    result['eigen_equation_max_residual']=float(np.max(abs(H@V-V*w)))
    if delta>=1e7:
        w2,V2=eigh(H,driver='evr');C2=V2.conj().T@INIT
        tests=[result[k+'_time'] for k in keys]
        errs=[]
        for t in tests:
            a=state(t)[SQ];b=(V2@(np.exp(-1j*w2*t)[:,None]*C2))[SQ]
            errs.append(float(np.max(abs(abs(a)**2-abs(b)**2))))
        result['large_ramp_eigensolver_crosscheck_probability_error']=max(errs)
    return result

class Floquet:
    def __init__(self,J,Omega,steps):
        self.J=J;self.Omega=Omega;self.steps=steps
        self.T=2*np.pi/Omega;self.h=self.T/steps
        self.A=2.405*Omega/(2*np.sin(np.pi/27))
        self.w,self.V=eigh(-J,driver='evd')
        self.exps={}
        for c in set(COMPOSE):
            self.exps[c]=(self.V*np.expm1(-1j*self.w*c*self.h/2))@self.V.T
        U=np.eye(108,dtype=complex)
        self.max_polar_correction=0.
        prefix=np.empty((steps+1,108,108),complex);prefix[0]=U
        boundaries=np.r_[0.,np.cumsum(COMPOSE)];boundaries[-1]=1.
        for k in range(steps):
            for stage,c in enumerate(COMPOSE):
                # Work in the exact diagonal-field interaction frame. This
                # is the same symmetric split, with its large field phases
                # telescoped analytically rather than repeatedly multiplied.
                for endpoint in (boundaries[stage],boundaries[stage+1]):
                    phase=self.field_phase((k+endpoint)*self.h)
                    increment=phase.conj()[:,None]*self.exps[c]*phase[None,:]
                    U+=increment@U
            # Retract accumulated multiplication roundoff onto the unitary
            # group using one Newton polar iteration (near-identity defect).
            defect=U.conj().T@U-np.eye(108)
            correction=U@defect/2
            self.max_polar_correction=max(self.max_polar_correction,float(np.max(abs(correction))))
            U-=correction
            prefix[k+1]=self.field_phase(((k+1)%steps)*self.h)[:,None]*U
        U=prefix[-1]
        self.prefix=prefix
        self.raw_unitarity=float(np.max(abs(U.conj().T@U-np.eye(108))))
        S,Q=schur(U,output='complex')
        self.Q=Q
        self.eps=-np.angle(np.diag(S))/self.T
        # Exact unitary evolution has unit-modulus Floquet eigenvalues. Use
        # phases and an orthonormal Schur basis, reporting the roundoff removal.
        reconstructed=(Q*np.exp(-1j*self.eps*self.T))@Q.conj().T
        self.phase_projection_error=float(np.max(abs(U-reconstructed)))
        self.schur_offdiag=float(np.max(abs(S-np.diag(np.diag(S)))))
        self.C=Q.conj().T@INIT
        self.B=np.einsum('bij,jk->bik',prefix[:,SQ,:],Q,optimize=True)

    def field_phase(self,t):
        angle=(self.Omega*t)%(2*np.pi)
        chi=2*self.A/self.Omega*np.cos(THETA-angle/2)*np.sin(angle/2)
        return np.exp(-1j*chi)

    def state(self,t):
        n=int(math.floor(t/self.T))
        tau=t-n*self.T
        k=min(int(math.floor(tau/self.h)),self.steps-1)
        begin=k*self.h; remainder=tau-begin
        psi=self.prefix[k]@(self.Q@(np.exp(-1j*self.eps*(n*self.T))[:,None]*self.C))
        if remainder>1e-16:
            psi=self.field_phase(begin).conj()[:,None]*psi
            for c in COMPOSE:
                h=c*remainder
                phases=np.expm1(-1j*self.w*h/2)
                for endpoint in (begin,begin+h):
                    D=self.field_phase(endpoint)
                    psi=psi+D.conj()[:,None]*(self.V@(phases[:,None]*(self.V.T@(D[:,None]*psi))))
                begin+=h
            psi=self.field_phase(tau)[:,None]*psi
        return psi

    def samples(self,dt):
        ts=np.linspace(0,40,round(40/dt)+1)
        # Sample at the nearest integrator node; refine extrema at their actual
        # continuous times with exact-length split substeps. Include endpoints.
        absolute=np.rint(ts/self.h).astype(np.int64)
        ts=absolute*self.h
        n=absolute//self.steps;k=absolute%self.steps
        vals=[]
        for start in range(0,len(ts),4096):
            sl=slice(start,start+4096)
            phase=np.exp(-1j*(n[sl]*self.T)[:,None]*self.eps)
            a=np.einsum('bij,bja->bia',self.B[k[sl]],phase[:,:,None]*self.C[None,:,:],optimize=True)
            vals.append(metrics_from_amplitudes(a))
        return ts,np.concatenate(vals)

    def observables(self,dt=None):
        dt=min(.002,self.T/8) if dt is None else dt
        ts,values=self.samples(dt)
        result=extrema(ts,values,self.state)
        coarse=extrema(ts[::2],values[::2],self.state)
        keys=['first_pass','long_transfer','square_qubit_stay','single_corner_stay']
        result['sample_dt_nominal']=dt
        result['sample_halving_changes']={k:abs(result[k]-coarse[k]) for k in keys}
        normerr=0
        for t in np.linspace(0,40,161):
            normerr=max(normerr,float(np.max(abs(np.sum(abs(self.state(float(t)))**2,axis=0)-1))))
        result['norm_max_error']=normerr
        result['norm_check_times']=161
        result['one_period_raw_unitarity_error']=self.raw_unitarity
        result['one_period_phase_projection_max_entry_change']=self.phase_projection_error
        result['schur_offdiagonal_max']=self.schur_offdiag
        result['maximum_step_polar_roundoff_correction']=self.max_polar_correction
        result['steps_per_period']=self.steps;result['dt']=self.h
        result['A']=self.A;result['A_over_Omega']=self.A/self.Omega
        return result

    def work_check(self,times=(.123,2.5,40.)):
        """Work-energy balance, with the large field boundary term analytic.

        For H=K+V(t), integral <Vdot> = delta<V> + integral i<[V,K]>.
        Independently Fourier-integrate the commutator; compare it with delta<K>.
        This integration by parts avoids subtracting O(A*Omega) sampled powers.
        Each Fourier mode includes the exact Floquet quasienergy differences.
        """
        powers=np.empty((self.steps,108,108),complex)
        halfdiff=(THETA[:,None]-THETA[None,:])/2
        halfsum=(THETA[:,None]+THETA[None,:])/2
        for k in range(self.steps):
            t=k*self.h
            P=(self.prefix[k]@self.Q)*np.exp(1j*self.eps*t)
            field_difference=-2*self.A*np.sin(halfsum-self.Omega*t)*np.sin(halfdiff)
            commutator=-1j*field_difference*self.J
            powers[k]=P.conj().T@(commutator@P)
        coeff=fft(powers,axis=0)/self.steps
        del powers
        frequencies=fftfreq(self.steps,d=1/self.steps)*self.Omega
        K0=np.real(np.sum(INIT.conj()*(-self.J@INIT),axis=0))
        V0=np.sum(abs(INIT)**2*(self.A*np.cos(THETA))[:,None],axis=0)
        rows=[]
        de=self.eps[:,None]-self.eps[None,:]
        for t in times:
            psi=self.state(t)
            kinetic=np.real(np.sum(psi.conj()*(-self.J@psi),axis=0))
            potential=np.sum(abs(psi)**2*(self.A*np.cos(THETA-self.Omega*t))[:,None],axis=0)
            terms=[[],[]]
            for mode,f in enumerate(frequencies):
                rate=de+f
                factor=np.empty_like(rate,complex)
                nonzero=abs(rate)>1e-13
                factor[nonzero]=np.expm1(1j*rate[nonzero]*t)/(1j*rate[nonzero])
                factor[~nonzero]=t
                w=np.einsum('ia,ij,ja->a',self.C.conj(),coeff[mode]*factor,self.C,optimize=True).real
                for j in range(2):terms[j].append(float(w[j]))
            integral=np.array([math.fsum(x) for x in terms])
            work=potential-V0+integral
            rows.append({'t':t,'energy_change':(kinetic-K0+potential-V0).tolist(),'integrated_external_work':work.tolist(),
                         'kinetic_energy_change':(kinetic-K0).tolist(),'integrated_i_V_K_commutator':integral.tolist(),
                         'absolute_residual':abs(kinetic-K0-integral).tolist()})
        return {'method':'Independent Fourier integral of i<[V,K]>, with the exact potential-energy boundary term: integral <partial_t H> = delta<V> + integral i<[V,K]>',
                'rows':rows,'max_absolute_residual':max(max(r['absolute_residual']) for r in rows),
                'units':'reference edge coupling energy units, absolute, both initial states',
                'physical_energy_is_conserved':False}

    def independent_period_check(self):
        late=math.floor(40/self.T)*self.T
        initial=np.column_stack((INIT,self.state(late)))
        def rhs(angle,y):
            z=y.reshape(108,4)
            D=self.field_phase(angle/self.Omega)
            return (1j/self.Omega*D.conj()[:,None]*(self.J@(D[:,None]*z))).ravel()
        sol=solve_ivp(rhs,(0,2*np.pi),initial.ravel(),method='DOP853',rtol=2e-12,atol=2e-14,max_step=np.pi/64)
        assert sol.success
        expected=self.Q@(np.exp(-1j*self.eps*self.T)[:,None]*(self.Q.conj().T@initial))
        return {'method':'DOP853 in exact diagonal-field frame, one period, four vectors including two late-time states',
                'rtol':2e-12,'atol':2e-14,'max_angular_step':float(np.pi/64),'rhs_evaluations':sol.nfev,
                'max_amplitude_difference':float(np.max(abs(expected-sol.y[:,-1].reshape(108,4))))}

def driven(J,Omega,start_steps=128):
    keys=['first_pass','long_transfer','square_qubit_stay','single_corner_stay']
    history=[];previous=None
    for steps in [start_steps*2**j for j in range(6)]:
        begin=time.monotonic()
        f=Floquet(J,Omega,steps)
        row=f.observables()
        changes=None if previous is None else {k:abs(row[k]-previous[k]) for k in keys}
        item={'steps':steps,'dt':f.h,'metrics':{k:row[k] for k in keys},'dt_halving_changes':changes,
              'norm_max_error':row['norm_max_error'],'seconds':time.monotonic()-begin}
        print('spin',Omega,steps,item,flush=True)
        history.append(item)
        if changes is not None and max(changes.values())<1e-4 and max(row['sample_halving_changes'].values())<1e-4:
            work=f.work_check()
            history[-1]['work_energy_max_absolute_residual']=work['max_absolute_residual']
            print('work',Omega,steps,work['max_absolute_residual'],flush=True)
            # Preserve absolute tolerance rather than hiding it behind scaling.
            if work['max_absolute_residual']<=1e-9 and row['norm_max_error']<=1e-9:
                row['work_energy']=work;row['convergence_history']=history
                row['dt_halving_passed']=True;row['energy_check_passed']=True
                row['independent_period_check']=f.independent_period_check()
                assert row['independent_period_check']['max_amplitude_difference']<1e-9
                return row
            if steps>=2048:
                row['work_energy']=work;row['convergence_history']=history
                row['dt_halving_passed']=True;row['energy_check_passed']=False
                return row
        previous=row
        del f
    raise RuntimeError('Driven observable convergence did not reach 1e-4')

def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--only-static',action='store_true')
    parser.add_argument('--spin-test',nargs=4,metavar=('R','COUPLING','OMEGA','STEPS'))
    args=parser.parse_args()
    start=time.monotonic();source,pred,pred_hash=load_inputs()
    if args.spin_test:
        r,kind,omega,steps=args.spin_test
        J,meta=coupling(source,float(r),kind)
        print(json.dumps(meta),flush=True)
        f=Floquet(J,float(omega),int(steps))
        print(json.dumps(f.observables(),indent=2),flush=True)
        print(json.dumps(f.work_check(),indent=2),flush=True)
        return
    records=[];metadata=[]
    for r in [.1,.3]:
        for kind in ['a','b','c']:
            J,meta=coupling(source,r,kind);metadata.append(meta)
            for mode,parameter in [('none',0),('static',1000),('static',100000),('static',10000000)]+([] if kind=='b' or args.only_static else [('spinning',300),('spinning',3000)]):
                begin=time.monotonic()
                print('START',r,kind,mode,parameter,flush=True)
                if mode=='spinning':
                    result=driven(J,parameter)
                else:
                    dt=.002
                    result=stationary(J,parameter,dt)
                    while max(result['sample_halving_changes'].values())>=1e-4:
                        dt/=2
                        result=stationary(J,parameter,dt)
                prediction=next(p for p in pred['cells'] if p['r']==r and p['coupling']==kind and p['detuning']==mode and p['parameter']==parameter)
                records.append({'r':r,'coupling':kind,'detuning':mode,'parameter':parameter,**result,
                                'predicted_first_pass':prediction['first_pass'],
                                'prediction_status':'HELD' if f"{result['first_pass']:.2f}"==prediction['first_pass'] else 'FAILED',
                                'wall_seconds':time.monotonic()-begin})
                print('DONE',r,kind,mode,parameter,result['first_pass'],result['long_transfer'],result['square_qubit_stay'],flush=True)
                (HERE/'checkpoint.json').write_text(json.dumps({'records':records,'couplings':metadata},indent=2)+'\n')
    assert sha(SOURCE)==SOURCE_SHA and sha(HERE/'predictions.json')==pred_hash
    out={'completed_utc':datetime.now(timezone.utc).isoformat(),'source_sha256':SOURCE_SHA,
         'script_sha256':sha(__file__),'predictions_sha256':pred_hash,'records':records,'couplings':metadata,
         'environment':{'python':sys.version,'numpy':np.__version__,'scipy':scipy.__version__,
                        'platform':platform.platform(),'machine':platform.machine(),'logical_cpus':os.cpu_count()},
         'wall_seconds':time.monotonic()-start,'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*(1 if sys.platform=='darwin' else 1024),
         'integration':'Sixth-order Yoshida composition of symmetric kinetic/diagonal/kinetic substeps, implemented in the exact diagonal-field frame to telescope large phases analytically; periodic Floquet reconstruction; near-identity polar roundoff correction and unit-modulus eigenphase projection disclosed.',
         'extrema_convention':'Static sampling starts at 0.002; driven at min(0.002, period/8), each compared with twice that interval. Bounded local refinement of up to 24 strongest extrema per observable; sampled/refined estimates, not rigorous continuous-time bounds. Static sampling is refined until the comparison is below 1e-4.',
         'energy_note':'Instantaneous physical energy varies in driven runs. Norm and independent integrated external-work balance replace the inapplicable assertion of constant energy.'}
    out['restoration_assessments']=[]
    for p in pred['fat_tube_restoration']:
        actual=[v['parameter'] for v in records if v['r']==.3 and v['coupling']==p['coupling'] and v['detuning']=='static' and v['first_pass']>=.96]
        out['restoration_assessments'].append({**p,'actual_static_deltas':actual,'status':'HELD' if actual==p['predicted_static_deltas'] else 'FAILED'})
    magic=[m for m in metadata if m['coupling']=='c']
    q1=all(m['reference_coplanarity_residual']<1e-12 and all(abs(d['angular_factor'])<1e-12 for d in m['reference_diagonals']) for m in magic)
    q2=all(any(max(abs(x) for x in s['diagonal_J'])>1e-6 for s in m['all_station_diagonals']) for m in magic)
    q4=any(m['global_interstation_J_max']>2*m['J_max_from_bead0_other_station'] for m in metadata if m['r']==.3)
    out['qualitative_assessments']=[
        {'id':'Q1','prediction':pred['qualitative_predictions'][0],'status':'HELD' if q1 else 'FAILED','reason':'Reference-square coplanarity and both angular zero factors checked directly from imported coordinates.'},
        {'id':'Q2','prediction':pred['qualitative_predictions'][1],'status':'HELD' if q2 else 'FAILED','reason':'Other stations retain nonzero diagonals; a reference-square flip is not an ideal 27-square mala.'},
        {'id':'Q3','prediction':pred['qualitative_predictions'][2],'status':'FAILED','reason':'The static-limit clause is supported, but the grid did not establish the additional possibility claim about first-pass restoration without long-window stay. Conservatively marked failed as a fully validated compound prediction, not mathematically disproved.'},
        {'id':'Q4','prediction':pred['qualitative_predictions'][3],'status':'HELD' if q4 else 'FAILED','reason':'Reference-bead and global interstation maxima both reported and differ substantially.'}]
    (HERE/('static-only.json' if args.only_static else 'ideal3d.json')).write_text(json.dumps(out,indent=2)+'\n')
    print('FINISHED',out['wall_seconds'],flush=True)

if __name__=='__main__':main()
