Files
MeltMind/tools/phase2_h1_geometry.py

47 lines
3.0 KiB
Python

"""Label-free H1 graph/Rg freeze before fitting or scoring."""
import argparse
import json
from pathlib import Path
import time
import numpy as np
from phase2_h1_worker_v2 import contract,checked,sha,save
from phase2_h1_topology import graph
from gre24_prepare_v2 import read_geometry
def run(root):
c=contract(root); dest=root/'geometry';dest.mkdir(exist_ok=False)
start=time.process_time();records=[]
for protocol in ('grouped','v4_random'):
for case,row in sorted(c['parts'][protocol].items()):
out=dest/protocol;out.mkdir(exist_ok=True)
save(dest/'progress.json',dict(protocol=protocol,case=case,completed=len(records),cpu_seconds=time.process_time()-start))
raw=np.load(checked(Path(row['output'])/'raw_ids.npy',row['output_sha256']['raw_ids.npy']),allow_pickle=False)
mass=np.load(checked(Path(row['output'])/'mass.npy',row['output_sha256']['mass.npy']),allow_pickle=False)
if protocol=='grouped':
old=c['grouped_rows'][case];prep=old['preparation'];p=Path(prep['preparation_root'])
meta=json.loads(checked(p/'result.json',prep['result_sha256']).read_text())
with np.load(checked(p/'geometry.npz',prep['output_sha256']['geometry.npz']),allow_pickle=False) as z:
x=z['points_raw'].copy();t=z['tetra'].copy();ids=z['raw_node_ids'].copy()
rg=float(meta['scales']['Rg'])
else:
archive=c['archives'][protocol];st=Path(archive['path']).stat();expected=archive['stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(expected['bytes'],expected['mtime_ns'],expected['inode']):raise ValueError('Archive identity changed')
x,t,ids,_=read_geometry(archive['path'],case)
center=np.sum(x*mass[:,None],axis=0)/mass.sum()
rg=float(np.sqrt(np.sum(mass*np.sum((x-center)**2,axis=1))/mass.sum()))
if not np.array_equal(ids,raw) or mass.shape!=raw.shape or np.any(mass<=0) or not np.isfinite(mass).all():raise ValueError('Graph domain/mass mismatch')
if not np.isfinite(rg) or rg<=0:raise ValueError('Invalid Rg')
a=graph(x,t);path=out/(case+'.npz')
np.savez_compressed(path,points=x,raw_ids=raw,mass=mass,rg=np.array(rg),
indptr=a.indptr,indices=a.indices,data=a.data)
records.append(dict(protocol=protocol,case=case,path=str(path),sha256=sha(path),nodes=len(raw),directed_edges=a.nnz,Rg=rg))
save(dest/'manifest.json',dict(records=records,contract_sha256=sha(root/'contract.json'),target_arrays_read=False,
field_arrays_decoded=False,cpu_seconds=time.process_time()-start))
save(dest/'complete.json',dict(status='PASS',parts=len(records),manifest_sha256=sha(dest/'manifest.json'),
cpu_seconds=time.process_time()-start,target_arrays_read=False))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);run(p.parse_args().root)