File size: 11,043 Bytes
15d1f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
"""v5.2-rc5 evaluator with hybrid, causally isolated view-layout offsets.

RC5 retains every RC3 component except layout. A semantic role offset is the
coordinate median of raw offsets from its already one-to-one matched
primitives (LINE midpoint, CIRCLE/ARC centre). One match is sufficient. Only
with zero matched pairs is RC3's parameter-stable view anchor used as an
explicit fallback. Layout fails closed to zero when evidence is unavailable.
"""

from __future__ import annotations

import copy
import math
from itertools import combinations
from pathlib import Path
from typing import Any, Mapping, Sequence

import numpy as np

try:
    from . import eval_geometric052_rc3 as RC3
except ImportError:  # direct evaluator import
    import eval_geometric052_rc3 as RC3


METRIC_VERSION = "v5.2-rc5"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5"
ENGINEERING_THRESHOLDS = dict(RC3.ENGINEERING_THRESHOLDS)
PHYSICAL_SUPPORTED_SEMANTICS = RC3.PHYSICAL_SUPPORTED_SEMANTICS
OFFSET_DEFINITION = "GT_anchor-global_scale*Pred_anchor"


def _visibility(layer: Any) -> str:
    token = str(layer).casefold()
    return "hidden" if "hidden" in token or "dash" in token else "visible"


def _family_entities(entities: Mapping[str, Any], family: str) -> list[Any]:
    if family in {"visible_line", "hidden_line"}:
        expected = "visible" if family == "visible_line" else "hidden"
        return [
            item
            for item in entities.get("lines", [])
            if isinstance(item, Sequence)
            and not isinstance(item, (str, bytes))
            and item
            and _visibility(item[-1]) == expected
        ]
    return list(entities.get("circles" if family == "circle" else "arcs", []))


def _anchor(item: Sequence[Any], family: str) -> np.ndarray | None:
    try:
        if family in {"visible_line", "hidden_line"}:
            if len(item) < 4:
                return None
            return np.asarray(
                (
                    0.5 * (float(item[0]) + float(item[2])),
                    0.5 * (float(item[1]) + float(item[3])),
                ),
                dtype=float,
            )
        if len(item) < 2:
            return None
        return np.asarray((float(item[0]), float(item[1])), dtype=float)
    except (TypeError, ValueError):
        return None


def _role_offset(
    context: Mapping[str, Any],
    rows: Mapping[str, Any],
    role: str,
    *,
    scale: float,
    sheet_diagonal: float,
) -> tuple[np.ndarray | None, dict[str, Any]]:
    pred_index = rows[role].get("predicted_view_index")
    if not isinstance(pred_index, int) or not 0 <= pred_index < len(context["pred_views"]):
        return None, {
            "offset": None,
            "support_count": 0,
            "fallback_used": False,
            "offset_source": "unavailable",
            "offset_dispersion_fraction": None,
        }
    pred_view = context["pred_views"][pred_index]
    gt_view = context["gt_by_role"][role]
    pred_entities = pred_view.get("entities", {})
    gt_entities = gt_view.get("entities", {})
    offsets: list[np.ndarray] = []
    matched_by_family: dict[str, int] = {}
    predicted_count = 0
    target_count = 0
    for family in ("visible_line", "hidden_line", "circle", "arc"):
        predicted = _family_entities(pred_entities, family)
        target = _family_entities(gt_entities, family)
        predicted_count += len(predicted)
        target_count += len(target)
        accepted = 0
        for pair in rows[role]["primitive"][family].get("pairs", []):
            try:
                pred_item = predicted[int(pair["predicted_index"])]
                gt_item = target[int(pair["target_index"])]
            except (KeyError, TypeError, ValueError, IndexError):
                continue
            pred_anchor = _anchor(pred_item, family)
            gt_anchor = _anchor(gt_item, family)
            if pred_anchor is None or gt_anchor is None:
                continue
            offsets.append(gt_anchor - scale * pred_anchor)
            accepted += 1
        matched_by_family[family] = accepted

    support = len(offsets)
    fallback_used = False
    source = "matched_primitive_pair_median"
    if support:
        offset = np.median(np.asarray(offsets, dtype=float), axis=0)
        dispersion = float(
            np.median([np.linalg.norm(item - offset) for item in offsets])
            / sheet_diagonal
        )
    else:
        pred_anchor = pred_view.get("layout_anchor")
        gt_anchor = gt_view.get("layout_anchor")
        if pred_anchor is None or gt_anchor is None:
            offset = None
        else:
            offset = np.asarray(gt_anchor, dtype=float) - scale * np.asarray(
                pred_anchor, dtype=float
            )
            fallback_used = True
        dispersion = None
        source = "fallback_parameter_stable_view_anchor"

    precision = support / predicted_count if predicted_count else 0.0
    recall = support / target_count if target_count else 0.0
    return offset, {
        "offset": [RC3.BASE._round(float(value)) for value in offset]
        if offset is not None
        else None,
        "support_count": support,
        "matched_by_family": matched_by_family,
        "fallback_used": fallback_used,
        "offset_source": source if offset is not None else "unavailable",
        "predicted_anchor_count": predicted_count,
        "target_anchor_count": target_count,
        "anchor_precision": RC3.BASE._round(precision),
        "anchor_recall": RC3.BASE._round(recall),
        "offset_dispersion_fraction": RC3.BASE._round(dispersion),
    }


