File size: 23,538 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | #!/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",
]
|