"""Find a four-DOF preset pose directly from an observed whole-object target. The raster is a search accelerator, never the output geometry. Every returned polygon is instantiated from immutable metric artwork. No flexible glyph fit or previously mapped arrow is an input. """ import cv2 import time import numpy as np import shapely from scipy.optimize import minimize from standard_arrow_templates import KINDS, PROFILES, preset, polygon from registration import POLICY as GEOMETRY_POLICY VERSION = 'topdown-direct-original-paint-v6' CELL = .05 def observation_score(overlaps): """Fit original paint. Semantic masks propose objects, not metric truth.""" return float(np.asarray(overlaps,float)[0]/GEOMETRY_POLICY['min_iou']) def fit_target(target, *, max_options=4, evidence_penalty=None, geometric_constraints=None, object_constraints=None, preset_filter=None, evidence_seed=None, seed_targets=None): if target.is_empty or not target.is_valid or not .08 <= target.area <= 30: return [] # All initial measurements are peers. A coarse ranking against only the # primary paint mask used to erase a pose supported by another source, # while final admission legitimately checked every retained source. sources=[] for source in [target]+list(seed_targets or []): if source.is_empty or not source.is_valid:continue if any(source.wkb==q.wkb for q in sources):continue sources.append(source) lo=np.min([q.bounds[:2] for q in sources],axis=0)-1. hi=np.max([q.bounds[2:] for q in sources],axis=0)+1. if np.max(hi-lo)>16:return [] xx,yy=np.meshgrid(np.arange(lo[0],hi[0],CELL),np.arange(lo[1],hi[1],CELL)) masks=np.stack([shapely.contains_xy(q,xx,yy) for q in sources]);mask=masks[0] if not mask.any():return [] def raster_score(rendered): intersection=np.count_nonzero(masks&rendered[None],axis=(1,2)) union=np.count_nonzero(masks|rendered[None],axis=(1,2)) return observation_score(intersection/np.maximum(union,1)) def overlaps(q): return [q.intersection(p).area/max(q.union(p).area,1e-9) for p in sources] def exact_score(q): return overlaps(q)[0] def search_score(q): return observation_score(overlaps(q)) seed_shapes=[] for source in sources: if any(source.symmetric_difference(p).area/max(source.union(p).area,1e-9)<.02 for p in seed_shapes):continue seed_shapes.append(source) coarse = [] for kind in KINDS: for profile, dimensions in PROFILES.items(): template = preset(kind, profile) if preset_filter is not None and not preset_filter(template):continue unit = np.asarray(template.exterior.coords) centroid = np.asarray(template.centroid.coords[0]) def evaluate(p): x, y, a, s = p rotation = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) xy = unit @ rotation * s + [x, y] pixels = np.rint((xy-lo)/CELL).astype('int32') rendered = np.zeros(mask.shape, 'uint8') cv2.fillPoly(rendered, [pixels], 1) rendered = rendered.astype(bool) return raster_score(rendered) angles = np.arange(24) * (2*np.pi/24) seeds = [] for source in seed_shapes: center=np.asarray(source.centroid.coords[0]);coords=shapely.get_coordinates(source) for a in angles: axis = np.array([np.cos(a), np.sin(a)]) factor = np.ptp(coords @ axis) / dimensions['L'] if not .65 <= factor <= 1.40: continue factor = float(np.clip(factor, .75, 1.25)) rotation = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) xy = center - centroid @ rotation * factor pose = np.r_[xy, a, factor] seeds.append((evaluate(pose), pose)) # Retain competing classes until original-pixel verification. for score, pose in sorted(seeds, key=lambda x: -x[0])[:max(2,len(seed_shapes))]: coarse.append((score, kind, profile, pose)) diverse=[] for entry in sorted(coarse,key=lambda x:-x[0]): _,kind,profile,pose=entry if any(kind==v[1] and profile==v[2] and np.linalg.norm(pose[:2]-v[3][:2])<.06 and abs(pose[2]-v[3][2])<.02 and abs(pose[3]-v[3][3])<.015 for v in diverse):continue diverse.append(entry) # A cheap appearance score orders hypotheses; it cannot disprove a whole # semantic family. Repeated poses of one family must not evict another. family_counts={};family_seeds=[] for entry in diverse: key=entry[1:3] if family_counts.get(key,0)>=2:continue family_counts[key]=family_counts.get(key,0)+1;family_seeds.append(entry) candidates = [] for _, kind, profile, pose in family_seeds: unit = np.asarray(preset(kind, profile).exterior.coords) def objective(p): x, y, a, s = p rotation = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) pixels = np.rint((unit @ rotation*s + [x, y]-lo)/CELL).astype('int32') rendered = np.zeros(mask.shape, 'uint8') cv2.fillPoly(rendered, [pixels], 1) rendered = rendered.astype(bool) return -raster_score(rendered) bounds = [(pose[0]-.7, pose[0]+.7), (pose[1]-.7, pose[1]+.7), (pose[2]-.30, pose[2]+.30), (.75, 1.25)] fitted = minimize(objective, pose, method='Powell', bounds=bounds, options=dict(maxiter=12, maxfev=300, xtol=.001, ftol=.001)) best = min([pose, fitted.x], key=objective) q = polygon(kind, profile, best) exact = exact_score(q) # Preserve the original appearance prefilter. Other observations # contribute seeds, but cannot turn absent paint into a fit candidate. if overlaps(q)[0] < .35: continue if any(c['kind'] == kind and q.hausdorff_distance(c['geometry']) < .15 for c in candidates): continue candidates.append(dict(kind=kind, profile=profile, pose=best.tolist(), score=float(exact), search_score=search_score(q), initial_pose=best.tolist(), initial_score=float(exact), geometry=q)) # Remove coarse-raster bias before the original-pixel registration. Thin # stems are only a few pixels wide in the accelerator; its objective must # not determine final pose or throw away a valid shape's tips. refined = [] family_counts={} for candidate in sorted(candidates, key=lambda x: -x['search_score']): family=(candidate['kind'],candidate['profile']) if family_counts.get(family,0)>=max_options:continue family_counts[family]=family_counts.get(family,0)+1 kind, profile = candidate['kind'], candidate['profile'] pose = np.asarray(candidate['pose']) def exact_loss(p): q = polygon(kind, profile, p) overlap = search_score(q) return -overlap + (evidence_penalty(q) if evidence_penalty is not None else 0.) bounds = [(pose[0]-.6, pose[0]+.6), (pose[1]-.6, pose[1]+.6), (pose[2]-.2, pose[2]+.2), (.75, 1.25)] if geometric_constraints is not None: # Solve the actual fixed-preset feasibility problem. The previous # weighted landmark penalty traded shape overlap for a tighter, # arbitrary 9 cm margin, then tested a different 12 cm constraint. # Work in local variables so absolute map coordinates do not set # finite-difference scales. scale=np.array([1.,1.,1./PROFILES[profile]['L'],1./PROFILES[profile]['L']]) costs=dict(geometry_seconds=0.,object_seconds=0.,objective_seconds=0.,constraint_calls=0) lower,upper=np.asarray(bounds).T def physical(delta): # COBYLA may evaluate infeasible trial points; templates remain # inside their immutable scale envelope even during search. return np.clip(pose+delta*scale,lower,upper) def constraints(delta): p=physical(delta);q=polygon(kind,profile,p) begin=time.monotonic();values=list(geometric_constraints(q)) costs['geometry_seconds']+=time.monotonic()-begin;costs['constraint_calls']+=1 if object_constraints is not None: begin=time.monotonic();values.extend(np.atleast_1d(object_constraints(q,kind,profile,p)).tolist()) costs['object_seconds']+=time.monotonic()-begin return np.asarray(values,float) local_bounds=[((a-p)/unit,(b-p)/unit) for (a,b),p,unit in zip(bounds,pose,scale)] def objective(delta): begin=time.monotonic();value=exact_loss(physical(delta)) costs['objective_seconds']+=time.monotonic()-begin return value starts=[pose] if evidence_seed is not None:starts.append(evidence_seed(kind,profile,pose,bounds)) def violation(p):return float(np.maximum(-constraints((p-pose)/scale),0.).max()) legal_starts=[p for p in starts if violation(p)<=1e-12] if legal_starts: best=min(legal_starts,key=exact_loss);q=polygon(kind,profile,best) refined.append(dict(candidate,pose=best.tolist(),score=exact_score(q), objective=-float(exact_loss(best)),geometry=q,feasible=True,constraint_violation=0., optimizer='boundary-least-squares-fixed-preset',optimizer_converged=True,optimizer_evaluations=0,search_cost=dict(costs))) if object_constraints is not None:break continue candidate['start_diagnostics']=[dict(pose=p.tolist(),violation=violation(p),loss=float(exact_loss(p))) for p in starts] start=min(starts,key=lambda p:(violation(p),exact_loss(p))) solved=minimize(objective,(start-pose)/scale,method='COBYLA', bounds=local_bounds,constraints=[dict(type='ineq',fun=constraints)], options=dict(maxiter=900,rhobeg=.15,tol=1e-4,catol=1e-8)) alternatives=starts+[physical(solved.x)] def quality(p): violations=np.maximum(-constraints((p-pose)/scale),0.) return (float(violations.max()),exact_loss(p)) feasible=[p for p in alternatives if quality(p)[0] <= 1e-5] best=min(feasible,key=exact_loss) if feasible else min(alternatives,key=quality) q=polygon(kind,profile,best) refined.append(dict(candidate,pose=best.tolist(), score=exact_score(q), objective=-float(exact_loss(best)),geometry=q, feasible=bool(quality(best)[0]<=1e-5),constraint_violation=quality(best)[0], optimizer='COBYLA-fixed-preset',optimizer_converged=bool(solved.success), optimizer_evaluations=int(solved.nfev),search_cost=dict(costs))) print('POSE',kind,profile,int(solved.nfev),{k:round(v,3) for k,v in costs.items()},flush=True) # This is a feasibility task: once the highest-ranked remaining # hypothesis passes every original-pixel and whole-object gate, # evaluating lower-ranked classes cannot make it more admissible. # The independent verifier still measures the returned geometry. if object_constraints is not None and quality(best)[0]<=1e-12: break continue result = minimize(exact_loss, pose, method='Powell', bounds=bounds, options=dict(maxiter=30, maxfev=1000, xtol=1e-5, ftol=1e-5)) best = min([pose, result.x], key=exact_loss) # Translation and heading are coupled for a narrow stem. Coordinate # descent alone can stop at a slanted overlap ridge. simplex = np.vstack([best, best + np.diag([.04, .04, .01, .01])]) joint = minimize(exact_loss, best, method='Nelder-Mead', bounds=bounds, options=dict(initial_simplex=simplex, maxfev=800, xatol=1e-5, fatol=1e-7)) best = min([best, joint.x], key=exact_loss) q = polygon(kind, profile, best) refined.append(dict(candidate, pose=best.tolist(), score=exact_score(q), objective=-float(exact_loss(best)), geometry=q)) return sorted(refined, key=lambda x: -x['objective'])