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:
@@ -188,6 +188,88 @@ def segments_in(entities, clip, layers):
|
||||
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:
|
||||
args = parse_args()
|
||||
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
|
||||
@@ -256,9 +338,36 @@ def main() -> int:
|
||||
continue
|
||||
for a, b in zip(pts, pts[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":
|
||||
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:
|
||||
kind = entity.dxftype()
|
||||
if kind == "INSERT":
|
||||
@@ -266,27 +375,7 @@ def main() -> int:
|
||||
collect_insert_lines(entity)
|
||||
continue
|
||||
if kind in {"TEXT", "MTEXT"}:
|
||||
content = entity_text(entity)
|
||||
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})
|
||||
classify_text(entity, kind)
|
||||
elif kind == "LINE":
|
||||
d = entity.dxf
|
||||
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)
|
||||
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
|
||||
# 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
|
||||
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
|
||||
@@ -372,16 +468,27 @@ def main() -> int:
|
||||
vert.append((sx + ex) / 2)
|
||||
elif dy < 2.0 and (dx > min_grid_len or tick_min < dx < tick_max):
|
||||
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({
|
||||
"key": floor_key_for(t["name"], used_keys),
|
||||
"name": t["name"],
|
||||
"clip": [round(c, 1) for c in clip],
|
||||
"_vx": cluster_positions(vert, args.grid_bin),
|
||||
"_hy": cluster_positions(horiz, args.grid_bin),
|
||||
"_walls": segments_in(lines, clip, wall_layers),
|
||||
"_aux": bool(qualifier),
|
||||
})
|
||||
|
||||
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]
|
||||
|
||||
alignment = []
|
||||
@@ -392,18 +499,35 @@ def main() -> int:
|
||||
continue
|
||||
dx, vx = vote_translation(reference["_vx"], f["_vx"], 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:
|
||||
f["offset"] = [round(dx, 1), round(dy, 1)]
|
||||
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}")
|
||||
else:
|
||||
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
|
||||
round(reference["clip"][1] - f["clip"][1], 1)]
|
||||
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}{aux_tag}")
|
||||
continue
|
||||
# Grid voting failed (no axis geometry in this frame). Try wall-profile
|
||||
# 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(
|
||||
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:
|
||||
f.pop("_vx"), f.pop("_hy")
|
||||
f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux")
|
||||
|
||||
config = {
|
||||
"project_name": path.stem,
|
||||
|
||||
Reference in New Issue
Block a user