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:
2026-07-03 08:28:05 +08:00
parent 9729857549
commit fc05464749
6 changed files with 536 additions and 15 deletions

View File

@@ -73,11 +73,51 @@ FLOOR_NAME_KEY = [
def _cn(token: str) -> int:
"""Chinese numeral (1-99, incl. compounds 十一/二十/二十一) or digits to int."""
if token.isdigit():
return int(token)
if not token:
return 0
if "十" in token:
tens, _, ones = token.partition("十")
t = CN_NUM.get(tens, 0) if tens else 1
o = CN_NUM.get(ones, 0) if ones else 0
if tens and t == 0:
return 0
return t * 10 + o
return CN_NUM.get(token, 0)
def covered_floor_numbers(name: str) -> list[int]:
"""Floors covered by a multi-floor plan title, else [].
四、六、八层平面图 -> [4,6,8]; 十一至十四层平面图 -> [11,12,13,14].
One frame standing for N storeys is the norm in Chinese sets — hand-copying
N config entries is exactly where floors got silently lost (13号 b2).
"""
if "地下" in name or "夹层" in name:
return []
m = re.search(r"(?P<seq>[一二三四五六七八九十\d]+(?:(?:[、,,]|[至~~\-—])[一二三四五六七八九十\d]+)+)层", name)
if not m:
return []
nums: list[int] = []
for part in re.split(r"[、,,]", m.group("seq")):
rng = re.split(r"[至~~\-—]", part)
if len(rng) == 2:
a, b = _cn(rng[0]), _cn(rng[1])
if not (0 < a < b <= 99 and b - a <= 40):
return []
nums.extend(range(a, b + 1))
elif len(rng) == 1:
v = _cn(rng[0])
if v <= 0:
return []
nums.append(v)
else:
return []
return nums if len(nums) > 1 else []
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True)
@@ -569,6 +609,31 @@ def main() -> int:
for f in floors:
f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux")
# Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config
# entry per storey sharing the frame's clip/offset — hand-copying N entries
# is where floors silently vanished (13号 b2 F11-F16). z/height stay with
# the Agent: fill them from the storey-elevation evidence, do not guess.
config_floors: list[dict] = []
def _unique_key(key: str) -> str:
base, i = key, 2
while any(cf["key"] == key for cf in config_floors):
key = f"{base}_{i}"
i += 1
return key
for f in floors:
covers = covered_floor_numbers(f["name"])
if covers:
for n in covers:
config_floors.append({"key": _unique_key(f"F{n}"), "name": f"{n}层({f['name']})",
"clip": f["clip"], "offset": f["offset"]})
notes.append(f"{f['name']}: multi-floor title expanded to "
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)")
else:
config_floors.append({"key": _unique_key(f["key"]), "name": f["name"],
"clip": f["clip"], "offset": f["offset"]})
config = {
"project_name": path.stem,
"scale": 0.001,
@@ -577,7 +642,7 @@ def main() -> int:
"origin_strategy": "min",
"drawings": [{
"file": path.name,
"floors": [{k: f[k] for k in ("key", "name", "clip", "offset")} for f in floors],
"floors": config_floors,
}],
}
out_config = Path(args.out_config)
@@ -597,19 +662,20 @@ def main() -> int:
report.extend(f"- note: {n}" for n in notes)
if others:
seen = set()
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
frames_e: list[dict] = []
for o in sorted(others, key=lambda o: -o.get("h", 0)):
key = o["name"]
if key in seen:
if o["name"] in seen:
continue
seen.add(key)
report.append(f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})")
# Storey-elevation suggestions: 标高 texts (e.g. 8.100) inside section/
# elevation frames, clustered. Feed floors[].z/height from these.
seen.add(o["name"])
frames_e.append(o)
# Storey-elevation evidence: 标高 texts (e.g. 8.100) inside section/
# elevation frames, collected PER FRAME (aggregated lists mix stair
# half-landings from 楼梯剖面 into the storey ladder — 27号 1#A lesson).
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter()
boxes = [(o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in others]
ladders: dict[str, set] = {o["name"]: set() for o in frames_e}
boxes = [(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06,
o["x"] + clip_w * 0.6, o["y"] + clip_h) for o in frames_e]
for entity in msp:
if entity.dxftype() != "TEXT":
continue
@@ -620,14 +686,53 @@ def main() -> int:
pos = entity.dxf.insert
except Exception:
continue
if any(b[0] <= pos.x <= b[2] and b[1] <= pos.y <= b[3] for b in boxes):
votes[round(float(content), 3)] += 1
for name, x1, y1, x2, y2 in boxes:
if x1 <= pos.x <= x2 and y1 <= pos.y <= y2:
v = round(float(content), 3)
ladders[name].add(v)
votes[v] += 1
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
for o in frames_e:
line = f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})"
vals = sorted(ladders.get(o["name"], ()))
if vals:
shown = ", ".join(f"{v:+.3f}" for v in vals[:40])
line += f" ladder: {shown}" + (" …" if len(vals) > 40 else "")
report.append(line)
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
if levels:
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference."])
# Uniform-step suggestion: the dominant consecutive difference and
# its longest chain. A SUGGESTION for the Agent to verify against
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
# 4.5 m storey), so per-frame ladders above are the ground truth.
majors = [v for v in levels if -0.5 <= v <= 200]
diff_votes: Counter = Counter()
for a, b in zip(majors, majors[1:]):
d = round(b - a, 2)
if 2.5 <= d <= 6.5:
diff_votes[d] += 1
if diff_votes:
step = diff_votes.most_common(1)[0][0]
best_chain: list[float] = []
for v0 in majors:
chain, cur = [v0], v0
while True:
nxt = [w for w in majors if abs(w - (cur + step)) <= 0.06]
if not nxt:
break
cur = nxt[0]
chain.append(cur)
if len(chain) > len(best_chain):
best_chain = chain
if len(best_chain) >= 4:
report.append(
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
"剖面/立面 per-frame ladders (podium and machine floors may differ)")
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
print(json.dumps({
"config": str(out_config), "report": args.out_report,

View File

@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Honest massing spec from a site-plan outline x storey count x storey height.
For buildings named on the 总平面 but with NO delivered drawings (27号 3#/4#:
EVTR outlines + `22F`/`21F` labels), the honest showcase move is an outline
extrusion clearly labeled as such — never a silently faked detailed model.
The spec slots straight into assemble_campus (per-floor walls from the
outline edges, footprint slabs, top cap) and prints manifest-ready anchors.
Usage:
python3 massing_from_outline.py --outline outline.json --storeys 22 \
--height 3.0 --name dikuai27_b3 [--label "3#楼 22F住宅"] --out spec.json
outline JSON: [[x,y],...] site-plan meters (or {"points": [...]}). The spec is
localized to the outline's min corner; anchors printed as JSON on stdout:
model_anchor_m (local centroid) + survey_anchor_m (site centroid), rotation 0
(the outline is already site-true).
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--outline", required=True, help="JSON [[x,y],...] site meters")
parser.add_argument("--storeys", type=int, required=True)
parser.add_argument("--height", type=float, default=3.0, help="storey height (m)")
parser.add_argument("--name", required=True, help="project_name for the spec")
parser.add_argument("--label", default="", help="human label for the description")
parser.add_argument("--wall-width", type=float, default=0.25)
parser.add_argument("--out", required=True)
args = parser.parse_args()
raw = json.loads(Path(args.outline).read_text(encoding="utf-8"))
pts = raw.get("points") if isinstance(raw, dict) else raw
outline = [(float(p[0]), float(p[1])) for p in pts]
if len(outline) < 3:
raise SystemExit("outline needs at least 3 points")
if args.storeys < 1:
raise SystemExit("storeys must be >= 1")
xs = [p[0] for p in outline]
ys = [p[1] for p in outline]
ox, oy = min(xs), min(ys)
poly = [[round(x - ox, 3), round(y - oy, 3)] for x, y in outline]
bounds = [0.0, 0.0, round(max(xs) - ox, 3), round(max(ys) - oy, 3)]
top_z = round(args.storeys * args.height, 3)
floors = {}
for i in range(1, args.storeys + 1):
walls = [{"start": a, "end": b, "width": args.wall_width, "layer": "MASSING"}
for a, b in zip(poly, poly[1:] + poly[:1])]
floors[f"F{i}"] = {
"name": f"{i}层(总图轮廓体量)",
"z": round((i - 1) * args.height, 3),
"height": args.height,
"bounds": bounds,
"segments": {"walls": walls},
"footprint": {"source": "site_outline", "polygons": [poly]},
"caps": [{"z": top_z, "polygons": [poly]}] if i == args.storeys else [],
}
label = args.label or args.name
spec = {
"project": args.name,
"description": (f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m "
"出体量(诚实标注,非详图模型)"),
"units": {"scale": 0.001, "origin_source": [ox, oy]},
"categories": {
"walls": {"label": "墙体(体量)", "color": "#d4cbb8", "width": args.wall_width},
"slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0},
},
"source": {"config": {"use_footprint_slabs": True, "generate_caps": True,
"roof_specs": [], "project_name": args.name}},
"floors": floors,
}
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
ctr = [round(sum(p[0] for p in poly) / len(poly), 3),
round(sum(p[1] for p in poly) / len(poly), 3)]
print(json.dumps({
"out": str(out), "floors": args.storeys, "top_z": top_z,
"model_anchor_m": ctr,
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)],
"rotation_deg": 0.0,
}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View 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())