96 lines
6.4 KiB
Python
96 lines
6.4 KiB
Python
"""Approved cache-only domain continuation; no archive access or decoder."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import time
|
|
import traceback
|
|
import shutil
|
|
import numpy as np
|
|
from freeze_g1_components import sha
|
|
from s2_custody_common import checked, read_json
|
|
from s2_recovery_supervisor import save
|
|
from naive_domain_common import contract
|
|
from naive_ordering_common import rows
|
|
from naive_ordering_math import cdf_interval, squared_wall_distance, volume_clock_curve
|
|
|
|
|
|
def run(root, index):
|
|
c=contract(root)
|
|
if index not in c['continuation_indices']:raise PermissionError('Only seven explicitly approved unfinished parts')
|
|
row=rows(c)[index];prep=row['preparation'];source=Path(prep['preparation_root'])
|
|
dest=root/'parts'/f'part-{index:03d}'/'output'
|
|
dest.mkdir(exist_ok=False)
|
|
start=time.monotonic();cpu=time.process_time()
|
|
save(dest/'started.json',dict(pid=os.getpid(),case=row['case'],index=index,unix=time.time(),
|
|
contract_sha256=sha(root/'contract.json'),custody_authorization=c['latest_ruling']))
|
|
try:
|
|
for name in ['geometry.npz','r2.npz','queries.npz']:checked(source/name,prep['output_sha256'][name])
|
|
metadata=read_json(checked(source/'result.json',prep['result_sha256']))
|
|
if metadata['r2']['columns'][8]!='Dw':raise ValueError('Expected original wall-distance column')
|
|
with np.load(source/'geometry.npz',allow_pickle=False) as z:
|
|
x=z['points_raw'];edges=z['edges'];mass=z['node_volume_raw'];raw=z['raw_node_ids'];gate=z['gate_location_raw']
|
|
with np.load(source/'r2.npz',allow_pickle=False) as z:
|
|
dw=z['features'][:,8];df1=z['Df'];vf=z['Vf']
|
|
with np.load(source/'queries.npz',allow_pickle=False) as z:
|
|
mask=z['eligible_s2'];ids=z['anchor_ids'][mask];query_raw=z['raw_node_ids'][mask];counts=z['multiplicity'][mask]
|
|
if not np.array_equal(raw[ids],query_raw):raise ValueError('Query/raw-ID mismatch')
|
|
original=c['continuation_inputs'][str(index)]
|
|
label=checked(original['label_path'],original['label_sha256'])
|
|
with np.load(label,allow_pickle=False) as z:
|
|
full=z['seconds'].copy()
|
|
if not np.array_equal(z['retained_tet_raw_ids'],raw):raise ValueError('Frozen tet geometry/raw IDs changed')
|
|
inside=np.zeros(len(full),bool);inside[raw]=True
|
|
invalid=(~np.isfinite(full))|(full<0)
|
|
if not np.array_equal(invalid,~inside) or not np.isnan(full[~inside]).all():
|
|
raise ValueError('Continuation is limited to observed outside-tet NaN pattern')
|
|
if int(invalid.sum())!=original['invalid_outside_tet'] or np.any(full[raw]<0) or not np.isfinite(full[raw]).all() or full[raw].max()<=0:
|
|
raise ValueError('Invalid labels inside frozen tet domain; do not filter by finiteness')
|
|
shutil.copy2(label,dest/'full-node-labels.npz')
|
|
if sha(dest/'full-node-labels.npz')!=original['label_sha256']:raise ValueError('Raw NaN cache bytes changed')
|
|
save(dest/'cache-reuse-receipt.json',dict(case=row['case'],original_label_path=str(label),
|
|
label_sha256=original['label_sha256'],new_decodes=0,original_decode_count=1,
|
|
invalid_outside_tet=int(invalid.sum()),invalid_in_tet=0,domain_ruling=c['domain_ruling'],scope_ruling=c['scope_ruling']))
|
|
old={v['case']:v for v in read_json(checked(c['label_index'],c['label_index_sha256']))}[row['case']]
|
|
with np.load(checked(old['path'],old['sha256']),allow_pickle=False) as z:
|
|
if not np.array_equal(z['raw_ids'],query_raw) or not np.array_equal(z['counts'],counts) or not np.array_equal(z['seconds'],full[query_raw]):
|
|
raise ValueError('Full decode differs from immutable S2 query cache')
|
|
left1,right1=cdf_interval(df1,mass)
|
|
difference=float(np.max(np.abs(left1-vf)))
|
|
if difference>1e-12:raise ValueError('Existing B0 is not the expected full-volume strict D_w Dijkstra CDF')
|
|
save(dest/'progress.json',dict(stage='Dw_squared_graph',cpu_seconds=time.process_time()-cpu))
|
|
df2,gate_node,zero_edges=squared_wall_distance(x,edges,dw,gate)
|
|
left2,right2=cdf_interval(df2,mass)
|
|
leftT,rightT=cdf_interval(full[raw],mass)
|
|
np.savez_compressed(dest/'full-domain-maps.npz',raw_ids=raw,truth_left=leftT,truth_right=rightT,
|
|
df1_left=left1,df1_right=right1,df2_left=left2,df2_right=right2)
|
|
end=float(full[raw].max());tet_end=end;query_end=float(full[query_raw].max())
|
|
positive=float(mass[dw>0].sum()/mass.sum());K=int(counts.sum());alpha=positive*K/metadata['draw_slots']
|
|
curve=volume_clock_curve(full[raw],mass,end,prep['t_set'])
|
|
curve['T_end_tet_domain']=curve.pop('full_VTU_end')
|
|
curve['over_tet_end']=curve.pop('over_full_end')
|
|
curve['raw_VTU_end']=None
|
|
curve['outside_tet_NaN_retained']=int(invalid.sum())
|
|
save(dest/'volume-clock-curve.json',curve)
|
|
save(dest/'result.json',dict(status='COMPLETE',case=row['case'],index=index,component_id=row['component_id'],
|
|
t_set=prep['t_set'],full_VTU_T_end=None,full_tet_T_end=tet_end,query_T_max=query_end,
|
|
raw_nodes=len(full),tet_nodes=len(raw),zero_mass_excluded_VTU_nodes=len(full)-len(raw),
|
|
full_vs_tet_end_difference=None,eligible_slots=K,draw_slots=metadata['draw_slots'],
|
|
positive_mass_fraction=positive,estimated_alpha=alpha,alpha_is_estimate=True,
|
|
DKW_halfwidth_if_fixed_score_independent_PPS=float(np.sqrt(np.log(40)/(2*K))),
|
|
baseline_Dw_Vf_max_abs_difference=difference,Dw_solve_reused=True,Dw2_solver='tet-edge Dijkstra approximation',
|
|
zero_midpoint_edges_excluded=zero_edges,gate_node=gate_node,
|
|
cpu_seconds=time.process_time()-cpu,wall_seconds=time.monotonic()-start,
|
|
output_sha256={p.name:sha(p) for p in dest.glob('*') if p.is_file() and p.name not in ['progress.json']},
|
|
no_training=True,no_GPU=True,decode_count=0,cache_reused=True,outside_tet_NaN_retained=int(invalid.sum())))
|
|
return 0
|
|
except Exception as exc:
|
|
save(dest/'failure.json',dict(type=type(exc).__name__,message=str(exc),traceback=traceback.format_exc(),
|
|
cpu_seconds=time.process_time()-cpu,wall_seconds=time.monotonic()-start,retry=False))
|
|
raise
|
|
|
|
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('index',type=int);a=p.parse_args()
|
|
raise SystemExit(run(a.root,a.index))
|