B5 approved bounded local prism certificates and seven synthetic checks

This commit is contained in:
Frank14f committed 2026-11-17 12:57:43 +08:00
1 parent a6998f72a9
commit 8ac1090a21
17 files changed
+1836

No files matched your search

+167
View File
@@ -0,0 +1,167 @@
"""Conservative exact-rational certificate on the stored binary-float tet domain.
No approximate predicate can turn UNKNOWN into acceptance. Complexity and CPU
limits return UNKNOWN. This certifies selected subpatches, not CAD wall truth.
"""
from fractions import Fraction as F
from itertools import combinations
from math import gcd,lcm
import time
class Unknown(RuntimeError):pass
class Work:
def __init__(self,operations=70000,cpu_seconds=300):
self.operations=0;self.limit=operations;self.start=time.process_time();self.cpu_limit=cpu_seconds
def tick(self):
self.operations+=1
if self.operations>self.limit or time.process_time()-self.start>self.cpu_limit:raise Unknown('exact predicate complexity/CPU limit')
def point(p):return tuple(F.from_float(float(v)) for v in p)
def sub(a,b):return tuple(x-y for x,y in zip(a,b))
def dot(a,b):return sum(x*y for x,y in zip(a,b))
def cross(a,b):return (a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0])
def det(a,b,c):return dot(a,cross(b,c))
def primitive(values):
den=lcm(*(v.denominator for v in values));nums=[int(v*den) for v in values]
div=gcd(*map(abs,nums))
if div==0:raise Unknown('zero plane')
return tuple(v//div for v in nums)
def tetra_planes(vertices):
x=tuple(vertices);planes=[]
if det(sub(x[1],x[0]),sub(x[2],x[0]),sub(x[3],x[0]))==0:raise Unknown('degenerate tet')
for omitted in range(4):
face=[x[i] for i in range(4) if i!=omitted];n=cross(sub(face[1],face[0]),sub(face[2],face[0]));d=-dot(n,face[0])
if dot(n,x[omitted])+d>0:n=tuple(-v for v in n);d=-d
planes.append(primitive((*n,d)))
return tuple(planes)
def evalplane(plane,p):return dot(plane[:3],p)+plane[3]
def vertices(planes,work):
planes=tuple(dict.fromkeys(planes))
if len(planes)>24:raise Unknown('too many clipping planes')
out=set()
for a,b,c in combinations(planes,3):
work.tick();den=det(a[:3],b[:3],c[:3])
if den==0:continue
bc=cross(b[:3],c[:3]);ca=cross(c[:3],a[:3]);ab=cross(a[:3],b[:3])
p=tuple(F(-a[3]*bc[i]-b[3]*ca[i]-c[3]*ab[i],den) for i in range(3))
if all(evalplane(h,p)<=0 for h in planes):out.add(p)
return tuple(sorted(out))
def poly(planes,work):
h=tuple(dict.fromkeys(planes));return h,vertices(h,work)
def hull2(items,axes):
ordered=sorted(items,key=lambda p:(p[axes[0]],p[axes[1]]))
def turn(a,b,c):return (b[axes[0]]-a[axes[0]])*(c[axes[1]]-a[axes[1]])-(b[axes[1]]-a[axes[1]])*(c[axes[0]]-a[axes[0]])
lower=[];upper=[]
for p in ordered:
while len(lower)>1 and turn(lower[-2],lower[-1],p)<=0:lower.pop()
lower.append(p)
for p in reversed(ordered):
while len(upper)>1 and turn(upper[-2],upper[-1],p)<=0:upper.pop()
upper.append(p)
return lower[:-1]+upper[:-1]
def volume(p):
planes,verts=p
if len(verts)<4:return F(0)
directions=[sub(v,verts[0]) for v in verts[1:]]
first=next((v for v in directions if any(v)),None)
if first is None:return F(0)
normal=next((cross(first,v) for v in directions if any(cross(first,v))),None)
if normal is None or all(dot(normal,v)==0 for v in directions):return F(0)
total=F(0);seen=set()
for plane in planes:
face=tuple(v for v in verts if evalplane(plane,v)==0)
if len(face)<3 or frozenset(face) in seen:continue
seen.add(frozenset(face));axis=max(range(3),key=lambda i:abs(plane[i]));axes=[i for i in range(3) if i!=axis]
boundary=hull2(face,axes)
if plane[axis]*(1 if axis!=1 else -1)<0:boundary.reverse()
for j in range(1,len(boundary)-1):total+=det(boundary[0],boundary[j],boundary[j+1])/6
if total<0:raise Unknown('oriented volume inconsistency')
return total
def clip(p,plane,work):
h,v=p
if not v:return p
vals=[evalplane(plane,x) for x in v]
if max(vals)<=0:return p
if min(vals)>0:return (h+(plane,),())
return poly(h+(plane,),work)
def outside(p,solid_planes,work):
remaining=p;pieces=[]
for h in solid_planes:
if not remaining[1]:break
fragment=clip(remaining,tuple(-v for v in h),work)
if volume(fragment)>0:pieces.append(fragment)
remaining=clip(remaining,h,work)
return pieces
def in_common(p,shared):
if not shared:return False
if len(shared)==1:return p==shared[0]
a=shared[0];b=sub(shared[1],a);v=sub(p,a)
if len(shared)==2:
k=next((i for i in range(3) if b[i]!=0),None)
if k is None:return p==a
t=v[k]/b[k];return 0<=t<=1 and all(v[i]==t*b[i] for i in range(3))
c=sub(shared[2],a)
for i,j in combinations(range(3),2):
d=b[i]*c[j]-b[j]*c[i]
if d:
u=(v[i]*c[j]-v[j]*c[i])/d;w=(b[i]*v[j]-b[j]*v[i])/d
return u>=0 and w>=0 and u+w<=1 and all(v[k]==u*b[k]+w*c[k] for k in range(3))
raise Unknown('degenerate shared reference face')
PRISM=((0,1,2,5),(0,4,1,5),(0,3,4,5))
def certify(points,cavity_tets,work=None):
work=work or Work();x=tuple(point(p) for p in points)
reference_order=(0,1,2,3,4,5)
if len(x)!=6 or len(set(x))!=6:return dict(status='REJECT',reason='non-distinct prism vertices')
signs=[det(sub(x[t[1]],x[t[0]]),sub(x[t[2]],x[t[0]]),sub(x[t[3]],x[t[0]])) for t in PRISM]
if all(v<0 for v in signs):
reference_order=(0,2,1,3,5,4)
x=tuple(x[i] for i in (0,2,1,3,5,4));signs=[det(sub(x[t[1]],x[t[0]]),sub(x[t[2]],x[t[0]]),sub(x[t[3]],x[t[0]])) for t in PRISM]
if any(v<=0 for v in signs):return dict(status='REJECT',reason='folded or degenerate product mapping')
polys=[(tetra_planes([x[i] for i in t]),tuple(x[i] for i in t)) for t in PRISM]
for i,j in combinations(range(3),2):
intersection=vertices(polys[i][0]+polys[j][0],work)
shared=[x[k] for k in sorted(set(PRISM[i]) & set(PRISM[j]))]
if any(not in_common(p,shared) for p in intersection):return dict(status='REJECT',reason='nonlocal image self intersection')
cavity=[]
for t in cavity_tets:
work.tick();cavity.append(tetra_planes(tuple(point(p) for p in t)))
for p in polys:
uncovered=[p]
for planes in cavity:
work.tick()
uncovered=[q for prior in uncovered for q in outside(prior,planes,work)]
if len(uncovered)>256:raise Unknown('uncovered polytope count cap')
if not uncovered:break
if uncovered:return dict(status='REJECT',reason='positive volume outside original cavity union',uncovered_volume=float(sum(volume(p) for p in uncovered)))
v=sum(signs)/6
return dict(status='CERTIFIED',volume=float(v),volume_fraction_exact=[str(v.numerator),str(v.denominator)],
operations=work.operations,verification='exact rational predicates for stored binary-float coordinates',tetrahedra=3,
reference_vertex_order=list(reference_order))
+152
View File
@@ -0,0 +1,152 @@
"""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))
+24
View File
@@ -0,0 +1,24 @@
import unittest
import numpy as np
from phase2_b5_certificate import certify,PRISM,Work,Unknown
class CertificateTests(unittest.TestCase):
def test_triangular_plate_exact_cover_and_oblique_transform(self):
p=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[1,0,1],[0,1,1]],float)
for x in (p,p@np.array([[1,.25,0],[0,1,.5],[.25,0,1]])+np.array([2.,-1.,3.])):
r=certify(x,x[np.array(PRISM)]);self.assertEqual(r['status'],'CERTIFIED')
def test_foldback_air_gap_rejected(self):
p=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,3],[1,0,3],[0,1,3]],float)
lower=p.copy();lower[3:,2]=1;upper=p.copy();upper[:3,2]=2
cavity=np.concatenate([lower[np.array(PRISM)],upper[np.array(PRISM)]])
r=certify(p,cavity);self.assertEqual(r['status'],'REJECT');self.assertIn('outside',r['reason'])
def test_rib_root_folded_correspondence_rejected(self):
p=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[0,1,1],[1,0,1]],float)
r=certify(p,np.zeros((0,4,3)));self.assertEqual(r['status'],'REJECT')
def test_budget_is_unknown_not_acceptance(self):
p=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[1,0,1],[0,1,1]],float)
with self.assertRaises(Unknown):certify(p,p[np.array(PRISM)],Work(operations=1))
if __name__=='__main__':unittest.main()
+48
View File
@@ -0,0 +1,48 @@
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
import numpy as np
from phase2_b5_certificate import certify,PRISM,Work,F,Unknown
from phase2_b5_gate import candidates,union_add,run,sha
def fixture():
x=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,.125],[1,0,.125],[0,1,.125]],float)
t=np.array(PRISM);faces={}
for tet in t:
for k in range(4):
face=tuple(sorted(np.delete(tet,k)));faces[face]=faces.get(face,0)+1
boundary=np.array([f for f,n in faces.items() if n==1]);raw=np.arange(100,106)
return x,t,boundary,raw
class IntegrationTests(unittest.TestCase):
def test_boundary_selection_certificate_and_duplicate_union(self):
x,t,faces,raw=fixture();selected=candidates(x,t,faces,raw,{})
self.assertTrue(selected);self.assertLessEqual(len(selected),3)
item=next(p for p in selected if set(p['local_ids'])==set(range(6)))
points=np.array(item['points']);r=certify(points,x[t]);self.assertEqual(r['status'],'CERTIFIED')
added,polys=union_add(points,r,[],Work());self.assertEqual(added,F(1,16))
duplicate,_=union_add(points,r,polys,Work());self.assertEqual(duplicate,0)
def test_reversed_reference_metadata_reconstructs_volume(self):
x,t,_,_=fixture();p=x[[0,2,1,3,5,4]];r=certify(p,x[t])
self.assertEqual(r['status'],'CERTIFIED');self.assertEqual(r['reference_vertex_order'],[0,2,1,3,5,4])
added,_=union_add(p,r,[],Work());self.assertEqual(added,F(1,16))
def test_one_part_pipeline_reads_only_geometry_and_preserves_unknown(self):
x,t,faces,raw=fixture()
with TemporaryDirectory() as temp:
base=Path(temp);source=base/'source';source.mkdir();root=base/'gate';root.mkdir()
np.savez(source/'geometry.npz',points_raw=x,tetra=t,boundary_triangles=faces,raw_node_ids=raw,node_volume_raw=np.full(6,1/96))
row=dict(case='synthetic',component_id='synthetic',preparation=dict(preparation_root=str(source),output_sha256={'geometry.npz':sha(source/'geometry.npz')}))
run(root,dict(parts=[row]));part=json.loads((root/'parts/synthetic/result.json').read_text())
self.assertTrue(part['union_coverage_complete']);self.assertAlmostEqual(part['certified_union_fraction'],1.)
self.assertFalse(part['labels_read']);self.assertIsNone(part['independently_checked_cross_air_acceptances'])
self.assertEqual(json.loads((root/'result.json').read_text())['decision'],'PARK_COVERAGE_UNKNOWN')
with self.assertRaises(Unknown):
r=certify(x,x[t]);union_add(x,r,union_add(x,r,[],Work())[1],Work(operations=0))
if __name__=='__main__':unittest.main()