153 lines
10 KiB
Python
153 lines
10 KiB
Python
"""B5: <=3 selected boundary-triangle prism candidates on ten learning parts."""
|
|
import argparse
|
|
import hashlib
|
|
from itertools import permutations
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
import time
|
|
import numpy as np
|
|
from scipy.spatial import cKDTree
|
|
from phase2_b5_certificate import (certify,Work,Unknown,PRISM,point,tetra_planes,volume,outside,F,det,sub)
|
|
from phase2_h1_worker_v2 import checked,sha,save
|
|
from r4bc_guard import supervise
|
|
|
|
BASE=Path('/home/frank14f/optane/MeltMind')
|
|
ROOT=BASE/'artifacts/phase2-b5-gate-2026-11-17'
|
|
def read(p):return json.loads(Path(p).read_text())
|
|
|
|
|
|
def prepare(acceptance):
|
|
tests=read(acceptance)
|
|
if tests['status']!='PASS':raise ValueError('B5 synthetic acceptance missing')
|
|
for p,h in tests['code_sha256'].items():checked(BASE/p,h)
|
|
prior=BASE/'artifacts/phase2-b3-gate-2026-11-17/contract.json';parts=read(prior)['parts'][:10]
|
|
code={f'tools/{n}.py':sha(BASE/f'tools/{n}.py') for n in ['phase2_b5_gate','phase2_b5_certificate','phase2_h1_worker_v2','phase2_residual_math','r4bc_guard','s2_recovery_supervisor','s2_recovery_monitoring']}
|
|
ROOT.mkdir(exist_ok=False)
|
|
save(ROOT/'contract.json',dict(version='B5-local-prism-certificate-v1',authorizing_ruling='1794887072.921849',parts=parts,
|
|
code_sha256=code,source_sha256={str(prior):sha(prior),str(acceptance):sha(acceptance)},
|
|
selection='first10 of frozen B3 component-hash panel; no label access',candidate_policy=dict(max_candidates=3,
|
|
anchor_boundary_faces=16,nearest_face_centers=32,opposing_normal_dot_max=-.8,max_distance_over_sqrt_area=4.,
|
|
min_abs_determinant_over_max_edge_cubed=1e-12,vertex_correspondence='minimum sum squared paired-vertex distance; permutation lex tie'),
|
|
certificate='positive oriented affine prism tets; exact pair intersections equal common reference simplices; exact subtraction proves whole image inside original tet union',
|
|
limits=dict(worker_cpu=20,worker_cpu_seconds=7080,total_cpu_seconds=7200,per_part_predicate_cpu_seconds=300,per_part_predicate_operations=70000,
|
|
rss_bytes=8*1024**3,disk_bytes=5*1024**3),new_decodes=0,new_models=0,gpu=False,retry=False,
|
|
decision='any independently confirmed false acceptance prunes implementation; >=6/10 exact certified unions below .20 parks whole-part layering; incomplete coverage stays unknown',
|
|
interpretation='certificate for stored binary-float mesh and nominated boundary facets; no independent true wall-pair labels or physical thin-gap guarantee'))
|
|
|
|
|
|
def config(root):
|
|
c=read(root/'contract.json')
|
|
for p,h in {**c['source_sha256'],**c['code_sha256']}.items():checked(p,h)
|
|
for r in c['parts']:
|
|
a=next(x for x in r['assignments'] if x['fold']==0)
|
|
if a['role']!='learning' or '100' not in a['learning_pools']:raise PermissionError('B5 held-out role denied')
|
|
return c
|
|
|
|
|
|
def candidates(x,t,faces,raw,c):
|
|
centers=x[faces].mean(axis=1);tree=cKDTree(centers)
|
|
anchors=sorted(range(len(faces)),key=lambda k:(hashlib.sha256(','.join(map(str,sorted(map(int,raw[faces[k]])))).encode()).hexdigest(),k))[:16]
|
|
flat=t.ravel();order=np.argsort(flat,kind='stable');ends=np.r_[0,np.cumsum(np.bincount(flat,minlength=len(x)))];owners=order//4
|
|
def normal(face):
|
|
possible=owners[ends[face[0]]:ends[face[0]+1]]
|
|
keep=(t[possible,:,None]==face[None,None,:]).any(axis=1).all(axis=1);owner=possible[keep]
|
|
if len(owner)!=1:raise Unknown('boundary face does not have one owning tet')
|
|
opposite=next(i for i in t[owner[0]] if i not in face)
|
|
a,b,d=x[face];n=np.cross(b-a,d-a);length=np.linalg.norm(n)
|
|
if not np.isfinite(length) or length<=0:raise Unknown('degenerate boundary triangle')
|
|
if np.dot(n,x[opposite]-a)>0:n=-n
|
|
return n/length,length/2
|
|
found={}
|
|
for i in anchors:
|
|
ni,ai=normal(faces[i]);_,near=tree.query(centers[i],k=min(32,len(faces)))
|
|
for j in np.atleast_1d(near):
|
|
j=int(j)
|
|
if j==i or set(faces[i]) & set(faces[j]):continue
|
|
nj,aj=normal(faces[j]);d=centers[j]-centers[i];distance=float(np.linalg.norm(d));scale=float(np.sqrt(min(ai,aj)))
|
|
if ni@nj>-.8 or ni@d>=0 or nj@d<=0 or distance>4*scale:continue
|
|
key=tuple(sorted((i,j)))
|
|
if key in found:continue
|
|
bottom=faces[i];top=faces[j]
|
|
perm=min(permutations(range(3)),key=lambda p:(float(np.sum((x[bottom]-x[top[list(p)]])**2)),p))
|
|
ids=np.r_[bottom,top[list(perm)]];points=x[ids]
|
|
found[key]=dict(wall_face_indices=[i,j],wall_raw_ids=[list(map(int,raw[bottom])),list(map(int,raw[top]))],
|
|
raw_ids=list(map(int,raw[ids])),local_ids=list(map(int,ids)),points=points.tolist(),selection_score=distance/scale)
|
|
return sorted(found.values(),key=lambda r:(r['selection_score'],r['wall_face_indices']))[:3]
|
|
|
|
|
|
def union_add(points,result,accepted,work):
|
|
vertices=tuple(point(points[i]) for i in result['reference_vertex_order'])
|
|
new=[(tetra_planes([vertices[i] for i in tet]),tuple(vertices[i] for i in tet)) for tet in PRISM]
|
|
added=F(0)
|
|
for poly in new:
|
|
fragments=[poly]
|
|
for old in accepted:
|
|
work.tick()
|
|
fragments=[q for f in fragments for q in outside(f,old[0],work)]
|
|
if len(fragments)>256:raise Unknown('union fragmentation cap')
|
|
added+=sum((volume(p) for p in fragments),F(0))
|
|
return added,new
|
|
|
|
|
|
def run(root,c):
|
|
start=time.process_time();out=root/'parts';out.mkdir(exist_ok=False);results=[];failures=[]
|
|
for row in c['parts']:
|
|
dest=out/row['case'];dest.mkdir();work=Work(70000,300);records=[];accepted=[];union=F(0);exact_coverage=True
|
|
try:
|
|
p=row['preparation'];source=Path(p['preparation_root'])
|
|
with np.load(checked(source/'geometry.npz',p['output_sha256']['geometry.npz']),allow_pickle=False) as z:
|
|
x=z['points_raw'];t=z['tetra'];faces=z['boundary_triangles'];raw=z['raw_node_ids'];mass=z['node_volume_raw']
|
|
selected=candidates(x,t,faces,raw,c);save(dest/'candidates.json',selected)
|
|
total_volume=float(mass.sum());mins=x[t].min(axis=1);maxs=x[t].max(axis=1)
|
|
for k,proposal in enumerate(selected):
|
|
points=np.asarray(proposal['points']);h=float(np.max(np.linalg.norm(points[:,None]-points[None,:],axis=2)))
|
|
signs=[float(det(sub(point(points[b]),point(points[a])),sub(point(points[d]),point(points[a])),sub(point(points[e]),point(points[a])))) for a,b,d,e in PRISM]
|
|
if h<=0 or min(map(abs,signs))/h**3<1e-12:
|
|
records.append(dict(candidate=k,status='UNKNOWN',reason='orientation/degeneracy margin'));continue
|
|
relevant=np.flatnonzero(np.all(maxs>=points.min(axis=0),axis=1)&np.all(mins<=points.max(axis=0),axis=1))
|
|
try:
|
|
result=certify(points,x[t[relevant]],work)
|
|
result.update(candidate=k,cavity_tet_ids=list(map(int,relevant)))
|
|
if result['status']=='CERTIFIED':
|
|
added,new=union_add(points,result,accepted,work)
|
|
union+=added;accepted+=new;result['new_union_volume']=float(added)
|
|
records.append(result)
|
|
except Unknown as exc:
|
|
records.append(dict(candidate=k,status='UNKNOWN',reason=str(exc)));exact_coverage=False;break
|
|
report=dict(case=row['case'],component_id=row['component_id'],candidates=len(selected),attempted=len(records),records=records,
|
|
certified_patches=sum(r['status']=='CERTIFIED' for r in records),certified_union_volume=float(union),original_volume=total_volume,
|
|
certified_union_fraction=float(union)/total_volume,union_coverage_complete=exact_coverage,
|
|
no_candidate=not selected,operations=work.operations,predicate_cpu_seconds=time.process_time()-work.start,
|
|
independently_checked_cross_air_acceptances=None,independent_wall_pair_truth=False,labels_read=False)
|
|
save(dest/'result.json',report);results.append(report)
|
|
except Exception as exc:
|
|
failure=dict(case=row['case'],type=type(exc).__name__,message=str(exc));save(dest/'failure.json',failure);failures.append(failure)
|
|
save(root/'progress.json',dict(completed=len(results),failures=len(failures),cpu_seconds=time.process_time()-start))
|
|
low=sum(r['union_coverage_complete'] and r['certified_union_fraction']<.2 for r in results)
|
|
decision='PARK_WHOLE_PART_LAYERING_KEEP_LOCAL_CERTIFICATES' if len(results)==10 and low>=6 else 'PARK_COVERAGE_UNKNOWN' if len(results)!=10 or failures or any(not r['union_coverage_complete'] for r in results) else 'RETAIN_LOCAL_CERTIFICATE_ROUTE'
|
|
save(root/'result.json',dict(status='COMPLETE',gate='B5',decision=decision,parts=results,failures=failures,low_coverage_parts=low,
|
|
independently_checked_cross_air_acceptances=None,independent_wall_pair_error_rate=None,
|
|
synthetic_negatives='air-gap and folded-correspondence rejections; no industrial true-pair error claim',
|
|
interpretation='exact containment in stored tet union; finite candidate policy and complexity failures do not refute all partition routes',
|
|
cpu_seconds=time.process_time()-start))
|
|
|
|
|
|
def supervise_gate(root):
|
|
c=config(root);limits=c['limits'];os.sched_setaffinity(0,[limits['worker_cpu']]);start=time.process_time()
|
|
if (root/'actual-start.json').exists():raise FileExistsError('No B5 retry')
|
|
save(root/'actual-start.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json')))
|
|
g=supervise([sys.executable,'tools/phase2_b5_gate.py','worker',str(root)],root/'guard',dict(cpu_seconds=7080,wall_seconds=7080,rss_bytes=limits['rss_bytes'],disk_bytes=limits['disk_bytes']))
|
|
guard_cpu=time.process_time()-start;total=g['cpu_seconds']+guard_cpu+60
|
|
status='PASS' if g['status']=='PASS' and total<=7200 and (root/'result.json').exists() else 'STOPPED'
|
|
save(root/'complete.json',dict(status=status,guard=g,guard_cpu_seconds=guard_cpu,setup_charge_seconds=60,cumulative_charge_seconds=total,retry=False))
|
|
return 0 if status=='PASS' else 1
|
|
|
|
|
|
if __name__=='__main__':
|
|
p=argparse.ArgumentParser();p.add_argument('mode',choices=['prepare','worker','supervise']);p.add_argument('path',type=Path);a=p.parse_args()
|
|
if a.mode=='prepare':prepare(a.path)
|
|
elif a.mode=='worker':run(a.path,config(a.path))
|
|
else:raise SystemExit(supervise_gate(a.path))
|