CAD / CODE /evaluation /eval /eval_geometric052_rc5h.py
641071660J's picture
Add frozen CODE evaluation toolkit and portable full-GT scoring CLI
15d1f1d verified
Raw History Blame Contribute Delete
23.5 kB
#!/usr/bin/env python3
"""Binding-aware native-DIMENSION spam gate for v5.2-rc5g-final.
RC5G inherits a historical naming error: EV43 groups native dimensions by
semantic family and displayed value in order to balance drawing-scale votes,
then v5/v5.1 reuses ``n_dimensions - n_groups`` as a *true duplicate* count.
Legitimate equal dimensions in different views therefore can hard-zero an
otherwise perfect drawing.
RC5H deliberately leaves the EV43 scale-consistency grouping untouched. It
only replaces the anti-hack identity used by the binary structure gate:
* LINEAR/ALIGNED dimensions are duplicates only when their unordered measured
endpoint pair is the same (within drawing-relative coordinate quantisation);
* DIAMETER/RADIUS dimensions are compared through a common circle centre,
radius, and diameter-equivalent displayed value;
* a reference signature must bind to actual drawing geometry. An unresolved
or detached dimension is never certified as a true duplicate merely because
its displayed value happens to match another annotation.
The module is an add-only candidate wrapper around
``eval_geometric052_rc5g_final``. It updates the top-level anti-hack record,
both structure components, both formal rewards, and the offline benchmark.
No continuous component definition is changed.
"""
from __future__ import annotations
import copy
import math
from collections import defaultdict
from pathlib import Path
from typing import Any, Mapping, Sequence
try:
from . import eval_geometric052_rc5g_final as RC5G_FINAL
except ImportError: # direct evaluator import
import eval_geometric052_rc5g_final as RC5G_FINAL
METRIC_VERSION = "v5.2-rc5h"
SCHEMA_VERSION = "edp-geometric-evaluator-v5.2-rc5h"
ENGINEERING_THRESHOLDS = dict(RC5G_FINAL.ENGINEERING_THRESHOLDS)
PHYSICAL_SUPPORTED_SEMANTICS = RC5G_FINAL.PHYSICAL_SUPPORTED_SEMANTICS
MAX_MATCHED_OFFSET_DISPERSION_FRACTION = (
RC5G_FINAL.MAX_MATCHED_OFFSET_DISPERSION_FRACTION
)
RC3 = RC5G_FINAL.RC5G.RC5F.RC5.RC3
BASE = RC3.BASE
COORDINATE_QUANTISATION_FRACTION = 1.0e-5
COORDINATE_QUANTISATION_ABS = 1.0e-6
GEOMETRY_BINDING_FRACTION = 5.0e-4
DISPLAY_VALUE_QUANTISATION_REL = 1.0e-6
DISPLAY_VALUE_QUANTISATION_ABS = 1.0e-6
TRUE_DUPLICATE_GATE_RATIO = 0.50
def _finite_number(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 _finite_point(value: Any) -> tuple[float, float] | None:
if (
not isinstance(value, Sequence)
or isinstance(value, (str, bytes))
or len(value) < 2
):
return None
first, second = _finite_number(value[0]), _finite_number(value[1])
if first is None or second is None:
return None
return first, second
def _normalised_family(value: Any) -> str | None:
family = str(value or "").casefold()
if family in {"linear", "aligned"}:
return "linear"
if family in {"diameter", "radius"}:
return "circular"
return None
def _normalised_display_value(dimension: Mapping[str, Any]) -> float | None:
value = _finite_number(dimension.get("display_value"))
if value is None:
return None
family = str(dimension.get("family") or "").casefold()
if family == "radius":
value *= 2.0
return abs(value)
def _drawing_diagonal(entities: Mapping[str, Any]) -> float:
"""Return a finite geometry-only scale; DIMENSION placement is ignored."""
try:
bounds = BASE.EV5._safe_bbox(entities)
if bounds is not None:
low, high = bounds
dx = float(high[0]) - float(low[0])
dy = float(high[1]) - float(low[1])
diagonal = math.hypot(dx, dy)
if math.isfinite(diagonal) and diagonal > 0.0:
return max(diagonal, 1.0)
except (AttributeError, IndexError, TypeError, ValueError):
pass
points: list[tuple[float, float]] = []
for dimension in entities.get("dims", []):
if not isinstance(dimension, Mapping):
continue
refs = dimension.get("ref_points")
if not isinstance(refs, Mapping):
continue
for raw in refs.values():
point = _finite_point(raw)
if point is not None:
points.append(point)
if not points:
return 1.0
xs, ys = zip(*points)
diagonal = math.hypot(max(xs) - min(xs), max(ys) - min(ys))
return max(diagonal, 1.0) if math.isfinite(diagonal) else 1.0
def _coordinate_key(point: tuple[float, float], tolerance: float) -> tuple[int, int]:
return int(round(point[0] / tolerance)), int(round(point[1] / tolerance))
def _value_key(value: float) -> tuple[int, int]:
tolerance = max(
DISPLAY_VALUE_QUANTISATION_ABS,
DISPLAY_VALUE_QUANTISATION_REL * max(abs(value), 1.0),
)
# Include the logarithmic tolerance band so values from different scales
# cannot collide merely because each was divided by its own tolerance.
band = int(math.floor(math.log10(tolerance)))
return band, int(round(value / tolerance))
def _point_segment_distance(
point: tuple[float, float], line: Sequence[Any]
) -> float | None:
if len(line) < 4:
return None
ax, ay = _finite_number(line[0]), _finite_number(line[1])
bx, by = _finite_number(line[2]), _finite_number(line[3])
if None in {ax, ay, bx, by}:
return None
dx, dy = float(bx) - float(ax), float(by) - float(ay)
denominator = dx * dx + dy * dy
if denominator <= 1.0e-18:
return math.dist(point, (float(ax), float(ay)))
fraction = (
(point[0] - float(ax)) * dx + (point[1] - float(ay)) * dy
) / denominator
fraction = min(1.0, max(0.0, fraction))
return math.hypot(
point[0] - (float(ax) + fraction * dx),
point[1] - (float(ay) + fraction * dy),
)
def _distance_to_geometry(
point: tuple[float, float], entities: Mapping[str, Any]
) -> float:
distances: list[float] = []
for line in entities.get("lines", []):
if isinstance(line, Sequence) and not isinstance(line, (str, bytes)):
distance = _point_segment_distance(point, line)
if distance is not None and math.isfinite(distance):
distances.append(distance)
for family in ("circles", "arcs"):
for item in entities.get(family, []):
if (
not isinstance(item, Sequence)
or isinstance(item, (str, bytes))
or len(item) < 3
):
continue
cx, cy, radius = (
_finite_number(item[0]),
_finite_number(item[1]),
_finite_number(item[2]),
)
if cx is None or cy is None or radius is None:
continue
radial = math.dist(point, (cx, cy))
distances.extend((abs(radial - abs(radius)), radial))
return min(distances) if distances else math.inf
def _linear_signature(
dimension: Mapping[str, Any],
entities: Mapping[str, Any],
*,
coordinate_tolerance: float,
binding_tolerance: float,
) -> tuple[tuple[Any, ...], dict[str, Any]] | None:
refs = dimension.get("ref_points")
if not isinstance(refs, Mapping):
return None
first = _finite_point(refs.get("defpoint2"))
second = _finite_point(refs.get("defpoint3"))
value = _normalised_display_value(dimension)
if first is None or second is None or value is None:
return None
distances = (
_distance_to_geometry(first, entities),
_distance_to_geometry(second, entities),
)
if any(
not math.isfinite(distance) or distance > binding_tolerance
for distance in distances
):
return None
endpoints = tuple(
sorted(
(
_coordinate_key(first, coordinate_tolerance),
_coordinate_key(second, coordinate_tolerance),
)
)
)
signature = ("linear", _value_key(value), endpoints)
detail = {
"family": "linear",
"normalised_display_value": BASE._round(value),
"geometry": {
"kind": "unordered_reference_endpoint_pair",
"endpoints": [
[
BASE._round(key[0] * coordinate_tolerance),
BASE._round(key[1] * coordinate_tolerance),
]
for key in endpoints
],
},
"binding_max_distance": BASE._round(max(distances)),
}
return signature, detail
def _circular_primitives(
entities: Mapping[str, Any],
) -> list[tuple[float, float, float]]:
result: list[tuple[float, float, float]] = []
for family in ("circles", "arcs"):
for item in entities.get(family, []):
if (
not isinstance(item, Sequence)
or isinstance(item, (str, bytes))
or len(item) < 3
):
continue
cx, cy, radius = (
_finite_number(item[0]),
_finite_number(item[1]),
_finite_number(item[2]),
)
if cx is None or cy is None or radius is None or abs(radius) <= 1.0e-12:
continue
result.append((cx, cy, abs(radius)))
return result
def _circular_signature(
dimension: Mapping[str, Any],
entities: Mapping[str, Any],
*,
coordinate_tolerance: float,
binding_tolerance: float,
) -> tuple[tuple[Any, ...], dict[str, Any]] | None:
refs = dimension.get("ref_points")
if not isinstance(refs, Mapping):
return None
defpoint = _finite_point(refs.get("defpoint"))
defpoint4 = _finite_point(refs.get("defpoint4"))
value = _normalised_display_value(dimension)
if defpoint is None or defpoint4 is None or value is None:
return None
distance = math.dist(defpoint, defpoint4)
if not math.isfinite(distance) or distance <= 1.0e-12:
return None
raw_family = str(dimension.get("family") or "").casefold()
if raw_family == "radius":
inferred_center = defpoint
inferred_radius = distance
elif raw_family == "diameter":
inferred_center = (
0.5 * (defpoint[0] + defpoint4[0]),
0.5 * (defpoint[1] + defpoint4[1]),
)
inferred_radius = 0.5 * distance
else:
return None
candidates: list[tuple[float, tuple[float, float, float], float, float]] = []
for primitive in _circular_primitives(entities):
center_error = math.dist(inferred_center, primitive[:2])
radius_error = abs(inferred_radius - primitive[2])
if center_error <= binding_tolerance and radius_error <= binding_tolerance:
candidates.append(
(center_error + radius_error, primitive, center_error, radius_error)
)
if not candidates:
return None
_, primitive, center_error, radius_error = min(candidates, key=lambda row: row[0])
center_key = _coordinate_key(primitive[:2], coordinate_tolerance)
radius_key = int(round(primitive[2] / coordinate_tolerance))
signature = ("circular", _value_key(value), center_key, radius_key)
detail = {
"family": "circular",
"normalised_display_value": BASE._round(value),
"geometry": {
"kind": "certified_circular_center_radius",
"center": [
BASE._round(center_key[0] * coordinate_tolerance),
BASE._round(center_key[1] * coordinate_tolerance),
],
"radius": BASE._round(radius_key * coordinate_tolerance),
},
"binding_center_error": BASE._round(center_error),
"binding_radius_error": BASE._round(radius_error),
}
return signature, detail
def dimension_duplicate_diagnostics(
entities: Mapping[str, Any],
) -> dict[str, Any]:
"""Return binding-aware true-duplicate diagnostics for native dimensions."""
dimensions = [
item for item in entities.get("dims", []) if isinstance(item, Mapping)
]
diagonal = _drawing_diagonal(entities)
coordinate_tolerance = max(
COORDINATE_QUANTISATION_ABS,
COORDINATE_QUANTISATION_FRACTION * diagonal,
)
binding_tolerance = max(
COORDINATE_QUANTISATION_ABS,
GEOMETRY_BINDING_FRACTION * diagonal,
)
groups: defaultdict[tuple[Any, ...], list[tuple[int, dict[str, Any]]]] = (
defaultdict(list)
)
unresolved: list[int] = []
supported = 0
for index, dimension in enumerate(dimensions):
family = _normalised_family(dimension.get("family"))
if family is None:
unresolved.append(index)
continue
supported += 1
if family == "linear":
row = _linear_signature(
dimension,
entities,
coordinate_tolerance=coordinate_tolerance,
binding_tolerance=binding_tolerance,
)
else:
row = _circular_signature(
dimension,
entities,
coordinate_tolerance=coordinate_tolerance,
binding_tolerance=binding_tolerance,
)
if row is None:
unresolved.append(index)
continue
signature, detail = row
groups[signature].append((index, detail))
duplicate_groups: list[dict[str, Any]] = []
duplicate_count = 0
for rows in groups.values():
if len(rows) < 2:
continue
duplicate_count += len(rows) - 1
detail = copy.deepcopy(rows[0][1])
detail.update(
{
"dimension_indices": [int(index) for index, _ in rows],
"count": len(rows),
"duplicate_extras": len(rows) - 1,
}
)
duplicate_groups.append(detail)
duplicate_groups.sort(key=lambda row: row["dimension_indices"])
ratio = duplicate_count / max(len(dimensions), 1)
return {
"policy": "binding_aware_geometry_signature_v1",
"n_dimensions": len(dimensions),
"n_supported_family": supported,
"n_bound_signatures": sum(len(rows) for rows in groups.values()),
"unresolved_dimension_count": len(unresolved),
"unresolved_dimension_indices": unresolved,
"true_duplicate_dimension_count": duplicate_count,
"true_duplicate_dimension_ratio": BASE._round(ratio),
"duplicate_groups": duplicate_groups,
"drawing_diagonal": BASE._round(diagonal),
"coordinate_quantisation_tolerance": BASE._round(
coordinate_tolerance, 9
),
"geometry_binding_tolerance": BASE._round(binding_tolerance, 9),
"unresolved_is_never_duplicate_by_value_alone": True,
"dimension_line_or_label_placement_is_ignored": True,
}
def _number(value: Any, default: float = 0.0) -> float:
number = _finite_number(value)
return number if number is not None else default
def _update_anti_hack(
anti_hack: Mapping[str, Any], diagnostics: Mapping[str, Any]
) -> dict[str, Any]:
result = copy.deepcopy(dict(anti_hack))
old_count = _number(result.get("true_duplicate_dimension_count"))
old_ratio = _number(result.get("true_duplicate_dimension_ratio"))
true_count = int(diagnostics["true_duplicate_dimension_count"])
true_ratio = float(diagnostics["true_duplicate_dimension_ratio"])
unmatched_count = _number(result.get("unmatched_dimension_count"))
unmatched_ratio = _number(result.get("unmatched_dimension_ratio"))
spam_count = max(float(true_count), unmatched_count)
spam_ratio = max(true_ratio, unmatched_ratio)
result.update(
{
"same_semantic_value_repeat_count": old_count,
"same_semantic_value_repeat_ratio": BASE._round(old_ratio),
"same_semantic_value_repeat_scope": "scale_consistency_vote_balancing_only",
"true_duplicate_dimension_count": true_count,
"true_duplicate_dimension_ratio": BASE._round(true_ratio),
"dimension_spam_count": spam_count,
"dimension_spam_ratio": BASE._round(spam_ratio),
# Backwards-compatible aliases retain v5.1's broad spam channel;
# structure reads only true_duplicate_dimension_ratio.
"duplicate_dimension_count": spam_count,
"duplicate_dimension_ratio": BASE._round(spam_ratio),
"true_duplicate_dimension_policy": diagnostics["policy"],
"true_duplicate_dimension_diagnostics": copy.deepcopy(
dict(diagnostics)
),
}
)
flags = [
str(flag)
for flag in result.get("flags", [])
if str(flag) != "true_duplicate_dimension_spam"
]
if true_ratio >= TRUE_DUPLICATE_GATE_RATIO:
flags.append("true_duplicate_dimension_spam")
result["flags"] = list(dict.fromkeys(flags))
return result
def _corrected_structure(
original: Mapping[str, Any],
anti_hack: Mapping[str, Any],
diagnostics: Mapping[str, Any],
) -> dict[str, Any]:
if not original.get("eligible") or not isinstance(original.get("details"), Mapping):
return copy.deepcopy(dict(original))
details = copy.deepcopy(dict(original["details"]))
readable = bool(details.get("readable"))
nondegenerate = bool(details.get("nondegenerate"))
accounting_ok = bool(details.get("all_extra_clusters_accounted_for"))
unsupported = int(_number(details.get("unsupported_geometry_like")))
predicted_inventory = int(_number(details.get("predicted_annotation_inventory")))
severe_limit = int(_number(details.get("severe_annotation_spam_limit")))
severe_spam = predicted_inventory > severe_limit
duplicate_ratio = _number(anti_hack.get("true_duplicate_dimension_ratio"))
valid = bool(
readable
and nondegenerate
and accounting_ok
and unsupported == 0
and duplicate_ratio < TRUE_DUPLICATE_GATE_RATIO
and not severe_spam
)
flags = [
name
for name, active in (
("unreadable_or_degenerate", not (readable and nondegenerate)),
("extra_cluster_accounting_incomplete", not accounting_ok),
("unsupported_geometry_like", unsupported > 0),
(
"true_duplicate_dimension_spam",
duplicate_ratio >= TRUE_DUPLICATE_GATE_RATIO,
),
("severe_dimension_or_text_spam", severe_spam),
)
if active
]
details.update(
{
"flags": flags,
"true_duplicate_dimension_count": int(
diagnostics["true_duplicate_dimension_count"]
),
"true_duplicate_dimension_ratio": BASE._round(duplicate_ratio),
"true_duplicate_dimension_policy": diagnostics["policy"],
"same_semantic_value_repeat_count": anti_hack.get(
"same_semantic_value_repeat_count"
),
"same_semantic_value_repeat_ratio": anti_hack.get(
"same_semantic_value_repeat_ratio"
),
"semantic_value_groups_are_scale_only": True,
"unresolved_dimensions_are_fail_open_for_duplicate_identity": True,
}
)
return BASE._component(
1.0 if valid else 0.0,
True,
"ok" if valid else "independent_validity_or_anti_hack_gate_failed",
**details,
)
def _rescore_downstream(result: dict[str, Any]) -> None:
components = result.get("components")
prompt = result.get("online_reward_prompt_masked")
prompt_components = prompt.get("components") if isinstance(prompt, Mapping) else None
if not isinstance(components, dict) or not isinstance(prompt_components, dict):
return
atomic = result.get("diagnostics", {}).get("atomic_geometry", {})
if not isinstance(atomic, Mapping):
atomic = {}
result["verified_reward_full_gt"] = RC3._scoped_hierarchical_reward(
components,
atomic,
scope="offline_full_gt_executed_dxf",
)
prompt_reward = RC3._scoped_hierarchical_reward(
prompt_components,
atomic,
scope="prompt_masked_actual_geometry",
)
result["online_reward_prompt_masked"] = {
**prompt_reward,
"components": prompt_components,
}
result["benchmark"] = RC3._benchmark(components)
result["engineering_success"] = result["benchmark"]["engineering_success"]
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 = RC5G_FINAL.score_dxf_pair(
pred,
gt,
sidecar=sidecar,
category=category,
**kwargs,
)
result["schema_version"] = SCHEMA_VERSION
result["metric_version"] = METRIC_VERSION
result.setdefault("metric_definition", {})[
"true_duplicate_dimension_policy"
] = {
"identity": "normalised_family_value_plus_bound_geometry_signature",
"linear_aligned_geometry": "unordered_quantised_defpoint2_defpoint3",
"diameter_radius_geometry": "certified_quantised_circle_center_radius",
"radius_value_is_converted_to_diameter_equivalent": True,
"ev43_semantic_value_groups": "scale_consistency_only",
"unresolved_binding_policy": "never_true_duplicate_by_value_alone",
"structure_gate_ratio": TRUE_DUPLICATE_GATE_RATIO,
"continuous_component_definitions_changed": False,
}
try:
raw_pred = BASE.EV5._extract_entities(Path(pred))
except Exception as exc: # preserve rc5g's invalid-prediction result
result.setdefault("diagnostics", {})["rc5h_dimension_identity"] = {
"applied": False,
"reason": "prediction_dimension_extraction_failed",
"exception_type": type(exc).__name__,
}
release = result.get("diagnostics", {}).get("release_status")
if isinstance(release, dict):
release["candidate"] = METRIC_VERSION
return result
diagnostics = dimension_duplicate_diagnostics(raw_pred)
result.setdefault("diagnostics", {})["rc5h_dimension_identity"] = {
"applied": True,
**copy.deepcopy(diagnostics),
}
anti_hack = _update_anti_hack(result.get("anti_hack", {}), diagnostics)
result["anti_hack"] = anti_hack
components = result.get("components")
if isinstance(components, dict) and isinstance(components.get("structure"), Mapping):
corrected = _corrected_structure(
components["structure"], anti_hack, diagnostics
)
components["structure"] = corrected
prompt = result.get("online_reward_prompt_masked")
if isinstance(prompt, dict) and isinstance(prompt.get("components"), dict):
prompt["components"]["structure"] = copy.deepcopy(corrected)
_rescore_downstream(result)
release = result.get("diagnostics", {}).get("release_status")
if isinstance(release, dict):
release["candidate"] = METRIC_VERSION
return result
__all__ = [
"COORDINATE_QUANTISATION_FRACTION",
"ENGINEERING_THRESHOLDS",
"MAX_MATCHED_OFFSET_DISPERSION_FRACTION",
"METRIC_VERSION",
"PHYSICAL_SUPPORTED_SEMANTICS",
"SCHEMA_VERSION",
"TRUE_DUPLICATE_GATE_RATIO",
"dimension_duplicate_diagnostics",
"score_dxf_pair",
]