132 lines
9.4 KiB
Python
132 lines
9.4 KiB
Python
"""R-independent E6 diagnostics on three cached real meshes.
|
|
|
|
Four-point integration here measures spectral indicator volume of the OLD P1
|
|
3-hop field. It is explicitly NOT the proposed physical-kernel estimator.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import resource
|
|
import time
|
|
import numpy as np
|
|
if __package__:
|
|
from .projector_remesh_probe import grouped
|
|
from .run_volume_quadrature_trial import tetra_rule
|
|
else:
|
|
from projector_remesh_probe import grouped
|
|
from run_volume_quadrature_trial import tetra_rule
|
|
|
|
|
|
def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
|
|
|
|
|
|
def layer_proxy(points, distance):
|
|
"""2*P1 distance / centroid chord of ONE tet along its distance gradient.
|
|
|
|
Neither 2*d nor this ratio is a measured wall thickness / whole-wall tet count.
|
|
"""
|
|
edge=points[:,1:]-points[:,:1]
|
|
volume=abs(np.linalg.det(edge))/6
|
|
if np.any(volume<=0) or not np.isfinite(volume).all(): raise ValueError('Invalid tetra volume')
|
|
grad=np.linalg.solve(edge,(distance[:,1:]-distance[:,:1])[...,None])[...,0]
|
|
norm=np.linalg.norm(grad,axis=1);valid=norm>1e-8
|
|
h=np.full(len(points),np.nan);proxy=np.full(len(points),np.nan)
|
|
beta=np.linalg.solve(edge[valid].transpose(0,2,1),(grad[valid]/norm[valid,None])[...,None])[...,0]
|
|
beta=np.c_[-beta.sum(1),beta]
|
|
h[valid]=.25/beta.max(1)-.25/beta.min(1)
|
|
if not np.all(h[valid]>0): raise ValueError('Invalid directional chord')
|
|
proxy[valid]=2*distance[valid].mean(1)/h[valid]
|
|
return volume,valid,h,proxy
|
|
|
|
|
|
def spectrum(t):
|
|
val=np.linalg.eigvalsh(t)[:,::-1]
|
|
valid=np.isfinite(val).all(1)&(val.sum(1)>1e-10)
|
|
if np.any(val[:,-1]<-1e-10): raise ValueError('Non-PSD cached field')
|
|
gaps=(val[:,:-1]-val[:,1:])/np.maximum(val[:,:1],1e-12)
|
|
mode=(gaps[:,0]>.1).astype(int)+2*(gaps[:,1]>.1);mode[~valid]=-1
|
|
near=(gaps>=.05)&(gaps<=.15)&valid[:,None]
|
|
return valid,gaps,mode,near
|
|
|
|
|
|
class VolumeCounter:
|
|
def __init__(self):
|
|
self.mass=0.;self.samples=0;self.modes={str(k):0. for k in [-1,0,1,2,3]};self.near=np.zeros(3);self.hist=np.zeros((2,8));self.edges=np.array([0,.05,.1,.15,.25,.5,.75,1,np.inf])
|
|
def add(self,t,w):
|
|
valid,gap,mode,near=spectrum(t)
|
|
self.mass+=float(w.sum());self.samples+=len(w)
|
|
for k in self.modes:self.modes[k]+=float(w[mode==int(k)].sum())
|
|
self.near+=np.array([w[near[:,0]].sum(),w[near[:,1]].sum(),w[near.any(1)].sum()])
|
|
for j in range(2):self.hist[j]+=np.histogram(gap[valid,j],bins=self.edges,weights=w[valid])[0]
|
|
def result(self):
|
|
return dict(field='cached_3hop_baseline_P1_NOT_new_kernel_candidate',samples=self.samples,total_volume_raw=self.mass,
|
|
mode_volume_fraction={k:v/self.mass for k,v in self.modes.items()},
|
|
spectrally_defined_volume_fraction=1-self.modes['-1']/self.mass,
|
|
directionally_grouped_volume_fraction=sum(self.modes[str(k)] for k in [1,2,3])/self.mass,
|
|
relative_gap_near_cut_volume_fraction=dict(gap12=float(self.near[0]/self.mass),gap23=float(self.near[1]/self.mass),either=float(self.near[2]/self.mass)),
|
|
gap_histogram_edges=[0,.05,.1,.15,.25,.5,.75,1,'infinity'],gap_histogram_volume_fraction=(self.hist/self.mass).tolist(),
|
|
physical_support_valid_volume_fraction=None,quadrature_accuracy_certified=False,
|
|
validity_scope='Only trace>1e-10 and hard relative spectral gaps >0.1; no new physical support or quadrature quality certification.')
|
|
|
|
|
|
def pose_chunks(x,t,mass,gate,R,shift):
|
|
flip_mass=0.;qualified_mass=0.;pe=ge=distance_error=0.
|
|
for begin in range(0,len(x),4096):
|
|
xx=x[begin:begin+4096];tt=t[begin:begin+4096];w=mass[begin:begin+4096]
|
|
transformed=xx@R.T+shift;gg=gate@R.T+shift
|
|
a=grouped(tt,.1);b=grouped(R@tt@R.T,.1)
|
|
same=a['code']==b['code'];ok=same&np.isin(a['code'],[1,2,3]);flip_mass+=float(w[~same].sum());qualified_mass+=float(w[ok].sum())
|
|
expected=R@a['projector']@R.T
|
|
pe=max(pe,float(np.linalg.norm(b['projector'][ok]-expected[ok],axis=(2,3)).max(initial=0)))
|
|
v=gate-xx;vp=gg-transformed
|
|
av=np.einsum('ngij,nj->ngi',a['projector'],v);bv=np.einsum('ngij,nj->ngi',b['projector'],vp)
|
|
ge=max(ge,float(np.linalg.norm(bv[ok]-av[ok]@R.T,axis=2).max(initial=0)))
|
|
distance_error=max(distance_error,float(abs(np.linalg.norm(vp,axis=1)-np.linalg.norm(v,axis=1)).max(initial=0)))
|
|
return dict(mode_flip_volume_fraction=flip_mass/mass.sum(),qualified_directional_volume_fraction=qualified_mass/mass.sum(),grouped_projector_covariance_max=pe,projected_gate_vector_covariance_max_raw=ge,gate_distance_error_max_raw=distance_error,scope='Algebraic grouped-projector/gate-vector check on cached tensor under simultaneous rigid motion; not a new mesh/estimator or model-prediction rerun.')
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser();p.add_argument('output',type=Path);out=p.parse_args().output
|
|
contract=json.loads((out/'execution_contract.json').read_text())
|
|
for path,h in contract['input_sha256'].items():
|
|
if sha(path)!=h: raise ValueError('Changed source '+path)
|
|
with (out/'E6.started.json').open('x') as f:json.dump(dict(contract_sha256=sha(out/'execution_contract.json')),f)
|
|
started=time.monotonic();results=[];bary=tetra_rule()
|
|
prior_pose=json.loads(Path(contract['prior_gate_pose']).read_text())
|
|
rng=np.random.default_rng(421);Q,_=np.linalg.qr(rng.normal(size=(3,3)));Q*=np.linalg.det(Q)
|
|
for spec in contract['cases']:
|
|
tick=time.monotonic();case=spec['case'];print('START',case,flush=True)
|
|
data=np.load(spec['sample']);cache=np.load(spec['tensor_cache']);old=json.loads(Path(spec['prior_result']).read_text())
|
|
assert sha(spec['sample'])==old['source_sample_sha256'] and sha(spec['distance'])==old['source_distance_sha256']
|
|
x=data['points_raw'];tet=data['tetra'];mass=data['node_volume_raw'];gate=data['gate_location_raw'];d=np.load(spec['distance']);t=cache['tensor']
|
|
assert len(x)==old['nodes']==len(t)==len(d) and np.isfinite(t).all() and np.all(mass>0)
|
|
four=VolumeCounter();volumes=[];proxies=[];validities=[]
|
|
for begin in range(0,len(tet),8192):
|
|
ids=tet[begin:begin+8192];v,valid,h,proxy=layer_proxy(x[ids],d[ids]);volumes.append(v);proxies.append(proxy);validities.append(valid)
|
|
qt=np.einsum('qj,tjkl->tqkl',bary,t[ids]).reshape(-1,3,3)
|
|
four.add(qt,np.repeat(v/4,4))
|
|
v=np.concatenate(volumes);proxy=np.concatenate(proxies);valid=np.concatenate(validities)
|
|
assert np.isclose(v.sum(),mass.sum(),rtol=1e-10)
|
|
layer_edges=[0,1,2,3,4,8,16,32,np.inf]
|
|
sorted_ids=np.argsort(proxy[valid]);pv=proxy[valid][sorted_ids];weights=v[valid][sorted_ids]
|
|
quantiles=None
|
|
if len(pv):
|
|
cumulative=np.cumsum(weights)/weights.sum();quantiles={str(q):float(pv[min(np.searchsorted(cumulative,q),len(pv)-1)]) for q in [.05,.5,.95]}
|
|
layer=dict(meaning='Resolution proxy 2*d_P1(centroid)/h_tet(centroid, normalized grad d_P1); NOT measured wall thickness or whole-wall tet layer count.',valid_gradient_volume_fraction=float(v[valid].sum()/v.sum()),undefined_gradient_volume_fraction=float(v[~valid].sum()/v.sum()),conditional_volume_weighted_quantiles=quantiles,histogram_edges=[0,1,2,3,4,8,16,32,'infinity'],histogram_fraction_of_total_volume=(np.histogram(proxy[valid],bins=layer_edges,weights=v[valid])[0]/v.sum()).tolist(),limitations=['2*d is an inscribed-diameter proxy, not full wall thickness; P1 distance is not exact centroid distance.','The directional chord is across one tetrahedron, not a counted sequence through the wall.','Medial/junction ambiguity and zero gradients prevent a true thickness-layer interpretation; no support pass/fail imposed.'])
|
|
quadrature={'tetra_four_point_baseline_volume':four.result()}
|
|
if spec['lumped_diagnostic']:
|
|
lumped=VolumeCounter()
|
|
for begin in range(0,len(x),8192):lumped.add(t[begin:begin+8192],mass[begin:begin+8192])
|
|
quadrature['lumped_vertex_baseline_volume']=lumped.result()
|
|
poses={name:pose_chunks(x,t,mass,gate,R,np.array([3.1,-7.,2.])) for name,R in [('proper_rotation_translation',Q),('reflection_translation',Q@np.diag([-1.,1.,1.]))]}
|
|
old_gate=next(row for row in prior_pose['cases'] if row['case']==case)
|
|
row=dict(case=case,nodes=len(x),tets=len(tet),total_volume_raw=float(v.sum()),layers=layer,baseline_volume_diagnostics=quadrature,new_algebraic_pose_checks=poses,reused_independent_mesh_pose=old['pose_checks'],reused_gate_pose=old_gate['checks'],new_candidate_status='NOT_RUN_missing_real_R_and_covariant_support_quality_definition',wall_seconds=time.monotonic()-tick,peak_rss_kib_so_far=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
|
|
(out/(case+'.json')).write_text(json.dumps(row,indent=2,allow_nan=False)+'\n');results.append(row);print('DONE',case,row['wall_seconds'],flush=True)
|
|
del data,cache,x,tet,mass,gate,d,t,v,proxy,valid,volumes,proxies,validities
|
|
result=dict(status='INDEPENDENT_DIAGNOSTICS_COMPLETE_NEW_PHYSICAL_KERNEL_CANDIDATE_PENDING_DEFINITION',cases=results,wall_seconds=time.monotonic()-started,peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,new_real_kernel_estimates=0,new_distance_queries=0,new_geometry_meshes=0,new_baseline_volume_estimates=4,training=False,O1=False,O2A_rerun=False,O2B=False,O2S=False)
|
|
(out/'E6_result.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n');print('COMPLETE',result['wall_seconds'],flush=True)
|
|
|
|
|
|
if __name__=='__main__':main()
|