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

@@ -82,7 +82,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
- Use `references/pipeline.md` and `references/building_spec_schema.md`.
- Map CAD layers to normalized categories: `walls`, `glazing`, `roof`, `columns`, `beams`, `railings`, `doors`, `detail_lines`, `floor_lines`, and `grid`.
- Identify one drawing per floor or split sheets that contain multiple floor plans side by side.
- MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too; elevation/section frames are listed for floor heights (`z`/`height` from DIM_ELEV 标高 texts like `8.100`), not as floors. Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row.
- MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Multi-floor titles (四、六、八层平面图 / 十一至十四层平面图) are expanded into one config entry per storey sharing the frame's clip/offset — hand-copying N entries is where floors silently vanished (13号 b2). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too; elevation/section frames are listed for floor heights with a PER-FRAME `ladder:` of DIM_ELEV values plus a `suggested storey table` line (uniform-step chain) — the suggestion is evidence, not a decision: fill `z`/`height` yourself after checking the 剖面 ladder (stair sections beat at half-storey rhythm; podium/machine floors differ). Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row.
- Align floors by structural grid or repeated control axes. Use millimeters-to-meters scale (`0.001`) unless the report proves the CAD is already in meters.
- Floor keys: `floor_sort_key` treats a leading `B` as basement (sorted below ground). Do not invent keys like `B1F` for "Building 1 Floor" — use per-building specs instead, and set explicit `floor_order` whenever keys are nonstandard.
- When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation. Footprints are hulled PER proximity cluster (`footprint_cluster_linkage`, 6 m): a floor holding two disconnected masses (13号 twin towers in one floor key) gets separate hulls — a single concave hull would bridge the void and `use_footprint_slabs` would lay plates across it; genuinely linked wings stay merged because the 连廊 walls connect the clusters.
@@ -134,8 +134,8 @@ A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: seve
- Place buildings with a site manifest: from 总图/定位图 (prefer a "带轴号(可点坐标)" version if present) measure each building's anchor point and rotation, then assemble per-building GLBs in the viewer/scene with those transforms. Record the manifest (building -> position/rotation/source) in the notes file.
- Proven placement recipe (贝昂 case): find the building's envelope rectangle in the site drawing (layer 面积核算/建筑轮廓线) — its edge lengths must equal the model's wall-envelope bbox 1:1 (here 90.2 x 42.2 m exactly), edge angle gives rotation (7.57°), the corner matching the model's (min x, min y) gives translation. Resolve the 180° flip by densest-feature voting (e.g. machine-room walls inside a known sub-rect). Then EITHER merge at spec level (transform all segments/footprints/caps into site-local meters and append a SITE context floor) and export one GLB, OR keep per-building GLBs plus transforms in the manifest. Pick a site-local origin (用地红线 min corner), never raw surveying coordinates — float32 breaks at 349 km.
- Anchor placement on WALL evidence, never roof/eave envelopes: 屋面 outlines include canopies and asymmetric overhangs — concentric placement against one put 2# 0.45 m off (26 cm INSIDE its neighbour). Best anchors, in order: corner coordinate callouts (X=/Y= texts), wall lines, envelope rects whose edges equal the wall bbox exactly.
- Site plans without per-building envelope rects (27号 pattern): building outlines may hide on odd layers (EVTR!) — match each closed polyline to its nearest 楼栋 label, then register the model footprint onto the outline by point-to-edge ICP (brute-force angle + translation refine, trim worst 10%). Constrain the angle window when the outline is visibly axis-aligned — balcony bumps love a tilted false minimum. A building with NO drawn outline can still be anchored from its DIM_COOR corner callouts alone (pair X=/Y= texts, drop points that fall on the garage outline / fire-pad rects), and registering the UNION of several floors' footprints beats one floor when upper wings overhang. Surveying convention on both 13号/27号 site plans: drawing x = 测绘Y (east), drawing y = 测绘X (north), meters.
- Buildings named on the site plan but with NO delivered drawings (27号 3#/4#): build honest massing specs from the site outline x storey count x storey height (labels like `22F` sit next to each outline; heights from the sibling tower's ladder). Mark them as 总图轮廓体量 in the spec description and campus notes — never silently fake a detailed model.
- Site plans without per-building envelope rects (27号 pattern): building outlines may hide on odd layers (EVTR!) — match each closed polyline to its nearest 楼栋 label, then register the model footprint onto the outline with `scripts/register_site_outlines.py` (point-to-edge ICP: brute-force angle + translation refine, trim worst 10%; emits a manifest-ready placement + residual). Constrain `--angle-window` when the outline is visibly axis-aligned — balcony bumps love a tilted false minimum (2# found a 10.75° pit). A building with NO drawn outline can still be anchored from its DIM_COOR corner callouts alone (pair X=/Y= texts, drop points that fall on the garage outline / fire-pad rects), and registering the UNION of several floors' footprints (`--floors F1 F2 F4`) beats one floor when upper wings overhang. Judge residuals: 0.06 m = outline equals model; 0.5-1 m normal with balconies; >2 m = wrong outline/floors, check the overlay. Surveying convention on both 13号/27号 site plans: drawing x = 测绘Y (east), drawing y = 测绘X (north), meters.
- Buildings named on the site plan but with NO delivered drawings (27号 3#/4#): `scripts/massing_from_outline.py --outline pts.json --storeys 22 --height 3.0` builds an honest massing spec (outline-edge walls, footprint slabs, top cap, description marked 总图轮廓体量) and prints manifest-ready anchors — never silently fake a detailed model. Storey counts come from the `22F` labels next to each outline; heights from the sibling tower's ladder.
- Adjacent-building gap sanity check is mandatory: compute the wall-to-wall gap in the shared-edge frame. ~0.15-0.30 m means 贴建 with an expansion joint (变形缝) — corroborate with the neighbour's roof labeled on this building's roof plan and matching floor elevations. Several metres means fire separation. A NEGATIVE gap (overlap) is always a placement bug. Cross-check the chosen position against the boundary: if a hypothesis (e.g. a 10 m fire gap) pushes the building through 用地红线, the hypothesis is wrong.
- Site context is a deliverable, not decoration — a campus scene with only a few boundary lines reads as broken. Run `scripts/site_context_from_dump.py` on the 总图/定位图 dumps: it emits ready-to-merge floors for ground (用地红线 footprint slab), roads + parking stalls (lines, arcs, block-expanded 车位 INSERTs), fence (围墙 as 1.8 m railings), street trees (行道树 INSERT points as green posts, custom `trees` category), and low-confidence massings for context structures drawn only in the site plan (连廊/门卫/消控室, named by nearest label). It takes one plan-copy window (site sheets usually hold several scheme copies), a per-source unit scale (总图 in meters, 定位图 copies in mm), and an exclude-quad so the real building model replaces its own site outline. Buildings that have their own drawing sets get real models placed by the manifest — never fake them as massings.

View File

@@ -309,6 +309,15 @@ glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。
岗亭符号(2.4m 八边形)+门头雨篷(17.4m)——表达粒度不同,重心放置合理,
结案。
22. **场地机制产品化 + config 自动化**(本轮以会话脚本验证的能力固化进
scripts/):`register_site_outlines.py`(点-边 ICP 配准 CLI,manifest
片段直出,残差>2m 大声告警)、`massing_from_outline.py`(轮廓×层数
体量 spec CLI);detect 三项:多层合并图名自动展开(四、六、八/
十一至十四 → 每层一条 config 条目,13号 b2 静默丢层的根源性预防)、
复合中文数字解析(十一/二十一 不再变 F0 键)、逐框标高梯 + 均匀步进
层高建议(27号 2# 实测:19 层枚举图名自动展开、step 3.0×11 建议命中;
建议只是证据不自动填 z——楼梯剖面的半层节拍是反例)。回归 +11 项。
**仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度
只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的
"十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认

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

View File

@@ -13,6 +13,7 @@ Run: python3 tests/test_extraction_pipeline.py
from __future__ import annotations
import json
import math
import shutil
import subprocess
import sys
@@ -375,6 +376,45 @@ def make_titleblock_dxf(path: Path) -> None:
doc.saveas(path)
def make_ladder_dxf(path: Path) -> None:
"""Storey-table automation: a multi-floor title (三、五层平面图) must expand
into per-floor config entries, and the 剖面图 frame's DIM_ELEV ladder must
yield per-frame ladders + a uniform-step storey suggestion."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT", "DIM_ELEV"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str) -> None:
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
interior = [((8000 * i, 0), (8000 * i, 20000)) for i in range(1, 5)]
interior += [((0, 10000), (40000, 10000))]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000):
msp.add_line((x, -3000 + oy), (x, 26000 + oy), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
msp.add_line((-3000, y + oy), (46000, y + oy), dxfattribs={"layer": "DOTE"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
draw_frame(0.0, "一层平面图")
draw_frame(-pitch, "三、五层平面图")
draw_frame(-2 * pitch, "十一至十四层平面图")
# section frame with an elevation ladder: 0..21 step 3.0 + noise values
sx0 = 120000.0
msp.add_text("1-1剖面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((sx0 + 8000, -6000))
for k in range(8):
v = 3.0 * k
msp.add_text(f"{v:.3f}", height=350,
dxfattribs={"layer": "DIM_ELEV"}).set_placement((sx0 + 2000, 1000 + k * 3000))
for noise in ("0.150", "22.500"):
msp.add_text(noise, height=350,
dxfattribs={"layer": "DIM_ELEV"}).set_placement((sx0 + 6000, 2000))
doc.saveas(path)
def make_mixedrow_dxf(path: Path) -> None:
"""27号 1#B pattern: main plans stack in a COLUMN, but a couple of stray
same-row detail titles fabricate a bogus (much smaller) x-pitch. clip_w
@@ -980,6 +1020,77 @@ def main() -> int:
rc_good, md_good = cd_audit("good", -100000.0) # correct slot
check("correct slot PASSes cross-floor datum", rc_good == 0, md_good[-400:] if rc_good != 0 else "")
# --- multi-floor titles expand; per-frame ladders + storey suggestion (27号/13号 config 手写之痛) ---
ld_dir = WORK / "dxf_ladder"
ld_dir.mkdir(parents=True, exist_ok=True)
make_ladder_dxf(ld_dir / "ladder.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(ld_dir / "ladder.dxf"), "--out-config", str(WORK / "frames_ld.json"),
"--out-report", str(WORK / "frames_ld.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles ladder/multi-floor sheet", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
frames_ld = json.loads((WORK / "frames_ld.json").read_text(encoding="utf-8"))
ld = {f["key"]: f for f in frames_ld["drawings"][0]["floors"]}
check("enumerated title expands (三、五层)", "F3" in ld and "F5" in ld
and ld["F3"]["clip"] == ld["F5"]["clip"], str(sorted(ld)))
check("range title expands (十一至十四层)", all(f"F{n}" in ld for n in (11, 12, 13, 14)),
str(sorted(ld)))
check("compound CN numerals parsed (no F0 keys)", not any(k.startswith("F0") for k in ld),
str(sorted(ld)))
ld_md = (WORK / "frames_ld.md").read_text(encoding="utf-8")
check("per-frame elevation ladder reported", "1-1剖面图" in ld_md and "ladder:" in ld_md, ld_md[-500:])
check("uniform storey step suggested", "suggested storey table: uniform step 3.0" in ld_md, ld_md[-600:])
# --- register_site_outlines.py: ICP registration recovers rotation+translation ---
reg_dir = WORK / "register"
reg_dir.mkdir(parents=True, exist_ok=True)
# model footprint: 30x12 rect with an asymmetric notch (pins the 180° flip)
model_poly = [[0, 0], [30, 0], [30, 12], [8, 12], [8, 9], [0, 9]]
reg_spec = {
"project": "reg", "units": {"scale": 0.001}, "categories": {},
"source": {"config": {}},
"floors": {"F1": {"name": "F1", "z": 0.0, "height": 3.0,
"bounds": [0, 0, 30, 12],
"segments": {"walls": []},
"footprint": {"polygons": [model_poly]}, "caps": []}},
}
(reg_dir / "spec.json").write_text(json.dumps(reg_spec), encoding="utf-8")
th = math.radians(30.0)
site_pts = [[round(x * math.cos(th) - y * math.sin(th) + 500.0, 3),
round(x * math.sin(th) + y * math.cos(th) + 200.0, 3)] for x, y in model_poly]
(reg_dir / "pts.json").write_text(json.dumps(site_pts), encoding="utf-8")
proc = run([
sys.executable, "scripts/register_site_outlines.py",
"--spec", str(reg_dir / "spec.json"), "--floors", "F1",
"--site-points", str(reg_dir / "pts.json"), "--out", str(reg_dir / "reg.json"),
])
check("register_site_outlines runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
reg = json.loads((reg_dir / "reg.json").read_text(encoding="utf-8"))
d_rot = abs((reg["rotation_deg"] - 30.0 + 180) % 360 - 180)
check("registration recovers rotation", d_rot <= 0.5, str(reg))
check("registration residual small", reg["residual_m"] <= 0.15, str(reg))
check("manifest fragment emitted", "model_anchor_m" in reg.get("manifest_entry", {}), str(reg.keys()))
# --- massing_from_outline.py: honest massing spec from site outline ---
proc = run([
sys.executable, "scripts/massing_from_outline.py",
"--outline", str(reg_dir / "pts.json"), "--storeys", "5", "--height", "3.0",
"--name", "test_massing", "--out", str(reg_dir / "massing.json"),
])
check("massing_from_outline runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
ms = json.loads((reg_dir / "massing.json").read_text(encoding="utf-8"))
fl = ms["floors"]
top = fl[max(fl, key=lambda k: fl[k]["z"])]
check("massing has N floors with walls+footprint",
len(fl) == 5 and all(f["segments"]["walls"] and f["footprint"]["polygons"] for f in fl.values()),
str({k: len(v['segments']['walls']) for k, v in fl.items()}))
check("massing top floor capped", bool(top["caps"]), str(top.get("caps")))
check("massing marked as outline volume", "体量" in ms.get("description", ""), ms.get("description", ""))
# --- bogus x-pitch from stray same-row titles must not shrink clips (27号 1#B) ---
mx_dir = WORK / "dxf_mixedrow"
mx_dir.mkdir(parents=True, exist_ok=True)