CAD / CODE /evaluation /eval /eval_geometric052.py
641071660J's picture
Add frozen CODE evaluation toolkit and portable full-GT scoring CLI
15d1f1d verified
Raw History Blame Contribute Delete
35.3 kB
#!/usr/bin/env python3
"""Causally-audited geometric evaluator v5.2 (offline release candidate).
v5.2 keeps the public six-component schema but replaces the parts that the
real-GT counterfactual audit found to be coupled:
* semantic views are matched before a shared scale is fitted;
* geometry retains per-role/per-family one-to-one precision and recall;
* circle/arc parameters are measured explicitly, not inferred from Curve-F1;
* physical geometry never reads predicted DIMENSION text;
* annotation scores presence/type/display value/binding separately;
* structure is a binary validity/anti-hack gate, not a positive style reward;
* the scalar is hierarchical, so downstream quality cannot compensate for a
missing view or missing required feature.
The frozen v5.1 result is preserved under ``diagnostics.v51_frozen`` solely as
an audit baseline. This module is not connected to GRPO until its
counterfactual and real-generation acceptance suites pass.
"""
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
from scipy.optimize import linear_sum_assignment
try:
from . import curve_geometry_metric as CURVE
from . import eval_geometric05 as EV5
from . import eval_geometric051 as EV51
from . import feature_topology_diagnostic as FEATURE
from . import view_entity_matching_v52 as MATCH
except ImportError: # direct evaluator import
import curve_geometry_metric as CURVE
import eval_geometric05 as EV5
import eval_geometric051 as EV51
import feature_topology_diagnostic as FEATURE
import view_entity_matching_v52 as MATCH
METRIC_VERSION = "v5.2-rc1"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc1"
ENGINEERING_THRESHOLDS = {
"structure": 1.0,
"view": 1.0,
"geometry": 0.90,
"physical": 0.90,
"annotation": 0.90,
"layout": 0.85,
}
PHYSICAL_SUPPORTED_SEMANTICS = {
"profile_width",
"overall_width",
"profile_height",
"overall_height",
"extrusion_depth",
"thickness",
"profile_diameter",
"outer_diameter",
"inner_diameter",
"hole_diameter",
"radius",
"arc_radius",
}
def _round(value: float | None, digits: int = 6) -> float | None:
if value is None or not math.isfinite(float(value)):
return None
return round(float(value), digits)
def _clip(value: float) -> float:
return float(min(1.0, max(0.0, value)))
def _mean(values: Sequence[float]) -> float | None:
return float(np.mean(values)) if values else None
def _minimum(values: Sequence[float]) -> float | None:
return float(min(values)) if values else None
def _harmonic(first: float, second: float) -> float:
if first <= 0.0 or second <= 0.0:
return 0.0
return float(2.0 * first * second / (first + second))
def _component(
score: float | None, eligible: bool, reason: str, **details: Any
) -> dict[str, Any]:
if not eligible:
score = None
elif score is None:
raise ValueError("eligible component requires numeric score")
return {
"score": _round(_clip(float(score))) if score is not None else None,
"eligible": bool(eligible),
"reason": str(reason),
"details": details,
}
def _zero_components(reason: str) -> dict[str, dict[str, Any]]:
return {
name: _component(0.0, True, reason)
for name in ("view", "geometry", "physical", "annotation", "structure")
} | {"layout": _component(None, False, reason)}
def _curve_quality(curve: Mapping[str, Any]) -> tuple[float, dict[str, Any]]:
aggregate = curve.get("aggregate", {}) if isinstance(curve, Mapping) else {}
channel = aggregate.get("all", {}) if isinstance(aggregate, Mapping) else {}
cd = channel.get("normalized_chamfer") if isinstance(channel, Mapping) else None
f1 = None
thresholds = channel.get("thresholds", {}) if isinstance(channel, Mapping) else {}
if isinstance(thresholds, Mapping):
row = thresholds.get("0.02", {})
if isinstance(row, Mapping) and isinstance(row.get("f1"), (int, float)):
f1 = float(row["f1"])
if not isinstance(cd, (int, float)) or not math.isfinite(float(cd)):
return 0.0, {"normalized_chamfer": None, "f1_at_2pct": _round(f1), "reason": "curve_ineligible"}
cd_value = max(0.0, float(cd))
cd_quality = math.exp(-cd_value / 0.02)
quality = 0.75 * cd_quality + 0.25 * (f1 if f1 is not None else cd_quality)
return _clip(quality), {
"normalized_chamfer": _round(cd_value),
"chamfer_quality": _round(cd_quality),
"f1_at_2pct": _round(f1),
"score": _round(quality),
}
def _semantic_rows(context: Mapping[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
gt_by_role = context["gt_by_role"]
pred_views = context.get("pred_views", [])
alignment = context["alignment"]
role_to_pred = alignment.get("role_to_pred", {})
global_scale = float(alignment.get("global_scale", 1.0))
rows: dict[str, Any] = {}
curve_pred: dict[str, Mapping[str, Any] | None] = {}
curve_gt: dict[str, Mapping[str, Any]] = {}
for role, target_view in gt_by_role.items():
pred_index = role_to_pred.get(role)
predicted_view = (
pred_views[pred_index]
if isinstance(pred_index, int) and 0 <= pred_index < len(pred_views)
else None
)
primitive = MATCH.match_view_primitives(
predicted_view, target_view, global_scale=global_scale
)
target_entities = target_view["entities"]
predicted_entities = (
predicted_view["entities"]
if predicted_view is not None
else {"lines": [], "circles": [], "arcs": [], "dims": []}
)
diagonal = max(float(np.linalg.norm(np.asarray(target_view["size"], dtype=float))), 1.0)
pred_closure = FEATURE._endpoint_join_diagnostic(predicted_entities, diagonal=diagonal)
gt_closure = FEATURE._endpoint_join_diagnostic(target_entities, diagonal=diagonal)
closure = FEATURE._closure_retention(pred_closure, gt_closure)
strict = None
if predicted_view is not None:
strict = EV5.EV3.score_geometry(
predicted_entities,
target_entities,
np.asarray(predicted_view["center"], dtype=float),
np.asarray(target_view["center"], dtype=float),
global_scale,
diagonal,
)
rows[role] = {
"present": predicted_view is not None,
"predicted_view_index": pred_index,
"primitive": primitive,
"contour": {
"predicted": pred_closure,
"target": gt_closure,
"retention": closure,
},
"strict": strict,
}
curve_pred[role] = predicted_view
curve_gt[role] = target_view
curve = CURVE.score_matched_views(
curve_pred, curve_gt, global_scale=global_scale
)
return rows, curve
def _view_component(context: Mapping[str, Any], rows: Mapping[str, Any]) -> dict[str, Any]:
roles = list(context["gt_by_role"])
present = [role for role in roles if rows[role]["present"]]
coverage = len(present) / max(len(roles), 1)
missing = [role for role in roles if role not in present]
return _component(
coverage,
True,
"ok" if not missing else "semantic_roles_missing",
expected_roles=roles,
present_roles=present,
missing_roles=missing,
role_coverage=_round(coverage),
worst_role_present=not missing,
alignment_reason=context["alignment"].get("reason"),
alignment_pairs=context["alignment"].get("pairs", []),
)
def _layout_component(context: Mapping[str, Any], rows: Mapping[str, Any]) -> dict[str, Any]:
roles = [role for role, row in rows.items() if row["present"]]
if len(roles) < 2:
return _component(
None,
False,
"fewer_than_two_semantic_roles",
matched_roles=roles,
)
alignment = context["alignment"]
scale = float(alignment.get("global_scale", 1.0))
role_to_pred = alignment["role_to_pred"]
pred_views = context["pred_views"]
gt_by_role = context["gt_by_role"]
sheet_diagonal = max(float(alignment.get("sheet_diagonal", 1.0)), 1.0)
errors = []
pair_rows = []
for first, second in combinations(roles, 2):
pred_vector = scale * (
np.asarray(pred_views[role_to_pred[second]]["center"], dtype=float)
- np.asarray(pred_views[role_to_pred[first]]["center"], dtype=float)
)
gt_vector = (
np.asarray(gt_by_role[second]["center"], dtype=float)
- np.asarray(gt_by_role[first]["center"], dtype=float)
)
error = float(np.linalg.norm(pred_vector - gt_vector) / sheet_diagonal)
errors.append(error)
pair_rows.append(
{"roles": [first, second], "vector_error_fraction": _round(error)}
)
mean_error = float(np.mean(errors)) if errors else math.inf
score = math.exp(-mean_error / 0.10)
return _component(
score,
True,
"ok" if mean_error <= 0.02 else "relative_view_layout_mismatch",
matched_roles=roles,
mean_pair_vector_error_fraction=_round(mean_error),
pairs=pair_rows,
missing_roles_do_not_repeat_penalty=True,
)
def _geometry_component(
context: Mapping[str, Any], rows: Mapping[str, Any], curve: Mapping[str, Any]
) -> tuple[dict[str, Any], dict[str, Any]]:
feature_scores: list[float] = []
role_scores: dict[str, float] = {}
parameter_scores: list[float] = []
role_details: dict[str, Any] = {}
for role, row in rows.items():
local: list[float] = []
for family in ("visible_line", "hidden_line", "circle", "arc"):
item = row["primitive"][family]
if item.get("eligible") and isinstance(item.get("f1"), (int, float)):
value = float(item["f1"])
local.append(value)
feature_scores.append(value)
if family in {"circle", "arc"} and item.get("eligible"):
parameter = item.get("parameter_score")
if isinstance(parameter, (int, float)):
parameter_scores.append(float(parameter))
retention = row["contour"]["retention"]
if retention.get("eligible") and isinstance(retention.get("score"), (int, float)):
local.append(float(retention["score"]))
feature_scores.append(float(retention["score"]))
role_score = float(np.mean(local)) if local else (1.0 if row["present"] else 0.0)
role_scores[role] = role_score
role_details[role] = {
"feature_macro": _round(role_score),
"feature_worst": _round(min(local)) if local else _round(role_score),
}
macro = float(np.mean(feature_scores)) if feature_scores else 0.0
worst = min(
[min(role_scores.values()) if role_scores else 0.0]
+ [float(value) for value in feature_scores]
)
topology_score = 0.40 * macro + 0.60 * worst
extra_indices = context["alignment"].get("extra_predicted_indices", [])
pred_views = context.get("pred_views", [])
extra_primitives = int(
sum(
int(pred_views[index].get("n_primitives", 0))
for index in extra_indices
if isinstance(index, int) and 0 <= index < len(pred_views)
)
)
target_primitives = int(
sum(int(view.get("n_primitives", 0)) for view in context["gt_by_role"].values())
)
extra_precision = target_primitives / max(target_primitives + extra_primitives, 1)
topology_score *= extra_precision
curve_score, curve_details = _curve_quality(curve)
parameter_score = _mean(parameter_scores)
weighted = [(0.58, topology_score), (0.30, curve_score)]
if parameter_score is not None:
weighted.append((0.12, parameter_score))
weight_sum = sum(weight for weight, _ in weighted)
score = sum(weight * value for weight, value in weighted) / weight_sum
component = _component(
score,
True,
"ok" if score >= ENGINEERING_THRESHOLDS["geometry"] else "geometry_or_topology_mismatch",
topology_score=_round(topology_score),
feature_macro=_round(macro),
feature_worst=_round(worst),
extra_fragment_precision=_round(extra_precision),
extra_primitive_count=extra_primitives,
curve_score=_round(curve_score),
parameter_score=_round(parameter_score),
roles=role_details,
)
return component, {
"topology_score": topology_score,
"feature_macro": macro,
"feature_worst": worst,
"curve_score": curve_score,
"curve": curve_details,
"parameter_score": parameter_score,
}
def _prompt_semantics(sidecar: Mapping[str, Any] | None) -> tuple[list[str], list[str]]:
parameters = sidecar.get("parameters") if isinstance(sidecar, Mapping) else None
candidates = parameters.get("candidates") if isinstance(parameters, Mapping) else None
values: list[str] = []
if isinstance(candidates, Sequence) and not isinstance(candidates, (str, bytes)):
for item in candidates:
semantic = item.get("semantic") if isinstance(item, Mapping) else None
if isinstance(semantic, Mapping) and semantic.get("type"):
values.append(str(semantic["type"]))
supported = sorted({value for value in values if value in PHYSICAL_SUPPORTED_SEMANTICS})
unsupported = sorted({value for value in values if value not in PHYSICAL_SUPPORTED_SEMANTICS})
return supported, unsupported
def _physical_component(
context: Mapping[str, Any], rows: Mapping[str, Any], sidecar: Mapping[str, Any] | None
) -> dict[str, Any]:
alignment = context["alignment"]
scale = float(alignment.get("global_scale", 1.0))
role_to_pred = alignment.get("role_to_pred", {})
pred_views = context.get("pred_views", [])
gt_by_role = context["gt_by_role"]
extent_items: list[dict[str, Any]] = []
qualities: list[float] = []
for role, gt_view in gt_by_role.items():
pred_index = role_to_pred.get(role)
if not isinstance(pred_index, int) or not 0 <= pred_index < len(pred_views):
extent_items.append({"role": role, "eligible": False, "reason": "role_missing"})
continue
pred_size = np.asarray(pred_views[pred_index]["size"], dtype=float) * scale
gt_size = np.asarray(gt_view["size"], dtype=float)
for axis, name in enumerate(("width", "height")):
if gt_size[axis] <= 1e-9:
continue
log_error = abs(math.log(max(float(pred_size[axis]), 1e-12) / float(gt_size[axis])))
quality = math.exp(-log_error / 0.10)
qualities.append(quality)
extent_items.append(
{
"role": role,
"measurement": f"bbox_{name}",
"eligible": True,
"predicted_aligned": _round(float(pred_size[axis])),
"target": _round(float(gt_size[axis])),
"log_error": _round(log_error),
"relative_error": _round(abs(float(pred_size[axis]) / float(gt_size[axis]) - 1.0)),
"score": _round(quality),
}
)
primitive_items: list[dict[str, Any]] = []
for role, row in rows.items():
for family in ("circle", "arc"):
item = row["primitive"][family]
if item.get("eligible"):
value = item.get("parameter_score")
if isinstance(value, (int, float)):
qualities.append(float(value))
primitive_items.append(
{
"role": role,
"family": family,
"score": _round(float(value)),
"pairs": copy.deepcopy(item.get("pairs", [])),
"recall": item.get("recall"),
}
)
supported, unsupported = _prompt_semantics(sidecar)
if not qualities:
return _component(
None,
False,
"no_supported_actual_geometry_measurements",
extent_items=extent_items,
primitive_items=primitive_items,
supported_prompt_semantics=supported,
unsupported_prompt_semantics=unsupported,
reads_prediction_dimension_text=False,
)
macro = float(np.mean(qualities))
worst = min(qualities)
score = 0.55 * macro + 0.45 * worst
return _component(
score,
True,
"ok" if score >= ENGINEERING_THRESHOLDS["physical"] else "actual_geometry_measurement_mismatch",
measurement_scope="matched_view_extents_and_matched_circle_arc_parameters",
macro=_round(macro),
worst=_round(worst),
extent_items=extent_items,
primitive_items=primitive_items,
supported_prompt_semantics=supported,
unsupported_prompt_semantics=unsupported,
fail_closed_for_unsupported_semantics=True,
reads_prediction_dimension_text=False,
)
def _semantic_family(value: Any) -> str:
token = str(value or "").lower()
return "linear" if token in {"linear", "aligned"} else token
def _dimension_display_value(
dimension: Mapping[str, Any],
*,
target_value: float,
target_dimension: Mapping[str, Any],
global_scale: float,
) -> tuple[float | None, str]:
value = dimension.get("display_value")
if isinstance(value, (int, float)) and math.isfinite(float(value)):
return abs(float(value)), "explicit_display_text"
measurement = dimension.get("measurement")
target_measurement = target_dimension.get("measurement")
if (
isinstance(measurement, (int, float))
and isinstance(target_measurement, (int, float))
and abs(float(target_measurement)) > 1e-12
):
inferred = abs(float(measurement)) * global_scale * target_value / abs(float(target_measurement))
return inferred, "automatic_measurement_placeholder"
return None, "display_value_unavailable"
def _dimension_role(
sidecar: Mapping[str, Any] | None, gt_index: int
) -> str | None:
dimensions = sidecar.get("dimensions") if isinstance(sidecar, Mapping) else None
items = dimensions.get("items") if isinstance(dimensions, Mapping) else None
item = items[gt_index] if isinstance(items, Sequence) and 0 <= gt_index < len(items) else None
if isinstance(item, Mapping):
for key in ("nearest_view_position", "nearest_view_role"):
value = str(item.get(key) or "")
if value in {"front", "top", "right"}:
return value
try:
view_index = int(item.get("view_candidate_index"))
except (TypeError, ValueError):
view_index = -1
views = sidecar.get("views") if isinstance(sidecar, Mapping) else None
candidates = views.get("candidates") if isinstance(views, Mapping) else None
if isinstance(candidates, Sequence) and 0 <= view_index < len(candidates):
candidate = candidates[view_index]
if isinstance(candidate, Mapping) and candidate.get("name"):
return str(candidate["name"])
return None
def _annotation_component(
context: Mapping[str, Any], sidecar: Mapping[str, Any] | None
) -> tuple[dict[str, Any], dict[str, Any]]:
contract = EV51._scope_contracts(sidecar)
prompt = contract.get("prompt", {})
mask = prompt.get("annotation_mask", []) if isinstance(prompt, Mapping) else []
specs = [
dict(spec)
for spec, selected in zip(contract.get("specs", []), mask)
if selected
]
if not prompt.get("annotation_eligible") or not specs:
component = _component(
None,
False,
"prompt_annotation_mask_ineligible",
contract_errors=contract.get("errors", []),
reads_actual_geometry=False,
)
return component, {"items": [], "eligible": False}
raw_pred, raw_gt = context.get("raw_pred") or {}, context.get("raw_gt") or {}
pred_dims, gt_dims = list(raw_pred.get("dims", [])), list(raw_gt.get("dims", []))
targets: list[dict[str, Any]] = []
for spec in specs:
gt_index = int(spec["gt_dimension_index"])
if not 0 <= gt_index < len(gt_dims):
continue
targets.append(
{
"spec": spec,
"gt_index": gt_index,
"dimension": gt_dims[gt_index],
"role": _dimension_role(sidecar, gt_index),
}
)
if not targets:
component = _component(None, False, "no_valid_masked_target_dimensions")
return component, {"items": [], "eligible": False}
sheet_diagonal = max(float(context["alignment"].get("sheet_diagonal", 1.0)), 1.0)
costs = np.full((len(pred_dims), len(targets)), 10.0, dtype=float)
raw_cost: dict[tuple[int, int], dict[str, Any]] = {}
for pred_index, pred_dim in enumerate(pred_dims):
pred_binding = np.asarray(pred_dim.get("binding_point", (0.0, 0.0)), dtype=float)
for target_index, target in enumerate(targets):
role = target["role"]
transform = MATCH.role_local_transform(context, role) if role else None
if transform is None:
scale = float(context["alignment"].get("global_scale", 1.0))
translation = np.asarray(context["alignment"].get("translation", (0.0, 0.0)), dtype=float)
else:
scale, translation = transform
aligned_binding = pred_binding * scale + translation
gt_binding = np.asarray(target["dimension"].get("binding_point", (0.0, 0.0)), dtype=float)
distance = float(np.linalg.norm(aligned_binding - gt_binding) / sheet_diagonal)
pred_family = _semantic_family(pred_dim.get("family"))
target_family = _semantic_family(target["spec"].get("family"))
family_penalty = 0.05 if pred_family != target_family else 0.0
costs[pred_index, target_index] = distance + family_penalty
raw_cost[(pred_index, target_index)] = {
"binding_distance_fraction": distance,
"predicted_family": pred_family,
"target_family": target_family,
"role": role,
"scale": scale,
}
pairs: dict[int, int] = {}
if pred_dims:
rows, columns = linear_sum_assignment(costs)
for pred_index, target_index in zip(rows, columns):
if raw_cost[(int(pred_index), int(target_index))]["binding_distance_fraction"] <= 0.08:
pairs[int(target_index)] = int(pred_index)
item_rows: list[dict[str, Any]] = []
item_scores: list[float] = []
presence_values: list[float] = []
type_values: list[float] = []
value_values: list[float] = []
binding_values: list[float] = []
for target_index, target in enumerate(targets):
spec = target["spec"]
pred_index = pairs.get(target_index)
if pred_index is None:
presence_values.append(0.0)
type_values.append(0.0)
value_values.append(0.0)
binding_values.append(0.0)
item_scores.append(0.0)
item_rows.append(
{
"id": spec["id"],
"gt_dimension_index": target["gt_index"],
"pred_dimension_index": None,
"role": target["role"],
"presence": 0.0,
"type": 0.0,
"display_value": 0.0,
"binding": 0.0,
"score": 0.0,
"reason": "missing_dimension",
}
)
continue
pred_dim = pred_dims[pred_index]
detail = raw_cost[(pred_index, target_index)]
presence = 1.0
type_quality = float(detail["predicted_family"] == detail["target_family"])
target_value = abs(float(spec["value"]))
predicted_value, value_source = _dimension_display_value(
pred_dim,
target_value=target_value,
target_dimension=target["dimension"],
global_scale=float(detail["scale"]),
)
if predicted_value is None or target_value <= 1e-12:
relative_error, value_quality = None, 0.0
else:
relative_error = abs(predicted_value / target_value - 1.0)
value_quality = math.exp(
-abs(math.log(max(predicted_value, 1e-12) / target_value)) / 0.10
)
binding_quality = math.exp(-float(detail["binding_distance_fraction"]) / 0.03)
item_score = 0.35 * presence + 0.20 * type_quality + 0.30 * value_quality + 0.15 * binding_quality
presence_values.append(presence)
type_values.append(type_quality)
value_values.append(value_quality)
binding_values.append(binding_quality)
item_scores.append(item_score)
item_rows.append(
{
"id": spec["id"],
"gt_dimension_index": target["gt_index"],
"pred_dimension_index": pred_index,
"role": target["role"],
"presence": 1.0,
"type": _round(type_quality),
"display_value": _round(value_quality),
"binding": _round(binding_quality),
"target_display_value": _round(target_value),
"predicted_display_value": _round(predicted_value),
"display_value_source": value_source,
"display_value_relative_error": _round(relative_error),
"binding_distance_fraction": _round(float(detail["binding_distance_fraction"])),
"score": _round(item_score),
"reason": "ok" if item_score >= 0.90 else "annotation_field_mismatch",
}
)
macro = float(np.mean(item_scores))
worst = min(item_scores)
score = 0.50 * macro + 0.50 * worst
component = _component(
score,
True,
"ok" if score >= ENGINEERING_THRESHOLDS["annotation"] else "masked_annotation_mismatch",
n_target=len(targets),
n_predicted_native=len(pred_dims),
presence_recall=_round(float(np.mean(presence_values))),
type_macro=_round(float(np.mean(type_values))),
display_value_macro=_round(float(np.mean(value_values))),
binding_macro=_round(float(np.mean(binding_values))),
item_macro=_round(macro),
item_worst=_round(worst),
items=item_rows,
reads_actual_geometry=False,
unmasked_target_dimensions_ignored=True,
)
return component, {"eligible": True, "items": item_rows}
def _structure_component(
context: Mapping[str, Any], frozen: Mapping[str, Any]
) -> dict[str, Any]:
anti_hack = frozen.get("anti_hack", {}) if isinstance(frozen, Mapping) else {}
spam_ratio = anti_hack.get("dimension_spam_ratio", anti_hack.get("duplicate_dimension_ratio", 0.0))
try:
spam_ratio = float(spam_ratio or 0.0)
except (TypeError, ValueError):
spam_ratio = 0.0
valid = bool(
context.get("prediction_valid")
and context.get("pred_meta", {}).get("readable")
and spam_ratio < 0.50
)
return _component(
1.0 if valid else 0.0,
True,
"ok" if valid else "invalid_or_anti_hack_gate_failed",
gate_only=True,
readable=bool(context.get("pred_meta", {}).get("readable")),
nondegenerate=bool(context.get("prediction_valid")),
dimension_spam_ratio=_round(spam_ratio),
positive_continuous_reward=False,
)
def _hierarchical_reward(components: Mapping[str, Mapping[str, Any]], atomic: Mapping[str, Any]) -> dict[str, Any]:
def score(name: str, fallback: float = 1.0) -> float:
row = components[name]
value = row.get("score")
return float(value) if row.get("eligible") and isinstance(value, (int, float)) else fallback
structure_gate = score("structure", 0.0)
view = score("view", 0.0)
topology = float(atomic.get("topology_score", 0.0))
geometry = score("geometry", 0.0)
layout = score("layout", 1.0)
physical = score("physical", geometry)
annotation = score("annotation", 1.0)
view_topology_gate = _harmonic(view, topology)
geometry_gate = _harmonic(view_topology_gate, geometry)
physical_gate = _harmonic(geometry_gate, physical)
stages = {
"view_topology": 0.70 * view_topology_gate + 0.30 * view_topology_gate * layout,
"geometry": view_topology_gate * geometry,
"physical": geometry_gate * physical,
"annotation": physical_gate * annotation,
}
reward = structure_gate * (
0.35 * stages["view_topology"]
+ 0.30 * stages["geometry"]
+ 0.20 * stages["physical"]
+ 0.15 * stages["annotation"]
)
return {
"score": _round(reward),
"structure_gate": _round(structure_gate),
"view_topology_gate": _round(view_topology_gate),
"geometry_gate": _round(geometry_gate),
"physical_gate": _round(physical_gate),
"stages": {name: _round(value) for name, value in stages.items()},
"policy": {
"structure": "binary_multiplicative_gate",
"view_topology": "harmonic_gate",
"downstream": "each_stage_multiplied_by_upstream_gate",
"weights": {
"view_topology": 0.35,
"geometry": 0.30,
"physical": 0.20,
"annotation": 0.15,
},
},
}
def _benchmark(components: Mapping[str, Mapping[str, Any]]) -> dict[str, Any]:
states: dict[str, bool | None] = {}
for name, threshold in ENGINEERING_THRESHOLDS.items():
row = components[name]
value = row.get("score")
states[f"{name}_pass"] = (
bool(float(value) >= threshold)
if row.get("eligible") and isinstance(value, (int, float))
else None
)
evaluable = all(value is not None for value in states.values())
success = all(bool(value) for value in states.values()) if evaluable else None
return {
**states,
"fully_evaluable": evaluable,
"engineering_success": success,
"cad_pass": success,
"thresholds": dict(ENGINEERING_THRESHOLDS),
"strict_scope": "prompt_observable_v52",
}
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 an executed DXF pair with independent v5.2 components."""
frozen = 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: _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"] = _benchmark(components)
result["engineering_success"] = None
return result
if not context.get("prediction_valid"):
components = _zero_components("prediction_dxf_unreadable_or_degenerate")
reward = _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"] = _benchmark(components)
result["engineering_success"] = result["benchmark"]["engineering_success"]
return result
rows, curve = _semantic_rows(context)
view = _view_component(context, rows)
layout = _layout_component(context, rows)
geometry, atomic = _geometry_component(context, rows, curve)
physical = _physical_component(context, rows, sidecar)
annotation, annotation_diagnostic = _annotation_component(context, sidecar)
structure = _structure_component(context, frozen)
components = {
"view": view,
"geometry": geometry,
"physical": physical,
"annotation": annotation,
"layout": layout,
"structure": structure,
}
reward = _hierarchical_reward(components, atomic)
benchmark = _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",
},
}
)
return result
__all__ = [
"ENGINEERING_THRESHOLDS",
"METRIC_VERSION",
"PHYSICAL_SUPPORTED_SEMANTICS",
"SCHEMA_VERSION",
"score_dxf_pair",
]