From 972985754973b8548ec9b2e793bcf6d0ac39b661 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Fri, 3 Jul 2026 08:05:57 +0800 Subject: [PATCH] Land the two deferred gaps: title-block frame clips + cross-floor datum gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - detect_sheet_frames: title-block INSERTs (A0_V1/A0+0.5_V1/*图框*) define the clip window when they contain the title — pitch windows halved elongated sheets (13号 加长A0, one frame holding both towers); wall refine is clamped inside the frame rect; 13号 b1 real data: all 45 frames rect-clipped - audit floors_aligned: cross-floor wall-profile datum check catches "self-consistent but misplaced" floors (13号 F3 错槽 85.8m that envelope centers PASSed); zero-shift guard kills the dense-podium false positive (27号 1#A PH matched "better" 1.5m off while already fitting in place) - 门卫 size mismatch root-caused as representation granularity (gate compound vs kiosk symbol), not an extraction bug — closed in the log - regression suite +6 checks (titleblock / crossdatum bad+good), all three projects re-audited with no false positives Co-Authored-By: Claude Fable 5 --- SKILL.md | 4 +- references/generalization_test_log.md | 27 ++++-- scripts/audit_showcase_extraction.py | 60 +++++++++++++- scripts/detect_sheet_frames.py | 48 ++++++++++- tests/test_extraction_pipeline.py | 113 ++++++++++++++++++++++++++ 5 files changed, 239 insertions(+), 13 deletions(-) diff --git a/SKILL.md b/SKILL.md index fb6c719..93b5692 100644 --- a/SKILL.md +++ b/SKILL.md @@ -54,7 +54,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate 1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `cached_xref_content` -> the XREF content is CACHED as in-file block definitions, expand blocks (≈bind) instead of asking for a re-export; `likely_xref_shell` (no cached content) -> user re-exported with XREFs bound. 2. Frame alignment proven: detect report shows `grid-aligned, votes x>=3 y>=3` per floor (any `WEAK grid match` floor was verified on its overlay SVG). -3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. Never pass `--no-strict-gates` to proceed. +3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. `floors_aligned` also cross-checks every floor's wall profile against the group's reference floor (a strong correlation peak at a non-zero shift = "self-consistent but misplaced", the 13号 F3 错槽 pattern that envelope centers cannot see). Never pass `--no-strict-gates` to proceed. 4. No `WARNING topless_group` from derive (roof handled via caps or `roof_specs`), and no `WARNING mesh_from_polygons` from the GLB build (else slabs/roofs silently vanished — install mapbox_earcut). 5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise; and check the AIR between separate masses in the front/side views — bridged footprint hulls lay slab plates between twin towers, invisible in top views and to every gate). 6. Campus placement (if 总图/定位图 exists): building envelope dims match the site rect 1:1 (e.g. 面积核算 frame), rotation taken from the rect edge angle, 180° flip disambiguated by an asymmetric feature (machine rooms / basement / entrance), and a top-view overlay image confirms the building inside its site rect. Neighbour gaps measured numerically: no overlaps, 贴建 joints 0.15-0.3 m with corroborating evidence, buildings inside 红线. @@ -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), proposes a wall-bbox-refined `clip` per floor frame, 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). 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. - 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. diff --git a/references/generalization_test_log.md b/references/generalization_test_log.md index 632f608..a5d22b8 100644 --- a/references/generalization_test_log.md +++ b/references/generalization_test_log.md @@ -292,12 +292,27 @@ glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。 场景(两簇 40m 距,断言 2 包且无 25m+ 跨包)。教训:**门禁与顶视图对 桥接楼板都不敏感,侧视/正视目检必须看"楼间空气"**——已列入 DoD 目检项。 -**已知未修(记录在案)**:③ 图签块 INSERT 定图框(加长A0 被 pitch 截半, -13号教训——mixed-pitch 修复部分缓解,完整方案待设计);⑤ floors_aligned -跨层公共基准核验(对"自洽但整体错位"仍失明,13号 round 6 发现);⑦ 未命名 -详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度只覆盖有名字的辅助框; -27号 门卫模型/总图尺寸不符未溯源;2# 的"十九、二十一层平面图"修改单簇 -(无障碍改造相关)未并入模型。 +19. **图签块 INSERT 定图框**(留档项③落地,13号 加长A0 教训):detect 预扫 + msp 中 A0/A1/A0+0.5_V1/图框/图签 类块名的 INSERT,世界 bbox 通过尺寸/ + 长宽比合理性检验后作为该框 clip 窗(墙精修结果 clamp 在框内,不吞邻图); + 13号 b1 实测 45 框全部由图签矩形定窗。回归 titleblock 场景(加长A0 一框 + 双塔,pitch 窗必截半)。 +20. **floors_aligned 跨层墙基准核验**(留档项⑤落地,13号 F3 错槽教训): + audit 对同组楼层做墙剖面互相关(对墙量最大的参考层),强峰在非零位移 + (|shift|>1m,coverage≥0.45,ratio≥1.5)→ FAIL "自洽但整体错位"。 + **零位移护栏**:目标层在原位已贴合(zero_cov≥0.7×best)则不报—— + 密集裙房参考层会让小轮廓层"哪儿都能贴上"(27号 1#A PH 在 1.5m 处 + 出过伪峰)。回归 crossdatum 场景(错槽 FAIL/对槽 PASS)+ 三项目审计 + 无误报。 +21. **门卫"尺寸不符"溯源结论(非缺陷)**:模型 42.8m 是大门建筑组 + (两侧门房 x 0-8/21-29 + 端部围墙 39-42 + 中间门洞幕墙带),总图只画 + 岗亭符号(2.4m 八边形)+门头雨篷(17.4m)——表达粒度不同,重心放置合理, + 结案。 + +**仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度 +只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的 +"十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认 +以哪版为准)。 (待续) diff --git a/scripts/audit_showcase_extraction.py b/scripts/audit_showcase_extraction.py index 3462c6c..831c548 100755 --- a/scripts/audit_showcase_extraction.py +++ b/scripts/audit_showcase_extraction.py @@ -401,10 +401,68 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[ "detail": worst[1] + ". Floors are not stacked — per-frame offsets are missing or wrong; " "run detect_sheet_frames.py and use its clip/offset config.", } + # Cross-floor datum: envelope centers are blind to "self-consistent but + # misplaced" floors (13号 F3 sat one tower-slot off — 85.8 m — and PASSed: + # the merged twin-tower envelope hid it). Correlate each floor's wall + # profile against the group's reference floor: a strong off-zero peak + # means the whole floor sits N meters from the shared wall datum. + try: + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from detect_sheet_frames import correlate_shift, wall_profile + except Exception: + correlate_shift = wall_profile = None # type: ignore + if correlate_shift is not None: + wall_segs: dict[str, list[tuple[float, float, float, float]]] = {} + for fk, floor in spec.get("floors", {}).items(): + segs = floor.get("segments", {}).get("walls") or [] + if len(segs) >= 10: + wall_segs[fk] = [(s["start"][0], s["start"][1], s["end"][0], s["end"][1]) for s in segs] + by_group: dict[str, list[str]] = defaultdict(list) + for fk in wall_segs: + by_group[derive._cap_floor_group(fk, config)].append(fk) + for grp, keys in by_group.items(): + if len(keys) < 2: + continue + ref_key = max(keys, key=lambda k: sum( + math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k])) + ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4) + ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4) + def zero_cov(ref_prof, prof, tol: float = 0.25) -> float: + total = sum(w for _, w in prof) + if total <= 0: + return 0.0 + matched = sum(w for p, w in prof + if any(abs(p - rp) <= tol for rp, _ in ref_prof)) + return matched / total + + for fk in keys: + if fk == ref_key: + continue + for axis, ref_prof in ((0, ref_x), (1, ref_y)): + prof = wall_profile(wall_segs[fk], axis, axis_tol=0.02, min_len=0.4) + shift, cov, ratio = correlate_shift(ref_prof, prof, coarse=0.5, fine=0.05) + # a floor already matching IN PLACE is not misplaced, however + # attractive some shifted peak looks (dense podium references + # let any small profile "match" somewhere: 27号 1#A PH) + if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov: + continue + if (shift is not None and cov >= 0.45 and ratio >= 1.5 + and abs(shift) > 1.0): + return { + "name": "floors_aligned", + "status": "FAIL", + "detail": ( + f"cross_floor_datum {grp}: {fk} wall profile matches {ref_key} " + f"only when shifted {round(shift, 1)} m in {'xy'[axis]} " + f"(coverage {cov:.2f}, peak ratio {min(ratio, 99):.1f}) — the floor is " + "self-consistent but misplaced (wrong frame offset / wrong tower slot, " + "13号 F3 错槽 pattern). Re-check that frame's offset against the shared datum." + ), + } return { "name": "floors_aligned", "status": "PASS", - "detail": "Wall-bbox centers of same-stack floors coincide.", + "detail": "Wall-bbox centers of same-stack floors coincide; cross-floor wall-profile datum consistent.", } diff --git a/scripts/detect_sheet_frames.py b/scripts/detect_sheet_frames.py index 8c0323a..39e36c5 100644 --- a/scripts/detect_sheet_frames.py +++ b/scripts/detect_sheet_frames.py @@ -205,7 +205,7 @@ def title_qualifier(name: str) -> str: return name if m is None else name[: m.start()] -def wall_profile(segs, axis: int): +def wall_profile(segs, axis: int, axis_tol: float = 2.0, min_len: float = 400.0): """Length-weighted axis positions of straight walls. axis=0: vertical segments -> x positions; axis=1: horizontal -> y. @@ -213,13 +213,14 @@ def wall_profile(segs, axis: int): in the frame (13号 tower / 27号 2#): correlating profiles between frames recovers the true translation where clip-corner anchoring is off by whole bays (wall bbox min-corner varies with balconies). + Defaults are mm-scale; pass axis_tol/min_len in meters for spec-space use. """ out = [] for sx, sy, ex, ey in segs: dx, dy = abs(ex - sx), abs(ey - sy) - if axis == 0 and dx < 2.0 and dy > 400: + if axis == 0 and dx < axis_tol and dy > min_len: out.append(((sx + ex) / 2, dy)) - elif axis == 1 and dy < 2.0 and dx > 400: + elif axis == 1 and dy < axis_tol and dx > min_len: out.append(((sy + ey) / 2, dx)) return out @@ -368,6 +369,34 @@ def main() -> int: elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes): others.append({"name": content, "x": x, "y": y, "h": height}) + # Title-block frame INSERTs (A0_V1 / A0+0.5_V1 / *图框* …) carry the TRUE + # sheet rect. Pitch-sized windows halve elongated sheets (13号 加长A0 held + # both towers in one frame and F1 lost a tower) — prefer the block rect. + frame_block_re = re.compile(r"(?i)(^A[0-4](\+[0-9.]+)?([_\-]|$))|图框|图签|(^TK([_\-]|$))") + frame_rects: list[tuple[float, float, float, float]] = [] + for entity in msp.query("INSERT"): + name = str(entity.dxf.name) + if not frame_block_re.search(name): + continue + xs_fb: list[float] = [] + ys_fb: list[float] = [] + try: + for ve in entity.virtual_entities(): + vk = ve.dxftype() + if vk == "LINE": + for p in (ve.dxf.start, ve.dxf.end): + xs_fb.append(float(p.x)); ys_fb.append(float(p.y)) + elif vk == "LWPOLYLINE": + for px, py in ve.get_points("xy"): + xs_fb.append(float(px)); ys_fb.append(float(py)) + except Exception: + continue + if not xs_fb: + continue + w, h = max(xs_fb) - min(xs_fb), max(ys_fb) - min(ys_fb) + if w >= 20000 and h >= 15000 and 0.3 <= (w / h) <= 4.0: # plausible sheet + frame_rects.append((min(xs_fb), min(ys_fb), max(xs_fb), max(ys_fb))) + for entity in msp: kind = entity.dxftype() if kind == "INSERT": @@ -439,6 +468,13 @@ def main() -> int: if pitch_x and not pitch_y: # row layout: title x may sit anywhere under its frame; centre on it rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h] + frame_rect = next((r for r in frame_rects + if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None) + if frame_rect is not None: + fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1] + rough = [frame_rect[0] + fw * 0.01, frame_rect[1] + fh * 0.01, + frame_rect[2] - fw * 0.01, frame_rect[3] - fh * 0.01] + notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)") clip = None for group in refine_groups: found = segments_in(lines, rough, group) @@ -447,10 +483,14 @@ def main() -> int: ys_ = [v for s in found for v in (s[1], s[3])] margin = pitch * 0.06 clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin] + if frame_rect is not None: # never swallow the neighbour sheet + clip = [max(clip[0], rough[0]), max(clip[1], rough[1]), + min(clip[2], rough[2]), min(clip[3], rough[3])] break if clip is None: clip = rough - notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip") + if frame_rect is None: + notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip") # Axis geometry lives OUTSIDE the wall-tight clip (axis-number stubs sit # beyond the facade), so collect grid candidates in an expanded window. axis_margin = pitch * 0.16 diff --git a/tests/test_extraction_pipeline.py b/tests/test_extraction_pipeline.py index 22c9c73..0c19593 100644 --- a/tests/test_extraction_pipeline.py +++ b/tests/test_extraction_pipeline.py @@ -333,6 +333,48 @@ def make_blocktitle_dxf(path: Path) -> None: doc.saveas(path) +def make_titleblock_dxf(path: Path) -> None: + """13号 加长A0 pattern: one ELONGATED sheet holds two towers far apart; the + pitch-sized rough window sees only the tower above the title and the clip + truncates the sheet. Title-block INSERTs (A0+0.5_V1 …) carry the true + frame rect and must define the clip.""" + doc = ezdxf.new("R2010", setup=True) + for layer in ("WALL", "DOTE", "PUB_TEXT", "TK"): + doc.layers.add(layer) + msp = doc.modelspace() + pitch = 98100.0 + + def tower(ox: float, oy: float, bays: tuple) -> None: + outline = [((ox, oy), (ox + 40000, oy)), ((ox + 40000, oy), (ox + 40000, oy + 20000)), + ((ox + 40000, oy + 20000), (ox, oy + 20000)), ((ox, oy + 20000), (ox, oy))] + for (sx, sy), (ex, ey) in outline: + msp.add_line((sx, sy), (ex, ey), dxfattribs={"layer": "WALL"}) + for b in bays: + msp.add_line((ox + b, oy), (ox + b, oy + 20000), dxfattribs={"layer": "WALL"}) + for x in (0, 8000, 19000, 26000, 37000, 40000): + msp.add_line((ox + x, oy - 3000), (ox + x, oy + 26000), dxfattribs={"layer": "DOTE"}) + for y in (0, 6000, 10000, 20000): + msp.add_line((ox - 3000, oy + y), (ox + 43000, oy + y), dxfattribs={"layer": "DOTE"}) + + def frame_block(name: str, w: float, h: float) -> str: + if name not in doc.blocks: + blk = doc.blocks.new(name=name) + blk.add_lwpolyline([(0, 0), (w, 0), (w, h), (0, h)], close=True, + dxfattribs={"layer": "TK"}) + return name + + # F1: elongated sheet, twin towers 110 m apart inside ONE frame + tower(0.0, 0.0, (8000, 19000, 26000)) + tower(110000.0, 0.0, (5000, 14000, 33000)) + msp.add_blockref(frame_block("A0+0.5_V1", 179000, 85100), (-12000, -22000)) + msp.add_text("一层平面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -9000)) + # F2: normal sheet below, single tower + tower(0.0, -pitch, (8000, 19000, 26000)) + msp.add_blockref(frame_block("A1_V1", 85100, 60400), (-12000, -pitch - 22000)) + msp.add_text("二层平面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -pitch - 9000)) + 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 @@ -867,6 +909,77 @@ def main() -> int: ok_bt = f2 is not None and abs(f2["offset"][0]) <= 120 and abs(f2["offset"][1] - 98100.0) <= 120 check("block-wrapped frames aligned", ok_bt, str(f2 and f2["offset"])) + # --- title-block INSERTs define clips; elongated sheets must not be halved (13号 加长A0) --- + tb_dir = WORK / "dxf_titleblock" + tb_dir.mkdir(parents=True, exist_ok=True) + make_titleblock_dxf(tb_dir / "titleblock.dxf") + proc = run([ + sys.executable, "scripts/detect_sheet_frames.py", + "--dxf", str(tb_dir / "titleblock.dxf"), "--out-config", str(WORK / "frames_tb.json"), + "--out-report", str(WORK / "frames_tb.md"), "--vendor-dir", str(VENDOR), + ]) + check("detect handles title-block frames", proc.returncode == 0, proc.stderr[-500:]) + if proc.returncode == 0: + frames_tb = json.loads((WORK / "frames_tb.json").read_text(encoding="utf-8")) + tb = {f["name"]: f for f in frames_tb["drawings"][0]["floors"]} + f1 = tb.get("一层平面图") + ok_tb = f1 is not None and f1["clip"][0] <= 0 and f1["clip"][2] >= 149000 + check("elongated-A0 clip spans both towers", ok_tb, str(f1 and f1["clip"])) + tb_md = (WORK / "frames_tb.md").read_text(encoding="utf-8") + check("frame-block clips reported", "frame-block" in tb_md, tb_md[-300:]) + + # --- cross-floor datum: self-consistent but misplaced floor must FAIL audit (13号 F3 错槽) --- + cd_dir = WORK / "dxf_crossdatum" + cd_dir.mkdir(parents=True, exist_ok=True) + cd_doc = ezdxf.new("R2010", setup=True) + cd_doc.layers.add("WALL") + cd_msp = cd_doc.modelspace() + + def cd_tower(ox: float, bays: tuple) -> None: + for start, end in [((ox, 0), (ox + 20000, 0)), ((ox + 20000, 0), (ox + 20000, 10000)), + ((ox + 20000, 10000), (ox, 10000)), ((ox, 10000), (ox, 0))]: + cd_msp.add_line(start, end, dxfattribs={"layer": "WALL"}) + for b in bays: + cd_msp.add_line((ox + b, 0), (ox + b, 10000), dxfattribs={"layer": "WALL"}) + cd_msp.add_line((ox + 2000, 5200), (ox + 18000, 5200), dxfattribs={"layer": "WALL"}) + cd_msp.add_line((ox + 1000, 2600), (ox + 19000, 2600), dxfattribs={"layer": "WALL"}) + cd_msp.add_line((ox + bays[0] + 800, 0), (ox + bays[0] + 800, 10000), dxfattribs={"layer": "WALL"}) + + # F1 sheet: towers A (distinct bays) + B, 36 m apart. F2 sheet at x=100000: + # tower-A pattern that belongs in the A slot. + cd_tower(0.0, (3200, 7500, 16100)) + cd_tower(36000.0, (4900, 12300, 17700)) + cd_tower(100000.0, (3200, 7500, 16100)) + cd_doc.saveas(cd_dir / "crossdatum.dxf") + + def cd_audit(tag: str, offset_x: float) -> tuple[int, str]: + cfg = { + "scale": 0.001, "generate_footprints": True, + "drawings": [{"file": "crossdatum.dxf", "floors": [ + {"key": "F1", "name": "一层", "z": 0.0, "height": 3.0, + "clip": [-2000.0, -2000.0, 58000.0, 12000.0], "offset": [0.0, 0.0]}, + {"key": "F2", "name": "二层", "z": 3.0, "height": 3.0, + "clip": [98000.0, -2000.0, 122000.0, 12000.0], "offset": [offset_x, 0.0]}, + ]}], + } + cfg_path = WORK / f"cd_config_{tag}.json" + cfg_path.write_text(json.dumps(cfg, ensure_ascii=False), encoding="utf-8") + spec_path = WORK / f"cd_spec_{tag}.json" + run([sys.executable, "scripts/derive_showcase_spec.py", + "--dxf-dir", str(cd_dir), "--config", str(cfg_path), + "--out", str(spec_path), "--vendor-dir", str(VENDOR)]) + proc = run([sys.executable, "scripts/audit_showcase_extraction.py", + "--dxf-dir", str(cd_dir), "--config", str(cfg_path), + "--spec", str(spec_path), "--out", str(WORK / f"cd_audit_{tag}"), + "--vendor-dir", str(VENDOR)]) + md = (WORK / f"cd_audit_{tag}" / "extraction_audit.json").read_text(encoding="utf-8") + return proc.returncode, md + + rc_bad, md_bad = cd_audit("bad", -64000.0) # A-pattern lands in the B slot (36 m off) + check("misplaced floor FAILs cross-floor datum", rc_bad != 0 and "cross_floor" in md_bad, md_bad[-400:] if rc_bad == 0 else "") + 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 "") + # --- 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)