#!/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"]