101 lines
8.1 KiB
Python
101 lines
8.1 KiB
Python
"""Common capacity-constrained search for all O1 arms; no post-cut remapping.
|
|
|
|
Dual offsets target equal transported mass on fixed seed-to-node graph distances.
|
|
Indivisible nodes can prevent exact equality; ONLY outputs passing hard +/-5%
|
|
volume bounds and connectivity are feasible. Failure is reported, never repaired
|
|
by remapping edge costs after obtaining a partition.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import resource
|
|
import time
|
|
import numpy as np
|
|
from scipy.optimize import minimize
|
|
from scipy.sparse.csgraph import dijkstra
|
|
if __package__:
|
|
from .route_feasibility import graph_from_edges,partition_report,matched_acceptance
|
|
from .review_partition_scale import histogram_control
|
|
else:
|
|
from route_feasibility import graph_from_edges,partition_report,matched_acceptance
|
|
from review_partition_scale import histogram_control
|
|
|
|
|
|
class FeasibleFound(Exception):pass
|
|
|
|
|
|
def capacity_assignment(distances,mass,bound=.05,maxiter=300):
|
|
k,n=distances.shape;target=mass.sum()/k;normalized_mass=mass/target
|
|
if not np.isfinite(distances).all():raise ValueError('Unreachable node')
|
|
scale=float(np.median(distances[distances>0]));cost=distances/scale
|
|
evaluations=0;best=None;last=None
|
|
def objective(free):
|
|
nonlocal evaluations,best,last
|
|
offsets=np.r_[0.,free];score=cost+offsets[:,None];labels=np.argmin(score,axis=0)
|
|
volume=np.bincount(labels,weights=normalized_mass,minlength=k);violation=float(abs(volume-1).max())
|
|
value=float(offsets.sum()-np.dot(normalized_mass,score[labels,np.arange(n)]))
|
|
evaluations+=1
|
|
candidate=dict(labels=labels.copy(),offsets=offsets.copy(),volume_ratios=volume.copy(),violation=violation,dual_objective=value)
|
|
if best is None or violation<best['violation']:best=candidate
|
|
last=candidate
|
|
if violation<=bound:best=candidate;raise FeasibleFound
|
|
return value,(1-volume)[1:]
|
|
try:
|
|
result=minimize(objective,np.zeros(k-1),method='L-BFGS-B',jac=True,options={'maxiter':maxiter,'maxls':40,'ftol':1e-13,'gtol':1e-9})
|
|
termination=str(result.message)
|
|
except FeasibleFound:termination='first_capacity_feasible_assignment'
|
|
if best is None:raise RuntimeError('No evaluated assignment')
|
|
return best['labels'],dict(capacity_feasible=bool(best['violation']<=bound),maximum_relative_volume_error=best['violation'],volume_ratios=best['volume_ratios'].tolist(),dual_offsets_normalized=best['offsets'].tolist(),distance_normalization=scale,evaluations=evaluations,termination=termination,bound=bound,optimality_claim=False)
|
|
|
|
|
|
def boundary_summary(labels,points,faces,mass):
|
|
q=points[faces];area=np.linalg.norm(np.cross(q[:,1]-q[:,0],q[:,2]-q[:,0]),axis=1)/2
|
|
nodearea=np.bincount(faces.ravel(),weights=np.repeat(area/3,3),minlength=len(points))
|
|
vol=np.bincount(labels,weights=mass);surface=np.bincount(labels,weights=nodearea)
|
|
return dict(exterior_area_fraction=(surface/surface.sum()).tolist(),dimensionless_exterior_exposure=(surface/vol**(2/3)).tolist())
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser();p.add_argument('case');p.add_argument('output',type=Path);a=p.parse_args()
|
|
out=a.output/a.case;out.mkdir(parents=True,exist_ok=True)
|
|
if (out/'capacity_contract.json').exists():raise FileExistsError('Preserve existing execution')
|
|
old=Path('artifacts/routes-review-2026-11-13')/a.case
|
|
previous=json.loads((old/'scale_contract.json').read_text());previous_result=json.loads((old/'result.json').read_text());saved=np.load(old/'partitions.npz')
|
|
d=np.load(Path('artifacts/intake-2026-11-13/samples')/(a.case+'.npz'))
|
|
x=d['points_raw'];edges=d['edges'];mass=d['node_volume_raw'];kind=saved['cleaned_type'];seeds=saved['seeds'];k=len(seeds)
|
|
length=np.linalg.norm(x[edges[:,0]]-x[edges[:,1]],axis=1);graph=graph_from_edges(len(x),edges,length)
|
|
contract=dict(K=k,S_raw=float(mass.sum()/k),source_scale_contract_sha256=hashlib.sha256((old/'scale_contract.json').read_bytes()).hexdigest(),capacity_fraction=.05,capacity_status='New common engineering bound, not previously frozen H1 acceptance. It is sufficient for pairwise volume-fraction L1 <= 0.1 when every arm passes.',capacity_lower=float(.95*mass.sum()/k),capacity_upper=float(1.05*mass.sum()/k),alphas=[4,16,64],matching=previous['thresholds_unchanged'],solver='Fixed-seed graph-distance capacity dual with first-feasible hard-volume check; L-BFGS-B bounded at 300 iterations. Connectivity separately mandatory. No post-hoc node or cost remapping.',control='Exact original edge-cost multiset matched within 20 length strata before shortest paths and capacity solve; held fixed during solve.',full_acceptance_missing=['frozen absolute capacity tolerance approval','pool-level shape statistic and threshold','pool-level boundary-fraction statistic and threshold','type alignment effect threshold','repair/exclusion budget and train/validation pool definition'],execution='CPU only; geometry and saved types only')
|
|
(out/'capacity_contract.json').write_text(json.dumps(contract,indent=2)+'\n')
|
|
start=time.monotonic();records={};cache={};cross=kind[edges[:,0]]!=kind[edges[:,1]]
|
|
def run(name,weights):
|
|
tick=time.monotonic();input_hash=hashlib.sha256(weights.tobytes()).hexdigest()
|
|
g=graph_from_edges(len(x),edges,weights);dist=dijkstra(g,directed=False,indices=seeds)
|
|
labels,solver=capacity_assignment(dist,mass,bound=contract['capacity_fraction'])
|
|
if len(np.unique(labels))==k:
|
|
report=partition_report(labels,graph,edges,x,mass,kind)
|
|
else:
|
|
report=dict(k=int(len(np.unique(labels))),all_connected=False,volume_fractions=(np.bincount(labels,weights=mass,minlength=k)/mass.sum()).tolist(),missing_groups=True)
|
|
# Vanishing groups are invalid and cannot be padded into a pass.
|
|
report['capacity']=solver;report['capacity_and_connectivity_pass']=bool(solver['capacity_feasible'] and report['k']==k and report['all_connected'])
|
|
report['boundary']=boundary_summary(labels,x,d['boundary_triangles'],mass) if report['k']==k and len(np.unique(labels))==k else None
|
|
report['cost_hash_before']=input_hash;report['cost_hash_after']=hashlib.sha256(weights.tobytes()).hexdigest();report['seconds']=time.monotonic()-tick
|
|
records[name]=report;cache[name]=labels
|
|
print(a.case[:8],name,'capacity',report['capacity_and_connectivity_pass'],'maxdev',solver['maximum_relative_volume_error'],'seconds',report['seconds'],flush=True)
|
|
run('generic',length)
|
|
comparisons={}
|
|
for alpha in contract['alphas']:
|
|
weights=length*(1+alpha*cross);control=histogram_control(weights,length)
|
|
if not np.array_equal(np.sort(weights),np.sort(control)):raise AssertionError('Unmatched control costs')
|
|
run(f'type_{alpha}',weights);run(f'control_{alpha}',control)
|
|
t=records[f'type_{alpha}'];c=records[f'control_{alpha}'];g=records['generic']
|
|
checks={label:matched_acceptance(left,right) for label,left,right in [('type_generic',t,g),('control_generic',c,g),('type_control',t,c)]} if all(r['k']==k and len(r['volume_fractions'])==k for r in [t,c,g]) else {}
|
|
capacities=all(r['capacity_and_connectivity_pass'] for r in [t,c,g])
|
|
comparisons[str(alpha)]=dict(capacity_and_connectivity_all_pass=capacities,unchanged_numeric_checks=checks,all_defined_numeric_checks_pass=capacities and len(checks)==3 and all(c['pass_provisional'] for c in checks.values()),full_acceptance='NOT_ESTABLISHED_missing_frozen_pool_items',matched_cost_multiset=True,alignment_interpretation_withheld=True)
|
|
np.savez_compressed(out/'candidate_partitions.npz',**cache)
|
|
result=dict(case=a.case,contract=contract,records=records,comparisons=comparisons,wall_seconds=time.monotonic()-start,peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,solver_limit='A failed bounded search does not prove the capacity-constrained partition problem infeasible. Accepted assignments are feasible certificates, not global optima.')
|
|
(out/'capacity_result.json').write_text(json.dumps(result,indent=2)+'\n')
|
|
print(json.dumps({'case':a.case,'checks':{k:v['all_defined_numeric_checks_pass'] for k,v in comparisons.items()},'wall_seconds':result['wall_seconds'],'peak_rss_kib':result['peak_rss_kib']},indent=2),flush=True)
|
|
|
|
if __name__=='__main__':main()
|