File size: 8,518 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
#!/usr/bin/env python3
"""v5.2-rc2 acceptance candidate.

This add-only module keeps rc1 available for comparison while fixing four
issues found by the real-GT counterfactual audit: outlier-sensitive view
clustering, non-JSON diagnostics, missing primitive recall in the physical
score, and an alignment-dependent structure gate.
"""

from __future__ import annotations

import copy
from pathlib import Path
from typing import Any, Mapping

try:
    from . import eval_geometric052 as BASE
    from . import view_entity_matching_v52_rc2 as MATCH
except ImportError:  # direct evaluator import
    import eval_geometric052 as BASE
    import view_entity_matching_v52_rc2 as MATCH


METRIC_VERSION = "v5.2-rc2"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc2"
ENGINEERING_THRESHOLDS = BASE.ENGINEERING_THRESHOLDS
PHYSICAL_SUPPORTED_SEMANTICS = BASE.PHYSICAL_SUPPORTED_SEMANTICS | {
    "bounding_box_width",
    "bounding_box_height",
    "cut_profile_diameter",
}


def _physical_component(
    context: Mapping[str, Any],
    rows: Mapping[str, Any],
    sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
    """Include circle/arc matching recall in physical feature quality."""

    component = copy.deepcopy(BASE._physical_component(context, rows, sidecar))
    if not component.get("eligible"):
        return component
    details = component.get("details", {})
    qualities: list[float] = []
    for item in details.get("extent_items", []):
        value = item.get("score")
        if item.get("eligible") and isinstance(value, (int, float)):
            qualities.append(float(value))
    for item in details.get("primitive_items", []):
        role, family = item.get("role"), item.get("family")
        raw = item.get("score")
        family_row = rows.get(role, {}).get("primitive", {}).get(family, {})
        match_f1 = family_row.get("f1")
        if not isinstance(raw, (int, float)) or not isinstance(match_f1, (int, float)):
            continue
        effective = float(raw) * float(match_f1)
        item["raw_parameter_score"] = BASE._round(float(raw))
        item["match_f1"] = BASE._round(float(match_f1))
        item["score"] = BASE._round(effective)
        qualities.append(effective)
    if not qualities:
        return BASE._component(
            None,
            False,
            "no_supported_actual_geometry_measurements",
            **details,
        )
    macro = sum(qualities) / len(qualities)
    worst = min(qualities)
    score = 0.55 * macro + 0.45 * worst
    component["score"] = BASE._round(score)
    component["reason"] = (
        "ok"
        if score >= ENGINEERING_THRESHOLDS["physical"]
        else "actual_geometry_measurement_mismatch"
    )
    details["macro"] = BASE._round(macro)
    details["worst"] = BASE._round(worst)
    details["primitive_recall_is_scored"] = True
    details["reads_prediction_dimension_text"] = False
    return component


def _structure_component(
    context: Mapping[str, Any], frozen: Mapping[str, Any]
) -> dict[str, Any]:
    """Use only true duplicate dimensions for the anti-spam validity gate."""

    anti_hack = frozen.get("anti_hack", {}) if isinstance(frozen, Mapping) else {}
    try:
        duplicate_ratio = float(anti_hack.get("true_duplicate_dimension_ratio", 0.0) or 0.0)
    except (TypeError, ValueError):
        duplicate_ratio = 0.0
    readable = bool(context.get("pred_meta", {}).get("readable"))
    nondegenerate = bool(context.get("prediction_valid"))
    valid = bool(readable and nondegenerate and duplicate_ratio < 0.50)
    return BASE._component(
        1.0 if valid else 0.0,
        True,
        "ok" if valid else "invalid_or_true_dimension_spam_gate_failed",
        gate_only=True,
        readable=readable,
        nondegenerate=nondegenerate,
        true_duplicate_dimension_ratio=BASE._round(duplicate_ratio),
        alignment_dependent_unmatched_dimensions_ignored=True,
        positive_continuous_reward=False,
    )


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]:
    """Score a DXF pair with the rc2 matching and causal component fixes."""

    frozen = BASE.EV51.score_dxf_pair(pred, gt, sidecar=sidecar, category=category)
    context = MATCH.build_pair_context(pred, gt, sidecar=sidecar)
    result: dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "metric_version": METRIC_VERSION,
        "category": category,
        "anti_hack": copy.deepcopy(frozen.get("anti_hack", {})),
        "diagnostics": {
            "v51_frozen": {
                "metric_version": frozen.get("metric_version"),
                "components": copy.deepcopy(frozen.get("components", {})),
                "benchmark": copy.deepcopy(frozen.get("benchmark", {})),
                "anti_hack": copy.deepcopy(frozen.get("anti_hack", {})),
            },
            "matching": {
                key: copy.deepcopy(value)
                for key, value in context.items()
                if key
                not in {
                    "raw_pred",
                    "raw_gt",
                    "canonical_pred",
                    "canonical_gt",
                    "pred_views",
                    "pred_views_all",
                    "gt_by_role",
                }
            },
        },
    }
    if not context.get("eligible"):
        components = {
            name: BASE._component(None, False, str(context.get("reason")))
            for name in ("view", "geometry", "physical", "annotation", "layout", "structure")
        }
        result["components"] = components
        result["hierarchical_reward"] = {"score": None, "reason": "target_ineligible"}
        result["online_reward"] = {"scope": "prompt_observable_v52", "components": components}
        result["benchmark"] = BASE._benchmark(components)
        result["engineering_success"] = None
        return result
    if not context.get("prediction_valid"):
        components = BASE._zero_components("prediction_dxf_unreadable_or_degenerate")
        reward = BASE._hierarchical_reward(components, {"topology_score": 0.0})
        result["components"] = components
        result["hierarchical_reward"] = reward
        result["online_reward"] = {
            "scope": "prompt_observable_v52",
            "components": components,
            "hierarchical_reward": reward,
        }
        result["benchmark"] = BASE._benchmark(components)
        result["engineering_success"] = result["benchmark"]["engineering_success"]
        return result

    rows, curve = BASE._semantic_rows(context)
    view = BASE._view_component(context, rows)
    layout = BASE._layout_component(context, rows)
    geometry, atomic = BASE._geometry_component(context, rows, curve)
    physical = _physical_component(context, rows, sidecar)
    annotation, annotation_diagnostic = BASE._annotation_component(context, sidecar)
    structure = _structure_component(context, frozen)
    components = {
        "view": view,
        "geometry": geometry,
        "physical": physical,
        "annotation": annotation,
        "layout": layout,
        "structure": structure,
    }
    reward = BASE._hierarchical_reward(components, atomic)
    benchmark = BASE._benchmark(components)
    result.update(
        {
            "components": components,
            "online_reward": {
                "scope": "prompt_observable_v52",
                "components": components,
                "hierarchical_reward": reward,
            },
            "hierarchical_reward": reward,
            "benchmark": benchmark,
            "engineering_success": benchmark["engineering_success"],
        }
    )
    result["diagnostics"].update(
        {
            "semantic_views": rows,
            "curve_geometry": curve,
            "atomic_geometry": {
                key: copy.deepcopy(value) for key, value in atomic.items() if key != "curve"
            },
            "curve_summary": atomic.get("curve"),
            "annotation_fields": annotation_diagnostic,
            "release_status": {
                "grpo_connected": False,
                "reason": "counterfactual_and_real_generation_acceptance_required",
                "candidate": METRIC_VERSION,
            },
        }
    )
    return result


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