Generalization hardening from 27号 (rounds 5-8): 6 gap fixes, all TDD

- detect_sheet_frames: auxiliary-titled frames (非机动坡道/无障碍改造…) never
  become the alignment reference; wall-profile correlation fallback when a
  frame has no axis geometry (coverage+peak-ratio gated); bogus x-pitch from
  stray same-row titles distrusted (pitch_x < 0.7*pitch_y); plan titles inside
  cached-xref blocks scanned too
- cad_dxf_report: cached_xref_content warning (msp INSERT stubs + in-file
  block cache -> expand_blocks ≈ bind, not a re-export ask)
- derive_showcase_spec: floor_order gaps warn loudly in both directions
- assemble_campus: per-building rotation_deg overrides the global one
- SKILL.md updated; regression suite +14 checks (auxref/nogrid/mixedrow/
  blocktitle/cachedxref/floor_order/rotation scenarios)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 00:39:32 +08:00
parent 07e3c12956
commit fe3d3cbbee
6 changed files with 527 additions and 34 deletions

View File

@@ -52,7 +52,7 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
The pipeline is designed so a first pass either succeeds or STOPS at a loud gate. Do not hand over a model unless every line below has evidence (a report line, a gate status, or an image): The pipeline is designed so a first pass either succeeds or STOPS at a loud gate. Do not hand over a model unless every line below has evidence (a report line, a gate status, or an image):
1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `likely_xref_shell` -> user re-exported with XREFs bound. 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). 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. 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). 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).
@@ -76,13 +76,13 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
- Install missing parser dependencies into the current project work area, not globally: - Install missing parser dependencies into the current project work area, not globally:
`python3 -m pip install --target work/vendor ezdxf` `python3 -m pip install --target work/vendor ezdxf`
- Inspect the Markdown/JSON report before modeling. Confirm drawings, units, bounding boxes, and the top layers for walls/glazing/roof/columns/beams/railings/doors/detail lines/floor lines/grid. - Inspect the Markdown/JSON report before modeling. Confirm drawings, units, bounding boxes, and the top layers for walls/glazing/roof/columns/beams/railings/doors/detail lines/floor lines/grid.
- Resolve the report's `Warnings` section before modeling. `likely_xref_shell` / `near_empty` means a sheet's real geometry lives in unbound XREFs and will silently become a missing floor: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done). - Resolve the report's `Warnings` section before modeling. `cached_xref_content` means the "empty" sheet's INSERT stubs reference block definitions cached INSIDE the file (AutoCAD keeps unbound-XREF content as blocks; both libredwg and ODA export the cache) — expand blocks in detect/derive (`expand_blocks` ≈ bind), no re-export needed. Only `likely_xref_shell` / `near_empty` WITHOUT cached content means geometry truly lives outside: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done).
3. Build the extraction config and `building_spec.json`. 3. Build the extraction config and `building_spec.json`.
- Use `references/pipeline.md` and `references/building_spec_schema.md`. - 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`. - 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. - 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), 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`). 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; elevation/section frames are listed for floor heights (`z`/`height` from DIM_ELEV 标高 texts like `8.100`), not as floors. - 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.
- 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. - 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. - 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. - 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.
@@ -129,11 +129,13 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: several buildings plus a site plan — NOT floors of one building. Never map "one DWG = one floor" here. A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: several buildings plus a site plan — NOT floors of one building. Never map "one DWG = one floor" here.
- Model each building separately: one detect-frames pass, one extraction config, one `building_spec.json`/GLB per building DWG. Small structures (机械停车坑/水池) are usually one or two frames. - Model each building separately: one detect-frames pass, one extraction config, one `building_spec.json`/GLB per building DWG. Small structures (机械停车坑/水池) are usually one or two frames.
- Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically. - Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically. Buildings on one campus can face different ways (27号: 4#楼 sits ~27° off its siblings): a per-building `rotation_deg` in the manifest overrides the global one.
- Units differ by sheet type: building plans are almost always millimeters (`scale 0.001`), while 总图 site plans are often METERS at real surveying coordinates (huge x/y like 349xxx/663xxx, texts ~2-4 units tall). The extraction config has a single global `scale`, so never mix a meters site plan and mm building plans in one spec. - Units differ by sheet type: building plans are almost always millimeters (`scale 0.001`), while 总图 site plans are often METERS at real surveying coordinates (huge x/y like 349xxx/663xxx, texts ~2-4 units tall). The extraction config has a single global `scale`, so never mix a meters site plan and mm building plans in one spec.
- 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. - 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. - 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. - 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.
- 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. - 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. - 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

@@ -151,7 +151,11 @@ def main() -> int:
survey = b.get("survey_anchor_m") or b.get("survey_center_m") survey = b.get("survey_anchor_m") or b.get("survey_center_m")
if not anchor or not survey: if not anchor or not survey:
raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m") raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m")
xf = make_xf(anchor, survey, origin, cos_t, sin_t) # Buildings on one campus can face different ways (27号: 4#楼 sits ~27°
# off its siblings) — per-building rotation_deg overrides the global.
b_theta = math.radians(float(b.get("rotation_deg", manifest.get("rotation_deg", 0.0))))
b_cos, b_sin = math.cos(b_theta), math.sin(b_theta)
xf = make_xf(anchor, survey, origin, b_cos, b_sin)
floors = transform_floors(spec, xf) floors = transform_floors(spec, xf)
prefix = str(b.get("prefix", "")) prefix = str(b.get("prefix", ""))
placed.update({prefix + fk: fl for fk, fl in floors.items()}) placed.update({prefix + fk: fl for fk, fl in floors.items()})

