File size: 25,009 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
#!/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",
]