File size: 5,593 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
#!/usr/bin/env python3
"""High-dispersion fail-closed gate for the final v5.2 layout verifier.

RC5F establishes whether each semantic role has sufficient anchor support.
RC5G additionally rejects contradictory matched-pair offsets: whenever a role
has at least two matches, its normalized offset dispersion must be present and
no greater than 0.02.  This prevents a coordinate median from cancelling
opposite geometric errors and spuriously increasing the total reward.
"""

from __future__ import annotations

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

try:
    from . import eval_geometric052_rc5f as RC5F
except ImportError:  # direct evaluator import
    import eval_geometric052_rc5f as RC5F


METRIC_VERSION = "v5.2-rc5g"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5g"
ENGINEERING_THRESHOLDS = dict(RC5F.ENGINEERING_THRESHOLDS)
PHYSICAL_SUPPORTED_SEMANTICS = RC5F.PHYSICAL_SUPPORTED_SEMANTICS
MAX_MATCHED_OFFSET_DISPERSION_FRACTION = 0.02


def _dispersion_unreliable_roles(
    role_offsets: Mapping[str, Any],
) -> list[str]:
    unreliable: list[str] = []
    for role, detail in role_offsets.items():
        if not isinstance(detail, Mapping):
            unreliable.append(str(role))
            continue
        try:
            support = int(detail.get("support_count", 0) or 0)
        except (TypeError, ValueError):
            support = 0
        if support < 2:
            continue
        dispersion = detail.get("offset_dispersion_fraction")
        valid = bool(
            isinstance(dispersion, (int, float))
            and not isinstance(dispersion, bool)
            and math.isfinite(float(dispersion))
            and float(dispersion) <= MAX_MATCHED_OFFSET_DISPERSION_FRACTION
        )
        if not valid:
            unreliable.append(str(role))
    return unreliable


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]:
    result = RC5F.score_dxf_pair(
        pred, gt, sidecar=sidecar, category=category, **kwargs
    )
    result["schema_version"] = SCHEMA_VERSION
    result["metric_version"] = METRIC_VERSION
    result.setdefault("metric_definition", {})[
        "layout_offset_dispersion_policy"
    ] = {
        "applies_when_support_count_ge": 2,
        "maximum_offset_dispersion_fraction": (
            MAX_MATCHED_OFFSET_DISPERSION_FRACTION
        ),
        "missing_dispersion_is_unreliable": True,
        "failure_policy": "active_layout_score_zero",
    }

    layout = result.get("components", {}).get("layout", {})
    details = layout.get("details", {}) if isinstance(layout, Mapping) else {}
    role_offsets = (
        details.get("role_offsets", {}) if isinstance(details, Mapping) else {}
    )
    existing = {
        str(role)
        for role in details.get("unreliable_roles", [])
    } if isinstance(details, Mapping) else set()
    if isinstance(role_offsets, Mapping):
        existing.update(
            str(role)
            for role, detail in role_offsets.items()
            if isinstance(detail, Mapping) and detail.get("reliable") is False
        )
        high_dispersion = _dispersion_unreliable_roles(role_offsets)
    else:
        high_dispersion = []
    unreliable = sorted(existing | set(high_dispersion))

    if unreliable:
        preserved = copy.deepcopy(dict(details))
        preserved.setdefault("prior_layout_score", layout.get("score"))
        preserved.setdefault("prior_layout_reason", layout.get("reason"))
        preserved.update(
            {
                "role_offsets": copy.deepcopy(role_offsets),
                "unreliable_roles": unreliable,
                "high_offset_dispersion_roles": sorted(high_dispersion),
                "maximum_offset_dispersion_fraction": (
                    MAX_MATCHED_OFFSET_DISPERSION_FRACTION
                ),
                "missing_dispersion_is_unreliable": True,
                "core_component_fail_closed": True,
            }
        )
        base = RC5F.RC5.RC3.BASE
        replacement = base._component(
            0.0, True, "insufficient_layout_evidence", **preserved
        )
        result["components"]["layout"] = replacement
        prompt_components = result["online_reward_prompt_masked"]["components"]
        prompt_components["layout"] = copy.deepcopy(replacement)
        atomic = result.get("diagnostics", {}).get("atomic_geometry", {})
        result["verified_reward_full_gt"] = (
            RC5F.RC5.RC3._scoped_hierarchical_reward(
                result["components"],
                atomic,
                scope="offline_full_gt_executed_dxf",
            )
        )
        prompt_reward = RC5F.RC5.RC3._scoped_hierarchical_reward(
            prompt_components,
            atomic,
            scope="prompt_masked_actual_geometry",
        )
        result["online_reward_prompt_masked"] = {
            **prompt_reward,
            "components": prompt_components,
        }
        result["benchmark"] = RC5F.RC5.RC3._benchmark(result["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",
    "MAX_MATCHED_OFFSET_DISPERSION_FRACTION",
    "METRIC_VERSION",
    "PHYSICAL_SUPPORTED_SEMANTICS",
    "SCHEMA_VERSION",
    "score_dxf_pair",
]