Productize site machinery + config automation (session-proven -> scripts/)
- register_site_outlines.py: point-to-edge ICP registration CLI (footprint union vs site outline / DIM_COOR corners), manifest-ready output, loud warning above 2 m residual - massing_from_outline.py: honest massing spec CLI (outline x storeys x height, labeled 总图轮廓体量), manifest anchors on stdout - detect_sheet_frames: multi-floor titles (四、六、八 / 十一至十四) expand to per-storey config entries sharing clip/offset — the 13号 b2 silent-floor- loss class is now prevented at the source; compound CN numerals parsed (十一/二十一 no longer collapse to F0 keys); per-frame DIM_ELEV ladders + uniform-step storey suggestion in the report (evidence, not auto-filled z) - 27号 2# real data: 19-storey enumerated title auto-expands, step 3.0 x 11 suggestion correct; regression suite +11 checks Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
198
scripts/register_site_outlines.py
Normal file
198
scripts/register_site_outlines.py
Normal file
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Register a building model's footprint onto its site-plan outline / corner
|
||||
callouts by point-to-edge ICP, and emit a site_manifest-ready placement.
|
||||
|
||||
Proven on 27号地块: site outlines can hide on odd layers (EVTR), a building
|
||||
may have NO drawn outline at all (1#A — only DIM_COOR corner callouts), and
|
||||
per-building rotations differ. This tool answers: given the model footprint
|
||||
polygon(s) and a set of site points (outline vertices or corner callouts, in
|
||||
site-plan meters), what rotation + anchor places the model on the site?
|
||||
|
||||
Method: brute-force angle sweep (score = trimmed mean distance from each site
|
||||
point to the nearest transformed footprint edge) + ICP translation refinement.
|
||||
Constrain --angle-window when the outline is visibly axis-aligned: balcony
|
||||
teeth love a tilted false minimum (27号 2# found a 10.75° pit before the
|
||||
window was clamped). Registering the UNION of several floors' footprints
|
||||
(--floors F1 F2 F4) beats one floor when upper wings overhang.
|
||||
|
||||
Usage:
|
||||
python3 register_site_outlines.py --spec outputs/x/spec_b1.json \
|
||||
--floors F4 --site-points outline.json [--angle-window -6 6] \
|
||||
--out registration.json [--prefix 1B]
|
||||
|
||||
site-points JSON: [[x, y], ...] (site-plan meters; surveying convention on
|
||||
both 13号/27号: drawing x = 测绘Y east, drawing y = 测绘X north), or
|
||||
{"points": [[x, y], ...]}.
|
||||
|
||||
Output JSON includes rotation_deg / model_anchor_m (footprint centroid) /
|
||||
survey_anchor_m / residual_m plus a ready-to-paste manifest_entry. Judge the
|
||||
residual: 配电房 hit 0.06 m (outline == model), 0.5-1 m is normal with
|
||||
balconies, several meters means wrong outline or wrong floors — check the
|
||||
overlay plot before trusting it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def dist_pt_seg(p, a, b) -> float:
|
||||
ax, ay = a
|
||||
bx, by = b
|
||||
px, py = p
|
||||
dx, dy = bx - ax, by - ay
|
||||
l2 = dx * dx + dy * dy
|
||||
if l2 == 0:
|
||||
return math.hypot(px - ax, py - ay)
|
||||
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / l2))
|
||||
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
|
||||
|
||||
|
||||
def poly_edges(poly):
|
||||
return list(zip(poly, poly[1:] + poly[:1]))
|
||||
|
||||
|
||||
def centroid(pts):
|
||||
return (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
|
||||
|
||||
|
||||
def rot(p, th, c):
|
||||
x, y = p[0] - c[0], p[1] - c[1]
|
||||
ct, st = math.cos(th), math.sin(th)
|
||||
return (x * ct - y * st, x * st + y * ct)
|
||||
|
||||
|
||||
def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
|
||||
trim=0.9):
|
||||
"""Best (theta_deg, translation, score) overlaying model polygons on points.
|
||||
|
||||
score = trimmed mean distance from each site point to the nearest
|
||||
transformed model edge (worst 10% dropped: corner callouts include strays).
|
||||
"""
|
||||
all_pts = [p for poly in model_polys for p in poly]
|
||||
mc = centroid(all_pts)
|
||||
sc = centroid(site_pts)
|
||||
edges_m = [e for poly in model_polys for e in poly_edges(poly)]
|
||||
|
||||
def score_at(th_deg, t):
|
||||
th = math.radians(th_deg)
|
||||
edges = [((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]),
|
||||
(rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1]))
|
||||
for a, b in edges_m]
|
||||
ds = sorted(min(dist_pt_seg(p, a, b) for a, b in edges) for p in site_pts)
|
||||
k = max(1, int(len(ds) * trim))
|
||||
return sum(ds[:k]) / k
|
||||
|
||||
lo, hi = angle_window if angle_window else (-180.0, 180.0)
|
||||
best = (lo, sc, 1e9)
|
||||
th = lo
|
||||
while th < hi + 1e-9:
|
||||
s = score_at(th, sc)
|
||||
if s < best[2]:
|
||||
best = (th, sc, s)
|
||||
th += coarse
|
||||
th0 = best[0]
|
||||
t = list(best[1])
|
||||
for _ in range(4):
|
||||
thr = math.radians(th0)
|
||||
edges = [((rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]),
|
||||
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1]))
|
||||
for a, b in edges_m]
|
||||
vecs = []
|
||||
for p in site_pts:
|
||||
dmin, q = 1e9, None
|
||||
for a, b in edges:
|
||||
ax, ay = a
|
||||
bx, by = b
|
||||
dx, dy = bx - ax, by - ay
|
||||
l2 = dx * dx + dy * dy or 1e-9
|
||||
tt = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / l2))
|
||||
qq = (ax + tt * dx, ay + tt * dy)
|
||||
d = math.hypot(p[0] - qq[0], p[1] - qq[1])
|
||||
if d < dmin:
|
||||
dmin, q = d, qq
|
||||
vecs.append((p[0] - q[0], p[1] - q[1], dmin))
|
||||
vecs.sort(key=lambda v: v[2])
|
||||
k = max(1, int(len(vecs) * trim))
|
||||
t[0] += sum(v[0] for v in vecs[:k]) / k
|
||||
t[1] += sum(v[1] for v in vecs[:k]) / k
|
||||
best_f = (th0, score_at(th0, t))
|
||||
dth = -1.5
|
||||
while dth <= 1.5 + 1e-9:
|
||||
cand = th0 + dth
|
||||
if lo - 1e-9 <= cand <= hi + 1e-9:
|
||||
s = score_at(cand, t)
|
||||
if s < best_f[1]:
|
||||
best_f = (cand, s)
|
||||
dth += refine
|
||||
th0 = best_f[0]
|
||||
return th0, tuple(t), score_at(th0, t), mc
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--spec", required=True, help="building_spec.json")
|
||||
parser.add_argument("--floors", nargs="+", required=True,
|
||||
help="floor keys whose footprints form the registration target")
|
||||
parser.add_argument("--site-points", required=True,
|
||||
help="JSON: [[x,y],...] site outline vertices / corner callouts (m)")
|
||||
parser.add_argument("--angle-window", nargs=2, type=float, default=None,
|
||||
metavar=("LO", "HI"), help="restrict rotation search (deg)")
|
||||
parser.add_argument("--out", required=True)
|
||||
parser.add_argument("--prefix", default="", help="building prefix for the manifest entry")
|
||||
args = parser.parse_args()
|
||||
|
||||
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
|
||||
polys = []
|
||||
for fk in args.floors:
|
||||
floor = spec.get("floors", {}).get(fk)
|
||||
if floor is None:
|
||||
raise SystemExit(f"floor {fk!r} not in spec")
|
||||
polys.extend((floor.get("footprint") or {}).get("polygons") or [])
|
||||
if not polys:
|
||||
raise SystemExit("no footprint polygons on the requested floors — "
|
||||
"enable generate_footprints or pick other floors")
|
||||
raw = json.loads(Path(args.site_points).read_text(encoding="utf-8"))
|
||||
site_pts = raw.get("points") if isinstance(raw, dict) else raw
|
||||
site_pts = [(float(p[0]), float(p[1])) for p in site_pts]
|
||||
if len(site_pts) < 4:
|
||||
raise SystemExit("need at least 4 site points")
|
||||
|
||||
window = tuple(args.angle_window) if args.angle_window else None
|
||||
th, t, score, mc = register(polys, site_pts, angle_window=window)
|
||||
result = {
|
||||
"spec": args.spec,
|
||||
"floors": args.floors,
|
||||
"rotation_deg": round(th, 3),
|
||||
"model_anchor_m": [round(mc[0], 3), round(mc[1], 3)],
|
||||
"survey_anchor_m": [round(t[0], 3), round(t[1], 3)],
|
||||
"residual_m": round(score, 3),
|
||||
"site_points": len(site_pts),
|
||||
"manifest_entry": {
|
||||
"spec": args.spec,
|
||||
"prefix": args.prefix,
|
||||
"model_anchor_m": [round(mc[0], 3), round(mc[1], 3)],
|
||||
"survey_anchor_m": [round(t[0], 3), round(t[1], 3)],
|
||||
"rotation_deg": round(th, 3),
|
||||
"registration_residual_m": round(score, 3),
|
||||
},
|
||||
}
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
print(json.dumps({"out": str(out), "rotation_deg": result["rotation_deg"],
|
||||
"residual_m": result["residual_m"]}, ensure_ascii=False))
|
||||
if score > 2.0:
|
||||
print(f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, "
|
||||
"or the site points include strays (garage outline / fire pads); "
|
||||
"plot the overlay before trusting this placement.", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user