Download CODE/evaluation/eval/eval_geometric04.py from QLU-LLM/CAD: direct link, hf CLI and curl.
- Browser
- Download file 25 kB
-
https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/eval_geometric04.py
- Command line
-
hf download hf://datasets/QLU-LLM/CAD/CODE/evaluation/eval/eval_geometric04.py
-
curl -L -o eval_geometric04.py https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/eval_geometric04.py
25 kB
| #!/usr/bin/env python3 | |
| """Representation-invariant metric helpers for the direct ezdxf task. | |
| Metric v4 is deliberately versioned beside v2/v3. Its first validated scope is | |
| the DISK family. The important change is that a mathematically straight edge | |
| is scored as one edge regardless of how many contiguous DXF LINE entities were | |
| used to encode it. Rich DIMENSION extraction also lets the evaluator verify | |
| that displayed values agree with measured drawing geometry under one sheet | |
| scale, instead of checking dimension text alone. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from collections import defaultdict | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| import ezdxf | |
| import numpy as np | |
| try: # package import used by tests | |
| from . import eval_geometric02 as EV2 | |
| from . import eval_geometric03 as EV3 | |
| except ImportError: # direct/module import used by reward workers | |
| import eval_geometric02 as EV2 | |
| import eval_geometric03 as EV3 | |
| CANONICAL_ABS_TOL = 1e-6 | |
| CANONICAL_REL_TOL = 1e-6 | |
| DIMENSION_SCALE_INLIER_REL = 0.05 | |
| DIMENSION_SCALE_DECAY = 0.05 | |
| DISK_RATIO_DECAY = 0.12 | |
| def _visibility(layer: Any) -> str: | |
| return "hidden" if "hidden" in str(layer).lower() else "visible" | |
| def _clean(value: float) -> float: | |
| value = round(float(value), 12) | |
| return 0.0 if abs(value) < 5e-13 else value | |
| def _empty_entities() -> dict[str, list[Any]]: | |
| return {"lines": [], "circles": [], "arcs": [], "dims": []} | |
| def extract_entities(dxf_path: str | Path) -> dict[str, Any] | None: | |
| """Extract primitives plus lossless-enough DIMENSION diagnostics. | |
| Unlike v2, every dimension is a dictionary containing its raw ezdxf | |
| measurement and all available definition/reference points. Measurements | |
| are paper/model-space lengths; displayed text is usually a physical length, | |
| so their ratio (not equality) is checked by :func:`score_dimension_consistency`. | |
| """ | |
| try: | |
| doc = ezdxf.readfile(str(dxf_path)) | |
| except Exception: | |
| return None | |
| entities = _empty_entities() | |
| for entity in doc.modelspace(): | |
| entity_type = entity.dxftype() | |
| layer = entity.dxf.layer if entity.dxf.hasattr("layer") else "0" | |
| 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 == "CIRCLE": | |
| entities["circles"].append( | |
| ( | |
| float(entity.dxf.center.x), | |
| float(entity.dxf.center.y), | |
| float(entity.dxf.radius), | |
| 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, | |
| ) | |
| ) | |
| elif entity_type == "DIMENSION": | |
| dimtype = int(entity.dxf.dimtype) if entity.dxf.hasattr("dimtype") else 0 | |
| text = str(entity.dxf.text) if entity.dxf.hasattr("text") else "" | |
| points: dict[str, tuple[float, float]] = {} | |
| for name in ( | |
| "defpoint", | |
| "defpoint2", | |
| "defpoint3", | |
| "defpoint4", | |
| "defpoint5", | |
| ): | |
| if entity.dxf.hasattr(name): | |
| point = getattr(entity.dxf, name) | |
| points[name] = (float(point.x), float(point.y)) | |
| base = dimtype & 0x0F | |
| if base in (0, 1) and "defpoint2" in points and "defpoint3" in points: | |
| first, second = points["defpoint2"], points["defpoint3"] | |
| binding = ((first[0] + second[0]) / 2, (first[1] + second[1]) / 2) | |
| elif base in (3, 4) and "defpoint4" in points: | |
| binding = points["defpoint4"] | |
| else: | |
| binding = points.get("defpoint", (0.0, 0.0)) | |
| try: | |
| measurement = float(entity.get_measurement()) | |
| if not math.isfinite(measurement): | |
| measurement = None | |
| except Exception: | |
| measurement = None | |
| text_family, display_value, _ = EV2.parse_dim_value(text) | |
| type_family = EV2.dim_type_name(dimtype) | |
| family = ( | |
| type_family | |
| if type_family in {"linear", "aligned", "diameter", "radius"} | |
| else text_family | |
| ) | |
| entities["dims"].append( | |
| { | |
| "dimtype": dimtype, | |
| "family": family, | |
| "text": text, | |
| "display_value": display_value, | |
| "measurement": measurement, | |
| "layer": layer, | |
| "definition_point": points.get("defpoint", (0.0, 0.0)), | |
| "binding_point": binding, | |
| "ref_points": points, | |
| } | |
| ) | |
| return entities | |
| def canonicalize_entities( | |
| entities: dict[str, Any], | |
| *, | |
| abs_tol: float = CANONICAL_ABS_TOL, | |
| rel_tol: float = CANONICAL_REL_TOL, | |
| ) -> dict[str, Any]: | |
| """Merge overlapping/touching collinear LINEs without bridging real gaps. | |
| Visible and hidden geometry are isolated, while arbitrary visible layer | |
| names are treated as representation detail. The operation is deterministic | |
| and idempotent. Circles, arcs and rich dimensions are retained unchanged. | |
| """ | |
| result = { | |
| "lines": [], | |
| "circles": list(entities.get("circles", [])), | |
| "arcs": list(entities.get("arcs", [])), | |
| "dims": list(entities.get("dims", [])), | |
| } | |
| diagonal = EV2.bbox_diagonal( | |
| { | |
| "lines": list(entities.get("lines", [])), | |
| "circles": result["circles"], | |
| "arcs": result["arcs"], | |
| "dims": [], | |
| } | |
| ) | |
| tolerance = max(float(abs_tol), float(rel_tol) * max(diagonal, 1.0)) | |
| angular_tolerance = max(1e-10, tolerance / max(diagonal, 1.0)) | |
| clusters: list[dict[str, Any]] = [] | |
| ordered_lines = sorted( | |
| entities.get("lines", []), | |
| key=lambda line: ( | |
| _visibility(line[4]), | |
| min(float(line[0]), float(line[2])), | |
| min(float(line[1]), float(line[3])), | |
| max(float(line[0]), float(line[2])), | |
| max(float(line[1]), float(line[3])), | |
| str(line[4]), | |
| ), | |
| ) | |
| for x1, y1, x2, y2, layer in ordered_lines: | |
| first = np.asarray([float(x1), float(y1)], dtype=float) | |
| second = np.asarray([float(x2), float(y2)], dtype=float) | |
| delta = second - first | |
| length = float(np.linalg.norm(delta)) | |
| if not math.isfinite(length) or length <= 1e-12: | |
| continue | |
| direction = delta / length | |
| if direction[0] < -angular_tolerance or ( | |
| abs(direction[0]) <= angular_tolerance and direction[1] < 0 | |
| ): | |
| direction = -direction | |
| normal = np.asarray([-direction[1], direction[0]], dtype=float) | |
| offset = float(np.dot(normal, first)) | |
| visibility = _visibility(layer) | |
| selected = None | |
| for cluster in clusters: | |
| if cluster["visibility"] != visibility: | |
| continue | |
| cross = abs(float(np.cross(cluster["direction"], direction))) | |
| if cross > angular_tolerance: | |
| continue | |
| # Recompute offset using the cluster normal so reversed/nearly-equal | |
| # directions cannot split an otherwise identical support line. | |
| cluster_offset = float(np.dot(cluster["normal"], first)) | |
| if abs(cluster_offset - cluster["offset"]) <= tolerance: | |
| selected = cluster | |
| break | |
| if selected is None: | |
| selected = { | |
| "visibility": visibility, | |
| "direction": direction, | |
| "normal": normal, | |
| "offset": offset, | |
| "intervals": [], | |
| "layers": [], | |
| } | |
| clusters.append(selected) | |
| start = float(np.dot(selected["direction"], first)) | |
| end = float(np.dot(selected["direction"], second)) | |
| selected["intervals"].append((min(start, end), max(start, end))) | |
| selected["layers"].append(str(layer)) | |
| merged: list[tuple[float, float, float, float, str]] = [] | |
| for cluster in clusters: | |
| intervals = sorted(cluster["intervals"]) | |
| if not intervals: | |
| continue | |
| union: list[list[float]] = [[intervals[0][0], intervals[0][1]]] | |
| for start, end in intervals[1:]: | |
| if start <= union[-1][1] + tolerance: | |
| union[-1][1] = max(union[-1][1], end) | |
| else: | |
| union.append([start, end]) | |
| output_layer = "HIDDEN" if cluster["visibility"] == "hidden" else min(cluster["layers"]) | |
| for start, end in union: | |
| first = cluster["direction"] * start + cluster["normal"] * cluster["offset"] | |
| second = cluster["direction"] * end + cluster["normal"] * cluster["offset"] | |
| merged.append( | |
| ( | |
| _clean(first[0]), | |
| _clean(first[1]), | |
| _clean(second[0]), | |
| _clean(second[1]), | |
| output_layer, | |
| ) | |
| ) | |
| result["lines"] = sorted( | |
| merged, | |
| key=lambda line: (_visibility(line[4]), *line[:4], str(line[4])), | |
| ) | |
| return result | |
| def _point_segment_distance( | |
| point: tuple[float, float], line: tuple[Any, ...] | |
| ) -> float: | |
| value = np.asarray(point, dtype=float) | |
| first = np.asarray(line[:2], dtype=float) | |
| second = np.asarray(line[2:4], dtype=float) | |
| delta = second - first | |
| denominator = float(np.dot(delta, delta)) | |
| if denominator <= 1e-18: | |
| return float(np.linalg.norm(value - first)) | |
| fraction = float(np.dot(value - first, delta) / denominator) | |
| projection = first + min(1.0, max(0.0, fraction)) * delta | |
| return float(np.linalg.norm(value - projection)) | |
| def _distance_to_geometry(point: tuple[float, float], entities: dict[str, Any]) -> float: | |
| distances: list[float] = [] | |
| for line in entities.get("lines", []): | |
| if _visibility(line[-1]) == "visible": | |
| distances.append(_point_segment_distance(point, line)) | |
| for cx, cy, radius, layer in entities.get("circles", []): | |
| if _visibility(layer) == "visible": | |
| radial = math.dist(point, (float(cx), float(cy))) | |
| distances.append(abs(radial - abs(float(radius)))) | |
| distances.append(radial) # centre references are valid for circular dims | |
| for cx, cy, radius, start, end, layer in entities.get("arcs", []): | |
| if _visibility(layer) == "visible": | |
| distances.append(abs(math.dist(point, (float(cx), float(cy))) - abs(float(radius)))) | |
| return min(distances) if distances else math.inf | |
| def _dimension_reference_points(dimension: dict[str, Any]) -> list[tuple[float, float]]: | |
| refs = dimension.get("ref_points") or {} | |
| family = str(dimension.get("family", "")) | |
| if family in {"linear", "aligned"}: | |
| return [refs[name] for name in ("defpoint2", "defpoint3") if name in refs] | |
| if family in {"diameter", "radius"}: | |
| points = [refs[name] for name in ("defpoint4", "defpoint") if name in refs] | |
| return points or list(refs.values()) | |
| return list(refs.values()) | |
| def score_dimension_consistency(entities: dict[str, Any]) -> dict[str, Any]: | |
| """Check shared drawing scale and whether dimensions bind to the outline.""" | |
| dimensions = entities.get("dims", []) | |
| if not dimensions: | |
| return { | |
| "score": 1.0, | |
| "n_dimensions": 0, | |
| "n_valid": 0, | |
| "n_invalid": 0, | |
| "drawing_scale": None, | |
| "scale_consistency": 1.0, | |
| "binding_quality": 1.0, | |
| "data_valid": True, | |
| "items": [], | |
| } | |
| diagonal = max(EV2.bbox_diagonal(entities), 1.0) | |
| binding_sigma = max(1e-6, 0.005 * diagonal) | |
| items: list[dict[str, Any]] = [] | |
| valid_logs: list[float] = [] | |
| for dimension in dimensions: | |
| value = dimension.get("display_value") | |
| measurement = dimension.get("measurement") | |
| family = str(dimension.get("family", "")) | |
| valid = ( | |
| family in {"linear", "aligned", "diameter", "radius"} | |
| and isinstance(value, (int, float)) | |
| and isinstance(measurement, (int, float)) | |
| and math.isfinite(float(value)) | |
| and math.isfinite(float(measurement)) | |
| and abs(float(value)) > 1e-9 | |
| and abs(float(measurement)) > 1e-9 | |
| ) | |
| ratio = abs(float(measurement) / float(value)) if valid else None | |
| if ratio is not None and ratio > 0: | |
| valid_logs.append(math.log(ratio)) | |
| references = _dimension_reference_points(dimension) | |
| reference_distances = [_distance_to_geometry(point, entities) for point in references] | |
| finite_distances = [distance for distance in reference_distances if math.isfinite(distance)] | |
| if finite_distances: | |
| # Every extension/reference endpoint should be attached. A mean | |
| # prevents one valid endpoint from hiding a detached second endpoint. | |
| binding = float(np.mean(np.exp(-np.asarray(finite_distances) / binding_sigma))) | |
| else: | |
| binding = 0.0 | |
| items.append( | |
| { | |
| "family": family, | |
| "text": dimension.get("text", ""), | |
| "display_value": value, | |
| "measurement": measurement, | |
| "scale_ratio": ratio, | |
| "valid": bool(valid), | |
| "binding_quality": round(binding, 6), | |
| "reference_distance_mean": ( | |
| round(float(np.mean(finite_distances)), 6) if finite_distances else None | |
| ), | |
| } | |
| ) | |
| if valid_logs: | |
| threshold = math.log1p(DIMENSION_SCALE_INLIER_REL) | |
| candidates: list[tuple[int, float, list[float]]] = [] | |
| global_median = float(np.median(valid_logs)) | |
| for candidate in valid_logs: | |
| inliers = [value for value in valid_logs if abs(value - candidate) <= threshold] | |
| centre = float(np.median(inliers)) | |
| candidates.append((len(inliers), -abs(centre - global_median), inliers)) | |
| _, _, consensus = max(candidates, key=lambda value: (value[0], value[1])) | |
| centre_log = float(np.median(consensus)) | |
| qualities = [ | |
| math.exp(-abs(value - centre_log) / DIMENSION_SCALE_DECAY) | |
| for value in valid_logs | |
| ] | |
| scale_consistency = float(np.mean(qualities)) | |
| drawing_scale = math.exp(centre_log) | |
| else: | |
| centre_log = None | |
| scale_consistency = 0.0 | |
| drawing_scale = None | |
| valid_index = 0 | |
| for item in items: | |
| if item["scale_ratio"] is None or centre_log is None: | |
| item["scale_inlier"] = False | |
| item["scale_quality"] = 0.0 | |
| continue | |
| log_ratio = valid_logs[valid_index] | |
| valid_index += 1 | |
| item["scale_inlier"] = abs(log_ratio - centre_log) <= math.log1p(DIMENSION_SCALE_INLIER_REL) | |
| item["scale_quality"] = round( | |
| math.exp(-abs(log_ratio - centre_log) / DIMENSION_SCALE_DECAY), 6 | |
| ) | |
| binding_quality = float(np.mean([item["binding_quality"] for item in items])) | |
| n_valid = len(valid_logs) | |
| n_invalid = len(dimensions) - n_valid | |
| completeness = n_valid / max(len(dimensions), 1) | |
| score = scale_consistency * binding_quality * completeness | |
| return { | |
| "score": round(float(score), 6), | |
| "n_dimensions": len(dimensions), | |
| "n_valid": n_valid, | |
| "n_invalid": n_invalid, | |
| "drawing_scale": round(float(drawing_scale), 8) if drawing_scale is not None else None, | |
| "scale_consistency": round(float(scale_consistency), 6), | |
| "binding_quality": round(float(binding_quality), 6), | |
| "data_valid": bool(n_invalid == 0 and scale_consistency >= 0.8), | |
| "items": items, | |
| } | |
| def _connected_line_components(lines: list[tuple[Any, ...]], tolerance: float) -> list[list[tuple[Any, ...]]]: | |
| if not lines: | |
| return [] | |
| parent = list(range(len(lines))) | |
| 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) -> None: | |
| a, b = find(first), find(second) | |
| if a != b: | |
| parent[b] = a | |
| endpoints = [ | |
| (np.asarray(line[:2], dtype=float), np.asarray(line[2:4], dtype=float)) | |
| for line in lines | |
| ] | |
| for first in range(len(lines)): | |
| for second in range(first + 1, len(lines)): | |
| if any( | |
| float(np.linalg.norm(a - b)) <= tolerance | |
| for a in endpoints[first] | |
| for b in endpoints[second] | |
| ): | |
| union(first, second) | |
| groups: dict[int, list[tuple[Any, ...]]] = defaultdict(list) | |
| for index, line in enumerate(lines): | |
| groups[find(index)].append(line) | |
| return list(groups.values()) | |
| def _rectangle_sides(entities: dict[str, Any]) -> list[tuple[float, float]]: | |
| visible = [line for line in entities.get("lines", []) if _visibility(line[-1]) == "visible"] | |
| tolerance = max(1e-6, 1e-5 * max(EV2.bbox_diagonal(entities), 1.0)) | |
| rectangles: list[tuple[float, float]] = [] | |
| for component in _connected_line_components(visible, tolerance): | |
| points = np.asarray([point for line in component for point in (line[:2], line[2:4])], dtype=float) | |
| low = points.min(axis=0) | |
| high = points.max(axis=0) | |
| width, height = float(high[0] - low[0]), float(high[1] - low[1]) | |
| if width <= tolerance or height <= tolerance: | |
| continue | |
| horizontal = vertical = 0.0 | |
| for x1, y1, x2, y2, _ in component: | |
| if abs(float(y2) - float(y1)) <= tolerance: | |
| horizontal += abs(float(x2) - float(x1)) | |
| elif abs(float(x2) - float(x1)) <= tolerance: | |
| vertical += abs(float(y2) - float(y1)) | |
| if horizontal >= 1.8 * width and vertical >= 1.8 * height: | |
| rectangles.append((width, height)) | |
| return rectangles | |
| 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 | |
| precision = min(predicted, target) / predicted | |
| recall = min(predicted, target) / target | |
| return 2 * precision * recall / (precision + recall) | |
| def _disk_features(entities: dict[str, Any]) -> dict[str, Any]: | |
| circles = [circle for circle in entities.get("circles", []) if _visibility(circle[-1]) == "visible"] | |
| rectangles = _rectangle_sides(entities) | |
| circle_diameter = float(np.median([2 * abs(float(circle[2])) for circle in circles])) if circles else None | |
| diameter_sides: list[float] = [] | |
| thickness_sides: list[float] = [] | |
| if circle_diameter and circle_diameter > 1e-9: | |
| for width, height in rectangles: | |
| if abs(math.log(max(width, 1e-12) / circle_diameter)) <= abs( | |
| math.log(max(height, 1e-12) / circle_diameter) | |
| ): | |
| diameter_sides.append(width) | |
| thickness_sides.append(height) | |
| else: | |
| diameter_sides.append(height) | |
| thickness_sides.append(width) | |
| ratios = [thickness / diameter for thickness, diameter in zip(thickness_sides, diameter_sides) if diameter > 1e-9] | |
| return { | |
| "n_circles": len(circles), | |
| "n_rectangles": len(rectangles), | |
| "circle_diameter": circle_diameter, | |
| "diameter_sides": diameter_sides, | |
| "thickness_sides": thickness_sides, | |
| "thickness_ratios": ratios, | |
| } | |
| def score_disk_semantics( | |
| predicted: dict[str, Any], target: dict[str, Any] | |
| ) -> dict[str, Any]: | |
| """Score the one-circle + two D-by-T views of a simple positive disk.""" | |
| pred = _disk_features(predicted) | |
| gt = _disk_features(target) | |
| applicable = gt["n_circles"] == 1 and gt["n_rectangles"] == 2 and not target.get("arcs") | |
| gt_ratios = gt["thickness_ratios"] | |
| data_valid = bool( | |
| applicable | |
| and len(gt_ratios) == 2 | |
| and all(math.isfinite(value) and value > 1e-9 for value in gt_ratios) | |
| ) | |
| circle_count = _count_f1(pred["n_circles"], gt["n_circles"]) | |
| rectangle_count = _count_f1(pred["n_rectangles"], gt["n_rectangles"]) | |
| completeness = 0.5 * (circle_count + rectangle_count) | |
| if not applicable: | |
| return { | |
| "score": 1.0, | |
| "applicable": False, | |
| "data_valid": False, | |
| "diameter_score": 1.0, | |
| "thickness_score": 1.0, | |
| "view_completeness": round(completeness, 6), | |
| } | |
| if pred["circle_diameter"] and pred["diameter_sides"]: | |
| diameter_errors = [ | |
| abs(math.log(max(value, 1e-12) / pred["circle_diameter"])) | |
| for value in pred["diameter_sides"] | |
| ] | |
| diameter_score = float(np.mean(np.exp(-np.asarray(diameter_errors) / DISK_RATIO_DECAY))) | |
| else: | |
| diameter_score = 0.0 | |
| if data_valid and pred["thickness_ratios"]: | |
| pred_ratio = float(np.median(pred["thickness_ratios"])) | |
| gt_ratio = float(np.median(gt_ratios)) | |
| ratio_quality = math.exp(-abs(math.log(pred_ratio / gt_ratio)) / DISK_RATIO_DECAY) | |
| internal = float( | |
| np.mean( | |
| np.exp( | |
| -np.abs(np.log(np.asarray(pred["thickness_ratios"]) / pred_ratio)) | |
| / DISK_RATIO_DECAY | |
| ) | |
| ) | |
| ) | |
| thickness_score = ratio_quality * internal | |
| else: | |
| pred_ratio = None | |
| gt_ratio = float(np.median(gt_ratios)) if gt_ratios else None | |
| thickness_score = 0.0 | |
| score = completeness * (0.25 * diameter_score + 0.75 * thickness_score) | |
| return { | |
| "score": round(float(score), 6), | |
| "applicable": True, | |
| "data_valid": data_valid, | |
| "diameter_score": round(float(diameter_score), 6), | |
| "thickness_score": round(float(thickness_score), 6), | |
| "view_completeness": round(float(completeness), 6), | |
| "predicted_thickness_ratio": round(pred_ratio, 8) if pred_ratio is not None else None, | |
| "target_thickness_ratio": round(gt_ratio, 8) if gt_ratio is not None else None, | |
| "predicted_features": pred, | |
| "target_features": gt, | |
| } | |
| def legacy_dimension_entities(entities: dict[str, Any]) -> dict[str, Any]: | |
| """Adapt rich v4 dimensions to the v2 tuple API without losing primitives.""" | |
| converted = { | |
| "lines": list(entities.get("lines", [])), | |
| "circles": list(entities.get("circles", [])), | |
| "arcs": list(entities.get("arcs", [])), | |
| "dims": [], | |
| } | |
| for dimension in entities.get("dims", []): | |
| if not isinstance(dimension, dict): | |
| converted["dims"].append(dimension) | |
| continue | |
| definition = dimension.get("definition_point", (0.0, 0.0)) | |
| binding = dimension.get("binding_point", definition) | |
| converted["dims"].append( | |
| ( | |
| int(dimension.get("dimtype", 0)), | |
| str(dimension.get("text", "")), | |
| str(dimension.get("layer", "0")), | |
| float(definition[0]), | |
| float(definition[1]), | |
| float(binding[0]), | |
| float(binding[1]), | |
| ) | |
| ) | |
| return converted | |
| def representation_quality(raw: dict[str, Any], canonical: dict[str, Any]) -> float: | |
| """Continuous anti-duplication score that does not punish edge splitting.""" | |
| raw_length = sum(math.dist(line[:2], line[2:4]) for line in raw.get("lines", [])) | |
| union_length = sum(math.dist(line[:2], line[2:4]) for line in canonical.get("lines", [])) | |
| line_quality = min(1.0, union_length / raw_length) if raw_length > 1e-12 else 1.0 | |
| primitive_qualities = [line_quality] | |
| for family in ("circles", "arcs"): | |
| values = raw.get(family, []) | |
| if values: | |
| keys = { | |
| tuple(round(float(item), 8) if isinstance(item, (int, float)) else str(item) for item in value) | |
| for value in values | |
| } | |
| primitive_qualities.append(len(keys) / len(values)) | |
| return float(np.mean(primitive_qualities)) | |
| __all__ = [ | |
| "canonicalize_entities", | |
| "extract_entities", | |
| "legacy_dimension_entities", | |
| "representation_quality", | |
| "score_dimension_consistency", | |
| "score_disk_semantics", | |
| ] | |