File size: 7,415 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
#!/usr/bin/env python3
"""Open-contour-safe retention candidate layered on v5.2-rc5h.

The historical closure-retention formula is ``min(1, predicted / target)``.
It is correct whenever the target has at least one joined endpoint, but maps
the legitimate ``open target / equally open prediction`` case (0 / 0) to
zero.  That makes a GT drawing score below one against itself (notably
``0073_00731389``).

RC5I treats the target joined-endpoint fraction as a lower-bound requirement:

* a prediction at least as closed as the target receives one;
* a less-closed prediction receives ``predicted / target``;
* a completely open target imposes no closure requirement, so every numeric
  prediction -- including an equally open one -- receives one.

The wrapper preserves RC5H and only replaces changed contour-retention rows,
the geometry component derived from those rows, and dependent aggregates.
"""

from __future__ import annotations

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

try:
    from . import eval_geometric052_rc5h as RC5H
except ImportError:  # direct evaluator import
    import eval_geometric052_rc5h as RC5H


METRIC_VERSION = "v5.2-rc5i"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5i"
ENGINEERING_THRESHOLDS = dict(RC5H.ENGINEERING_THRESHOLDS)
PHYSICAL_SUPPORTED_SEMANTICS = RC5H.PHYSICAL_SUPPORTED_SEMANTICS
MAX_MATCHED_OFFSET_DISPERSION_FRACTION = (
    RC5H.MAX_MATCHED_OFFSET_DISPERSION_FRACTION
)

RC3 = RC5H.RC3
BASE = RC5H.BASE
OPEN_TARGET_EPSILON = 1.0e-12


def _finite_fraction(value: Any) -> float | None:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    number = float(value)
    return number if math.isfinite(number) else None


def closure_retention(
    predicted: Mapping[str, Any], target: Mapping[str, Any]
) -> dict[str, Any]:
    """Score retained closure as a one-sided target requirement.

    Endpoint-join fractions are produced in [0, 1].  Clipping here keeps the
    helper fail-safe for direct unit use without changing valid diagnostics.
    """

    target_fraction = _finite_fraction(target.get("joined_endpoint_fraction"))
    predicted_fraction = _finite_fraction(
        predicted.get("joined_endpoint_fraction")
    )
    if target_fraction is None:
        return {
            "eligible": False,
            "score": None,
            "reason": "target_closure_ineligible",
        }
    if predicted_fraction is None:
        return {
            "eligible": True,
            "score": 0.0,
            "reason": "prediction_has_no_contour",
        }

    target_value = min(1.0, max(0.0, target_fraction))
    predicted_value = min(1.0, max(0.0, predicted_fraction))
    if target_value <= OPEN_TARGET_EPSILON:
        score = 1.0
    else:
        score = min(1.0, predicted_value / target_value)
    return {
        "eligible": True,
        "score": float(score),
        "reason": "ok",
        "predicted_joined_fraction": float(predicted_fraction),
        "target_joined_fraction": float(target_fraction),
    }


def _replace_retention_rows(rows: Mapping[str, Any]) -> list[str]:
    """Replace only rows whose numeric retention score actually changes."""

    corrected_roles: list[str] = []
    for role, row in rows.items():
        if not isinstance(row, dict):
            continue
        contour = row.get("contour")
        if not isinstance(contour, dict):
            continue
        predicted = contour.get("predicted")
        target = contour.get("target")
        previous = contour.get("retention")
        if not isinstance(predicted, Mapping) or not isinstance(target, Mapping):
            continue
        replacement = closure_retention(predicted, target)
        previous_score = (
            previous.get("score") if isinstance(previous, Mapping) else None
        )
        if replacement.get("score") == previous_score:
            continue
        contour["retention"] = replacement
        corrected_roles.append(str(role))
    return corrected_roles


def _mark_release(result: dict[str, Any]) -> None:
    release = result.get("diagnostics", {}).get("release_status")
    if isinstance(release, dict):
        release["candidate"] = METRIC_VERSION


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 RC5H, then repair only open-target closure retention."""

    result = RC5H.score_dxf_pair(
        pred,
        gt,
        sidecar=sidecar,
        category=category,
        **kwargs,
    )
    result["schema_version"] = SCHEMA_VERSION
    result["metric_version"] = METRIC_VERSION
    result.setdefault("metric_definition", {})[
        "contour_closure_retention_policy"
    ] = {
        "definition": "one_sided_target_joined_endpoint_fraction_requirement",
        "score": "1_if_target_open_else_min_1_predicted_over_target",
        "open_target_epsilon": OPEN_TARGET_EPSILON,
        "more_closed_than_target_is_not_penalized": True,
        "changed_component_definitions": ["geometry"],
    }

    # Rebuild the same deterministic semantic rows used by RC3.  This avoids
    # reverse-engineering a geometry score from rounded public diagnostics.
    context = RC3._consume_appended_omitted_marker(
        RC3.MATCH.build_pair_context(pred, gt, sidecar=sidecar)
    )
    if not context.get("eligible") or not context.get("prediction_valid"):
        result.setdefault("diagnostics", {})[
            "rc5i_open_contour_retention"
        ] = {
            "applied": False,
            "reason": "pair_context_ineligible_or_prediction_invalid",
            "corrected_roles": [],
        }
        _mark_release(result)
        return result

    rows, curve = BASE._semantic_rows(context)
    corrected_roles = _replace_retention_rows(rows)
    result.setdefault("diagnostics", {})[
        "rc5i_open_contour_retention"
    ] = {
        "applied": bool(corrected_roles),
        "reason": "corrected" if corrected_roles else "no_score_change",
        "corrected_roles": corrected_roles,
        "open_target_epsilon": OPEN_TARGET_EPSILON,
    }
    if not corrected_roles:
        _mark_release(result)
        return result

    geometry, atomic = BASE._geometry_component(context, rows, curve)
    components = result.get("components")
    prompt = result.get("online_reward_prompt_masked")
    prompt_components = prompt.get("components") if isinstance(prompt, dict) else None
    if not isinstance(components, dict) or not isinstance(prompt_components, dict):
        _mark_release(result)
        return result

    components["geometry"] = geometry
    prompt_components["geometry"] = copy.deepcopy(geometry)
    diagnostics = result["diagnostics"]
    diagnostics["semantic_views"] = rows
    diagnostics["curve_geometry"] = curve
    diagnostics["atomic_geometry"] = {
        key: copy.deepcopy(value) for key, value in atomic.items() if key != "curve"
    }
    diagnostics["curve_summary"] = copy.deepcopy(atomic.get("curve"))
    RC5H._rescore_downstream(result)
    _mark_release(result)
    return result


__all__ = [
    "ENGINEERING_THRESHOLDS",
    "MAX_MATCHED_OFFSET_DISPERSION_FRACTION",
    "METRIC_VERSION",
    "OPEN_TARGET_EPSILON",
    "PHYSICAL_SUPPORTED_SEMANTICS",
    "SCHEMA_VERSION",
    "closure_retention",
    "score_dxf_pair",
]