#!/usr/bin/env python3 """Release candidate: fragment-safe views and hidden-only Curve bounds. This add-only final supersedes ``eval_geometric052_rc5j``. The host cannot update an existing file, so the conservative visible-first Curve contract is published under an explicit final entry point. Two scoped repairs are stacked on RC5I: * uniquely contained disconnected prediction fragments may be reassociated with one transformed semantic reference box; outside or ambiguous fragments remain explicit extras; * Curve-CD/F1 retains its legacy visible-only bounds bit-for-bit whenever those bounds exist. Only a hidden-only target/prediction falls back to analytic bounds of the non-degenerate LINE/CIRCLE/ARC primitives that Curve actually samples. There is no path/hash identity shortcut and no change to global alignment, sampling density, Curve thresholds, or downstream reward formulae. """ from __future__ import annotations import math import threading from pathlib import Path from typing import Any, Mapping, Sequence import numpy as np try: from . import eval_geometric052_rc5i as RC5I from . import view_entity_matching_v52_rc5j_fragment_candidate as MATCH except ImportError: # direct evaluator import import eval_geometric052_rc5i as RC5I import view_entity_matching_v52_rc5j_fragment_candidate as MATCH METRIC_VERSION = "v5.2-rc5j-final" SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5j-final" ENGINEERING_THRESHOLDS = dict(RC5I.ENGINEERING_THRESHOLDS) PHYSICAL_SUPPORTED_SEMANTICS = RC5I.PHYSICAL_SUPPORTED_SEMANTICS MAX_MATCHED_OFFSET_DISPERSION_FRACTION = ( RC5I.MAX_MATCHED_OFFSET_DISPERSION_FRACTION ) RC3 = RC5I.RC3 BASE = RC5I.BASE CURVE = BASE.CURVE _PATCH_LOCK = threading.RLock() def _hidden_fallback_entity_bounds( entities: Mapping[str, Any], ) -> tuple[np.ndarray, np.ndarray] | None: """Return legacy visible bounds, else sampled all-channel analytic bounds.""" visible_bounds = BASE.EV5._safe_bbox(entities) if visible_bounds is not None: return visible_bounds records = BASE.EV5._primitive_records(entities) sampled: list[Mapping[str, Any]] = [] for record in records: family = str(record.get("family") or "") primitive = record.get("primitive") if not isinstance(primitive, Sequence) or isinstance(primitive, (str, bytes)): continue try: if family == "lines": length = math.hypot( float(primitive[2]) - float(primitive[0]), float(primitive[3]) - float(primitive[1]), ) elif family == "circles": length = 2.0 * math.pi * abs(float(primitive[2])) elif family == "arcs": radius = abs(float(primitive[2])) sweep_degrees = ( float(primitive[4]) - float(primitive[3]) ) % 360.0 if sweep_degrees <= 1.0e-12: sweep_degrees = 360.0 length = radius * math.radians(sweep_degrees) else: continue except (IndexError, TypeError, ValueError): continue if math.isfinite(length) and length > 1.0e-12: sampled.append(record) if not sampled: return None lows = np.stack( [np.asarray(record["low"], dtype=float) for record in sampled] ) highs = np.stack( [np.asarray(record["high"], dtype=float) for record in sampled] ) if not np.isfinite(lows).all() or not np.isfinite(highs).all(): return None return np.min(lows, axis=0), np.max(highs, axis=0) def score_dxf_pair( pred: str | Path, gt: str | Path, sidecar: Mapping[str, Any] | None = None, category: str | None = None, **kwargs: Any, ) -> dict[str, Any]: with _PATCH_LOCK: original_match = RC3.MATCH original_curve_bounds = CURVE._entity_bounds RC3.MATCH = MATCH CURVE._entity_bounds = _hidden_fallback_entity_bounds try: result = RC5I.score_dxf_pair( pred, gt, sidecar=sidecar, category=category, **kwargs, ) finally: CURVE._entity_bounds = original_curve_bounds RC3.MATCH = original_match result["schema_version"] = SCHEMA_VERSION result["metric_version"] = METRIC_VERSION result.setdefault("metric_definition", {}).update( { "fragment_reassociation_policy": { "partition": ( "unique_complete_bbox_containment_after_coarse_shared_transform" ), "outside_or_ambiguous_fragments": "retained_as_explicit_extras", "activation": "strict_shape_layout_objective_improvement", "path_or_hash_identity_used": False, }, "curve_bounds_policy": { "families": ["LINE", "CIRCLE", "ARC"], "visibility": "legacy_visible_first_hidden_only_fallback", "bounds": ( "legacy_visible_bounds_else_analytic_extrema_of_all_" "nonzero_arc_length_primitives" ), "global_alignment_changed": False, "curve_sampling_or_thresholds_changed": False, }, } ) result.setdefault("diagnostics", {})["rc5j_repairs"] = { "fragment_context_builder": MATCH.SCHEMA_VERSION, "curve_bounds_hidden_fallback_only": True, "path_or_hash_identity_used": False, } release = result.get("diagnostics", {}).get("release_status") if isinstance(release, dict): release["candidate"] = METRIC_VERSION return result __all__ = [ "ENGINEERING_THRESHOLDS", "MAX_MATCHED_OFFSET_DISPERSION_FRACTION", "METRIC_VERSION", "PHYSICAL_SUPPORTED_SEMANTICS", "SCHEMA_VERSION", "_hidden_fallback_entity_bounds", "score_dxf_pair", ]