Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
121 lines
6.5 KiB
Python
121 lines
6.5 KiB
Python
"""Choose whole admissible configurations; never manufacture geometry.
|
|
|
|
Observation rewards belong to immutable metric samples, not objects. A sample
|
|
covered by several compatible configurations is paid once. Fresh-run input
|
|
objects must each be retained or replaced exactly once. Solver limits return a
|
|
checked feasible incumbent, with a distinct status from proven optimality.
|
|
"""
|
|
from collections import defaultdict
|
|
import time
|
|
import numpy as np
|
|
from scipy.optimize import Bounds, LinearConstraint, milp
|
|
from scipy.sparse import coo_matrix
|
|
|
|
|
|
def conflict_cliques(count,edges):
|
|
"""Exact edge cover by cliques; no new conflicts and no lost conflicts.
|
|
|
|
Family subseries produce dense overlap graphs. Encoding each overlap as a
|
|
separate matrix row is wasteful. Bitset intersection only joins vertices
|
|
already pairwise incompatible. Residual pairs are valid size-two cliques.
|
|
"""
|
|
adjacency=[0]*count
|
|
for a,b in edges:adjacency[a]|=1<<b;adjacency[b]|=1<<a
|
|
remaining=adjacency.copy();groups=[]
|
|
while any(remaining):
|
|
pivot=max(range(count),key=lambda i:remaining[i].bit_count())
|
|
allowed=remaining[pivot];clique=[pivot];mask=1<<pivot
|
|
while allowed:
|
|
bit=allowed&-allowed;v=bit.bit_length()-1
|
|
clique.append(v);mask|=bit;allowed&=adjacency[v]
|
|
for v in clique:remaining[v]&=~mask
|
|
groups.append(clique)
|
|
return groups
|
|
|
|
|
|
def choose(nodes, conflicts, samples, seconds=30., component_seconds=5.):
|
|
started=time.monotonic()
|
|
nodes=sorted(nodes,key=lambda n:n['id'])
|
|
index={n['id']:i for i,n in enumerate(nodes)}
|
|
assert len(index)==len(nodes)
|
|
ownership=defaultdict(list)
|
|
for i,n in enumerate(nodes):
|
|
for source in n['sources']:ownership[source].append(i)
|
|
edges=[(index[a],index[b]) for a,b in conflicts]
|
|
groups=defaultdict(float)
|
|
for members,weight in samples:
|
|
key=tuple(sorted(index[n] for n in members))
|
|
if key:groups[key]+=weight
|
|
parent=list(range(len(nodes)))
|
|
def root(i):
|
|
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
|
|
return i
|
|
def connect(ids):
|
|
for i in ids[1:]:parent[root(i)]=root(ids[0])
|
|
for ids in list(ownership.values())+list(groups)+[list(e) for e in edges]:connect(ids)
|
|
components=defaultdict(list)
|
|
for i in range(len(nodes)):components[root(i)].append(i)
|
|
selected=[];reports=[]
|
|
for members in sorted(components.values(),key=lambda ids:nodes[ids[0]]['id']):
|
|
local={i:k for k,i in enumerate(members)};m=len(members)
|
|
rewards=[(tuple(local[i] for i in ids),w) for ids,w in groups.items() if ids[0] in local]
|
|
c=np.array([nodes[i]['cost'] for i in members]+[-w for _,w in rewards],float)
|
|
rr=[];cc=[];vv=[];lower=[];upper=[]
|
|
def constraint(terms,lo,hi):
|
|
row=len(lower)
|
|
for col,value in terms:rr.append(row);cc.append(col);vv.append(value)
|
|
lower.append(lo);upper.append(hi)
|
|
for ids in ownership.values():
|
|
if ids[0] in local:constraint([(local[i],1) for i in ids],1,1)
|
|
local_edges=[(local[a],local[b]) for a,b in edges if a in local]
|
|
cliques=conflict_cliques(m,local_edges)
|
|
for ids in cliques:constraint([(i,1) for i in ids],-np.inf,1)
|
|
for k,(ids,_) in enumerate(rewards):
|
|
constraint([(m+k,1)]+[(i,-1) for i in ids],-np.inf,0)
|
|
A=coo_matrix((vv,(rr,cc)),shape=(len(lower),len(c))).tocsc()
|
|
lb=np.array(lower);ub=np.array(upper)
|
|
fallback=np.zeros(len(c))
|
|
fallback[:m]=[bool(nodes[i].get('incumbent')) for i in members]
|
|
for k,(ids,_) in enumerate(rewards):fallback[m+k]=any(fallback[i] for i in ids)
|
|
def valid(x):
|
|
return x is not None and np.isfinite(x).all() and np.all(abs(x-np.rint(x))<1e-6) and np.all(x>=-1e-6) and np.all(x<=1+1e-6) and np.all(A@x>=lb-1e-6) and np.all(A@x<=ub+1e-6)
|
|
assert valid(fallback),'Invalid current-run incumbent'
|
|
# A bounded primal construction over already measured configurations.
|
|
# It creates no geometry, performs no image query, and never splits a
|
|
# family. Exact conservation constraints still govern every source.
|
|
adjacency=[set() for _ in members]
|
|
for a,b in local_edges:adjacency[a].add(b);adjacency[b].add(a)
|
|
source_sets=[set(nodes[i]['sources']) for i in members]
|
|
source_members=defaultdict(set)
|
|
for k,ss in enumerate(source_sets):
|
|
for source in ss:source_members[source].add(k)
|
|
sample_sets=[set() for _ in members]
|
|
for k,(ids,_) in enumerate(rewards):
|
|
for i in ids:sample_sets[i].add(k)
|
|
weights=np.array([w for _,w in rewards])
|
|
chosen={i for i in range(m) if fallback[i]}
|
|
def vector(selection):
|
|
x=np.zeros(len(c));x[list(selection)]=1
|
|
covered=set().union(*(sample_sets[i] for i in selection)) if selection else set()
|
|
if covered:x[[m+k for k in covered]]=1
|
|
return x
|
|
order=sorted(range(m) if seconds>0 else [],key=lambda i:(-sum(weights[k] for k in sample_sets[i]),nodes[members[i]]['id']))
|
|
for i in order:
|
|
if i in chosen:continue
|
|
remove=adjacency[i]&chosen
|
|
for source in source_sets[i]:remove|=source_members[source]&chosen
|
|
if any(not source_sets[j]<=source_sets[i] for j in remove):continue
|
|
trial=(chosen-remove)|{i};x=vector(trial)
|
|
if valid(x) and c@x<c@fallback-1e-7:chosen=trial;fallback=x
|
|
budget=min(component_seconds,max(0.,seconds-(time.monotonic()-started)))
|
|
result=None
|
|
if budget>.001:
|
|
result=milp(c,integrality=np.ones(len(c)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options=dict(time_limit=budget,mip_rel_gap=0.))
|
|
x=fallback;status='incumbent-time-budget'
|
|
if result is not None and valid(result.x) and c@result.x<=c@fallback+1e-7:
|
|
x=np.rint(result.x);status='optimal' if result.status==0 else 'feasible-limit'
|
|
elif result is not None:status='incumbent-no-better-feasible-solution'
|
|
selected.extend(nodes[i]['id'] for k,i in enumerate(members) if x[k]>.5)
|
|
reports.append(dict(nodes=m,sample_groups=len(rewards),pairwise_conflicts=len(local_edges),conflict_cliques=len(cliques),status=status,objective=float(-c@x),incumbent_objective=float(-c@fallback),solver_status=None if result is None else int(result.status)))
|
|
return selected,dict(seconds=time.monotonic()-started,components=reports,optimal=all(r['status']=='optimal' for r in reports),fixed_sample_groups=len(groups))
|