File size: 67,636 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 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 | #!/usr/bin/env python3
"""Layered, diagnostic benchmark for executed ezdxf predictions.
Metric v5 intentionally consumes *DXF files after code execution*. It does not
execute generated Python and it does not replace any v2--v4.4 metric. Its public
entry point, :func:`score_dxf_pair`, separates six engineering concerns so a
failed sample can be attributed to a concrete stage instead of being hidden in
one weighted average.
The evaluator is invariant to a whole-sheet translation and positive uniform
scale. Collinear touching LINE fragments are canonicalised before geometry and
view scoring. Crucially, an unobservable or unsupported target property is
reported as ``eligible=False, score=None``; unknown is never silently converted
to zero.
"""
from __future__ import annotations
import math
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable, Mapping, Sequence
import ezdxf
import numpy as np
from scipy.optimize import linear_sum_assignment
try: # package imports used by tests
from . import eval_geometric02 as EV2
from . import eval_geometric03 as EV3
from . import eval_geometric04 as EV4
from . import eval_geometric043 as EV43
from . import eval_geometric044 as EV44
except ImportError: # direct import used by evaluator/reward workers
import eval_geometric02 as EV2
import eval_geometric03 as EV3
import eval_geometric04 as EV4
import eval_geometric043 as EV43
import eval_geometric044 as EV44
SUPPORTED_GEOMETRY = {"LINE", "CIRCLE", "ARC", "LWPOLYLINE", "POLYLINE"}
DIMENSION_FAMILIES = {"linear", "aligned", "diameter", "radius"}
VIEW_TARGET_COUNT = 3
VIEW_MERGE_TOL_FRAC = 0.003
DIM_BIND_TOL_FRAC = 0.03
PHYSICAL_LOG_DECAY = 0.10
LAYOUT_DECAY = 0.15
ENGINEERING_THRESHOLDS = {
"structure": 0.80,
"view": 0.98,
"geometry": 0.90,
"physical": 0.90,
"annotation": 0.90,
"layout": 0.85,
}
def _clip(value: float) -> float:
return float(min(1.0, max(0.0, value)))
def _round(value: float | None, digits: int = 6) -> float | None:
return round(float(value), digits) if value is not None and math.isfinite(float(value)) else None
def _component(
score: float | None,
eligible: bool,
reason: str,
**details: Any,
) -> dict[str, Any]:
"""Create a stable component record while enforcing unknown != zero."""
if not eligible:
score = None
elif score is None:
raise ValueError("an eligible component must have a numeric score")
return {
"score": _round(_clip(float(score))) if score is not None else None,
"eligible": bool(eligible),
"reason": str(reason),
"details": details,
}
def _empty_entities() -> dict[str, list[Any]]:
return {"lines": [], "circles": [], "arcs": [], "dims": []}
def _extract_entities(path: str | Path) -> dict[str, Any] | None:
"""Extract v4 primitives plus legal 2D polyline virtual primitives.
The historical extractor intentionally handled only LINE/CIRCLE/ARC. A
candidate may encode the exact same outline as a LWPOLYLINE/POLYLINE,
however, so treating that representation as empty would make the metric
depend on code style rather than engineering geometry.
"""
entities = EV4.extract_entities(path)
if entities is None:
return None
try:
doc = ezdxf.readfile(str(path))
except Exception:
return None
for parent in doc.modelspace():
if parent.dxftype() not in {"LWPOLYLINE", "POLYLINE"}:
continue
layer = parent.dxf.layer if parent.dxf.hasattr("layer") else "0"
try:
virtual_entities = parent.virtual_entities()
except Exception:
continue
for entity in virtual_entities:
entity_type = entity.dxftype()
if entity_type == "LINE":
entities["lines"].append(
(
float(entity.dxf.start.x),
float(entity.dxf.start.y),
float(entity.dxf.end.x),
float(entity.dxf.end.y),
layer,
)
)
elif entity_type == "ARC":
entities["arcs"].append(
(
float(entity.dxf.center.x),
float(entity.dxf.center.y),
float(entity.dxf.radius),
float(entity.dxf.start_angle),
float(entity.dxf.end_angle),
layer,
)
)
return entities
def _n_geometry(entities: Mapping[str, Any] | None) -> int:
if not entities:
return 0
return sum(len(entities.get(key, [])) for key in ("lines", "circles", "arcs"))
def _safe_bbox(entities: Mapping[str, Any] | None) -> tuple[np.ndarray, np.ndarray] | None:
if not entities:
return None
points = EV3.collect_alignment_points(dict(entities))
if not len(points) or not np.isfinite(points).all():
return None
return points.min(axis=0), points.max(axis=0)
def _bbox_center_size(entities: Mapping[str, Any]) -> tuple[np.ndarray, np.ndarray] | None:
bounds = _safe_bbox(entities)
if bounds is None:
return None
low, high = bounds
return 0.5 * (low + high), np.maximum(high - low, 0.0)
def _looks_like_dimension_text(entity: Any) -> bool:
if entity.dxftype() not in {"TEXT", "MTEXT"}:
return False
layer = str(entity.dxf.layer if entity.dxf.hasattr("layer") else "").lower()
try:
text = entity.plain_text() if entity.dxftype() == "MTEXT" else str(entity.dxf.text)
except Exception:
text = ""
stripped = text.strip().replace(" ", "")
starts_numeric = bool(stripped) and (stripped[0].isdigit() or stripped[0] in "+-.RrØ⌀")
return "dim" in layer or "anno" in layer or starts_numeric or "%%c" in stripped.lower()
def _read_structure(path: str | Path) -> dict[str, Any]:
"""Read file-level structure independently from the primitive extractor."""
try:
doc = ezdxf.readfile(str(path))
except Exception as exc:
return {
"readable": False,
"error": f"{type(exc).__name__}: {exc}",
"entity_type_counts": {},
"modelspace_entities": 0,
"native_dimensions": 0,
"dimension_like_text": 0,
"supported_geometry": 0,
"unsupported_geometry_like": 0,
}
counts: Counter[str] = Counter()
native_dimensions = 0
dimension_text = 0
supported = 0
unsupported_geometry = 0
unsupported_names = {
"LWPOLYLINE", "POLYLINE", "SPLINE", "ELLIPSE", "HATCH", "SOLID", "TRACE"
}
for entity in doc.modelspace():
name = entity.dxftype()
counts[name] += 1
if name in SUPPORTED_GEOMETRY:
supported += 1
elif name in unsupported_names:
unsupported_geometry += 1
if name == "DIMENSION":
native_dimensions += 1
elif _looks_like_dimension_text(entity):
dimension_text += 1
return {
"readable": True,
"error": None,
"entity_type_counts": dict(sorted(counts.items())),
"modelspace_entities": int(sum(counts.values())),
"native_dimensions": int(native_dimensions),
"dimension_like_text": int(dimension_text),
"supported_geometry": int(supported),
"unsupported_geometry_like": int(unsupported_geometry),
}
def _primitive_records(entities: Mapping[str, Any]) -> list[dict[str, Any]]:
records: list[dict[str, Any]] = []
for family in ("lines", "circles", "arcs"):
for index, primitive in enumerate(entities.get(family, [])):
if family == "lines":
xs = [float(primitive[0]), float(primitive[2])]
ys = [float(primitive[1]), float(primitive[3])]
elif family == "circles":
cx, cy, radius = map(float, primitive[:3])
radius = abs(radius)
xs = [cx - radius, cx + radius]
ys = [cy - radius, cy + radius]
else:
cx, cy, radius = map(float, primitive[:3])
radius = abs(radius)
start = float(primitive[3]) % 360.0
end = float(primitive[4]) % 360.0
sweep = (end - start) % 360.0
if sweep <= 1e-12:
angles = [0.0, 90.0, 180.0, 270.0]
else:
angles = [start, end]
angles.extend(
angle
for angle in (0.0, 90.0, 180.0, 270.0)
if (angle - start) % 360.0 <= sweep + 1e-12
)
points = [
(
cx + radius * math.cos(math.radians(angle)),
cy + radius * math.sin(math.radians(angle)),
)
for angle in angles
]
xs = [point[0] for point in points]
ys = [point[1] for point in points]
low = np.asarray([min(xs), min(ys)], dtype=float)
high = np.asarray([max(xs), max(ys)], dtype=float)
records.append(
{
"family": family,
"index": index,
"primitive": primitive,
"low": low,
"high": high,
"center": 0.5 * (low + high),
}
)
return records
def _box_distance(first: Mapping[str, Any], second: Mapping[str, Any]) -> float:
gap = np.maximum(0.0, np.maximum(first["low"] - second["high"], second["low"] - first["high"]))
return float(np.linalg.norm(gap))
def _cluster_views(entities: Mapping[str, Any]) -> list[dict[str, Any]]:
"""Group spatially disjoint primitive components without forcing three.
Not forcing ``k=3`` is important: a missing view must remain observable
rather than being manufactured by splitting one existing view.
"""
records = _primitive_records(entities)
if not records:
return []
all_low = np.min(np.stack([item["low"] for item in records]), axis=0)
all_high = np.max(np.stack([item["high"] for item in records]), axis=0)
diagonal = max(float(np.linalg.norm(all_high - all_low)), 1.0)
tolerance = VIEW_MERGE_TOL_FRAC * diagonal
parent = list(range(len(records)))
def find(index: int) -> int:
while parent[index] != index:
parent[index] = parent[parent[index]]
index = parent[index]
return index
def union(first: int, second: int) -> bool:
first_root, second_root = find(first), find(second)
if first_root == second_root:
return False
parent[second_root] = first_root
return True
for first in range(len(records)):
for second in range(first + 1, len(records)):
if _box_distance(records[first], records[second]) <= tolerance:
union(first, second)
# Once an outline is connected, its aggregate bbox also absorbs contained
# circles, hidden edges and centre marks that do not touch the boundary.
changed = True
while changed:
groups: dict[int, list[int]] = defaultdict(list)
for index in range(len(records)):
groups[find(index)].append(index)
roots = list(groups)
boxes: dict[int, dict[str, np.ndarray]] = {}
for root, indices in groups.items():
boxes[root] = {
"low": np.min(np.stack([records[index]["low"] for index in indices]), axis=0),
"high": np.max(np.stack([records[index]["high"] for index in indices]), axis=0),
}
changed = False
for first_pos, first in enumerate(roots):
for second in roots[first_pos + 1 :]:
if _box_distance(boxes[first], boxes[second]) <= tolerance:
changed |= union(first, second)
groups = defaultdict(list)
for index in range(len(records)):
groups[find(index)].append(index)
views: list[dict[str, Any]] = []
for indices in groups.values():
view_entities = _empty_entities()
lows, highs = [], []
for index in indices:
record = records[index]
view_entities[record["family"]].append(record["primitive"])
lows.append(record["low"])
highs.append(record["high"])
low = np.min(np.stack(lows), axis=0)
high = np.max(np.stack(highs), axis=0)
views.append(
{
"entities": view_entities,
"low": low,
"high": high,
"center": 0.5 * (low + high),
"size": high - low,
"n_primitives": len(indices),
}
)
return sorted(views, key=lambda view: (float(view["center"][0]), float(view["center"][1])))
def _views_from_reference_boxes(
entities: Mapping[str, Any],
definitions: Sequence[Mapping[str, Any]],
source_center: np.ndarray,
target_center: np.ndarray,
scale: float,
) -> list[dict[str, Any]]:
"""Partition primitives by audited target view boxes after sheet alignment.
This groups disconnected holes/arcs with their surrounding orthographic
view. Empty buckets remain absent, so a missing predicted view is still a
known failure. Geometry outside every audited view becomes one additional
bucket rather than disappearing from precision/structure diagnostics.
"""
records = _primitive_records(entities)
if not records or len(definitions) != VIEW_TARGET_COUNT:
return _cluster_views(entities)
boxes = []
for definition in definitions:
bbox = definition.get("bbox")
if not isinstance(bbox, Sequence) or len(bbox) != 4:
return _cluster_views(entities)
x0, y0, x1, y1 = map(float, bbox)
low = np.asarray([min(x0, x1), min(y0, y1)], dtype=float)
high = np.asarray([max(x0, x1), max(y0, y1)], dtype=float)
boxes.append((low, high, 0.5 * (low + high)))
sheet_low = np.min(np.stack([item[0] for item in boxes]), axis=0)
sheet_high = np.max(np.stack([item[1] for item in boxes]), axis=0)
tolerance = 1e-6 * max(float(np.linalg.norm(sheet_high - sheet_low)), 1.0)
groups: list[list[int]] = [[] for _ in boxes]
outside: list[int] = []
for index, record in enumerate(records):
aligned_bounds = EV2.transform_points(
np.asarray([record["low"], record["high"]], dtype=float),
source_center,
target_center,
scale,
)
aligned_low = np.min(aligned_bounds, axis=0)
aligned_high = np.max(aligned_bounds, axis=0)
aligned = 0.5 * (aligned_low + aligned_high)
candidates = [
box_index
for box_index, (low, high, _) in enumerate(boxes)
if float(
np.linalg.norm(
np.maximum(0.0, np.maximum(low - aligned_high, aligned_low - high))
)
)
<= tolerance
]
if candidates:
selected = min(
candidates,
key=lambda box_index: (
-float(
np.linalg.norm(
np.maximum(
0.0,
np.minimum(aligned_high, boxes[box_index][1])
- np.maximum(aligned_low, boxes[box_index][0]),
)
)
),
float(np.linalg.norm(aligned - boxes[box_index][2])),
),
)
groups[selected].append(index)
else:
outside.append(index)
if outside:
groups.append(outside)
views: list[dict[str, Any]] = []
for indices in groups:
if not indices:
continue
view_entities = _empty_entities()
lows, highs = [], []
for index in indices:
record = records[index]
view_entities[record["family"]].append(record["primitive"])
lows.append(record["low"])
highs.append(record["high"])
low = np.min(np.stack(lows), axis=0)
high = np.max(np.stack(highs), axis=0)
views.append(
{
"entities": view_entities,
"low": low,
"high": high,
"center": 0.5 * (low + high),
"size": high - low,
"n_primitives": len(indices),
}
)
return sorted(views, key=lambda view: (float(view["center"][0]), float(view["center"][1])))
def _count_f1(predicted: int, target: int) -> float:
if predicted == 0 and target == 0:
return 1.0
if predicted == 0 or target == 0:
return 0.0
matched = min(predicted, target)
precision, recall = matched / predicted, matched / target
return 2.0 * precision * recall / (precision + recall)
def _normalise_centers(views: Sequence[Mapping[str, Any]]) -> np.ndarray:
if not views:
return np.empty((0, 2), dtype=float)
points = np.stack([np.asarray(view["center"], dtype=float) for view in views])
center = points.mean(axis=0)
radii = np.linalg.norm(points - center, axis=1)
scale = float(np.sqrt(np.mean(radii**2))) if len(points) > 1 else 1.0
return (points - center) / max(scale, 1e-12)
def _layout_pairs(
predicted: Sequence[Mapping[str, Any]], target: Sequence[Mapping[str, Any]]
) -> tuple[list[tuple[int, int]], np.ndarray]:
pred_centers = _normalise_centers(predicted)
gt_centers = _normalise_centers(target)
if not len(pred_centers) or not len(gt_centers):
return [], np.empty((len(pred_centers), len(gt_centers)), dtype=float)
distances = np.linalg.norm(pred_centers[:, None] - gt_centers[None, :], axis=2)
rows, columns = linear_sum_assignment(distances)
return [(int(row), int(column)) for row, column in zip(rows, columns)], distances
def _geometry_pair_matrix(
predicted: Sequence[Mapping[str, Any]],
target: Sequence[Mapping[str, Any]],
global_scale: float,
layout_distances: np.ndarray,
) -> tuple[list[tuple[int, int]], dict[tuple[int, int], dict[str, Any]]]:
if not predicted or not target:
return [], {}
quality = np.zeros((len(predicted), len(target)), dtype=float)
details: dict[tuple[int, int], dict[str, Any]] = {}
for pred_index, pred_view in enumerate(predicted):
for gt_index, gt_view in enumerate(target):
pred_entities = pred_view["entities"]
gt_entities = gt_view["entities"]
source_center = np.asarray(pred_view["center"], dtype=float)
target_center = np.asarray(gt_view["center"], dtype=float)
diagonal = max(float(np.linalg.norm(gt_view["size"])), 1.0)
strict = EV3.score_geometry(
pred_entities,
gt_entities,
source_center,
target_center,
global_scale,
diagonal,
)
dense = EV3.dense_geometry_score(
pred_entities,
gt_entities,
source_center,
target_center,
global_scale,
diagonal,
)
quality[pred_index, gt_index] = float(dense)
details[(pred_index, gt_index)] = {
"strict": strict,
"dense": float(dense),
}
# The tiny layout tie break stabilises symmetric/equal-shape drawings but
# cannot override a meaningful shape difference.
tie_break = layout_distances if layout_distances.shape == quality.shape else np.zeros_like(quality)
rows, columns = linear_sum_assignment(-quality + 1e-6 * tie_break)
return [(int(row), int(column)) for row, column in zip(rows, columns)], details
def _aggregate_geometry(
pairs: Sequence[tuple[int, int]],
pair_details: Mapping[tuple[int, int], Mapping[str, Any]],
n_pred: int,
n_gt: int,
) -> dict[str, Any]:
denominator = max(n_pred, n_gt, 1)
strict_sum = dense_sum = visible_sum = 0.0
hidden_sum = 0.0
hidden_eligible = False
circles_sum = arcs_sum = 0.0
circles_eligible = arcs_eligible = False
pair_rows = []
for pred_index, gt_index in pairs:
item = pair_details[(pred_index, gt_index)]
strict = item["strict"]
dense_sum += float(item["dense"])
strict_sum += float(strict["score"])
visible_sum += float(strict["lines"]["f1"])
if strict["hidden"]["present"]:
hidden_eligible = True
hidden_sum += float(strict["hidden"]["f1"])
if strict["circles"]["n_pred"] or strict["circles"]["n_gt"]:
circles_eligible = True
circles_sum += float(strict["circles"]["match_f1"])
if strict["arcs"]["n_pred"] or strict["arcs"]["n_gt"]:
arcs_eligible = True
arcs_sum += float(strict["arcs"]["match_f1"])
pair_rows.append(
{
"pred_view": pred_index,
"gt_view": gt_index,
"strict": _round(float(strict["score"])),
"dense": _round(float(item["dense"])),
}
)
return {
"score": dense_sum / denominator,
"strict_score": strict_sum / denominator,
"visible_edge_f1": visible_sum / denominator,
"hidden_edge_f1": hidden_sum / denominator if hidden_eligible else None,
"hidden_eligible": hidden_eligible,
"circle_f1": circles_sum / denominator if circles_eligible else None,
"circle_eligible": circles_eligible,
"arc_f1": arcs_sum / denominator if arcs_eligible else None,
"arc_eligible": arcs_eligible,
"pairs": pair_rows,
}
def _layout_component(
predicted: Sequence[Mapping[str, Any]],
target: Sequence[Mapping[str, Any]],
layout_pairs: Sequence[tuple[int, int]],
distances: np.ndarray,
) -> dict[str, Any]:
if len(target) != VIEW_TARGET_COUNT:
return _component(
None,
False,
"target_view_partition_not_three",
pred_view_count=len(predicted),
gt_view_count=len(target),
)
if not predicted:
return _component(
0.0,
True,
"prediction_has_no_views",
pred_view_count=0,
gt_view_count=len(target),
matched_error=None,
)
errors = [float(distances[pred, gt]) for pred, gt in layout_pairs]
mean_error = float(np.mean(errors)) if errors else math.inf
count_quality = _count_f1(len(predicted), len(target))
score = count_quality * math.exp(-mean_error / LAYOUT_DECAY)
return _component(
score,
True,
"ok",
pred_view_count=len(predicted),
gt_view_count=len(target),
count_f1=_round(count_quality),
matched_error=_round(mean_error),
pairs=[{"pred_view": pred, "gt_view": gt} for pred, gt in layout_pairs],
)
def _view_component(
predicted: Sequence[Mapping[str, Any]],
target: Sequence[Mapping[str, Any]],
geometry_pairs: Sequence[tuple[int, int]],
layout_pairs: Sequence[tuple[int, int]],
) -> dict[str, Any]:
if len(target) != VIEW_TARGET_COUNT:
return _component(
None,
False,
"target_view_partition_not_three",
pred_view_count=len(predicted),
gt_view_count=len(target),
expected_view_count=VIEW_TARGET_COUNT,
role_eligible=False,
role_accuracy=None,
)
count_quality = _count_f1(len(predicted), len(target))
geometry_map = {pred: gt for pred, gt in geometry_pairs}
layout_map = {pred: gt for pred, gt in layout_pairs}
common = sorted(set(geometry_map) & set(layout_map))
role_accuracy = (
sum(geometry_map[index] == layout_map[index] for index in common) / len(target)
if common
else 0.0
)
score = count_quality * (0.5 + 0.5 * role_accuracy)
reason = "ok" if len(predicted) == VIEW_TARGET_COUNT else "prediction_view_count_mismatch"
return _component(
score,
True,
reason,
pred_view_count=len(predicted),
gt_view_count=len(target),
expected_view_count=VIEW_TARGET_COUNT,
count_f1=_round(count_quality),
role_eligible=True,
role_accuracy=_round(role_accuracy),
role_definition="agreement_between_shape_identity_and_sheet_position",
)
def _normalise_sidecar_views(sidecar: Mapping[str, Any] | None) -> list[dict[str, Any]]:
if not isinstance(sidecar, Mapping):
return []
raw = sidecar.get("views")
result: list[dict[str, Any]] = []
if isinstance(raw, Mapping) and isinstance(raw.get("candidates"), Sequence):
iterable = [
dict(value)
for value in raw.get("candidates", [])
if isinstance(value, Mapping)
]
elif isinstance(raw, Mapping):
iterable = []
for name, value in raw.items():
item = dict(value) if isinstance(value, Mapping) else {}
item.setdefault("name", str(name))
iterable.append(item)
elif isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)):
iterable = [dict(value) for value in raw if isinstance(value, Mapping)]
else:
iterable = []
for index, item in enumerate(iterable):
bbox = item.get("bbox") or item.get("bounds")
if not (isinstance(bbox, Sequence) and len(bbox) == 4):
geometry_bbox = item.get("geometry_bbox")
if isinstance(geometry_bbox, Mapping):
minimum = geometry_bbox.get("min")
maximum = geometry_bbox.get("max")
if (
isinstance(minimum, Sequence)
and isinstance(maximum, Sequence)
and len(minimum) >= 2
and len(maximum) >= 2
):
bbox = [minimum[0], minimum[1], maximum[0], maximum[1]]
if isinstance(bbox, Sequence) and len(bbox) == 4:
result.append(
{
"name": str(item.get("name") or item.get("id") or index),
"bbox": tuple(float(value) for value in bbox),
}
)
return result
def _target_view_names(
views: Sequence[Mapping[str, Any]], sidecar: Mapping[str, Any] | None
) -> dict[int, str]:
definitions = _normalise_sidecar_views(sidecar)
if not definitions:
return {}
names: dict[int, str] = {}
used: set[str] = set()
for index, view in enumerate(views):
center = view["center"]
candidates = []
for definition in definitions:
x0, y0, x1, y1 = definition["bbox"]
if min(x0, x1) <= center[0] <= max(x0, x1) and min(y0, y1) <= center[1] <= max(y0, y1):
candidates.append(definition["name"])
if len(candidates) == 1 and candidates[0] not in used:
names[index] = candidates[0]
used.add(candidates[0])
return names
def _measurement(entities: Mapping[str, Any], kind: str, index: int = 0) -> float | None:
bounds = _bbox_center_size(entities)
if bounds is None:
return None
_, size = bounds
if kind == "bbox_width":
return float(size[0])
if kind == "bbox_height":
return float(size[1])
if kind == "bbox_diagonal":
return float(np.linalg.norm(size))
if kind in {"circle_radius", "circle_diameter"}:
values = sorted(abs(float(item[2])) for item in entities.get("circles", []))
if not 0 <= index < len(values):
return None
return values[index] * (2.0 if kind == "circle_diameter" else 1.0)
if kind == "arc_radius":
values = sorted(abs(float(item[2])) for item in entities.get("arcs", []))
return values[index] if 0 <= index < len(values) else None
if kind == "line_length":
values = sorted(math.dist(item[:2], item[2:4]) for item in entities.get("lines", []))
return values[index] if 0 <= index < len(values) else None
return None
def _parameter_diagnostics(
sidecar: Mapping[str, Any] | None,
pred_views: Sequence[Mapping[str, Any]],
gt_views: Sequence[Mapping[str, Any]],
target_names: Mapping[int, str],
geometry_pairs: Sequence[tuple[int, int]],
global_scale: float,
) -> dict[str, Any]:
if not isinstance(sidecar, Mapping):
return {"eligible": False, "score": None, "reason": "no_sidecar_parameters", "items": []}
raw = sidecar.get("physical_parameters", sidecar.get("parameters"))
if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)) or not raw:
return {"eligible": False, "score": None, "reason": "no_sidecar_parameters", "items": []}
name_to_gt = {name: index for index, name in target_names.items()}
gt_to_pred = {gt: pred for pred, gt in geometry_pairs}
items = []
qualities = []
for position, spec_value in enumerate(raw):
if not isinstance(spec_value, Mapping):
items.append({"name": str(position), "eligible": False, "reason": "invalid_spec"})
continue
spec = dict(spec_value)
name = str(spec.get("name") or spec.get("id") or position)
kind = str(spec.get("kind") or spec.get("measurement") or "")
view_value = spec.get("view", spec.get("view_id", 0))
if isinstance(view_value, str):
gt_index = name_to_gt.get(view_value)
else:
try:
gt_index = int(view_value)
except Exception:
gt_index = None
try:
item_index = int(spec.get("index", 0))
except Exception:
item_index = 0
if gt_index is None or not 0 <= gt_index < len(gt_views):
items.append({"name": name, "kind": kind, "eligible": False, "reason": "unknown_view"})
continue
pred_index = gt_to_pred.get(gt_index)
if pred_index is None:
items.append({"name": name, "kind": kind, "eligible": True, "score": 0.0, "reason": "missing_predicted_view"})
qualities.append(0.0)
continue
gt_value = _measurement(gt_views[gt_index]["entities"], kind, item_index)
pred_value = _measurement(pred_views[pred_index]["entities"], kind, item_index)
if gt_value is None or pred_value is None or gt_value <= 1e-12:
items.append({"name": name, "kind": kind, "eligible": False, "reason": "unsupported_or_missing_measurement"})
continue
aligned_pred = pred_value * global_scale
relative_error = abs(aligned_pred / gt_value - 1.0)
quality = math.exp(-relative_error / 0.05)
qualities.append(quality)
items.append(
{
"name": name,
"kind": kind,
"eligible": True,
"score": _round(quality),
"predicted_drawing_value_aligned": _round(aligned_pred),
"target_drawing_value": _round(gt_value),
"declared_physical_value": spec.get("value", spec.get("target_value")),
"relative_error": _round(relative_error),
"within_1pct": relative_error <= 0.01,
"within_5pct": relative_error <= 0.05,
"within_10pct": relative_error <= 0.10,
}
)
if not qualities:
return {"eligible": False, "score": None, "reason": "no_supported_parameters", "items": items}
return {
"eligible": True,
"score": _round(float(np.mean(qualities))),
"reason": "ok",
"n_eligible": len(qualities),
"n_declared": len(raw),
"items": items,
}
def _physical_component(
predicted: Sequence[Mapping[str, Any]],
target: Sequence[Mapping[str, Any]],
geometry_pairs: Sequence[tuple[int, int]],
global_scale: float,
*,
raw_pred: Mapping[str, Any],
raw_gt: Mapping[str, Any],
sidecar: Mapping[str, Any] | None,
category: str | None,
annotation_diagnostics: Mapping[str, Any],
) -> dict[str, Any]:
if len(target) != VIEW_TARGET_COUNT:
return _component(
None,
False,
"target_view_partition_not_three",
scale_invariant_extent_score=None,
fmfs={"eligible": False, "score": None, "reason": "view_partition_unavailable", "items": []},
parameters={"eligible": False, "score": None, "reason": "view_partition_unavailable", "items": []},
category_semantics={"eligible": False, "score": None, "reason": "view_partition_unavailable"},
)
denominator = max(len(predicted), len(target), 1)
qualities = []
errors = []
for pred_index, gt_index in geometry_pairs:
pred_size = np.asarray(predicted[pred_index]["size"], dtype=float) * global_scale
gt_size = np.asarray(target[gt_index]["size"], dtype=float)
valid = gt_size > max(1e-9, 1e-6 * max(float(np.linalg.norm(gt_size)), 1.0))
if not np.any(valid):
continue
log_error = np.abs(np.log((pred_size[valid] + 1e-12) / (gt_size[valid] + 1e-12)))
mean_error = float(np.mean(log_error))
errors.append(mean_error)
qualities.append(math.exp(-mean_error / PHYSICAL_LOG_DECAY))
extent_score = sum(qualities) / denominator
names = _target_view_names(target, sidecar)
parameters = _parameter_diagnostics(sidecar, predicted, target, names, geometry_pairs, global_scale)
fmfs = _fmfs_diagnostics(sidecar, raw_pred, annotation_diagnostics)
category_name = str(category or "").upper()
if category_name == "DISK":
semantics = EV44.score_disk_semantics(dict(raw_pred), dict(raw_gt))
semantic_eligible = bool(semantics.get("applicable") and semantics.get("data_valid"))
category_semantics = {
"eligible": semantic_eligible,
"score": _round(float(semantics["score"])) if semantic_eligible else None,
"reason": "ok" if semantic_eligible else "disk_target_not_semantically_valid",
"details": semantics,
}
else:
category_semantics = {
"eligible": False,
"score": None,
"reason": "no_validated_category_specific_extractor",
"category": category,
}
# The online component remains dense on every valid three-view sample.
# When the evaluator-only FMFS manifest is trustworthy, physical feature
# correctness dominates the coarse extent proxy. Legacy parameter and
# category extractors remain diagnostics; mixing them into the scalar would
# give selected categories more reward weight than the rest of the corpus.
score = (
0.35 * extent_score + 0.65 * float(fmfs["score"])
if fmfs["eligible"]
else extent_score
)
return _component(
score,
True,
(
"ok"
if len(predicted) == len(target) and fmfs["eligible"]
else "fmfs_ineligible_extent_proxy_only"
if len(predicted) == len(target)
else "prediction_view_count_mismatch"
),
scale_invariant_extent_score=_round(extent_score),
mean_extent_log_error=_round(float(np.mean(errors))) if errors else None,
global_alignment_scale=_round(global_scale, 8),
fmfs=fmfs,
parameters=parameters,
category_semantics=category_semantics,
)
def _semantic_family(family: Any) -> str:
value = str(family or "").lower()
return "linear" if value in {"linear", "aligned"} else value
def _dimension_value(dimension: Mapping[str, Any], consistency: Mapping[str, Any]) -> float | None:
value = dimension.get("display_value")
if isinstance(value, (int, float)) and math.isfinite(float(value)):
return abs(float(value))
measurement = dimension.get("measurement")
drawing_scale = consistency.get("drawing_scale")
if (
isinstance(measurement, (int, float))
and isinstance(drawing_scale, (int, float))
and math.isfinite(float(measurement))
and float(drawing_scale) > 1e-12
):
return abs(float(measurement) / float(drawing_scale))
return None
def _diameter_equivalent(family: str, value: float | None) -> float | None:
if value is None:
return None
return 2.0 * value if family == "radius" else value
def _annotation_component(
predicted: Mapping[str, Any],
target: Mapping[str, Any],
source_center: np.ndarray,
target_center: np.ndarray,
global_scale: float,
pred_structure: Mapping[str, Any],
) -> tuple[dict[str, Any], dict[str, Any]]:
pred_dims = list(predicted.get("dims", []))
gt_dims = list(target.get("dims", []))
pred_consistency = EV43.score_dimension_consistency(dict(predicted))
gt_consistency = EV43.score_dimension_consistency(dict(target))
dimension_text = int(pred_structure.get("dimension_like_text", 0))
effective_pred_count = len(pred_dims) + dimension_text
denominator = max(effective_pred_count, len(gt_dims), 1)
editable_rate = len(pred_dims) / max(effective_pred_count, 1) if effective_pred_count else 1.0
if not pred_dims or not gt_dims:
score = 1.0 if effective_pred_count == 0 and not gt_dims else 0.0
reason = "ok" if score == 1.0 else "dimension_count_mismatch"
details = {
"n_pred_native": len(pred_dims),
"n_pred_text_only": dimension_text,
"n_gt": len(gt_dims),
"matched_by_binding": 0,
"coverage_recall": 1.0 if not gt_dims else 0.0,
"precision": 1.0 if effective_pred_count == 0 else 0.0,
"type_f1": score,
"value_f1": score,
"binding_f1": score,
"editable_dimension_rate": _round(editable_rate),
"prediction_consistency": pred_consistency,
"target_consistency": gt_consistency,
"pairs": [],
}
return _component(score, True, reason, **details), details
pred_bind = np.asarray([dimension.get("binding_point", (0.0, 0.0)) for dimension in pred_dims], dtype=float)
gt_bind = np.asarray([dimension.get("binding_point", (0.0, 0.0)) for dimension in gt_dims], dtype=float)
pred_bind = EV2.transform_points(pred_bind, source_center, target_center, global_scale)
distances = np.linalg.norm(pred_bind[:, None] - gt_bind[None, :], axis=2)
gt_diagonal = max(EV2.bbox_diagonal(dict(target)), 1.0)
bind_threshold = DIM_BIND_TOL_FRAC * gt_diagonal
assignment_cost = distances.copy()
for pred_index, pred_dim in enumerate(pred_dims):
pred_family = _semantic_family(pred_dim.get("family"))
pred_value = _diameter_equivalent(
pred_family, _dimension_value(pred_dim, pred_consistency)
)
for gt_index, gt_dim in enumerate(gt_dims):
gt_family = _semantic_family(gt_dim.get("family"))
gt_value = _diameter_equivalent(
gt_family, _dimension_value(gt_dim, gt_consistency)
)
type_penalty = float(pred_family != gt_family)
value_penalty = (
min(2.0, abs(math.log(max(pred_value, 1e-12) / max(gt_value, 1e-12))))
if pred_value is not None and gt_value is not None and gt_value > 1e-12
else 2.0
)
# Geometry binding remains primary; semantics resolve equal/near
# equal binding points instead of letting Hungarian ties swap
# different dimensions in an otherwise identical drawing.
assignment_cost[pred_index, gt_index] += bind_threshold * (
0.25 * type_penalty + 0.05 * value_penalty
)
rows, columns = linear_sum_assignment(assignment_cost)
type_quality_sum = value_quality_sum = binding_quality_sum = joint_sum = 0.0
pair_rows = []
by_type: dict[str, dict[str, int]] = defaultdict(lambda: {"gt": 0, "pred": 0, "matched": 0})
for dimension in gt_dims:
by_type[_semantic_family(dimension.get("family"))]["gt"] += 1
for dimension in pred_dims:
by_type[_semantic_family(dimension.get("family"))]["pred"] += 1
for pred_index, gt_index in zip(rows, columns):
distance = float(distances[pred_index, gt_index])
if distance > bind_threshold:
continue
pred_dim, gt_dim = pred_dims[int(pred_index)], gt_dims[int(gt_index)]
pred_family = _semantic_family(pred_dim.get("family"))
gt_family = _semantic_family(gt_dim.get("family"))
type_ok = pred_family == gt_family and pred_family in {"linear", "diameter", "radius"}
pred_value = _diameter_equivalent(
pred_family, _dimension_value(pred_dim, pred_consistency)
)
gt_value = _diameter_equivalent(gt_family, _dimension_value(gt_dim, gt_consistency))
if pred_value is not None and gt_value is not None:
value_error = abs(pred_value - gt_value)
value_ok = value_error <= max(EV2.DIM_ABS_TOL, EV2.DIM_REL_TOL * abs(gt_value))
relative_error = value_error / max(abs(gt_value), 1e-12)
else:
value_ok = False
relative_error = None
binding_quality = math.exp(-distance / max(0.01 * gt_diagonal, 1e-9))
type_quality_sum += float(type_ok)
value_quality_sum += float(value_ok)
binding_quality_sum += binding_quality
joint = float(type_ok and value_ok) * binding_quality
joint_sum += joint
if type_ok and value_ok:
by_type[gt_family]["matched"] += 1
pair_rows.append(
{
"pred_index": int(pred_index),
"gt_index": int(gt_index),
"pred_family": pred_family,
"gt_family": gt_family,
"type_correct": bool(type_ok),
"value_correct": bool(value_ok),
"value_relative_error": _round(relative_error),
"binding_distance_frac": _round(distance / gt_diagonal),
"binding_quality": _round(binding_quality),
}
)
matched_by_binding = len(pair_rows)
coverage = matched_by_binding / max(len(gt_dims), 1)
precision = matched_by_binding / max(effective_pred_count, 1)
joint_f1 = joint_sum / denominator
internal_binding = float(pred_consistency.get("binding_quality", 0.0))
target_internal_binding = float(gt_consistency.get("binding_quality", 0.0))
relative_internal_binding = (
min(1.0, internal_binding / target_internal_binding)
if target_internal_binding > 1e-12
else 1.0 if internal_binding >= target_internal_binding else 0.0
)
score = joint_f1 * editable_rate * (0.25 + 0.75 * relative_internal_binding)
details = {
"n_pred_native": len(pred_dims),
"n_pred_text_only": dimension_text,
"n_gt": len(gt_dims),
"matched_by_binding": matched_by_binding,
"coverage_recall": _round(coverage),
"precision": _round(precision),
"type_f1": _round(type_quality_sum / denominator),
"value_f1": _round(value_quality_sum / denominator),
"binding_f1": _round(binding_quality_sum / denominator),
"joint_type_value_binding_f1": _round(joint_f1),
"editable_dimension_rate": _round(editable_rate),
"prediction_internal_binding_quality": _round(internal_binding),
"target_internal_binding_quality": _round(target_internal_binding),
"relative_internal_binding_quality": _round(relative_internal_binding),
"binding_threshold_frac": DIM_BIND_TOL_FRAC,
"prediction_consistency": pred_consistency,
"target_consistency": gt_consistency,
"by_type": dict(by_type),
"pairs": pair_rows,
}
return _component(score, True, "ok", **details), details
def _fmfs_diagnostics(
sidecar: Mapping[str, Any] | None,
predicted: Mapping[str, Any],
annotation_diagnostics: Mapping[str, Any],
) -> dict[str, Any]:
"""Verify prompt-grounded manufacturing dimensions against native DIMENSIONs.
The sidecar decides target eligibility; a model can never earn or lose a
strict physical score on a target that failed that offline audit. For an
eligible target, each declared GT dimension must be represented by a native
predicted DIMENSION with the correct semantic type, physical value, and
geometric binding. The physical value is recovered from measured drawing
geometry under the prediction's consensus drawing scale, so correct text
attached to incorrect geometry does not pass.
"""
if not isinstance(sidecar, Mapping):
return {"eligible": False, "score": None, "reason": "no_sidecar_fmfs", "items": []}
manifest = sidecar.get("fmfs")
if not isinstance(manifest, Mapping):
return {"eligible": False, "score": None, "reason": "no_sidecar_fmfs", "items": []}
declared = manifest.get("items")
if not bool(manifest.get("eligible")):
return {
"eligible": False,
"score": None,
"reason": manifest.get("reason", "sidecar_fmfs_ineligible"),
"fully_derivable": bool(manifest.get("fully_derivable")),
"items": [],
}
if not isinstance(declared, Sequence) or isinstance(declared, (str, bytes)) or not declared:
return {"eligible": False, "score": None, "reason": "empty_sidecar_fmfs", "items": []}
pred_dims = list(predicted.get("dims", []))
pairs = {
int(pair["gt_index"]): pair
for pair in annotation_diagnostics.get("pairs", [])
if isinstance(pair, Mapping)
and isinstance(pair.get("gt_index"), int)
and isinstance(pair.get("pred_index"), int)
}
consistency = annotation_diagnostics.get("prediction_consistency", {})
target_consistency = annotation_diagnostics.get("target_consistency", {})
consistency_items = (
list(consistency.get("items", [])) if isinstance(consistency, Mapping) else []
)
target_consistency_items = (
list(target_consistency.get("items", []))
if isinstance(target_consistency, Mapping)
else []
)
drawing_scale = consistency.get("drawing_scale") if isinstance(consistency, Mapping) else None
target_drawing_scale = (
target_consistency.get("drawing_scale")
if isinstance(target_consistency, Mapping)
else None
)
valid_scale = (
isinstance(drawing_scale, (int, float))
and math.isfinite(float(drawing_scale))
and float(drawing_scale) > 1e-12
)
rows: list[dict[str, Any]] = []
qualities: list[float] = []
for position, raw_spec in enumerate(declared):
if not isinstance(raw_spec, Mapping):
rows.append({"id": str(position), "score": 0.0, "reason": "invalid_manifest_item"})
qualities.append(0.0)
continue
spec = dict(raw_spec)
try:
gt_index = int(spec.get("gt_dimension_index"))
except (TypeError, ValueError):
gt_index = -1
pair = pairs.get(gt_index)
if pair is None:
rows.append(
{
"id": spec.get("id", str(position)),
"gt_dimension_index": gt_index,
"score": 0.0,
"reason": "missing_or_detached_predicted_dimension",
}
)
qualities.append(0.0)
continue
pred_index = int(pair["pred_index"])
if not 0 <= pred_index < len(pred_dims):
rows.append(
{
"id": spec.get("id", str(position)),
"gt_dimension_index": gt_index,
"score": 0.0,
"reason": "predicted_dimension_index_out_of_range",
}
)
qualities.append(0.0)
continue
dimension = pred_dims[pred_index]
pred_family = _semantic_family(dimension.get("family"))
target_family = _semantic_family(spec.get("family"))
type_quality = float(
pred_family == target_family
and target_family in {"linear", "diameter", "radius"}
)
measurement = dimension.get("measurement")
target_value = spec.get("value")
predicted_value = (
abs(float(measurement)) / float(drawing_scale)
if valid_scale
and isinstance(measurement, (int, float))
and math.isfinite(float(measurement))
else None
)
valid_value = (
predicted_value is not None
and isinstance(target_value, (int, float))
and math.isfinite(float(target_value))
and abs(float(target_value)) > 1e-12
)
log_error = (
abs(math.log(max(predicted_value, 1e-12) / abs(float(target_value))))
if valid_value
else None
)
value_quality = math.exp(-log_error / PHYSICAL_LOG_DECAY) if log_error is not None else 0.0
internal = consistency_items[pred_index] if pred_index < len(consistency_items) else {}
target_internal = (
target_consistency_items[gt_index]
if 0 <= gt_index < len(target_consistency_items)
else {}
)
raw_internal_binding = _clip(float(internal.get("binding_quality", 0.0)))
target_internal_binding = _clip(float(target_internal.get("binding_quality", 0.0)))
internal_binding = (
min(1.0, raw_internal_binding / target_internal_binding)
if target_internal_binding > 1e-12
else 1.0 if raw_internal_binding >= target_internal_binding else 0.0
)
scale_ratio = internal.get("scale_ratio")
raw_scale_quality = (
math.exp(
-abs(math.log(float(scale_ratio) / float(drawing_scale)))
/ EV4.DIMENSION_SCALE_DECAY
)
if valid_scale
and isinstance(scale_ratio, (int, float))
and float(scale_ratio) > 1e-12
else 0.0
)
target_scale_ratio = target_internal.get("scale_ratio")
target_scale_quality = (
math.exp(
-abs(
math.log(float(target_scale_ratio) / float(target_drawing_scale))
)
/ EV4.DIMENSION_SCALE_DECAY
)
if isinstance(target_drawing_scale, (int, float))
and float(target_drawing_scale) > 1e-12
and isinstance(target_scale_ratio, (int, float))
and float(target_scale_ratio) > 1e-12
else 0.0
)
scale_quality = (
min(1.0, raw_scale_quality / target_scale_quality)
if target_scale_quality > 1e-12
else 1.0 if raw_scale_quality >= target_scale_quality else 0.0
)
target_binding = _clip(float(pair.get("binding_quality", 0.0)))
quality = type_quality * value_quality * internal_binding * scale_quality * target_binding
qualities.append(quality)
relative_error = (
abs(predicted_value / abs(float(target_value)) - 1.0) if valid_value else None
)
rows.append(
{
"id": spec.get("id", str(position)),
"gt_dimension_index": gt_index,
"pred_dimension_index": pred_index,
"target_family": target_family,
"predicted_family": pred_family,
"target_physical_value": _round(abs(float(target_value))) if valid_value else None,
"predicted_physical_value": _round(predicted_value),
"relative_error": _round(relative_error),
"value_quality": _round(value_quality),
"type_quality": _round(type_quality),
"binding_quality": _round(target_binding),
"internal_binding_quality": _round(internal_binding),
"prediction_internal_binding_quality": _round(raw_internal_binding),
"target_internal_binding_quality": _round(target_internal_binding),
"scale_quality": _round(scale_quality),
"prediction_scale_quality": _round(raw_scale_quality),
"target_scale_quality": _round(target_scale_quality),
"score": _round(quality),
"within_1pct": bool(relative_error is not None and relative_error <= 0.01),
"within_5pct": bool(relative_error is not None and relative_error <= 0.05),
"within_10pct": bool(relative_error is not None and relative_error <= 0.10),
"reason": "ok" if quality >= 0.999 else "physical_feature_mismatch",
}
)
score = float(np.mean(qualities)) if qualities else 0.0
return {
"eligible": True,
"score": _round(score),
"reason": "ok" if score >= ENGINEERING_THRESHOLDS["physical"] else "fmfs_mismatch",
"fully_derivable": bool(manifest.get("fully_derivable")),
"n_declared": len(declared),
"n_matched": sum(row.get("pred_dimension_index") is not None for row in rows),
"drawing_scale": _round(float(drawing_scale), 8) if valid_scale else None,
"items": rows,
}
def _structure_component(
raw_pred: Mapping[str, Any],
canonical_pred: Mapping[str, Any],
raw_gt: Mapping[str, Any],
canonical_gt: Mapping[str, Any],
pred_meta: Mapping[str, Any],
gt_meta: Mapping[str, Any],
) -> tuple[dict[str, Any], dict[str, Any]]:
representation = EV4.representation_quality(dict(raw_pred), dict(canonical_pred))
pred_count = _n_geometry(canonical_pred)
gt_count = _n_geometry(canonical_gt)
ratio = pred_count / max(gt_count, 1)
inflation_quality = math.exp(-max(0.0, ratio - 1.5))
unsupported = int(pred_meta.get("unsupported_geometry_like", 0))
supported = int(pred_meta.get("supported_geometry", 0))
supported_rate = supported / max(supported + unsupported, 1)
if unsupported == 0:
supported_rate = 1.0
score = representation * inflation_quality * supported_rate
duplicate_ratio = max(0.0, 1.0 - representation)
raw_count = _n_geometry(raw_pred)
duplicate_count = int(round(raw_count * duplicate_ratio))
extra_ratio = max(0.0, pred_count - gt_count) / max(gt_count, 1)
dimension_consistency = EV43.score_dimension_consistency(dict(raw_pred))
duplicate_dimension_count = int(dimension_consistency.get("duplicate_dimensions", 0))
duplicate_dimension_ratio = duplicate_dimension_count / max(
int(dimension_consistency.get("n_dimensions", 0)), 1
)
anti_hack = {
"representation_quality": _round(representation),
"canonical_entity_ratio_pred_to_gt": _round(ratio),
"entity_inflation_quality": _round(inflation_quality),
"supported_geometry_rate": _round(supported_rate),
"duplicate_or_overlap_ratio": _round(duplicate_ratio),
"canonical_extra_entity_ratio": _round(extra_ratio),
"duplicate_entity_count": duplicate_count,
"duplicate_entity_ratio": _round(duplicate_ratio),
"duplicate_dimension_count": duplicate_dimension_count,
"duplicate_dimension_ratio": _round(duplicate_dimension_ratio),
"unsupported_geometry_like": unsupported,
"flags": [
flag
for flag, active in (
("duplicate_or_overlapping_entities", duplicate_ratio > 0.10),
("entity_inflation", ratio > 2.0),
("unsupported_geometry_representation", unsupported > 0),
)
if active
],
"penalty": _round(1.0 - score),
}
component = _component(
score,
True,
"ok" if not anti_hack["flags"] else "anti_hack_flags_present",
prediction=pred_meta,
target=gt_meta,
**anti_hack,
)
return component, anti_hack
def _invalid_result(
pred_path: str | Path,
gt_path: str | Path,
pred_meta: Mapping[str, Any],
gt_meta: Mapping[str, Any],
*,
target_valid: bool,
category: str | None,
sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
fmfs = sidecar.get("fmfs") if isinstance(sidecar, Mapping) else None
views = sidecar.get("views") if isinstance(sidecar, Mapping) else None
target_engineering_eligible = bool(
target_valid
and isinstance(fmfs, Mapping)
and fmfs.get("eligible")
and isinstance(views, Mapping)
and views.get("candidate_count") == VIEW_TARGET_COUNT
)
if target_valid:
components = {
name: _component(0.0, True, "prediction_dxf_unreadable_or_degenerate")
for name in ("view", "geometry", "physical", "annotation", "layout", "structure")
}
else:
components = {
name: _component(None, False, "target_dxf_unreadable_or_degenerate")
for name in ("view", "geometry", "physical", "annotation", "layout", "structure")
}
return {
"metric_version": "v5.0",
"category": category,
"components": components,
"diagnostics": {
"paths": {"prediction": str(pred_path), "target": str(gt_path)},
"prediction_structure": dict(pred_meta),
"target_structure": dict(gt_meta),
"failure_stage": "prediction_dxf" if target_valid else "target_dxf",
},
"anti_hack": {"penalty": 0.0 if not target_valid else 1.0, "flags": []},
"benchmark": {
"cad_pass": False if target_valid else None,
"dxf_exec": False if target_valid else None,
"dxf_readable": bool(pred_meta.get("readable")),
"nondegenerate": False,
"three_views": False if target_valid else None,
"geometry_pass": False if target_valid else None,
"physical_pass": False if target_engineering_eligible else None,
"annotation_pass": False if target_valid else None,
"layout_pass": False if target_valid else None,
"structure_pass": False if target_valid else None,
"engineering_eligible": target_engineering_eligible,
"engineering_success": False if target_valid else None,
},
"engineering_eligible": target_engineering_eligible,
"engineering_success": False if target_valid else None,
}
def score_dxf_pair(
pred: str | Path,
gt: str | Path,
sidecar: Mapping[str, Any] | None = None,
category: str | None = None,
) -> dict[str, Any]:
"""Score one executed prediction DXF against a target DXF.
Parameters
----------
pred, gt:
Paths to readable DXF files. Generated Python must already have run.
sidecar:
Optional evaluator-only manifest. ``views`` may be a list/dict of
named target bboxes. ``physical_parameters`` (or ``parameters``) may
select ``bbox_width``, ``bbox_height``, ``bbox_diagonal``,
``circle_radius``, ``circle_diameter``, ``arc_radius`` or
``line_length`` for a named/indexed view. Unsupported declarations are
explicitly ineligible; they never receive a zero score.
category:
Enables a frozen category-specific diagnostic only where one exists.
Currently this is limited to ``DISK``.
"""
pred_path, gt_path = Path(pred), Path(gt)
pred_meta, gt_meta = _read_structure(pred_path), _read_structure(gt_path)
raw_gt = _extract_entities(gt_path) if gt_meta["readable"] else None
target_valid = bool(raw_gt is not None and _n_geometry(raw_gt) > 0 and _safe_bbox(raw_gt) is not None)
if not target_valid:
return _invalid_result(
pred_path,
gt_path,
pred_meta,
gt_meta,
target_valid=False,
category=category,
sidecar=sidecar,
)
raw_pred = _extract_entities(pred_path) if pred_meta["readable"] else None
prediction_valid = bool(
raw_pred is not None and _n_geometry(raw_pred) > 0 and _safe_bbox(raw_pred) is not None
)
if not prediction_valid:
return _invalid_result(
pred_path,
gt_path,
pred_meta,
gt_meta,
target_valid=True,
category=category,
sidecar=sidecar,
)
canonical_pred = EV4.canonicalize_entities(raw_pred)
canonical_gt = EV4.canonicalize_entities(raw_gt)
source_center, target_center, global_scale = EV3.shared_alignment(canonical_pred, canonical_gt)
view_definitions = _normalise_sidecar_views(sidecar)
if len(view_definitions) == VIEW_TARGET_COUNT:
pred_views = _views_from_reference_boxes(
canonical_pred,
view_definitions,
source_center,
target_center,
global_scale,
)
gt_views = _views_from_reference_boxes(
canonical_gt,
view_definitions,
target_center,
target_center,
1.0,
)
else:
pred_views, gt_views = _cluster_views(canonical_pred), _cluster_views(canonical_gt)
layout_pairs, layout_distances = _layout_pairs(pred_views, gt_views)
geometry_pairs, geometry_pair_details = _geometry_pair_matrix(
pred_views, gt_views, global_scale, layout_distances
)
view = _view_component(pred_views, gt_views, geometry_pairs, layout_pairs)
layout = _layout_component(pred_views, gt_views, layout_pairs, layout_distances)
if len(gt_views) == VIEW_TARGET_COUNT:
geometry_data = _aggregate_geometry(
geometry_pairs, geometry_pair_details, len(pred_views), len(gt_views)
)
geometry = _component(
geometry_data["score"],
True,
"ok" if len(pred_views) == len(gt_views) else "prediction_view_count_mismatch",
strict_score=_round(geometry_data["strict_score"]),
visible_edge_f1=_round(geometry_data["visible_edge_f1"]),
hidden_edge_f1=_round(geometry_data["hidden_edge_f1"]),
hidden_eligible=geometry_data["hidden_eligible"],
circle_f1=_round(geometry_data["circle_f1"]),
circle_eligible=geometry_data["circle_eligible"],
arc_f1=_round(geometry_data["arc_f1"]),
arc_eligible=geometry_data["arc_eligible"],
pairs=geometry_data["pairs"],
)
else:
geometry = _component(
None,
False,
"target_view_partition_not_three",
strict_score=None,
visible_edge_f1=None,
hidden_edge_f1=None,
hidden_eligible=False,
circle_f1=None,
circle_eligible=False,
arc_f1=None,
arc_eligible=False,
pairs=[],
)
annotation, annotation_diagnostics = _annotation_component(
raw_pred,
raw_gt,
source_center,
target_center,
global_scale,
pred_meta,
)
physical = _physical_component(
pred_views,
gt_views,
geometry_pairs,
global_scale,
raw_pred=canonical_pred,
raw_gt=canonical_gt,
sidecar=sidecar,
category=category,
annotation_diagnostics=annotation_diagnostics,
)
structure, anti_hack = _structure_component(
raw_pred, canonical_pred, raw_gt, canonical_gt, pred_meta, gt_meta
)
components = {
"view": view,
"geometry": geometry,
"physical": physical,
"annotation": annotation,
"layout": layout,
"structure": structure,
}
def passed(name: str) -> bool | None:
component = components[name]
if not component["eligible"] or component["score"] is None:
return None
return bool(float(component["score"]) >= ENGINEERING_THRESHOLDS[name])
fmfs = physical.get("details", {}).get("fmfs", {})
physical_pass = (
bool(float(fmfs["score"]) >= ENGINEERING_THRESHOLDS["physical"])
if isinstance(fmfs, Mapping)
and bool(fmfs.get("eligible"))
and isinstance(fmfs.get("score"), (int, float))
else None
)
strict_states = {
"three_views": passed("view"),
"geometry_pass": passed("geometry"),
"physical_pass": physical_pass,
"annotation_pass": passed("annotation"),
"layout_pass": passed("layout"),
"structure_pass": passed("structure"),
}
engineering_eligible = all(value is not None for value in strict_states.values())
engineering_success = (
all(bool(value) for value in strict_states.values())
if engineering_eligible
else None
)
benchmark = {
"cad_pass": engineering_success,
"dxf_exec": True,
"dxf_readable": True,
"nondegenerate": True,
**strict_states,
"engineering_eligible": engineering_eligible,
"engineering_success": engineering_success,
"thresholds": dict(ENGINEERING_THRESHOLDS),
}
return {
"metric_version": "v5.0",
"category": category,
"components": components,
"diagnostics": {
"paths": {"prediction": str(pred_path), "target": str(gt_path)},
"prediction_structure": pred_meta,
"target_structure": gt_meta,
"alignment": {
"translation_invariant": True,
"uniform_scale_invariant": True,
"rotation_invariant": False,
"source_center": [_round(float(value)) for value in source_center],
"target_center": [_round(float(value)) for value in target_center],
"scale": _round(global_scale, 8),
},
"view_partition": {
"predicted": [
{
"index": index,
"center": [_round(float(value)) for value in view_item["center"]],
"size": [_round(float(value)) for value in view_item["size"]],
"n_primitives": view_item["n_primitives"],
}
for index, view_item in enumerate(pred_views)
],
"target": [
{
"index": index,
"name": _target_view_names(gt_views, sidecar).get(index),
"center": [_round(float(value)) for value in view_item["center"]],
"size": [_round(float(value)) for value in view_item["size"]],
"n_primitives": view_item["n_primitives"],
}
for index, view_item in enumerate(gt_views)
],
},
"annotation": annotation_diagnostics,
},
"anti_hack": anti_hack,
"benchmark": benchmark,
"engineering_eligible": engineering_eligible,
"engineering_success": engineering_success,
}
__all__ = ["ENGINEERING_THRESHOLDS", "score_dxf_pair"]
|