View File

@@ -278,6 +278,28 @@ def count_plan_titles(entities) -> int:
return len(seen) return len(seen)
def insert_block_content(doc, entities) -> list[dict]:
"""Entity counts of blocks referenced by modelspace INSERTs.
AutoCAD stores unbound-XREF content as CACHED block definitions inside the
host DWG (13号: X-00-0011 held 5,306 entities while msp had 3 stubs), and
both libredwg and ODA export that cache as ordinary blocks. A "near empty"
msp made of INSERT stubs therefore often has ALL its geometry in-file —
expand_blocks ≈ bind, no re-export needed.
"""
names = {str(e.dxf.name) for e in entities if e.dxftype() == "INSERT"}
out = []
for name in names:
try:
block = doc.blocks[name]
except Exception:
continue
count = sum(1 for _ in block)
if count >= 100:
out.append({"name": name, "entities": count})
return sorted(out, key=lambda b: -b["entities"])[:8]
def file_warnings(item: dict) -> list[str]: def file_warnings(item: dict) -> list[str]:
warnings = [] warnings = []
entities = item.get("modelspace_entities") entities = item.get("modelspace_entities")
@@ -291,7 +313,17 @@ def file_warnings(item: dict) -> list[str]:
"This file holds a whole sheet set — never model it as a single floor and never stack frames " "This file holds a whole sheet set — never model it as a single floor and never stack frames "
"without per-floor offsets. Run scripts/detect_sheet_frames.py to generate clip/offset config." "without per-floor offsets. Run scripts/detect_sheet_frames.py to generate clip/offset config."
) )
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD: cached = item.get("insert_block_content") or []
cached_total = sum(b["entities"] for b in cached)
if entities < NEAR_EMPTY_ENTITY_THRESHOLD and cached_total >= 200:
names = ", ".join(f"{b['name']}({b['entities']})" for b in cached[:4])
warnings.append(
f"cached_xref_content: modelspace is only {entities} entities (INSERT stubs) but "
f"block definitions cached INSIDE this file hold {cached_total} entities ({names}). "
"The referenced content is already in the file — expand blocks in detect/derive "
"(expand_blocks ≈ bind); do NOT ask for a re-exported bound DWG."
)
elif xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
names = ", ".join(x["name"] for x in xrefs[:4]) names = ", ".join(x["name"] for x in xrefs[:4])
warnings.append( warnings.append(
f"likely_xref_shell: only {entities} entities but {len(xrefs)} XREF definition(s) ({names}). " f"likely_xref_shell: only {entities} entities but {len(xrefs)} XREF definition(s) ({names}). "
@@ -365,6 +397,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
"bbox": geometry_bbox, "bbox": geometry_bbox,
"messages": messages, "messages": messages,
"xref_definitions": xref_definitions(doc), "xref_definitions": xref_definitions(doc),
"insert_block_content": insert_block_content(doc, entities),
} }
result["warnings"] = file_warnings(result) result["warnings"] = file_warnings(result)
return result return result

View File

