CAD / CODE /evaluation /eval /eval_geometric052_rc2.py
641071660J's picture
Add frozen CODE evaluation toolkit and portable full-GT scoring CLI
15d1f1d verified
Raw History Blame Contribute Delete
8.52 kB
#!/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",
]