99 lines
6.3 KiB
Python
99 lines
6.3 KiB
Python
"""Tet-only volume/area fingerprints for the fixed two-route candidate count."""
|
|
from pathlib import Path
|
|
from xml.etree import ElementTree as ET
|
|
from zipfile import ZipFile
|
|
import argparse, hashlib, json, os, resource, time
|
|
import numpy as np
|
|
from audit_samples import decode_array
|
|
from g1_registration_cost import sample_surface
|
|
from s2_e1_supervisor import save
|
|
|
|
ROOT=Path(os.environ.get('MELTMIND_G1_FINGERPRINT_ROOT','artifacts/s2-g1-candidates-2026-11-14'))
|
|
|
|
def read_tets(stream):
|
|
points=None;cells={};stack=[];allowed={'Points','connectivity','offsets','types'}
|
|
for event,e in ET.iterparse(stream,events=('start','end')):
|
|
if event=='start':
|
|
stack.append(e.tag)
|
|
if e.tag in ('PointData','CellData'):raise ValueError('Field association before geometry complete')
|
|
if e.tag=='VTKFile':
|
|
if e.get('byte_order')!='LittleEndian' or e.get('compressor')!='vtkZLibDataCompressor':raise ValueError('Unsupported geometry encoding')
|
|
header=e.get('header_type','UInt32')
|
|
else:
|
|
if e.tag=='DataArray':
|
|
name=e.get('Name')
|
|
if name not in allowed or stack[-2] not in ('Points','Cells'):raise ValueError('Non-geometry array')
|
|
v=decode_array(e,header).copy()
|
|
if name=='Points':points=v
|
|
else:cells[name]=v
|
|
e.clear()
|
|
if points is not None and len(cells)==3:break
|
|
stack.pop()
|
|
if points is None or len(cells)!=3:raise ValueError('Incomplete geometry')
|
|
offsets=np.r_[0,cells['offsets']];ids=np.flatnonzero(cells['types']==10)
|
|
if not len(ids) or np.any(offsets[ids+1]-offsets[ids]!=4):raise ValueError('Invalid tetrahedra')
|
|
return points,cells['connectivity'][offsets[ids,None]+np.arange(4)]
|
|
|
|
def fingerprint(points,tetra,prefix):
|
|
if not np.isfinite(points).all() or tetra.min()<0 or tetra.max()>=len(points):raise ValueError('Invalid geometry')
|
|
used=np.unique(tetra);x=np.asarray(points[used],dtype=np.float64);tet=np.searchsorted(used,tetra)
|
|
q=x[tet];volume=np.abs(np.einsum('ij,ij->i',np.cross(q[:,1]-q[:,0],q[:,2]-q[:,0]),q[:,3]-q[:,0]))/6
|
|
if np.any(volume<=0):raise ValueError('Zero-volume tetrahedron')
|
|
v=float(volume.sum());center=np.einsum('ni,n->i',q.mean(1),volume)/v
|
|
centered=q-center;tot=centered.sum(1)
|
|
# Exact degree-2 integration in each linear tetrahedron (Dirichlet moments).
|
|
covariance=(np.einsum('nki,nkj,n->ij',centered,centered,volume)+np.einsum('ni,nj,n->ij',tot,tot,volume))/(20*v)
|
|
eigenvalues=np.linalg.eigvalsh(covariance)
|
|
if eigenvalues[0]<=0:raise ValueError('Invalid volume covariance')
|
|
# Preserve the registration Rg convention: tetra volume/4 nodal quadrature.
|
|
rg=float(np.sqrt(np.einsum('nki,nki,n->',centered,centered,volume)/(4*v)))
|
|
del q,centered,tot
|
|
f=np.sort(tet[:,np.array([[0,1,2],[0,1,3],[0,2,3],[1,2,3]])].reshape(-1,3),axis=1)
|
|
unique,counts=np.unique(f,axis=0,return_counts=True)
|
|
if np.any(counts>2):raise ValueError('Nonmanifold tetra faces')
|
|
boundary=unique[counts==1];tri=x[boundary]
|
|
a=float(np.linalg.norm(np.cross(tri[:,1]-tri[:,0],tri[:,2]-tri[:,0]),axis=1).sum()/2)
|
|
g={'points':x,'boundary':boundary,'center':center,'rg':np.array(rg)}
|
|
sampled,_=sample_surface(g,prefix)
|
|
radial=np.quantile(np.linalg.norm(sampled-center,axis=1)/rg,[.1,.5,.9],method='inverted_cdf')
|
|
ratios=eigenvalues/eigenvalues.sum()
|
|
shape=np.r_[np.log(a/rg**2),np.log(v/rg**3),ratios[:2],radial]
|
|
# Exact boundary-mesh equality candidate, independent of vertex/face order.
|
|
surf_ids=np.unique(boundary);sx=x[surf_ids].copy();sx[sx==0]=0
|
|
sf=np.searchsorted(surf_ids,boundary);order=np.lexsort((sx[:,2],sx[:,1],sx[:,0]));inverse=np.empty_like(order);inverse[order]=np.arange(len(order))
|
|
canon=np.sort(inverse[sf],axis=1);canon=canon[np.lexsort((canon[:,2],canon[:,1],canon[:,0]))]
|
|
h=hashlib.sha256();h.update(np.asarray(sx[order],dtype='<f8').tobytes());h.update(np.asarray(canon,dtype='<i8').tobytes())
|
|
return g,{'volume':v,'area':a,'rg_registration_quadrature':rg,'volume_center':center.tolist(),
|
|
'exact_volume_covariance_eigenvalues':eigenvalues.tolist(),'shape_vector':shape.tolist(),
|
|
'physical_vector':np.r_[shape,np.log(rg)].tolist(),'surface_radial_quantiles':radial.tolist(),
|
|
'exact_boundary_mesh_sha256':h.hexdigest(),'tetrahedra':len(tet),'surface_triangles':len(boundary)}
|
|
|
|
def check_contract(root):
|
|
c=json.loads((root/'contract.json').read_text())
|
|
for path,h in {**c['code_sha256'],**c['input_sha256']}.items():
|
|
if hashlib.sha256(Path(path).read_bytes()).hexdigest()!=h:raise ValueError('Frozen input/source changed: '+path)
|
|
return c
|
|
|
|
def main():
|
|
ap=argparse.ArgumentParser();ap.add_argument('index',type=int);args=ap.parse_args();c=check_contract(ROOT)
|
|
job=json.loads((ROOT/'custodian/plan.json').read_text())['jobs'][args.index];case=job['case'];start=time.monotonic()
|
|
dest=ROOT/'custodian/fingerprints'/case;dest.mkdir(parents=True,exist_ok=False)
|
|
if job['tet_cache']:
|
|
if hashlib.sha256(Path(job['tet_cache']).read_bytes()).hexdigest()!=job['tet_cache_sha256']:raise ValueError('Tet cache changed')
|
|
with np.load(job['tet_cache'],allow_pickle=False) as z:
|
|
if 'fill_time_raw' in z.files:raise ValueError('Mixed label cache forbidden')
|
|
points=z['points_raw'];tetra=z['tetra']
|
|
mode='existing_label_free_tet_cache'
|
|
else:
|
|
verification=json.loads(Path(c['archive_verification']).read_text());st=Path(c['archive']).stat()
|
|
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(verification['bytes'],verification['mtime_ns'],verification['inode']):raise ValueError('Archive changed')
|
|
with ZipFile(c['archive']) as z,z.open(case+'_sim.vtu') as stream:points,tetra=read_tets(stream)
|
|
mode='geometry_prefix_for_missing_volume_fingerprint'
|
|
g,result=fingerprint(points,tetra,int(case.split('_')[0]));np.savez_compressed(dest/'geometry.npz',**g)
|
|
save(dest/'fingerprint.json',{'case':case,'source_key':job['source_key'],**result,'source_mode':mode,
|
|
'simulation_fields_read':False,'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),
|
|
'wall_seconds':time.monotonic()-start,'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024})
|
|
print(json.dumps({'index':args.index,'status':'FINGERPRINT_COMPLETE'}),flush=True)
|
|
|
|
if __name__=='__main__':main()
|