99 lines
7.5 KiB
Python
99 lines
7.5 KiB
Python
"""Only label-free B12/B13 preparation; immutable legacy helpers reused."""
|
|
import json
|
|
from pathlib import Path
|
|
import numpy as np
|
|
from scipy.sparse.csgraph import connected_components
|
|
from phase2_h1_worker_v2 import checked,sha,save
|
|
from gre24_features_v2 import mesh as flow_mesh,cell_flow_speed,exterior_faces
|
|
from o1_prepare import source_geometry
|
|
from o1_partition import graph,Metis,GeometryFailure,InputViolation,readout,LIBRARY_SHA,HEADER_SHA
|
|
from o1_v2 import array_sha
|
|
from phase2_b12_math import edge_geometry,paths,junction_depth
|
|
|
|
def read(p):return json.loads(Path(p).read_text())
|
|
|
|
|
|
def cached(row,name):
|
|
v=row['v5_cache'];return np.load(checked(Path(v['output'])/(name+'.npy'),v['output_sha256'][name+'.npy']),allow_pickle=False)
|
|
|
|
|
|
def input_geometry(row):
|
|
p=row['preparation'];v=row['v5_cache'];old=read(checked(Path(v['output'])/'result.json',v['result_sha256']))
|
|
if old['case']!=row['case'] or old['status']!='PASS' or old['t_scale_seconds']!=p['t_set']:
|
|
raise InputViolation('Frozen feature identity/clock differs')
|
|
with np.load(checked(Path(p['preparation_root'])/'geometry.npz',p['output_sha256']['geometry.npz']),allow_pickle=False) as z:
|
|
x=z['points_raw'].copy();t=z['tetra'].copy();raw=z['raw_node_ids'].copy()
|
|
if not np.array_equal(raw,cached(row,'raw_ids')):raise InputViolation('Original node identity differs')
|
|
return x,t,raw,old
|
|
|
|
|
|
def b12(row,c,dest):
|
|
x,t,raw,old=input_geometry(row);df=cached(row,'Df');dw=cached(row,'Dw');g=flow_mesh(x,t)
|
|
if not np.isfinite(df).all():raise GeometryFailure('NONFINITE_FROZEN_DF')
|
|
sources=np.searchsorted(raw,old['features']['gate_raw_ids'])
|
|
if np.any(sources>=len(raw)) or not np.array_equal(raw[sources],old['features']['gate_raw_ids']):raise InputViolation('Frozen gate identity absent')
|
|
speed,allwall=cell_flow_speed(g,dw,exterior_faces(t))
|
|
if not np.allclose([speed.min(),speed.max()],[old['features']['speed_min'],old['features']['speed_max']],rtol=1e-12,atol=0):raise InputViolation('Reconstructed R1 speed extrema differ')
|
|
adjacency,thickness=edge_geometry(x,t,g['volume'],speed)
|
|
parent,owner,features,diagnostic=paths(df,raw,sources,adjacency,thickness,g['mass'])
|
|
J,jdiag,tree=junction_depth(df,g['mass'],raw,adjacency,sources,owner)
|
|
extra=np.column_stack([features,J])
|
|
np.savez_compressed(dest/'path-tree.npz',parent=parent,root=owner,raw_ids=raw,**tree)
|
|
save(dest/'platforms.json',diagnostic.pop('platforms'))
|
|
valid=np.isfinite(extra);volume=g['mass'];reachable=owner>=0
|
|
return extra,dict(status='GEOMETRY_COMPLETE',kind='B12',**diagnostic,**jdiag,roots_raw_ids=raw[sources].tolist(),
|
|
finite_nodes_per_column=valid.sum(0).tolist(),finite_volume_fraction_per_column=(np.sum(valid*volume[:,None],axis=0)/volume.sum()).tolist(),
|
|
path_volume_coverage=float(volume[reachable].sum()/volume.sum()),all_missing_columns=np.all(~valid,axis=0).tolist(),
|
|
source_assignment=[dict(root_raw_id=int(raw[s]),nodes=int(np.sum(owner==s)),volume=float(volume[owner==s].sum())) for s in sources],
|
|
all_wall_tetrahedra=len(allwall),R1_speed_extrema=[float(speed.min()),float(speed.max())],path_tree_sha256=sha(dest/'path-tree.npz'),
|
|
original_gate_mode=old['features']['gate_mode'],no_Df_recompute=True,labels_read=False)
|
|
|
|
|
|
def g_metrics(mesh,g,labels):
|
|
if not np.array_equal(np.unique(labels),np.arange(8)):raise GeometryFailure('NOT_EIGHT_NONEMPTY')
|
|
volumes=np.bincount(labels,weights=mesh['volume'],minlength=8);fraction=volumes/volumes.sum();connected=[]
|
|
for region in range(8):
|
|
ids=np.flatnonzero(labels==region)
|
|
connected.append(connected_components(g['adjacency'][ids][:,ids],directed=False,return_labels=False)==1)
|
|
cut=float(g['area'][labels[g['edges'][:,0]]!=labels[g['edges'][:,1]]].sum())
|
|
return dict(volumes=volumes.tolist(),fractions=fraction.tolist(),region_connected=connected,cut_area=cut,
|
|
passed=bool(np.all(fraction>=.95/8) and np.all(fraction<=1.05/8) and all(connected) and cut>0))
|
|
|
|
|
|
def b13(row,c,dest):
|
|
# Recover original mixed-VTU tet indices exactly; stop before field arrays.
|
|
mesh,decoded=source_geometry(c['archive'],row['case']);x,t,raw,old=input_geometry(row)
|
|
if not np.array_equal(mesh['raw_nodes'],raw) or not np.array_equal(mesh['points'],x):raise InputViolation('Canonical node geometry differs')
|
|
st=np.sort(t,axis=1);ct=mesh['tets'];order=lambda a:np.lexsort(tuple(a[:,i] for i in (3,2,1,0)))
|
|
if not np.array_equal(st[order(st)],ct[order(ct)]):raise InputViolation('Canonical tetra membership differs')
|
|
g=graph(mesh);fingerprints={k:array_sha(g[k]) for k in ['xadj','adjncy','vwgt','adjwgt']};engine=Metis();cache=c['G_cache'].get(row['case']);calls=0
|
|
if cache:
|
|
prior=read(checked(cache['result'],cache['result_sha256']));arm=prior['arms']['G']
|
|
if arm['input_sha256']!=fingerprints or arm['seed']!=0:raise InputViolation('Existing G input/parameter fingerprint differs')
|
|
if 'partition_sha256' not in arm:
|
|
return np.full((len(raw),2),np.nan),dict(kind='B13',status='SCIENTIFIC_MISSING',reason='REUSED_ORIGINAL_G_FAILURE: '+arm.get('reason','unknown'),cache_hit=True,partition_calls=0,source_result=cache['result'],source_result_sha256=cache['result_sha256'],labels_read=False)
|
|
if arm['options']!=engine.options(0).tolist():raise InputViolation('Existing G options differ')
|
|
with np.load(checked(cache['graph'],prior['output_sha256']['graph.npz']),allow_pickle=False) as z:
|
|
for k,a in [('raw_nodes',mesh['raw_nodes']),('raw_cells',mesh['raw_cells']),('volume',mesh['volume'])]:
|
|
if not np.array_equal(z[k],a):raise InputViolation('Existing G mesh/order fingerprint differs')
|
|
with np.load(checked(cache['partition'],arm['partition_sha256']),allow_pickle=False) as z:labels=z['labels'].copy()
|
|
returned=dict(seed=0,cache_hit=True,source_partition=cache['partition'],source_partition_sha256=arm['partition_sha256'])
|
|
else:
|
|
calls=1;labels,returned=engine.partition(g,mesh['raw_cells'],0);returned.update(seed=0,cache_hit=False)
|
|
np.savez_compressed(dest/'graph.npz',**{k:g[k] for k in ['xadj','adjncy','vwgt','adjwgt','edges','faces_raw','area']},raw_nodes=raw,raw_cells=mesh['raw_cells'],volume=mesh['volume'])
|
|
if fingerprints!={k:array_sha(g[k]) for k in fingerprints}:raise InputViolation('METIS mutated input')
|
|
np.savez_compressed(dest/'G-partition.npz',labels=labels)
|
|
metrics=g_metrics(mesh,g,labels)
|
|
report=dict(kind='B13',partition_calls=calls,input_fingerprints=fingerprints,**returned,**metrics,decoded_geometry_arrays=decoded,
|
|
partition_sha256=sha(dest/'G-partition.npz'),labels_read=False)
|
|
if not metrics['passed']:return np.full((len(raw),2),np.nan),dict(status='SCIENTIFIC_MISSING',reason='G_SINGLE_ARM_GEOMETRY_FAIL',**report)
|
|
features=cached(row,'features');dw=cached(row,'Dw')
|
|
if not np.isfinite(dw).all() or dw.max()<=0:return np.full((len(raw),2),np.nan),dict(status='SCIENTIFIC_MISSING',reason='DW_NORMALIZATION_UNDEFINED',**report)
|
|
values=features[:,[0,9]]
|
|
if not np.isfinite(values).all():raise InputViolation('Frozen F/Dw_star nonfinite')
|
|
extra=readout(mesh['tets'],mesh['volume'],values[mesh['tets']].mean(axis=1),labels,len(raw))
|
|
mass=np.bincount(mesh['tets'].ravel(),weights=np.repeat(mesh['volume']/4,4),minlength=len(raw))
|
|
before=(mass[:,None]*values).sum(0);after=(mass[:,None]*extra).sum(0)
|
|
if not np.allclose(before,after,rtol=1e-11,atol=1e-12):raise InputViolation('Regional readout mass identity failed')
|
|
return extra,dict(status='GEOMETRY_COMPLETE',mass_integral_before=before.tolist(),mass_integral_after=after.tolist(),**report)
|