Archived
Freeze approved B14 exact channel-family geometry gate
This commit is contained in:
1 parent
8ea58fe9d2
commit
47c85a8a14
6 files changed
+108884
No files matched your search
@@ -0,0 +1,81 @@
|
||||
"""Independent B14 channel gate, original B12 scientific fitting/scoring reused."""
|
||||
import argparse,fcntl,json,os,resource,sys,time,traceback
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from phase2_b1213_gate import config,read,coverage,train,predict,score
|
||||
from phase2_b1213_features import input_geometry,cached,flow_mesh,cell_flow_speed,exterior_faces,InputViolation
|
||||
from phase2_h1_worker_v2 import checked,sha,save
|
||||
from phase2_fixed_io import BASE,freeze
|
||||
from r4bc_guard import supervise
|
||||
from s2_recovery_monitoring import disk_usage
|
||||
from phase2_b14_math import channels
|
||||
|
||||
def field(root,c,index):
|
||||
row=c['parts'][index];dest=root/'parts'/f'{index:04d}';start=time.process_time()
|
||||
try:
|
||||
x,t,raw,old=input_geometry(row);g=flow_mesh(x,t);F=cached(row,'Vf');df=cached(row,'Df');dw=cached(row,'Dw')
|
||||
source=np.searchsorted(raw,old['features']['gate_raw_ids'])
|
||||
if np.any(source>=len(raw)) or not np.array_equal(raw[source],old['features']['gate_raw_ids']):raise InputViolation('Gate identity')
|
||||
speed,allwall=cell_flow_speed(g,dw,exterior_faces(t))
|
||||
if not np.allclose([speed.min(),speed.max()],[old['features']['speed_min'],old['features']['speed_max']],rtol=1e-12,atol=0):raise InputViolation('Shared R1 speed differs')
|
||||
if not np.isfinite(F).all() or not np.isfinite(df).all() or np.any(F<0) or np.any(F>1) or np.any(df<0):raise ValueError('Invalid frozen F/Df')
|
||||
receipts=[]
|
||||
def emit(record,arrays):
|
||||
p=dest/f'layer-{len(receipts):03d}.npz';np.savez_compressed(p,**arrays);receipts.append(dict(**record,path=str(p),sha256=sha(p)))
|
||||
save(dest/'progress.json',dict(layers_completed=len(receipts),last_layer=record,cpu_seconds=time.process_time()-start))
|
||||
extra,report,dg=channels(x,t,F,df,g['mass'],g['volume'],speed,source,emit)
|
||||
np.save(dest/'extra.npy',extra,allow_pickle=False);np.savez_compressed(dest/'distances.npz',dG=dg,Df=df,F=F,raw_ids=raw)
|
||||
complete=report['valid_nonroot_volume_fraction']>=.8
|
||||
save(dest/'result.json',dict(case=row['case'],component_id=row['component_id'],index=index,nodes=row['nodes'],status='GEOMETRY_COMPLETE' if complete else 'SCIENTIFIC_MISSING',reason=None if complete else 'NONROOT_VOLUME_WITNESS_COVERAGE_BELOW_80PCT',
|
||||
extra_sha256=sha(dest/'extra.npy'),distances_sha256=sha(dest/'distances.npz'),layer_receipts=receipts,labels_read=False,all_families_attempted=True,**report,cpu_seconds=time.process_time()-start))
|
||||
except BaseException as exc:
|
||||
save(dest/'failure.json',dict(type=type(exc).__name__,reason=str(exc),traceback=traceback.format_exc(),cpu_seconds=time.process_time()-start,partial_is_not_complete=True));raise
|
||||
|
||||
|
||||
def run(root):
|
||||
c=config(root);os.sched_setaffinity(0,[26]);lock=(root/'run.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if (root/'started.json').exists():raise FileExistsError('Single launch; zero retries')
|
||||
start=time.process_time();u0=resource.getrusage(resource.RUSAGE_CHILDREN);charged=0.;records=[];entries=[];results={}
|
||||
def total():
|
||||
u=resource.getrusage(resource.RUSAGE_CHILDREN);return 60+max(charged,u.ru_utime+u.ru_stime-u0.ru_utime-u0.ru_stime)+time.process_time()-start
|
||||
def guard(mode,dest,cap,wall,index=None):
|
||||
nonlocal charged
|
||||
remaining=c['disk_bytes']-disk_usage(root)
|
||||
cap=min(cap,7200-total()-120)
|
||||
if cap<=0 or remaining<=0:raise RuntimeError('Resource reserve exhausted')
|
||||
command=[sys.executable,'tools/phase2_b14_gate.py',mode,str(root)]+([] if index is None else [str(index)])
|
||||
g=supervise(command,dest,dict(cpu_seconds=cap,wall_seconds=wall,rss_bytes=c['rss_bytes'],disk_bytes=remaining))
|
||||
charged+=g['cpu_seconds'];records.append(dict(mode=mode,index=index,guard=g));save(root/'phase-ledger.json',dict(records=records,cumulative_cpu_seconds=total()))
|
||||
if g['status']!='PASS' or total()>7200 or disk_usage(root)>c['disk_bytes']:raise RuntimeError('ENGINEERING_OR_RESOURCE_STOP')
|
||||
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json')))
|
||||
try:
|
||||
for i,row in enumerate(c['parts']):
|
||||
if total()-60+c['part_cpu_seconds']>c['geometry_cpu_cap']:raise RuntimeError('PARK_RESOURCE_GEOMETRY_CAP')
|
||||
dest=root/'parts'/f'{i:04d}';dest.mkdir(parents=True,exist_ok=False)
|
||||
save(root/'live-progress.json',dict(stage='GEOMETRY_ONLY',index=i,case=row['case'],cumulative_cpu_seconds=total(),unix=time.time()))
|
||||
guard('field',dest,c['part_cpu_seconds'],c['part_wall_seconds'],i)
|
||||
result=read(dest/'result.json');results[row['case']]=result;entries.append(dict(case=row['case'],index=i,result_sha256=sha(dest/'result.json')))
|
||||
if i+1==c['cost_checkpoint']:
|
||||
projected=1.25*(total()-60)*sum(r['nodes'] for r in c['parts'])/sum(r['nodes'] for r in c['parts'][:i+1])
|
||||
save(root/'first-ten-cost-check.json',dict(projected_geometry_cpu_seconds=projected,cap=c['geometry_cpu_cap'],passed=projected<=c['geometry_cpu_cap'],actual_cpu_seconds=total()))
|
||||
if projected>c['geometry_cpu_cap']:raise RuntimeError('PARK_RESOURCE_FIRST_TEN_PROJECTION')
|
||||
cov={role:coverage(rows,results) for role,rows in c['rows'].items()};save(root/'coverage.json',cov)
|
||||
save(root/'features-manifest.json',dict(entries=entries,all431_terminal=True,labels_read=False))
|
||||
freeze(root,'features',[root/'contract.json',root/'features-manifest.json',root/'coverage.json',*[BASE/p for p in c['code_sha256']]])
|
||||
if c['kind']=='B14' and any(v['fraction']<.8 for v in cov.values()):
|
||||
save(root/'complete.json',dict(status='COMPLETE',scientific_gate='PARK_CHANNEL_COVERAGE',coverage=cov,cumulative_cpu_seconds=total(),records=records,models_fit=0,retry=False));return
|
||||
for mode,cap in [('train',c['fit_cpu_cap']),('predict',c['predict_cpu_cap']),('score',c['score_cpu_cap'])]:
|
||||
if mode=='predict':freeze(root,'model',[root/'contract.json',root/'phases/train/model.ubj',root/'phases/train/result.json',*[BASE/p for p in c['code_sha256']]])
|
||||
if mode=='score':freeze(root,'predictions',[root/'contract.json',root/'phases/predict/manifest.json',*[BASE/p for p in c['code_sha256']]])
|
||||
dest=root/'phases'/mode;dest.mkdir(parents=True,exist_ok=False);save(root/'live-progress.json',dict(stage=mode,cumulative_cpu_seconds=total(),unix=time.time()))
|
||||
guard(mode,dest,cap,cap+60)
|
||||
save(root/'complete.json',dict(status='COMPLETE',scientific_gate=read(root/'phases/score/result.json')['decision'],cumulative_cpu_seconds=total(),records=records,models_fit=1,retry=False))
|
||||
except BaseException as exc:
|
||||
save(root/'complete.json',dict(status='STOPPED',reason=type(exc).__name__+': '+str(exc),cumulative_cpu_seconds=total(),records=records,completed_geometry_parts=len(entries),retry=False));raise
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('mode',choices=['run','field','train','predict','score']);p.add_argument('root',type=Path);p.add_argument('index',nargs='?',type=int);a=p.parse_args()
|
||||
if a.mode=='run':run(a.root)
|
||||
elif a.mode=='field':field(a.root,config(a.root),a.index)
|
||||
else:dict(train=train,predict=predict,score=score)[a.mode](a.root,config(a.root))
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Exact P1 band volumes, face-connected families and once-crossing paths."""
|
||||
import itertools
|
||||
import numpy as np
|
||||
from scipy.sparse import coo_matrix
|
||||
from scipy.sparse.csgraph import connected_components,dijkstra
|
||||
PAIRS=list(itertools.combinations(range(4),2))
|
||||
FACES=list(itertools.combinations(range(4),3))
|
||||
|
||||
def below_fraction(values,t,inclusive=False):
|
||||
f=np.sort(np.asarray(values,np.longdouble),axis=1);n=np.sum(f<=t if inclusive else f<t,axis=1);v=np.zeros(len(f),np.longdouble);v[n==4]=1
|
||||
for count in [1,2,3]:
|
||||
ix=n==count;a=f[ix]
|
||||
if not len(a):continue
|
||||
if count==1:v[ix]=np.prod((t-a[:,0,None])/(a[:,1:]-a[:,0,None]),axis=1)
|
||||
elif count==3:v[ix]=1-np.prod((a[:,3,None]-t)/(a[:,3,None]-a[:,:3]),axis=1)
|
||||
else:
|
||||
q02=(t-a[:,0])/(a[:,2]-a[:,0]);q03=(t-a[:,0])/(a[:,3]-a[:,0]);q12=(t-a[:,1])/(a[:,2]-a[:,1]);q13=(t-a[:,1])/(a[:,3]-a[:,1])
|
||||
v[ix]=q02*q03+q02*q13*(1-q03)+q12*q13*(1-q02)
|
||||
return v
|
||||
|
||||
def band_fraction(f,lo,hi):
|
||||
result=below_fraction(f,hi)-below_fraction(f,lo,True)
|
||||
expected=(np.min(f,axis=1)<hi)&(np.max(f,axis=1)>lo)
|
||||
if np.any(result<0) or np.any(result>1) or np.any(expected&(result<=0)):raise ValueError('Unresolved positive-volume clip / numerical cancellation')
|
||||
return np.asarray(result,np.float64)
|
||||
|
||||
def layers(F):
|
||||
out=np.zeros(len(F));good=F>0
|
||||
_,e=np.frexp(F[good]/2);out[good]=np.ldexp(np.ones(sum(good)),np.minimum(e-1,-1));return out
|
||||
|
||||
def graph(n,edges,cost,mask=None,initial=None):
|
||||
if mask is not None:edges=edges[mask];cost=cost[mask]
|
||||
u=np.r_[edges[:,0],edges[:,1]];v=np.r_[edges[:,1],edges[:,0]];w=np.r_[cost,cost]
|
||||
if initial is not None:
|
||||
ii=np.flatnonzero(np.isfinite(initial));u=np.r_[u,np.full(len(ii),n)];v=np.r_[v,ii];w=np.r_[w,initial[ii]];n+=1
|
||||
return coo_matrix((w,(u,v)),shape=(n,n)).tocsr()
|
||||
|
||||
def edge_data(x,t,speed):
|
||||
all_edges=np.sort(t[:,PAIRS].reshape(-1,2),axis=1);edges,inverse=np.unique(all_edges,axis=0,return_inverse=True)
|
||||
fastest=np.zeros(len(edges));np.maximum.at(fastest,inverse,np.repeat(speed,6));cost=np.linalg.norm(x[edges[:,0]]-x[edges[:,1]],axis=1)/fastest
|
||||
if not np.isfinite(cost).all() or np.any(cost<=0):raise ValueError('Nonpositive/nonfinite true edge cost')
|
||||
return edges,inverse,cost
|
||||
|
||||
def families(t,F,volume,r):
|
||||
frac=band_fraction(F[t],.75*r,1.25*r);active=frac>0;ids=np.flatnonzero(active);label=np.full(len(t),-1,int)
|
||||
faces=np.sort(t[:,FACES].reshape(-1,3),axis=1);uniq,inv,count=np.unique(faces,axis=0,return_inverse=True,return_counts=True)
|
||||
order=np.argsort(inv,kind='stable');starts=np.r_[0,np.cumsum(count[:-1])];two=np.flatnonzero(count==2)
|
||||
owners=np.repeat(np.arange(len(t)),4);a=owners[order[starts[two]]];b=owners[order[starts[two]+1]]
|
||||
values=F[uniq[two]];ok=active[a]&active[b]&(values.min(1)<1.25*r)&(values.max(1)>.75*r)
|
||||
local=np.full(len(t),-1,int);local[ids]=np.arange(len(ids));aa=local[a[ok]];bb=local[b[ok]]
|
||||
mat=coo_matrix((np.ones(2*len(aa)),(np.r_[aa,bb],np.r_[bb,aa])),shape=(len(ids),len(ids))).tocsr()
|
||||
n,labels=connected_components(mat,directed=False);label[ids]=labels;vol=np.bincount(labels,weights=volume[ids]*frac[ids],minlength=n)
|
||||
if not np.isclose(vol.sum(),np.sum(volume*frac),rtol=1e-13,atol=0):raise ValueError('Band volume conservation')
|
||||
badface=np.flatnonzero((count>2)&(F[uniq].min(1)<1.25*r)&(F[uniq].max(1)>.75*r))
|
||||
return label,vol,frac,uniq[badface]
|
||||
|
||||
def manifold_edge(tets,u,v):
|
||||
links=[tuple(int(x) for x in tet if x!=u and x!=v) for tet in tets];adj={}
|
||||
for a,b in links:adj.setdefault(a,set()).add(b);adj.setdefault(b,set()).add(a)
|
||||
if len(set(tuple(sorted(x)) for x in links))!=len(links) or any(len(v)>2 for v in adj.values()):return False
|
||||
seen=set();todo=[next(iter(adj))]
|
||||
while todo:
|
||||
a=todo.pop()
|
||||
if a not in seen:seen.add(a);todo.extend(adj[a]-seen)
|
||||
return len(seen)==len(adj)
|
||||
|
||||
def channels(x,t,F,Df,mass,volume,speed,sources,emit):
|
||||
n=len(x);edges,inv,cost=edge_data(x,t,speed);G=graph(n,edges,cost);_,physical=connected_components(G,directed=False)
|
||||
dG=dijkstra(G,directed=False,indices=sources,min_only=True);source=np.zeros(n,bool);source[sources]=True
|
||||
comparable=np.isfinite(dG)&np.isfinite(Df)&(dG>=.95*Df)&(dG<=1.05*Df)
|
||||
extra=np.full((n,2),np.nan);extra[source]=[1,0];layer=layers(F);diag=[]
|
||||
edgeorder=np.argsort(inv,kind='stable');edgecount=np.bincount(inv,minlength=len(edges));edgestart=np.r_[0,np.cumsum(edgecount[:-1])];owners=np.repeat(np.arange(len(t)),6)
|
||||
for r in np.unique(layer[(~source)&(F>0)]):
|
||||
target=np.flatnonzero((layer==r)&~source);label,V,frac,badfaces=families(t,F,volume,r)
|
||||
low=F<=r;cross=low[edges[:,0]]!=low[edges[:,1]];ce=np.flatnonzero(cross);u=edges[ce,0].copy();v=edges[ce,1].copy();rev=~low[u];u[rev],v[rev]=v[rev].copy(),u[rev].copy()
|
||||
flabel=np.full(len(ce),-1,int);ambiguous=set(physical[badfaces.ravel()].tolist())
|
||||
for j,e in enumerate(ce):
|
||||
incident=owners[edgeorder[edgestart[e]:edgestart[e]+edgecount[e]]];labels=np.unique(label[incident]);labels=labels[labels>=0]
|
||||
if len(labels)!=1 or not manifold_edge(t[incident],int(u[j]),int(v[j])):ambiguous.add(int(physical[u[j]]))
|
||||
else:flabel[j]=labels[0]
|
||||
lowG=graph(n,edges,cost,low[edges[:,0]]&low[edges[:,1]])
|
||||
dm=dijkstra(lowG,directed=False,indices=sources,min_only=True);highmask=~low[edges[:,0]]&~low[edges[:,1]]
|
||||
count=np.zeros(len(target),int);sums=np.zeros(len(target));maximum=np.zeros(len(target));qt=[];qa=[];ql=[]
|
||||
eligible=comparable[target]&~np.isin(physical[target],list(ambiguous));limit=float(np.max(1.05*Df[target]))
|
||||
for a in range(len(V)):
|
||||
es=np.flatnonzero(flabel==a)
|
||||
if not len(es):continue
|
||||
init=np.full(n,np.inf);np.minimum.at(init,v[es],dm[u[es]]+cost[ce[es]])
|
||||
H=graph(n,edges,cost,highmask,init);L=dijkstra(H,directed=True,indices=n,limit=limit)[:n][target]
|
||||
qualifies=eligible&np.isfinite(L)&(L<=1.05*Df[target])
|
||||
if np.any(L[np.isfinite(L)]+1e-10*np.maximum(1,dG[target][np.isfinite(L)])<dG[target][np.isfinite(L)]):raise ValueError('Restricted path below full graph distance')
|
||||
count[qualifies]+=1;sums[qualifies]+=V[a];maximum[qualifies]=np.maximum(maximum[qualifies],V[a]);qt.extend(target[qualifies]);qa.extend(np.full(sum(qualifies),a));ql.extend(L[qualifies])
|
||||
extra[target[eligible],0]=count[eligible];w=eligible&(count>0);extra[target[w],1]=1-maximum[w]/sums[w]
|
||||
record=dict(r=float(r),targets=len(target),families=len(V),band_volume=float(V.sum()),ambiguous_components=sorted(ambiguous),qualified_targets=int(sum(w)),comparable_targets=int(sum(comparable[target])),no_witness=int(sum(eligible&(count==0))))
|
||||
emit(record,dict(family_volume=V,tet_family=label,tet_band_fraction=frac,target_ids=target,qualified_target=np.asarray(qt,int),qualified_family=np.asarray(qa,int),qualified_cost=np.asarray(ql,float)))
|
||||
diag.append(record)
|
||||
nonroot=~source;den=float(mass[nonroot].sum());valid=np.isfinite(extra).all(1)&nonroot
|
||||
reason=dict(distance_low=float(mass[nonroot&(dG<.95*Df)].sum()/den),distance_high=float(mass[nonroot&(dG>1.05*Df)].sum()/den),nonroot_zero_F=float(mass[nonroot&(F==0)].sum()/den))
|
||||
return extra,dict(layers=diag,valid_nonroot_volume_fraction=float(mass[valid].sum()/den),two_family_nonroot_volume_fraction=float(mass[valid&(extra[:,0]>=2)].sum()/den),missing_reasons_volume_fraction=reason,source_nodes=int(sum(source)),nonroot_volume=den),dG
|
||||
@@ -0,0 +1,36 @@
|
||||
import unittest,itertools
|
||||
import numpy as np
|
||||
from scipy.spatial import ConvexHull
|
||||
from phase2_b14_math import below_fraction,band_fraction,layers,manifold_edge,channels,families
|
||||
class ChannelTests(unittest.TestCase):
|
||||
def test_clip_against_convex_hull(self):
|
||||
rng=np.random.default_rng(17);x=np.vstack([np.zeros(3),np.eye(3)])
|
||||
for k in range(80):
|
||||
f=rng.uniform(-1,1,4);cut=float(rng.uniform(f.min(),f.max()));pts=list(x[f<cut])
|
||||
for i,j in itertools.combinations(range(4),2):
|
||||
if (f[i]<cut)!=(f[j]<cut):pts.append(x[i]+(cut-f[i])/(f[j]-f[i])*(x[j]-x[i]))
|
||||
vol=ConvexHull(np.array(pts)).volume*6;self.assertAlmostEqual(float(below_fraction(f[None],cut)[0]),vol,places=12)
|
||||
def test_constant_strict_boundary(self):
|
||||
f=np.array([[1,1,1,1],[.5,.5,.5,.5],[0,0,1,1]],float)
|
||||
np.testing.assert_allclose(band_fraction(f,.5,1),[0,0,.5])
|
||||
def test_partition_volume(self):
|
||||
f=np.array([[0,.1,.7,1],[0,0,1,1]],float)
|
||||
total=sum(band_fraction(f,a,b) for a,b in zip([0,.2,.5,.7],[.2,.5,.7,1]))
|
||||
np.testing.assert_allclose(total,1,atol=1e-14)
|
||||
def test_binary_layers(self):
|
||||
np.testing.assert_array_equal(layers(np.array([0,.25,.5,1.])),[0,.125,.25,.5])
|
||||
def test_edge_link_point_contact_and_fork(self):
|
||||
self.assertFalse(manifold_edge([[0,1,2,3],[0,1,4,5]],0,1))
|
||||
self.assertFalse(manifold_edge([[0,1,2,3],[0,1,3,4],[0,1,3,5]],0,1))
|
||||
self.assertTrue(manifold_edge([[0,1,2,3],[0,1,3,4]],0,1))
|
||||
def test_single_tet_witness_and_mismatch(self):
|
||||
x=np.vstack([np.zeros(3),np.eye(3)]);t=np.array([[0,1,2,3]]);f=np.array([0,1,1,1.]);d=np.array([0,1,1,1.]);mass=np.ones(4)/24
|
||||
e,r,g=channels(x,t,f,d,mass,np.array([1/6]),np.ones(1),np.array([0]),lambda *a:None)
|
||||
np.testing.assert_allclose(e,np.tile([1,0],(4,1)))
|
||||
e,r,g=channels(x,t,f,d*.8,mass,np.array([1/6]),np.ones(1),np.array([0]),lambda *a:None)
|
||||
self.assertTrue(np.isnan(e[1:]).all());np.testing.assert_array_equal(e[0],[1,0])
|
||||
def test_disconnected_tets_no_air_family(self):
|
||||
t=np.array([[0,1,2,3],[4,5,6,7]]);f=np.tile([0,1,1,1.],2)
|
||||
label,v,frac,bad=families(t,f,np.array([1.,3.]),.5)
|
||||
self.assertEqual(len(v),2);self.assertAlmostEqual(v.max()/v.min(),3)
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in new issue
Block a user