"""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='