@@ -978,6 +978,23 @@ def finalize_spec(
scale = float(config.get("scale", config.get("scale_to_meters", 0.001))) scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
origin = source_origin(floor_data, config) origin = source_origin(floor_data, config)
ordered_keys = config.get("floor_order") or sorted(floor_data.keys(), key=floor_sort_key) ordered_keys = config.get("floor_order") or sorted(floor_data.keys(), key=floor_sort_key)
# floor_order gaps must be LOUD: a stale floor_order copied from a sibling
# config silently dropped 13号 b2 F11-F16 ("floors":12 was the only tell).
missing_from_order = [k for k in floor_data if k not in ordered_keys]
if missing_from_order:
print(
f"WARNING floor_order missing keys {missing_from_order}: these floors are "
"extracted in config drawings but NOT in floor_order — they would be "
"silently dropped. Add them to floor_order (or remove them from drawings).",
file=sys.stderr,
)
ghost_keys = [k for k in ordered_keys if k not in floor_data]
if ghost_keys:
print(
f"WARNING floor_order ghost keys {ghost_keys}: present in floor_order but "
"no drawing produces them — check for typos or missing drawing entries.",
file=sys.stderr,
)
floors: dict[str, Any] = {} floors: dict[str, Any] = {}
for index, key in enumerate(ordered_keys): for index, key in enumerate(ordered_keys):

View File

@@ -188,6 +188,88 @@ def segments_in(entities, clip, layers):
return out return out
# A plan title is "pure" when everything before 平面图 is floor vocabulary
# (numbers, 地下/夹层/标准层/机房/屋顶...). Any other prefix (非机动坡道/
# 无障碍住房改造/人防...) marks an auxiliary structure or a revision sheet:
# its grid belongs to a DIFFERENT building, so it must never become the
# alignment reference (27号 2#: the bike-ramp frame grabbed F1 and every
# tower frame went WEAK against it).
PURE_TITLE_RE = re.compile(
r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
)
def title_qualifier(name: str) -> str:
"""Chars before the floor-word core; nonempty => auxiliary-titled frame."""
m = PURE_TITLE_RE.search(name)
return name if m is None else name[: m.start()]
def wall_profile(segs, axis: int):
"""Length-weighted axis positions of straight walls.
axis=0: vertical segments -> x positions; axis=1: horizontal -> y.
Wall positions fingerprint the plan even when NO axis geometry exists
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).
"""
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:
out.append(((sx + ex) / 2, dy))
elif axis == 1 and dy < 2.0 and dx > 400:
out.append(((sy + ey) / 2, dx))
return out
def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0):
"""Best d such that {src + d} overlays {ref}, weighted-histogram voting.
Returns (shift, coverage, ratio): coverage = matched mass / min side mass,
ratio = peak mass / best rival peak >=3 coarse bins away. Both gate
acceptance so unrelated structures (a bike ramp vs the tower) refuse to
correlate instead of snapping to a spurious peak.
"""
if len(ref_pos) < 4 or len(src_pos) < 4:
return None, 0.0, 0.0
ref_h: dict[int, float] = defaultdict(float)
src_h: dict[int, float] = defaultdict(float)
for p, w in ref_pos:
ref_h[round(p / coarse)] += w
for p, w in src_pos:
src_h[round(p / coarse)] += w
votes: dict[int, float] = defaultdict(float)
for rb, rw in ref_h.items():
for sb, sw in src_h.items():
votes[rb - sb] += min(rw, sw)
if not votes:
return None, 0.0, 0.0
best = max(votes, key=lambda k: votes[k])
best_mass = votes[best] + 0.5 * (votes.get(best - 1, 0.0) + votes.get(best + 1, 0.0))
rival = max((m for d, m in votes.items() if abs(d - best) >= 3), default=0.0)
total = min(sum(w for _, w in ref_pos), sum(w for _, w in src_pos))
coverage = best_mass / total if total > 0 else 0.0
ratio = best_mass / rival if rival > 0 else float("inf")
# refine around the coarse peak with exact position pairs
center = best * coarse
fine_votes: dict[int, float] = defaultdict(float)
for rp, rw in ref_pos:
for sp, sw in src_pos:
d = rp - sp
if abs(d - center) <= coarse:
fine_votes[round(d / fine)] += min(rw, sw)
if not fine_votes:
return None, 0.0, 0.0
fb = max(fine_votes, key=lambda k: fine_votes[k])
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos
if abs((rp - sp) - fb * fine) <= fine]
mass = sum(w for _, w in sel)
shift = sum(d * w for d, w in sel) / mass if mass else center
return shift, coverage, ratio
def main() -> int: def main() -> int:
args = parse_args() args = parse_args()
ezdxf, recover = import_ezdxf(Path(args.vendor_dir)) ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
@@ -256,9 +338,36 @@ def main() -> int:
continue continue
for a, b in zip(pts, pts[1:]): for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1])) lines.append((layer, a[0], a[1], b[0], b[1]))
elif vkind in {"TEXT", "MTEXT"}:
# Cached-XREF sheets keep their plan TITLES inside the block
# (13号: msp = INSERT stubs only) — classify them like msp text.
classify_text(ve, vkind)
elif vkind == "INSERT": elif vkind == "INSERT":
collect_insert_lines(ve, depth + 1) collect_insert_lines(ve, depth + 1)
def classify_text(entity, kind) -> None:
content = entity_text(entity)
if not content or len(content) > 40:
return
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
return
# MTEXT stores char_height; asking MTEXT for "height" raises
# DXFAttributeError (only undefined-for-type attributes raise).
try:
height_attr = "char_height" if kind == "MTEXT" else "height"
height = float(entity.dxf.get(height_attr, 0) or 0)
except Exception:
height = 0.0
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
for entity in msp: for entity in msp:
kind = entity.dxftype() kind = entity.dxftype()
if kind == "INSERT": if kind == "INSERT":
@@ -266,27 +375,7 @@ def main() -> int:
collect_insert_lines(entity) collect_insert_lines(entity)
continue continue
if kind in {"TEXT", "MTEXT"}: if kind in {"TEXT", "MTEXT"}:
content = entity_text(entity) classify_text(entity, kind)
if not content or len(content) > 40:
continue
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
continue
# MTEXT stores char_height; asking MTEXT for "height" raises
# DXFAttributeError (only undefined-for-type attributes raise).
try:
height_attr = "char_height" if kind == "MTEXT" else "height"
height = float(entity.dxf.get(height_attr, 0) or 0)
except Exception:
height = 0.0
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
elif kind == "LINE": elif kind == "LINE":
d = entity.dxf d = entity.dxf
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y))) lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
@@ -327,6 +416,13 @@ def main() -> int:
row = sorted(row) row = sorted(row)
x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000) x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000)
pitch_x = statistics.median(x_gaps) if x_gaps else None pitch_x = statistics.median(x_gaps) if x_gaps else None
# A couple of stray same-row detail titles can fabricate an x-pitch far
# smaller than the sheet height (27号 1#B: 非机动坡道 row → pitch_x≈15.8k vs
# pitch_y≈59k). A real 2D sheet grid has pitch_x ≈ sheet width, never much
# below pitch_y — distrust the fabricated one or clip windows shrink and
# drop whole building wings.
if pitch_x and pitch_y and pitch_x < pitch_y * 0.7:
pitch_x = None
pitch = pitch_y or pitch_x or 98100.0 pitch = pitch_y or pitch_x or 98100.0
clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect
clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2 clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2
@@ -372,16 +468,27 @@ def main() -> int:
vert.append((sx + ex) / 2) vert.append((sx + ex) / 2)
elif dy < 2.0 and (dx > min_grid_len or tick_min < dx < tick_max): elif dy < 2.0 and (dx > min_grid_len or tick_min < dx < tick_max):
horiz.append((sy + ey) / 2) horiz.append((sy + ey) / 2)
qualifier = title_qualifier(t["name"])
if qualifier:
notes.append(
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy"
)
floors.append({ floors.append({
"key": floor_key_for(t["name"], used_keys), "key": floor_key_for(t["name"], used_keys),
"name": t["name"], "name": t["name"],
"clip": [round(c, 1) for c in clip], "clip": [round(c, 1) for c in clip],
"_vx": cluster_positions(vert, args.grid_bin), "_vx": cluster_positions(vert, args.grid_bin),
"_hy": cluster_positions(horiz, args.grid_bin), "_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
}) })
def ref_rank(f): def ref_rank(f):
return (0 if f["key"] == "F1" else 1, -(len(f["_vx"]) + len(f["_hy"]))) # never anchor on auxiliary structures (bike ramps, 人防 revisions...);
# prefer a pure ground-floor plan, then the richest grid
f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1
return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0] reference = sorted(floors, key=ref_rank)[0]
alignment = [] alignment = []
@@ -392,18 +499,35 @@ def main() -> int:
continue continue
dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin) dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin)
dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin) dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin)
aux_tag = " [auxiliary-titled frame]" if f["_aux"] else ""
if dx is not None and dy is not None and vx >= 3 and vy >= 3: if dx is not None and dy is not None and vx >= 3 and vy >= 3:
f["offset"] = [round(dx, 1), round(dy, 1)] f["offset"] = [round(dx, 1), round(dy, 1)]
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}") alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}{aux_tag}")
else: continue
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1), # Grid voting failed (no axis geometry in this frame). Try wall-profile
round(reference["clip"][1] - f["clip"][1], 1)] # correlation before surrendering to the clip-corner anchor, which is
# off by whole bays whenever wall bboxes differ between floors.
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0),
wall_profile(f["_walls"], 0))
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1),
wall_profile(f["_walls"], 1))
if (wdx is not None and wdy is not None
and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5):
f["offset"] = [round(wdx, 1), round(wdy, 1)]
alignment.append( alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']} — verify overlay!" f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} "
f"y={covy:.2f}, ratio x={min(ratx, 99):.1f} y={min(raty, 99):.1f}), "
f"offset={f['offset']}{aux_tag} — verify overlay!"
) )
continue
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
round(reference["clip"][1] - f["clip"][1], 1)]
alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!"
)
for f in floors: for f in floors:
f.pop("_vx"), f.pop("_hy") f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux")
config = { config = {
"project_name": path.stem, "project_name": path.stem,

View File

@@ -230,6 +230,152 @@ def make_rowframe_dxf(path: Path, layer_prefix: str = "", grid_style: str = "lin
doc.saveas(path) doc.saveas(path)
def make_auxref_dxf(path: Path) -> None:
"""27号 2# pattern: an auxiliary structure ("非机动坡道一层平面图") sits ABOVE
the main plans, grabs the F1 key, and must NOT become the alignment
reference — its grid is unrelated to the tower's."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_main(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)), ((12000, 5000), (28000, 5000))]
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): # varied bays
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))
# ramp frame on top: tiny 6x10 structure with its own (unrelated) grid
ry = pitch
for start, end in [((0, 0), (6000, 0)), ((6000, 0), (6000, 10000)),
((6000, 10000), (0, 10000)), ((0, 10000), (0, 0)),
((0, 3300), (6000, 3300)), ((0, 7100), (6000, 7100)),
((2500, 0), (2500, 10000))]:
msp.add_line((start[0], start[1] + ry), (end[0], end[1] + ry), dxfattribs={"layer": "WALL"})
for x in (0, 2500, 6000):
msp.add_line((x, ry - 2600), (x, ry + 12600), dxfattribs={"layer": "DOTE"})
for y in (0, 3300, 10000):
msp.add_line((-2600, y + ry), (8600, y + ry), dxfattribs={"layer": "DOTE"})
msp.add_text("非机动坡道一层平面图", height=800,
dxfattribs={"layer": "PUB_TEXT"}).set_placement((2000, ry - 6000))
draw_main(0.0, "一层平面图")
draw_main(-pitch, "二层平面图")
doc.saveas(path)
def make_nogrid_dxf(path: Path) -> None:
"""27号 2#/13号 pattern: frames carry NO axis geometry at all, and floor wall
bboxes differ (F2 covers half the building) — clip-corner fallback is
off by 20 m in x; only wall-profile correlation recovers the offset."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str, full_walls: bool) -> None:
wall_x0 = 0 if full_walls else 20000
outline = [((wall_x0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (wall_x0, 20000)), ((wall_x0, 20000), (wall_x0, 0))]
# varied interior bays shared by both floors (the correlation fingerprint)
interior = [((26000, 0), (26000, 20000)), ((31000, 0), (31000, 20000)),
((37000, 0), (37000, 20000)), ((20000, 0), (20000, 20000)),
((23000, 0), (23000, 20000)),
((20000, 6000), (40000, 6000)), ((20000, 9400), (40000, 9400)),
((20000, 15000), (40000, 15000))]
if full_walls:
interior += [((6000, 0), (6000, 20000)), ((11000, 0), (11000, 20000)),
((0, 6000), (20000, 6000)), ((0, 15000), (20000, 15000))]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
draw_frame(0.0, "一层平面图", True)
draw_frame(-pitch, "二层平面图", False)
doc.saveas(path)
def make_blocktitle_dxf(path: Path) -> None:
"""13号 cached-XREF pattern: each sheet lives in ONE block (msp = INSERT
stubs), so plan TITLES are inside blocks too — title scan must expand."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def make_sheet(idx: int, title: str) -> str:
blk = doc.blocks.new(name=f"X-00-00{idx}")
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)), ((12000, 5000), (28000, 5000))]
for (sx, sy), (ex, ey) in outline + interior:
blk.add_line((sx, sy), (ex, ey), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000):
blk.add_line((x, -3000), (x, 26000), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
blk.add_line((-3000, y), (46000, y), dxfattribs={"layer": "DOTE"})
blk.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -6000))
return blk.name
msp.add_blockref(make_sheet(1, "一层平面图"), (0, 0))
msp.add_blockref(make_sheet(2, "二层平面图"), (0, -pitch))
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
then shrinks to that x-pitch and the refine window drops the building's
second wing (unit-block plans: one wing's midpoint falls outside)."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str) -> None:
# two wings: x 0..30000 and 50000..80000 (gap between); title under the LEFT wing
for x0 in (0.0, 50000.0):
outline = [((x0, 0), (x0 + 30000, 0)), ((x0 + 30000, 0), (x0 + 30000, 14000)),
((x0 + 30000, 14000), (x0, 14000)), ((x0, 14000), (x0, 0))]
interior = [((x0 + d, 0), (x0 + d, 14000)) for d in (6000, 13000, 21000)]
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, 30000, 50000, 61000, 72000, 80000):
msp.add_line((x, -3000 + oy), (x, 17000 + oy), dxfattribs={"layer": "DOTE"})
for y in (0, 5200, 9000, 14000):
msp.add_line((-3000, y + oy), (83000, y + oy), dxfattribs={"layer": "DOTE"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((12000, oy - 6000))
draw_frame(0.0, "一层平面图")
draw_frame(-pitch, "二层平面图")
# stray detail frames titled 平面图 in ONE row of their own, 15 m apart:
# their x-gap is the only same-row gap and must NOT define the clip width
# for the main column (real 1#B: 非机动坡道 frames row made pitch_x≈15.8k)
sy = -250000.0
for i, title in enumerate(("电梯机房平面图", "水箱间平面图")):
ox = 300000.0 + i * 15000.0
for start, end in [((ox, sy), (ox + 8000, sy)), ((ox + 8000, sy), (ox + 8000, sy + 6000)),
((ox + 8000, sy + 6000), (ox, sy + 6000)), ((ox, sy + 6000), (ox, sy)),
((ox + 4000, sy), (ox + 4000, sy + 6000)), ((ox, sy + 3000), (ox + 8000, sy + 3000)),
((ox + 2000, sy), (ox + 2000, sy + 6000)), ((ox + 6000, sy + 3000), (ox + 6000, sy + 6000)),
((ox + 1000, sy + 1500), (ox + 7000, sy + 1500)), ((ox + 1000, sy + 4500), (ox + 7000, sy + 4500))]:
msp.add_line(start, end, dxfattribs={"layer": "WALL"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((ox + 1000, sy - 6000))
doc.saveas(path)
def run(cmd: list[str]) -> subprocess.CompletedProcess: def run(cmd: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True) return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
@@ -242,6 +388,19 @@ def main() -> int:
make_plan_dxf(dxf_dir / "plan.dxf") make_plan_dxf(dxf_dir / "plan.dxf")
make_xref_shell_dxf(dxf_dir / "roof.dxf") make_xref_shell_dxf(dxf_dir / "roof.dxf")
# cached-xref sheet (13号 pattern): msp holds only INSERT stubs, the real
# content is CACHED as a block definition inside the same file
cx_doc = ezdxf.new("R2010")
cx_doc.layers.add("WALL")
cx_blk = cx_doc.blocks.new(name="X-00-0011")
for i in range(300):
cx_blk.add_line((i * 100, 0), (i * 100, 5000), dxfattribs={"layer": "WALL"})
cx_msp = cx_doc.modelspace()
cx_msp.add_text("总平面图", dxfattribs={"layer": "PUB_TEXT"})
for i in range(3):
cx_msp.add_blockref("X-00-0011", (i * 50000, 0))
cx_doc.saveas(dxf_dir / "cachedxref.dxf")
# --- cad_dxf_report: XREF shell must be flagged, plan must not --- # --- cad_dxf_report: XREF shell must be flagged, plan must not ---
proc = run([ proc = run([
sys.executable, "scripts/cad_dxf_report.py", sys.executable, "scripts/cad_dxf_report.py",
@@ -254,6 +413,9 @@ def main() -> int:
roof_warnings = " ".join(by_file.get("roof.dxf", {}).get("warnings", [])) roof_warnings = " ".join(by_file.get("roof.dxf", {}).get("warnings", []))
check("roof.dxf flagged as XREF shell", "likely_xref_shell" in roof_warnings, roof_warnings) check("roof.dxf flagged as XREF shell", "likely_xref_shell" in roof_warnings, roof_warnings)
check("plan.dxf has no warnings", not by_file.get("plan.dxf", {}).get("warnings"), str(by_file.get("plan.dxf", {}).get("warnings"))) check("plan.dxf has no warnings", not by_file.get("plan.dxf", {}).get("warnings"), str(by_file.get("plan.dxf", {}).get("warnings")))
cx_warnings = " ".join(by_file.get("cachedxref.dxf", {}).get("warnings", []))
check("cached-xref stub sheet points at expand_blocks", "cached_xref_content" in cx_warnings and "expand_blocks" in cx_warnings, cx_warnings)
check("cached-xref not misreported as re-export ask", "likely_xref_shell" not in cx_warnings and "near_empty" not in cx_warnings, cx_warnings)
md = (WORK / "read_report" / "cad_read_report.md").read_text(encoding="utf-8") md = (WORK / "read_report" / "cad_read_report.md").read_text(encoding="utf-8")
check("markdown has warnings section", "Warnings (resolve before modeling)" in md) check("markdown has warnings section", "Warnings (resolve before modeling)" in md)
@@ -645,6 +807,157 @@ def main() -> int:
ok_bg = "F2" in bg_off and abs(bg_off["F2"][0]) <= 120 and abs(bg_off["F2"][1] - 98100.0) <= 120 ok_bg = "F2" in bg_off and abs(bg_off["F2"][0]) <= 120 and abs(bg_off["F2"][1] - 98100.0) <= 120
check("block-grid correlation beats clip-corner fallback", ok_bg, str(bg_off)) check("block-grid correlation beats clip-corner fallback", ok_bg, str(bg_off))
# --- auxiliary-titled frame must not become the reference (27号 2#) ---
aux_dir = WORK / "dxf_auxref"
aux_dir.mkdir(parents=True, exist_ok=True)
make_auxref_dxf(aux_dir / "auxref.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(aux_dir / "auxref.dxf"), "--out-config", str(WORK / "frames_aux.json"),
"--out-report", str(WORK / "frames_aux.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles aux-titled frames", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
aux_md = (WORK / "frames_aux.md").read_text(encoding="utf-8")
ref_line = next((l for l in aux_md.splitlines() if l.startswith("- reference frame:")), "")
check("aux title is not the reference", "非机动坡道" not in ref_line, ref_line)
check("plain 一层平面图 is the reference", "(一层平面图)" in ref_line, ref_line)
frames_aux = json.loads((WORK / "frames_aux.json").read_text(encoding="utf-8"))
aux_off = {f["name"]: f["offset"] for f in frames_aux["drawings"][0]["floors"]}
f2 = aux_off.get("二层平面图")
ok_aux = f2 is not None and abs(f2[0]) <= 120 and abs(f2[1] - 98100.0) <= 120
check("main F2 aligns to main F1 (not ramp)", ok_aux, str(aux_off))
check("aux frame flagged in report", "auxiliary" in aux_md, aux_md[-400:])
# --- gridless frames: wall-profile correlation beats clip-corner (27号 2#/13号) ---
ng_dir = WORK / "dxf_nogrid"
ng_dir.mkdir(parents=True, exist_ok=True)
make_nogrid_dxf(ng_dir / "nogrid.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(ng_dir / "nogrid.dxf"), "--out-config", str(WORK / "frames_ng.json"),
"--out-report", str(WORK / "frames_ng.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles gridless frames", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
frames_ng = json.loads((WORK / "frames_ng.json").read_text(encoding="utf-8"))
ng_off = {f["name"]: f["offset"] for f in frames_ng["drawings"][0]["floors"]}
ng_md = (WORK / "frames_ng.md").read_text(encoding="utf-8")
f2 = ng_off.get("二层平面图")
ok_ng = f2 is not None and abs(f2[0]) <= 120 and abs(f2[1] - 98100.0) <= 120
check("wall-profile correlation recovers offset", ok_ng, str(ng_off))
check("wall correlation reported (not silent WEAK)", "wall-correlated" in ng_md, ng_md[-500:])
# --- plan titles inside cached-xref blocks (13号: msp = INSERT stubs only) ---
bt_dir = WORK / "dxf_blocktitle"
bt_dir.mkdir(parents=True, exist_ok=True)
make_blocktitle_dxf(bt_dir / "blocktitle.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(bt_dir / "blocktitle.dxf"), "--out-config", str(WORK / "frames_bt.json"),
"--out-report", str(WORK / "frames_bt.md"), "--vendor-dir", str(VENDOR),
])
bt_ok = proc.returncode == 0
check("detect finds titles inside blocks", bt_ok, (proc.stdout + proc.stderr)[-400:])
if bt_ok:
frames_bt = json.loads((WORK / "frames_bt.json").read_text(encoding="utf-8"))
bt = {f["name"]: f for f in frames_bt["drawings"][0]["floors"]}
check("both block-wrapped frames detected", set(bt) == {"一层平面图", "二层平面图"}, str(set(bt)))
f2 = bt.get("二层平面图")
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"]))
# --- 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)
make_mixedrow_dxf(mx_dir / "mixedrow.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(mx_dir / "mixedrow.dxf"), "--out-config", str(WORK / "frames_mx.json"),
"--out-report", str(WORK / "frames_mx.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles mixed row/column titles", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
frames_mx = json.loads((WORK / "frames_mx.json").read_text(encoding="utf-8"))
mx = {f["name"]: f for f in frames_mx["drawings"][0]["floors"]}
f1 = mx.get("一层平面图")
ok_span = f1 is not None and f1["clip"][0] <= 0 and f1["clip"][2] >= 80000
check("clip spans both wings despite stray x-pitch", ok_span, str(f1 and f1["clip"]))
f2 = mx.get("二层平面图")
ok_mx = f2 is not None and abs(f2["offset"][0]) <= 120 and abs(f2["offset"][1] - 98100.0) <= 120
check("mixed layout offset recovered", ok_mx, str(f2 and f2["offset"]))
# --- floor_order gaps must warn loudly, not silently drop floors (13号 b2: F11-F16 消失) ---
fo_config = {
"scale": 0.001,
"floor_order": ["1F", "GHOST"],
"drawings": [{"file": "plan.dxf", "floors": [
{"key": "1F", "name": "首层", "z": 0.0, "height": 4.2},
{"key": "2F", "name": "二层", "z": 4.2, "height": 4.2},
]}],
}
fo_path = WORK / "fo_config.json"
fo_path.write_text(json.dumps(fo_config, ensure_ascii=False), encoding="utf-8")
proc = run([
sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(dxf_dir), "--config", str(fo_path),
"--out", str(WORK / "fo_spec.json"), "--vendor-dir", str(VENDOR),
])
check("derive with floor_order gaps runs", proc.returncode == 0, proc.stderr[-400:])
check("missing-from-order floor warns", "floor_order" in proc.stderr and "2F" in proc.stderr, proc.stderr[-300:])
check("ghost order key warns", "GHOST" in proc.stderr, proc.stderr[-300:])
# --- assemble_campus: per-building rotation_deg (27号: 4#楼独自斜置) ---
asm_dir = WORK / "assemble"
asm_dir.mkdir(parents=True, exist_ok=True)
def mini_spec(tag: str) -> str:
walls = []
for (sx, sy), (ex, ey) in [((0, 0), (10, 0)), ((10, 0), (10, 20)),
((10, 20), (0, 20)), ((0, 20), (0, 0))]:
walls.append({"start": [sx, sy], "end": [ex, ey], "width": 0.2, "layer": "WALL"})
spec = {
"project": tag, "units": {"scale": 0.001},
"categories": {"walls": {"label": "墙", "color": "#ccc"}},
"source": {"config": {"use_footprint_slabs": True, "roof_specs": []}},
"floors": {"F1": {"name": "F1", "z": 0.0, "height": 3.0,
"bounds": [0, 0, 10, 20],
"segments": {"walls": walls},
"footprint": {"polygons": [[[0, 0], [10, 0], [10, 20], [0, 20]]]},
"caps": []}},
}
p = asm_dir / f"spec_{tag}.json"
p.write_text(json.dumps(spec), encoding="utf-8")
return str(p)
manifest = {
"campus_origin_surveying_m": [0.0, 0.0],
"rotation_deg": 0.0,
"buildings": {
"A": {"spec": mini_spec("a"), "prefix": "A", "model_anchor_m": [0.0, 0.0],
"survey_anchor_m": [0.0, 0.0]},
"B": {"spec": mini_spec("b"), "prefix": "B", "model_anchor_m": [0.0, 0.0],
"survey_anchor_m": [50.0, 0.0], "rotation_deg": 90.0},
},
}
mpath = asm_dir / "manifest.json"
mpath.write_text(json.dumps(manifest), encoding="utf-8")
proc = run([
sys.executable, "scripts/assemble_campus.py",
"--manifest", str(mpath), "--out", str(asm_dir / "campus.json"),
"--project-name", "rot-test", "--allow-overlap",
])
check("assemble_campus per-building rotation runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
campus = json.loads((asm_dir / "campus.json").read_text(encoding="utf-8"))
bb = campus["floors"]["BF1"]["bounds"]
ok_rot = (abs(bb[0] - 30.0) < 0.01 and abs(bb[1] - 0.0) < 0.01
and abs(bb[2] - 50.0) < 0.01 and abs(bb[3] - 10.0) < 0.01)
check("per-building rotation applied (90deg)", ok_rot, str(bb))
ab = campus["floors"]["AF1"]["bounds"]
ok_a = abs(ab[0]) < 0.01 and abs(ab[2] - 10.0) < 0.01 and abs(ab[3] - 20.0) < 0.01
check("unrotated sibling unaffected", ok_a, str(ab))
# --- isolated legend clusters (黄桥图签窗图例 -> footprint 细三角飘板) --- # --- isolated legend clusters (黄桥图签窗图例 -> footprint 细三角飘板) ---
iso_dir = WORK / "dxf_isolated" iso_dir = WORK / "dxf_isolated"
iso_dir.mkdir(parents=True, exist_ok=True) iso_dir.mkdir(parents=True, exist_ok=True)