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,36 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"tests": 7,
|
||||
"independent_clip_convex_hull_cases": 80,
|
||||
"test_sha256": "2e468015262e376c93a28460a50a45c537abd3b054259483fad5909ab6332823",
|
||||
"code_sha256": {
|
||||
"tools/phase2_b14_math.py": "bb2c2f1c852292365593fd1c6e712c1ca6feb38563721db2acd65c7cd81ed5a0",
|
||||
"tools/phase2_b14_gate.py": "50547261ad28451a49c0c35eda8271c63ad6764649599f69994e0bb131162988",
|
||||
"tools/s2_recovery_monitoring.py": "442c2a9c75e8c00b30a8f2e91cb52d87c466b19a80aea9128b10c021e61b922e",
|
||||
"tools/r4bc_guard.py": "437a756ddf10b125dce450f463e76e28df52724f8c5766e0a989dfa536805628",
|
||||
"tools/r4bc_common.py": "27543fff987975ece767167f9771e6621c825035a053805604e4a696794dfcbd",
|
||||
"tools/s2_recovery_supervisor.py": "f563ca3c2665f5baf0c04f296616e4640423a59b815fbb00479af0f29e57a919",
|
||||
"tools/s2_models/features.py": "3b34ae61cf8012ebd58b7505a73d7aa43d8ee1890ac54f98d7917b67887a45a4",
|
||||
"tools/phase2_fixed_io.py": "ea17fdfc7508f3f980e3cdf69534b1eb8ceb8a8e469c32451b2d5e16d0ada575",
|
||||
"tools/phase2_h1_worker_v2.py": "1543df85b615bb69b79bacd572074a7c77ae19dab110197601573a7e5805ed20",
|
||||
"tools/phase2_residual_math.py": "ffbd9624dec79bdaabf95244fe87209055908f31a977e73ea4377045d6f8fe62",
|
||||
"tools/gre24_models.py": "53b6fee8b700b9b982b06d29908ce2ce23e0c57512c46dbf74b2aade79e3ac3a",
|
||||
"tools/phase2_b1213_features.py": "d8e975b0a5362be7ff00fbf554f2b438b54af1b6b95f8993e7c2beae77f2c8f2",
|
||||
"tools/phase2_b12_math.py": "5465b34be5578cc62a7afc67e3cee3cd489ebb75ce6622a3fa320d1b81196c57",
|
||||
"tools/o1_v2.py": "7bfc81d820a1be7d40b97b2c0b65a616812cb7615b99d80c4ac589788282c291",
|
||||
"tools/o1_partition.py": "5e7dbf97604b9ea9646113a9847e7232020e5f9248fad388177c32ae2a7117da",
|
||||
"tools/o1_prepare.py": "1a695477ee6605d75e7e991205e3e6a49a0907a7733491af8d2771c7bc6a5c23",
|
||||
"tools/gre24_features.py": "92bca4d348f31246c2e931949e2ca38103881b1b784a621a42044db56a460026",
|
||||
"tools/boundary_distance.py": "a45c1cbce92521a96eb814913b4f465b926c0b3883932ab0b7c37d11db113ed7",
|
||||
"tools/audit_samples.py": "a3daf70ec3bcb77bf46d9dc4887d552cf7c422117880a169969780012278cd70",
|
||||
"tools/gre24_features_v2.py": "7dcd5ac218ffdc1ca149edcd87e8658fb3c59e18c0fb9ce47985c7f1357d2cdf",
|
||||
"tools/phase2_b1213_gate.py": "d5a023749e9d8bb6e04a2a2cbdbb8f0d9568924c534f36102d06707859853e10",
|
||||
"tools/s2_models/objectives.py": "5b6527a45f08690055d572335470ce5979e8bb86e1cab00de594f79ae21316b1",
|
||||
"tools/s2_custody_statistics.py": "188565801f6901d0192f79aec0889e632501e672a4149d76d1835efbb9b45447",
|
||||
"tools/s2_custody_common.py": "588c646101be0d50f505f9a12a1c98361aa3437c8c594eecb7321831f717a741",
|
||||
"tools/freeze_g1_components.py": "d0cee60d95243ac2c59ef3f2244ba818315718c4e3d1895f2f9f064f1f7f5ecd"
|
||||
},
|
||||
"gpu": false,
|
||||
"real_parts_executed": false,
|
||||
"CPU_in60second_setup_reserve": true
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
# B14 · 哪些节点可沿两条不同的近最短通道到达?
|
||||
|
||||
MoldAstra,2026-11-17。纸面规格,供 Claude 与 MeltAstra 使用。H2 的 GPU pilot、B1 评分、B12/B13 的父链均按原分工进行;B14 的计算顺序在 B13 之后。目标是给 A 加两列:可核实的近最短通道家族数,以及其中非最大通道的几何体积份额。[Claude 分工](https://arcticnimbus.slack.com/archives/C0C78UFKGRM/p1794900338137689)
|
||||
|
||||
**为什么要定义“家族”。** 把一条走廊重新剖分,可能凭空多出成千上万条长度相近的棱边路径。另一方面,一条几何曲线在三维中体积为零,从若干条曲线本身算不出体积份额。这里把在同一中途截带穿过同一连通通道的路径归为一族,按该段通道的实体体积计份额。这个定义只观察一个中途截带;若分叉与再汇合都发生在截带之前或之后,两条物理流路可以归为同族。单节点的 Df 值也不能识别实际分流比例。
|
||||
|
||||
### 1 用冻结场标识通道
|
||||
|
||||
使用同一件的 retained tet、浇口源集、原节点 ID、物理长度、R1 单元速度 a_K、原 FP64 Df 和严格体积分位 F。在每个 tet 内对节点 F 作 P1 插值,记为 f。对 Fᵢ>0 的目标 i,取满足 r≤Fᵢ/2 的最大二进制层 r=2⁻ᵏ(k≥1),固定截带 3r/4<f<5r/4。这样所有同层目标共用一套几何,浇口在带前,目标在带后。r 仅标记几何进度;**判 5% 用原 Df,不用 F**。
|
||||
|
||||
每个与截带有正体积交集的 tet 产生一个凸片,通过原公共面上具有正面积的带内交集相连;连通块即通道家族 a。其体积 Vₐ 为各凸片按物理坐标精确线性裁切的体积之和。整片处在开带边界时按严格不等号处理,等值平面通常为零体积。逐层核 ΣVₐ=带内总体积,不按 tet 数或路径数加权。每条跨中层的棱 u→v 满足 Fᵤ≤r<Fᵥ;其穿越点在开带内,用 incident tet 确定唯一通道标签。非流形边或只靠点/棱接触而出现不同标签时,记录该物理分量该层为歧义并留缺,不把两条通道强行焊接。分离模腔分别做连接;同一模腔的多个浇口共作源,家族标签按通道,不按浇口名字。
|
||||
|
||||
### 2 精确计算离散定义,不枚举路径
|
||||
|
||||
取真实 tet 无向棱,代价 wᵤᵥ=ℓᵤᵥ/max_{K⊃uv}a_K,复用 R4(a) 共享介质的图约定。tetFIM 允许穿过单元面,图只能沿棱;两个数值距离没有逐点大小保证。B12 的厚度积分是另一个量。为排除往返绕圈制造的假家族,容许路径只穿越中层一次:先在 F≤r 一侧行进,走一条标签为 a 的跨层棱,再在 F>r 一侧行进。带内无需处处单调。[R4(a) 距离定义](https://drive.google.com/file/d/16do4F5lLl2ct2NXm2nAfUd1rWKmNOVeq/view)
|
||||
|
||||
取低侧图上的多浇口最短距离 d₋(u),高侧图上的最短距离 d₊(v,i)。家族 a 的最小代价为
|
||||
|
||||
Lₐ(i) = min_{跨层棱 u→v 属于 a} [ d₋(u) + wᵤᵥ + d₊(v,i) ]。
|
||||
|
||||
缺路径取 +∞。上下两侧点集不相交且边权为正,有限最小值确有简单路径见证。每件先在完整边图跑一次多源最短路得 d_G 作口径检查。预定可比条件 0.95Dfᵢ≤d_G(i)≤1.05Dfᵢ,另列比值分布与高、低两侧超限节点质量。对可比节点取 Aᵢ={a:Lₐ(i)≤1.05Dfᵢ},含等号。由于 Lₐ≥d_G,此时每个家族代表确在原 Df 的 ±5% 内。若 d_G 太低或太高,记“距离口径不合”,不能事后改用 1.05d_G。若在容许图中没有单穿越路径达门,记“无见证”,这不能证明物理模腔没有竞争通道。
|
||||
|
||||
每层只需一次低侧 Dijkstra;每个通道在高侧以入棱两端的累积代价 d₋(u)+wᵤᵥ 初始化一次多源 Dijkstra,即可得到该层所有目标的 Lₐ。可按该层最大 1.05Dfᵢ 截断并逐族累加计数、体积和最大体积,避免存“节点×所有家族”稠密数组。成本随实际占用的层和通道数增长,不能承诺单次最短路成本。在预定顺序按已用 CPU 与剩余规模投影;不得只保留最先算完的几个家族当作全数。
|
||||
|
||||
### 3 输出、反例与判断
|
||||
|
||||
每个有见证的节点输出 Kᵢ=|Aᵢ| 和 Sᵢ=1−max_{a∈Aᵢ}Vₐ/Σ_{a∈Aᵢ}Vₐ。完整家族份额 pₐᵢ=Vₐ/ΣV 可由留存的家族体积、合格 ID 和成本复核;分母只包括可到**该目标**的合格通道,重复路径不会重复算体积。单通道给 (1,0)。若两支均达门、截带体积 3:1,则为 (2,0.25);若次支最短代价为 1.06Df 则为 (1,0)。源节点的零长路径约定 (1,0)。非源零分位、距离不合或标签歧义用双缺失;可比但无见证给 (0,缺失),避免伪称单通道。预定只把 K、S 加给 A,原因及可用性单独记账。即使 S=0.25,实际流量也可能因压差、黏度、支路宽厚与前沿状态而远离 25%。
|
||||
|
||||
按 B12 **实际冻结合同**复用单折 100% 学习名单、validation、全 tet A 的目标/权重/树配置、相同查询及组件配对 CI 与继续门,只将第 20–21 列换为 K、S;不重拟合能按哈希复用的 A。先冻结无标签输入和失败原因。逐件列双列有效的非源体积份额、有 ≥2 族的体积份额、全缺件和 CPU。建议几何覆盖门为学习与评价侧分别至少 80% 的亲缘组件,其每件至少 80% 非源体积有见证;不过则 PARKED(coverage),保留是图/FIM失配、分辨率还是单穿越限制所致的分项。资源帽沿 B12 每枝 2 worker CPU-h,计全部几何、拟合、预测与评分;超限 PARKED(resource)。通过只支持这种单截带描述子在原场/末点指标上有新增信息。失败也只约束本尺度、图度量和家族等价规则。
|
||||
@@ -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