"""Deterministic layout solver: one box per class from per-class size priors (``class_size_priors.json``). Used for k = 5 scenes, for never-co-occurring cliques and as the fallback of the language-model planner. """ from __future__ import annotations import json import math from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Optional, Sequence, Tuple import numpy as np DEFAULT_PRIORS_PATH = Path(__file__).resolve().parent / "class_size_priors.json" DEFAULT_PRIOR: Dict[str, float] = { "rel_area_p25": 0.03, "rel_area_p50": 0.08, "rel_area_p75": 0.18, "aspect_median": 1.0, } VEHICLES = {"bicycle", "car", "motorcycle", "bus", "train", "truck", "boat"} FURNITURE = {"bench", "chair", "couch", "bed", "dining table", "toilet"} ANIMALS = {"bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe"} PEOPLE = {"person"} GROUND_CONTACT_CLASSES = VEHICLES | FURNITURE | ANIMALS | PEOPLE @dataclass class SolverConfig: img_size: int = 1024 margin: int = 24 min_short_side: int = 96 min_rel_area: float = 0.02 max_rel_area: float = 0.30 max_iou: float = 0.02 min_center_dist_frac: float = 0.25 max_attempts: int = 2000 shrink_factor: float = 0.85 max_shrink_rounds: int = 12 ground_contact_lower_frac: float = 0.60 area_sigma_scale: float = 1.0 area_scale: float = 1.0 aspect_sigma: float = 0.15 min_aspect: float = 0.33 max_aspect: float = 3.0 def load_size_priors(path: Path = DEFAULT_PRIORS_PATH) -> Dict[str, Dict[str, float]]: with open(path) as f: d = json.load(f) return d.get("classes", d) def box_iou(a: Sequence[float], b: Sequence[float]) -> float: ix1, iy1 = max(a[0], b[0]), max(a[1], b[1]) ix2, iy2 = min(a[2], b[2]), min(a[3], b[3]) iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1) inter = iw * ih if inter <= 0: return 0.0 ua = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter return inter / ua if ua > 0 else 0.0 def _center(b: Sequence[float]) -> Tuple[float, float]: return (b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0 def _diag(b: Sequence[float]) -> float: return math.hypot(b[2] - b[0], b[3] - b[1]) def pair_ok(a: Sequence[float], b: Sequence[float], cfg: SolverConfig) -> bool: if box_iou(a, b) > cfg.max_iou: return False ca, cb = _center(a), _center(b) dist = math.hypot(ca[0] - cb[0], ca[1] - cb[1]) return dist >= cfg.min_center_dist_frac * min(_diag(a), _diag(b)) def _apply_size_floors(w: float, h: float, cfg: SolverConfig) -> Tuple[float, float]: """Short side >= min_short_side, area <= max_rel_area, inside the canvas.""" canvas = float(cfg.img_size) max_side = canvas - 2 * cfg.margin if min(w, h) < cfg.min_short_side: if w <= h: w = float(cfg.min_short_side) else: h = float(cfg.min_short_side) cap = cfg.max_rel_area * canvas * canvas if w * h > cap: s = math.sqrt(cap / (w * h)) w, h = max(w * s, cfg.min_short_side), max(h * s, cfg.min_short_side) w, h = min(w, max_side), min(h, max_side) return w, h def sample_target_sizes(labels: Sequence[str], priors: Dict[str, Dict[str, float]], rng: np.random.Generator, cfg: SolverConfig ) -> List[Tuple[float, float, float]]: """Per label: (w, h, target_rel_area) before any shrink round.""" canvas = float(cfg.img_size) out = [] for lbl in labels: p = priors.get(lbl, DEFAULT_PRIOR) p25 = max(float(p.get("rel_area_p25", DEFAULT_PRIOR["rel_area_p25"])), 1e-4) p50 = max(float(p.get("rel_area_p50", DEFAULT_PRIOR["rel_area_p50"])), 1e-4) p75 = max(float(p.get("rel_area_p75", DEFAULT_PRIOR["rel_area_p75"])), p25) sigma = cfg.area_sigma_scale * (math.log(p75) - math.log(p25)) / 1.349 rel = math.exp(math.log(p50) + rng.normal(0.0, max(sigma, 1e-3))) rel = min(max(rel, p25), p75) * cfg.area_scale rel = min(max(rel, cfg.min_rel_area), cfg.max_rel_area) ar = float(p.get("aspect_median", 1.0)) * math.exp(rng.normal(0.0, cfg.aspect_sigma)) ar = min(max(ar, cfg.min_aspect), cfg.max_aspect) area_px = rel * canvas * canvas w = math.sqrt(area_px * ar) h = math.sqrt(area_px / ar) w, h = _apply_size_floors(w, h, cfg) out.append((w, h, rel)) return out def _try_place(order: List[int], dims: List[Tuple[float, float]], labels: Sequence[str], rng: np.random.Generator, cfg: SolverConfig, attempt_budget: int ) -> Tuple[Optional[List[List[int]]], int]: """One placement pass. Returns (boxes in label order or None, attempts used).""" canvas = cfg.img_size placed: Dict[int, List[int]] = {} attempts = 0 per_obj = max(1, attempt_budget // max(1, len(order))) for i in order: w, h = dims[i] wi, hi = int(math.floor(w)), int(math.floor(h)) x_lo, x_hi = cfg.margin, canvas - cfg.margin - wi if labels[i] in GROUND_CONTACT_CLASSES: y2_lo = max(cfg.margin + hi, int(round((1.0 - cfg.ground_contact_lower_frac) * canvas))) y2_hi = canvas - cfg.margin y_lo, y_hi = y2_lo - hi, y2_hi - hi else: y_lo, y_hi = cfg.margin, canvas - cfg.margin - hi if x_hi < x_lo or y_hi < y_lo: return None, attempts ok = False for _ in range(per_obj): attempts += 1 x1 = int(rng.integers(x_lo, x_hi + 1)) y1 = int(rng.integers(y_lo, y_hi + 1)) cand = [x1, y1, x1 + wi, y1 + hi] if all(pair_ok(cand, b, cfg) for b in placed.values()): placed[i] = cand ok = True break if not ok: return None, attempts return [placed[i] for i in range(len(labels))], attempts def solve_layout(labels: Sequence[str], priors: Dict[str, Dict[str, float]], img_size: int = 1024, seed: int = 0, cfg: Optional[SolverConfig] = None, area_scale: float = 1.0) -> Dict: """Return ``{layout_boxes, layout_source, layout_attempts, layout_shrink_rounds, target_rel_areas}``. ``layout_source`` is ``"solver"`` on success and ``"grid_fallback"`` only if every shrink round failed (not expected for <= 8 objects at the configured floors). ``layout_attempts`` counts solver placements, not LLM calls; Stage 1 renames it to ``solver_attempts``.""" cfg = cfg or SolverConfig() if cfg.img_size != img_size or cfg.area_scale != area_scale: cfg = SolverConfig(**{**cfg.__dict__, "img_size": img_size, "area_scale": float(area_scale)}) rng = np.random.default_rng(int(seed)) sizes = sample_target_sizes(labels, priors, rng, cfg) base_dims = [(w, h) for w, h, _ in sizes] areas = [w * h for w, h in base_dims] order = sorted(range(len(labels)), key=lambda i: -areas[i]) total_attempts = 0 for rnd in range(cfg.max_shrink_rounds + 1): s = cfg.shrink_factor ** rnd dims = [_apply_size_floors(w * s, h * s, cfg) for w, h in base_dims] boxes, used = _try_place(order, dims, labels, rng, cfg, cfg.max_attempts) total_attempts += used if boxes is not None: return { "layout_boxes": boxes, "layout_source": "solver", "layout_attempts": total_attempts, "layout_shrink_rounds": rnd, "target_rel_areas": [round(float(r), 5) for _, _, r in sizes], } from strangebench.scene_specs.select_scenes_and_layouts import _grid_fallback return { "layout_boxes": _grid_fallback(list(labels), img_size), "layout_source": "grid_fallback", "layout_attempts": total_attempts, "layout_shrink_rounds": cfg.max_shrink_rounds, "target_rel_areas": [round(float(r), 5) for _, _, r in sizes], } def check_layout(boxes: Sequence[Sequence[int]], labels: Sequence[str], cfg: Optional[SolverConfig] = None) -> List[str]: """Return a list of violated rules (empty = valid). Used by the tests and by the Stage 1 driver as a cheap assertion on solver output.""" cfg = cfg or SolverConfig() canvas = cfg.img_size problems: List[str] = [] for i, b in enumerate(boxes): x1, y1, x2, y2 = b if not (cfg.margin <= x1 < x2 <= canvas - cfg.margin and cfg.margin <= y1 < y2 <= canvas - cfg.margin): problems.append(f"{labels[i]}: outside margins {b}") if min(x2 - x1, y2 - y1) < cfg.min_short_side: problems.append(f"{labels[i]}: short side < {cfg.min_short_side}") rel = (x2 - x1) * (y2 - y1) / float(canvas * canvas) if rel > cfg.max_rel_area + 1e-6: problems.append(f"{labels[i]}: rel area {rel:.3f} > {cfg.max_rel_area}") if labels[i] in GROUND_CONTACT_CLASSES and \ y2 < (1.0 - cfg.ground_contact_lower_frac) * canvas - 1: problems.append(f"{labels[i]}: ground-contact class floats (y2={y2})") for i in range(len(boxes)): for j in range(i + 1, len(boxes)): if not pair_ok(boxes[i], boxes[j], cfg): problems.append(f"{labels[i]} vs {labels[j]}: overlap/center rule") return problems def shrink_anchor_box(box: Sequence[int], img_size: int = 1024, max_rel_area: float = 0.02, min_short_side: int = 72, margin: int = 24) -> Tuple[List[int], float]: """Shrink ``box`` around its center so its area is <= ``max_rel_area`` of the canvas while keeping the short side >= ``min_short_side``. The aspect ratio is preserved unless the short-side floor forces the long side down to keep the area cap. Returns (new_box, realized_rel_area).""" x1, y1, x2, y2 = (float(v) for v in box) w, h = x2 - x1, y2 - y1 cx, cy = (x1 + x2) / 2.0, (y1 + y2) / 2.0 cap = max_rel_area * img_size * img_size if w * h > cap: s = math.sqrt(cap / (w * h)) w, h = w * s, h * s if min(w, h) < min_short_side: if w <= h: w = float(min_short_side) h = min(h, cap / w) else: h = float(min_short_side) w = min(w, cap / h) w, h = max(w, min(min_short_side, img_size - 2 * margin)), \ max(h, min(min_short_side, img_size - 2 * margin)) wi, hi = int(math.floor(w)), int(math.floor(h)) nx1, ny1 = cx - wi / 2.0, cy - hi / 2.0 nx1 = min(max(nx1, margin), img_size - margin - wi) ny1 = min(max(ny1, margin), img_size - margin - hi) x1i, y1i = int(round(nx1)), int(round(ny1)) nb = [x1i, y1i, x1i + wi, y1i + hi] rel = (nb[2] - nb[0]) * (nb[3] - nb[1]) / float(img_size * img_size) return nb, rel def rel_area_of_box(box: Sequence[float], img_size: int = 1024) -> float: return max(0.0, (box[2] - box[0])) * max(0.0, (box[3] - box[1])) / float(img_size * img_size)