def _layout_component(
    context: Mapping[str, Any], rows: Mapping[str, Any]
) -> dict[str, Any]:
    roles = [str(role) for role, row in rows.items() if row["present"]]
    alignment = context["alignment"]
    scale = float(alignment.get("global_scale", 1.0))
    sheet_diagonal = max(float(alignment.get("sheet_diagonal", 1.0)), 1.0)
    if len(roles) < 2:
        return RC3.BASE._component(
            0.0,
            True,
            "insufficient_layout_evidence",
            matched_roles=roles,
            global_scale=RC3.BASE._round(scale),
            core_component_fail_closed=True,
        )

    offsets: dict[str, np.ndarray] = {}
    diagnostics: dict[str, Any] = {}
    for role in roles:
        offset, detail = _role_offset(
            context, rows, role, scale=scale, sheet_diagonal=sheet_diagonal
        )
        diagnostics[role] = detail
        if offset is not None:
            offsets[role] = offset
    missing = [role for role in roles if role not in offsets]
    if missing:
        return RC3.BASE._component(
            0.0,
            True,
            "insufficient_layout_evidence",
            matched_roles=roles,
            missing_offset_roles=missing,
            role_offsets=diagnostics,
            global_scale=RC3.BASE._round(scale),
            scale_source="alignment.global_scale",
            core_component_fail_closed=True,
        )

    errors: list[float] = []
    pair_rows: list[dict[str, Any]] = []
    for first, second in combinations(roles, 2):
        error = float(np.linalg.norm(offsets[second] - offsets[first]) / sheet_diagonal)
        errors.append(error)
        pair_rows.append(
            {"roles": [first, second], "offset_error_fraction": RC3.BASE._round(error)}
        )
    mean_error = float(np.mean(errors))
    score = math.exp(-mean_error / 0.10)
    dispersions = [
        float(detail["offset_dispersion_fraction"])
        for detail in diagnostics.values()
        if detail.get("offset_dispersion_fraction") is not None
    ]
    return RC3.BASE._component(
        score,
        True,
        "ok" if mean_error <= 0.02 else "relative_view_layout_mismatch",
        matched_roles=roles,
        mean_pair_offset_error_fraction=RC3.BASE._round(mean_error),
        pairs=pair_rows,
        role_offsets=diagnostics,
        matched_support_total=sum(
            int(detail["support_count"]) for detail in diagnostics.values()
        ),
        fallback_role_count=sum(
            bool(detail["fallback_used"]) for detail in diagnostics.values()
        ),
        offset_dispersion_macro=RC3.BASE._round(float(np.mean(dispersions)))
        if dispersions
        else None,
        offset_definition=OFFSET_DEFINITION,
        global_scale=RC3.BASE._round(scale),
        scale_source="alignment.global_scale",
        uniform_sheet_scale_invariant=True,
        global_translation_invariant=True,
        core_component_fail_closed=True,
    )


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]:
    """Run RC3 once, then replace layout and all dependent aggregates."""

    result = RC3.score_dxf_pair(
        pred, gt, sidecar=sidecar, category=category, **kwargs
    )
    result["schema_version"] = SCHEMA_VERSION
    result["metric_version"] = METRIC_VERSION
    result.setdefault("metric_definition", {}).update(
        {
            "layout_offset_formula": OFFSET_DEFINITION,
            "layout_anchor_sources": [
                "line_midpoint",
                "circle_center",
                "arc_center",
            ],
            "layout_hybrid_policy": (
                "matched_pair_if_support_ge_1_else_parameter_stable_view_anchor"
            ),
            "layout_failure_policy": "core_component_score_zero",
        }
    )

    context = RC3._consume_appended_omitted_marker(
        RC3.MATCH.build_pair_context(pred, gt, sidecar=sidecar)
    )
    if context.get("eligible") and context.get("prediction_valid"):
        rows, _curve = RC3.BASE._semantic_rows(context)
        layout = _layout_component(context, rows)
        components = result["components"]
        components["layout"] = layout
        prompt_components = result["online_reward_prompt_masked"]["components"]
        prompt_components["layout"] = copy.deepcopy(layout)
        atomic = result.get("diagnostics", {}).get("atomic_geometry", {})
        result["verified_reward_full_gt"] = RC3._scoped_hierarchical_reward(
            components, atomic, scope="offline_full_gt_executed_dxf"
        )
        prompt_reward = RC3._scoped_hierarchical_reward(
            prompt_components, atomic, scope="prompt_masked_actual_geometry"
        )
        result["online_reward_prompt_masked"] = {
            **prompt_reward,
            "components": prompt_components,
        }
        result["benchmark"] = RC3._benchmark(components)
        result["engineering_success"] = result["benchmark"]["engineering_success"]
    release = result.get("diagnostics", {}).get("release_status")
    if isinstance(release, dict):
        release["candidate"] = METRIC_VERSION
    return result


__all__ = [
    "ENGINEERING_THRESHOLDS",
    "METRIC_VERSION",
    "OFFSET_DEFINITION",
    "PHYSICAL_SUPPORTED_SEMANTICS",
    "SCHEMA_VERSION",
    "score_dxf_pair",
]