#!/usr/bin/env python3 """RC2 repair layer for v5.2 semantic-view matching. The RC1 matcher has two useful, already-audited properties: it matches view roles before measuring primitives, and it fits one shared drawing scale. This module preserves those kernels and the :func:`build_pair_context` contract, while repairing two integration defects without changing the RC1 file: * predicted-view clustering no longer derives its merge tolerance from the full drawing diagonal, which can be dominated by one remote entity; * the returned context contains JSON-safe lists/scalars (including alignment diagnostics), so evaluator results can be written directly as JSON. No handle or entity-order identity is introduced. A remote entity remains an extra predicted cluster and is therefore visible to downstream anti-hack and precision diagnostics. """ from __future__ import annotations import math from collections import defaultdict from pathlib import Path from typing import Any, Mapping, Sequence import numpy as np try: from . import eval_geometric05 as EV5 from . import view_entity_matching_v52 as RC1 except ImportError: # direct evaluator import import eval_geometric05 as EV5 import view_entity_matching_v52 as RC1 SCHEMA_VERSION = "view-entity-matching-v5.2-rc2" MAX_PREDICTED_VIEW_CANDIDATES = RC1.MAX_PREDICTED_VIEW_CANDIDATES ROLE_CENTER_ACCEPT_FRAC = RC1.ROLE_CENTER_ACCEPT_FRAC # Connected/touching CAD edges do not need a sheet-sized tolerance. The # robust reference is capped relative to the median primitive size, so fewer # than half remote/huge primitives cannot inflate the merge radius. ROBUST_SIZE_CAP_MULTIPLIER = 8.0 CANONICAL_REL_TOL = 0.0 def _json_safe(value: Any) -> Any: """Return a recursively JSON-serialisable, numerically equivalent value.""" if isinstance(value, np.ndarray): return [_json_safe(item) for item in value.tolist()] if isinstance(value, np.generic): return value.item() if isinstance(value, Path): return str(value) if isinstance(value, Mapping): result: dict[Any, Any] = {} for key, item in value.items(): if isinstance(key, tuple): safe_key: Any = ":".join(str(part) for part in key) elif isinstance(key, (str, int, float, bool)) or key is None: safe_key = key else: safe_key = str(key) result[safe_key] = _json_safe(item) return result if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): return [_json_safe(item) for item in value] if isinstance(value, float) and not math.isfinite(value): return None return value def _robust_merge_tolerance(records: Sequence[Mapping[str, Any]]) -> float: sizes = [] for record in records: low = np.asarray(record["low"], dtype=float) high = np.asarray(record["high"], dtype=float) size = float(np.linalg.norm(high - low)) if math.isfinite(size) and size > 1e-12: sizes.append(size) if not sizes: reference = 1.0 elif len(sizes) == 1: reference = sizes[0] else: values = np.asarray(sizes, dtype=float) median = float(np.median(values)) upper_quartile = float(np.quantile(values, 0.75)) reference = min(upper_quartile, ROBUST_SIZE_CAP_MULTIPLIER * median) return max(1e-7, EV5.VIEW_MERGE_TOL_FRAC * max(reference, 1.0)) def _cluster_views_robust(entities: Mapping[str, Any]) -> list[dict[str, Any]]: """Cluster primitives using a local robust scale, not the sheet diagonal.""" records = EV5._primitive_records(entities) if not records: return [] tolerance = _robust_merge_tolerance(records) parent = list(range(len(records))) def find(index: int) -> int: while parent[index] != index: parent[index] = parent[parent[index]] index = parent[index] return index def union(first: int, second: int) -> bool: first_root, second_root = find(first), find(second) if first_root == second_root: return False parent[second_root] = first_root return True for first in range(len(records)): for second in range(first + 1, len(records)): if EV5._box_distance(records[first], records[second]) <= tolerance: union(first, second) # Preserve RC1/EV5 containment behaviour: disconnected holes, hidden edges # and centre marks inside an outline belong to that outline's view. changed = True while changed: groups: dict[int, list[int]] = defaultdict(list) for index in range(len(records)): groups[find(index)].append(index) boxes: dict[int, dict[str, np.ndarray]] = {} for root, indices in groups.items(): boxes[root] = { "low": np.min( np.stack([np.asarray(records[index]["low"], dtype=float) for index in indices]), axis=0, ), "high": np.max( np.stack([np.asarray(records[index]["high"], dtype=float) for index in indices]), axis=0, ), } roots = list(groups) changed = False for position, first in enumerate(roots): for second in roots[position + 1 :]: if EV5._box_distance(boxes[first], boxes[second]) <= tolerance: changed |= union(first, second) groups = defaultdict(list) for index in range(len(records)): groups[find(index)].append(index) views: list[dict[str, Any]] = [] for indices in groups.values(): view_entities = RC1._empty_entities() lows: list[np.ndarray] = [] highs: list[np.ndarray] = [] for index in indices: record = records[index] view_entities[record["family"]].append(record["primitive"]) lows.append(np.asarray(record["low"], dtype=float)) highs.append(np.asarray(record["high"], dtype=float)) low = np.min(np.stack(lows), axis=0) high = np.max(np.stack(highs), axis=0) views.append( { "entities": view_entities, "low": low, "high": high, "center": 0.5 * (low + high), "size": high - low, "n_primitives": len(indices), "merge_tolerance": tolerance, } ) return sorted( views, key=lambda view: (float(view["center"][0]), float(view["center"][1])), ) def _canonicalize(entities: Mapping[str, Any]) -> dict[str, Any]: # RC1's canonicalizer normally scales its tolerance by the full drawing # diagonal. rel_tol=0 prevents a remote coordinate from bridging local # gaps while retaining the audited absolute split-line tolerance. return EV5.EV4.canonicalize_entities( dict(entities), abs_tol=EV5.EV4.CANONICAL_ABS_TOL, rel_tol=CANONICAL_REL_TOL, ) def build_pair_context( pred: str | Path, gt: str | Path, *, sidecar: Mapping[str, Any] | None, ) -> dict[str, Any]: """Build an RC1-compatible context with robust clusters and JSON values.""" pred_path, gt_path = Path(pred), Path(gt) pred_meta, gt_meta = EV5._read_structure(pred_path), EV5._read_structure(gt_path) raw_pred = EV5._extract_entities(pred_path) if pred_meta.get("readable") else None raw_gt = EV5._extract_entities(gt_path) if gt_meta.get("readable") else None target_valid = bool( raw_gt and EV5._n_geometry(raw_gt) and EV5._safe_bbox(raw_gt) is not None ) prediction_valid = bool( raw_pred and EV5._n_geometry(raw_pred) and EV5._safe_bbox(raw_pred) is not None ) context: dict[str, Any] = { "schema_version": SCHEMA_VERSION, "target_valid": target_valid, "prediction_valid": prediction_valid, "pred_meta": pred_meta, "gt_meta": gt_meta, "raw_pred": raw_pred, "raw_gt": raw_gt, } if not target_valid: context.update( {"eligible": False, "reason": "target_dxf_unreadable_or_degenerate"} ) return _json_safe(context) canonical_gt = _canonicalize(raw_gt) gt_by_role, error = RC1._target_views_by_role(canonical_gt, sidecar) if error: context.update( { "eligible": False, "reason": error, "canonical_gt": canonical_gt, } ) return _json_safe(context) context["canonical_gt"] = canonical_gt context["gt_by_role"] = gt_by_role if not prediction_valid: alignment = RC1._fit_semantic_alignment( [], list(gt_by_role), list(gt_by_role.values()) ) context.update( { "eligible": True, "reason": "prediction_dxf_unreadable_or_degenerate", "canonical_pred": RC1._empty_entities(), "pred_views": [], "pred_views_all": [], "alignment": alignment, } ) return _json_safe(context) canonical_pred = _canonicalize(raw_pred) pred_views_all = _cluster_views_robust(canonical_pred) ranked = sorted( enumerate(pred_views_all), key=lambda item: ( int(item[1].get("n_primitives", 0)), float( np.linalg.norm( np.asarray(item[1].get("size", (0.0, 0.0)), dtype=float) ) ), ), reverse=True, ) selected_pairs = ranked[:MAX_PREDICTED_VIEW_CANDIDATES] pred_views = [view for _, view in selected_pairs] selected_original_indices = [index for index, _ in selected_pairs] roles = list(gt_by_role) alignment = RC1._fit_semantic_alignment( pred_views, roles, [gt_by_role[role] for role in roles] ) alignment["selected_original_indices"] = selected_original_indices alignment["omitted_original_indices"] = [ index for index in range(len(pred_views_all)) if index not in selected_original_indices ] alignment["cluster_policy"] = { "name": "primitive_median_scale_v1", "canonical_relative_tolerance": CANONICAL_REL_TOL, "size_cap_multiplier": ROBUST_SIZE_CAP_MULTIPLIER, } context.update( { "eligible": True, "reason": alignment["reason"], "canonical_pred": canonical_pred, "pred_views": pred_views, "pred_views_all": pred_views_all, "alignment": alignment, } ) return _json_safe(context) # The primitive kernels and role-local transform consume generic numeric # sequences, so they remain compatible with RC2's JSON-safe list values. match_view_primitives = RC1.match_view_primitives role_local_transform = RC1.role_local_transform __all__ = [ "CANONICAL_REL_TOL", "MAX_PREDICTED_VIEW_CANDIDATES", "ROBUST_SIZE_CAP_MULTIPLIER", "ROLE_CENTER_ACCEPT_FRAC", "SCHEMA_VERSION", "build_pair_context", "match_view_primitives", "role_local_transform", ]