text
stringlengths
0
1.47k
def _corridor_pending(b: dict) -> list[str]:
"""Infrastructure observations without a computed result explicitly addressing them."""
infra = [k for k, c in b["clues"].items() if _clue_kind(c["kind"]) == "infra" and c["status"] in ("observed", "read")]
done = {k for c in b["clues"].values()
if c["status"] == "computed" and c.get("resolves") and c.get("file") and Path(c["file"]).is_file()
for k in c.get("resolves", [])}
return [k for k in infra if k not in done]
def cmd_next(args, p: Path) -> None:
b = _load(p)
pend = _corridor_pending(b)
if pend:
print(f"→ First: infrastructure clue {', '.join(pend)} has no linked corridor result yet. `osm.py geom '<filter>' --bbox <region> --out lines.geojson` → "
f"`terrain.py scan --lines lines.geojson` (mountains fill the frame: add `--flat-run 0 --min-low-deg 0`) → `terrain.py fit`; "
f"two or three kinds of infrastructure: `osm.py near`. Record a result that actually tests the clue with "
f"`board.py clue '<result>' --kind corridor --status computed --file <output> --resolves <clue-id>` "
f"(repeat --resolves for each clue tested).")
lv = _frontier(b)
if not lv:
print("No candidates. First do step 2 (lookup clues) or step 4 (coarse location from the environment) and list the candidates in full (board.py children)")
return
rows = [r for r in _scores(b, lv, args.prior_by) if not r["excluded"]]
top = rows[0]
second = rows[1] if len(rows) > 1 else None
unused = [k for k, c in b["clues"].items() if not c["used"]]
print(f"Current frontier: {LEVEL_LABEL[lv]}, {len(rows)} not excluded; first {top['name']} {top['share']:.0%}"
+ (f", second {second['name']} {second['share']:.0%}" if second else ""))
if unused:
pending = ", ".join(f"{k}({b['clues'][k]['kind']})" for k in unused)
print(f"Clues not used yet: {pending} → evidence or apply first")
separable = (not second) or (top["share"] >= 0.7 and top["share"] / max(second["share"], 1e-9) >= 3)
if separable and top["n_verified"] == 0 and second:
print(f"{top['name']} leads but has no verified evidence at all (read/computed); it's built from inferences only: do one cheap verification before scanning.")
if separable:
pages, src = _cost_of(top["c"], args)
print(f"→ Ready to narrow/scan: {top['name']} ({src}, about {pages if pages is not None else '?'} pages).")
if src == "whole-district bbox":
print(" First `board.py urban <name>` or `scan-bbox` to shrink the extent to the built-up area; pages drop by an order of magnitude.")
elif pages is None:
print(f" It has no extent yet: `board.py urban {top['name']} --within <parent>` or `board.py scan-bbox {top['name']} --bbox s,w,n,e`, otherwise pages can't be computed.")
if top["name"] not in b["falsify"]:
print(f" Write the falsification condition before scanning: `board.py falsify {top['name']} --text \"…\"`")
print(" Let the machine rank the scan first: `sat_scan.py grid --bbox <scan_bbox> --preset …`, `osm.py buildings`, `poi.py`; look only at the top 20–30.")
return
print("→ Can't separate. Do discriminating tests from cheap to expensive, each on all non-excluded candidates together, not just the leader:")
kinds_have = {c["kind"] for c in b["clues"].values()}
pk = _region_of(b, rows)
tips = (pk or {}).get("tips") or {}
if pk:
print(f" (region pack {pk['code']}: `regions.py show {pk['code'].lower()}` lists its lookups, services and clue index)")
for kind, tip in [(k, tips.get(k, t)) for k, t in CHEAP_OPS]:
mark = "(you already have a clue of this kind; record evidence)" if any(k in kinds_have for k in kind.split("/")) else ""
print(f" - {kind}: {tip} {mark}")
print("→ All cheap tests done and still can't separate: don't stop. Scan in \"share ÷ pages\" order, finish the small ones first, set a page cap on the large ones:")
order = []
for r in rows:
pages, src = _cost_of(r["c"], args)
order.append((r["share"] / pages if pages else 0, r, pages, src))
order.sort(key=lambda t: -t[0])
for ratio, r, pages, src in order[:8]:
print(f" {r['name']:<14} share {r['share']:.0%} pages {pages if pages is not None else '?'} ({src}) share/page {ratio:.4f}")
if any(pages is None for _, _, pages, _ in order):
print(" Some candidates have no extent: fill it in with `board.py urban` or `scan-bbox`, otherwise they can't be ordered")
def _region_of(b: dict, rows: list[dict]) -> dict | None:
"""The board's country, else the one country all open frontier candidates share."""
if b.get("country"):
return regions.resolve(b["country"])
codes = {r["c"].get("country") for r in rows}
return regions.resolve(codes.pop()) if len(codes) == 1 and None not in codes else None
def _parse_covers(s: str) -> list[tuple[float, float]]:
"""--covers: 'lat,lon' or 'lat,lon:lat,lon' (the point/span the evidence actually covers). Returns [] if no coordinates parse."""
pts = []
for part in str(s).split(":"):
m = re.findall(r"-?\d+\.\d+|-?\d+", part)
if len(m) >= 2:
pts.append((float(m[0]), float(m[1])))
return pts
def _cov_span_m(a: tuple[float, float], b: tuple[float, float]) -> float:
kx = 111320.0 * math.cos(math.radians((a[0] + b[0]) / 2))
return math.hypot((b[1] - a[1]) * kx, (b[0] - a[0]) * 110540.0)
def _covers_ratio(c: dict, pts: list[tuple[float, float]]) -> tuple[float, float] | None:
"""(evidence coverage length / candidate extent diagonal, diagonal in meters). None if the candidate has no bbox (can't compute, only warn)."""
bb = c.get("bbox") or c.get("scan_bbox")
if not bb or len(bb) != 4:
return None
try:
sw, ww, nn, ee = (float(v) for v in bb)
except (TypeError, ValueError):
return None
diag = _cov_span_m((sw, ww), (nn, ee))
if diag <= 1.0: