File size: 30,943 Bytes
15d1f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
#!/usr/bin/env python3
"""Robust semantic-view and primitive matching kernels for geometric v5.2.

The frozen v5/v5.1 evaluators estimate a sheet transform before they know
which primitives belong to which orthographic view.  A missing view or a
changed circle can therefore perturb the shared scale and contaminate every
downstream component.  This module reverses that order:

1. canonicalise and cluster each drawing independently;
2. match clusters to the audited GT semantic roles;
3. estimate one positive shared scale from the matched view envelopes;
4. compare geometry with a role-local translation and the shared scale.

No DXF handles or entity order are used for matching.
"""

from __future__ import annotations

import math
from itertools import combinations
from pathlib import Path
from typing import Any, Mapping, Sequence

import numpy as np
from scipy.optimize import linear_sum_assignment

try:
    from . import eval_geometric05 as EV5
except ImportError:  # direct evaluator import
    import eval_geometric05 as EV5


SCHEMA_VERSION = "view-entity-matching-v5.2"
MAX_PREDICTED_VIEW_CANDIDATES = 8
ROLE_CENTER_ACCEPT_FRAC = 0.20


def _round(value: float | None, digits: int = 6) -> float | None:
    if value is None or not math.isfinite(float(value)):
        return None
    return round(float(value), digits)


def _clip(value: float) -> float:
    return float(min(1.0, max(0.0, value)))


def _empty_entities() -> dict[str, list[Any]]:
    return {"lines": [], "circles": [], "arcs": [], "dims": []}


def _visibility(layer: Any) -> str:
    token = str(layer).casefold()
    return "hidden" if "hidden" in token or "dash" in token else "visible"


def _definition_rows(sidecar: Mapping[str, Any] | None) -> list[dict[str, Any]]:
    rows = EV5._normalise_sidecar_views(sidecar)
    names = [str(row.get("name")) for row in rows]
    if len(rows) != EV5.VIEW_TARGET_COUNT or len(set(names)) != len(names):
        return []
    return rows


def _target_views_by_role(
    canonical_gt: Mapping[str, Any], sidecar: Mapping[str, Any] | None
) -> tuple[dict[str, Mapping[str, Any]], str | None]:
    definitions = _definition_rows(sidecar)
    if not definitions:
        return {}, "sidecar_reference_view_count_mismatch"
    origin = np.zeros(2, dtype=float)
    views = EV5._views_from_reference_boxes(
        canonical_gt, definitions, origin, origin, 1.0
    )
    result: dict[str, Mapping[str, Any]] = {}
    for view in views:
        center = np.asarray(view["center"], dtype=float)
        matches = []
        for definition in definitions:
            x0, y0, x1, y1 = map(float, definition["bbox"])
            if (
                min(x0, x1) - 1e-7 <= center[0] <= max(x0, x1) + 1e-7
                and min(y0, y1) - 1e-7 <= center[1] <= max(y0, y1) + 1e-7
            ):
                matches.append(str(definition["name"]))
        if len(matches) != 1 or matches[0] in result:
            return {}, "target_semantic_partition_ambiguous"
        result[matches[0]] = view
    expected = {str(row["name"]) for row in definitions}
    if set(result) != expected:
        return {}, "target_semantic_partition_incomplete"
    return result, None


def _family_counts(entities: Mapping[str, Any]) -> dict[str, int]:
    lines = list(entities.get("lines", []))
    return {
        "visible_line": sum(_visibility(line[-1]) == "visible" for line in lines),
        "hidden_line": sum(_visibility(line[-1]) == "hidden" for line in lines),
        "circle": len(entities.get("circles", [])),
        "arc": len(entities.get("arcs", [])),
    }


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 float(2.0 * precision * recall / (precision + recall))


def _local_shape_score(
    predicted: Mapping[str, Any], target: Mapping[str, Any]
) -> tuple[float, dict[str, Any]]:
    pred_size = np.asarray(predicted["size"], dtype=float)
    gt_size = np.asarray(target["size"], dtype=float)
    pred_diag = float(np.linalg.norm(pred_size))
    gt_diag = max(float(np.linalg.norm(gt_size)), 1e-9)
    if pred_diag <= 1e-12:
        return 0.0, {"reason": "degenerate_predicted_view"}
    local_scale = gt_diag / pred_diag
    strict = EV5.EV3.score_geometry(
        predicted["entities"],
        target["entities"],
        np.asarray(predicted["center"], dtype=float),
        np.asarray(target["center"], dtype=float),
        local_scale,
        max(gt_diag, 1.0),
    )
    dense = float(
        EV5.EV3.dense_geometry_score(
            predicted["entities"],
            target["entities"],
            np.asarray(predicted["center"], dtype=float),
            np.asarray(target["center"], dtype=float),
            local_scale,
            max(gt_diag, 1.0),
        )
    )
    pred_counts, gt_counts = _family_counts(predicted["entities"]), _family_counts(target["entities"])
    active = [
        _count_f1(pred_counts[name], gt_counts[name])
        for name in pred_counts
        if pred_counts[name] or gt_counts[name]
    ]
    count_score = float(np.mean(active)) if active else 0.0
    pred_nonzero = pred_size[pred_size > 1e-12]
    gt_nonzero = gt_size[gt_size > 1e-12]
    if len(pred_nonzero) == 2 and len(gt_nonzero) == 2:
        pred_aspect = float(pred_nonzero[0] / pred_nonzero[1])
        gt_aspect = float(gt_nonzero[0] / gt_nonzero[1])
        aspect_score = math.exp(-abs(math.log(max(pred_aspect, 1e-12) / max(gt_aspect, 1e-12))))
    else:
        aspect_score = 1.0
    score = _clip(
        0.42 * dense
        + 0.33 * float(strict.get("score", 0.0))
        + 0.17 * count_score
        + 0.08 * aspect_score
    )
    return score, {
        "score": _round(score),
        "dense": _round(dense),
        "strict": _round(float(strict.get("score", 0.0))),
        "count": _round(count_score),
        "aspect": _round(aspect_score),
        "local_scale": _round(local_scale, 8),
    }


def _positive_ratio(numerator: float, denominator: float) -> float | None:
    if numerator <= 1e-12 or denominator <= 1e-12:
        return None
    value = float(numerator / denominator)
    return value if math.isfinite(value) and value > 1e-8 else None


def _candidate_scales(
    predicted: Sequence[Mapping[str, Any]], target: Sequence[Mapping[str, Any]]
) -> list[float]:
    values: list[float] = []
    for pred in predicted:
        pred_size = np.asarray(pred["size"], dtype=float)
        for gt in target:
            gt_size = np.asarray(gt["size"], dtype=float)
            for numerator, denominator in (
                (float(np.linalg.norm(gt_size)), float(np.linalg.norm(pred_size))),
                (float(gt_size[0]), float(pred_size[0])),
                (float(gt_size[1]), float(pred_size[1])),
            ):
                ratio = _positive_ratio(numerator, denominator)
                if ratio is not None:
                    values.append(ratio)
    pred_pairs = list(combinations(range(len(predicted)), 2))
    target_pairs = list(combinations(range(len(target)), 2))
    for first, second in pred_pairs:
        pred_distance = float(
            np.linalg.norm(
                np.asarray(predicted[first]["center"], dtype=float)
                - np.asarray(predicted[second]["center"], dtype=float)
            )
        )
        for gt_first, gt_second in target_pairs:
            gt_distance = float(
                np.linalg.norm(
                    np.asarray(target[gt_first]["center"], dtype=float)
                    - np.asarray(target[gt_second]["center"], dtype=float)
                )
            )
            ratio = _positive_ratio(gt_distance, pred_distance)
            if ratio is not None:
                values.append(ratio)
    if not values:
        return [1.0]
    unique: dict[float, float] = {}
    for value in values:
        key = round(math.log(value), 6)
        unique.setdefault(key, value)
    return list(unique.values())


def _assignment(
    predicted: Sequence[Mapping[str, Any]],
    target: Sequence[Mapping[str, Any]],
    shape: np.ndarray,
    scale: float,
    translation: np.ndarray,
    sheet_diagonal: float,
) -> tuple[list[tuple[int, int]], np.ndarray, np.ndarray]:
    pred_centers = np.stack([np.asarray(view["center"], dtype=float) for view in predicted])
    gt_centers = np.stack([np.asarray(view["center"], dtype=float) for view in target])
    transformed = pred_centers * float(scale) + np.asarray(translation, dtype=float)
    center_error = np.linalg.norm(transformed[:, None, :] - gt_centers[None, :, :], axis=2) / max(sheet_diagonal, 1e-9)
    cost = center_error + 0.16 * (1.0 - shape)
    rows, columns = linear_sum_assignment(cost)
    pairs = [(int(row), int(column)) for row, column in zip(rows, columns)]
    return pairs, center_error, cost


def _fit_semantic_alignment(
    predicted: Sequence[Mapping[str, Any]],
    roles: Sequence[str],
    target: Sequence[Mapping[str, Any]],
) -> dict[str, Any]:
    if not predicted:
        return {
            "eligible": True,
            "reason": "prediction_has_no_views",
            "global_scale": 1.0,
            "translation": np.zeros(2, dtype=float),
            "role_to_pred": {},
            "pairs": [],
            "extra_predicted_indices": [],
            "shape_details": {},
        }
    target_lows = np.stack([np.asarray(view["low"], dtype=float) for view in target])
    target_highs = np.stack([np.asarray(view["high"], dtype=float) for view in target])
    sheet_diagonal = max(
        float(np.linalg.norm(np.max(target_highs, axis=0) - np.min(target_lows, axis=0))),
        1.0,
    )
    shape = np.zeros((len(predicted), len(target)), dtype=float)
    shape_details: dict[tuple[int, int], dict[str, Any]] = {}
    for pred_index, pred_view in enumerate(predicted):
        for gt_index, gt_view in enumerate(target):
            value, detail = _local_shape_score(pred_view, gt_view)
            shape[pred_index, gt_index] = value
            shape_details[(pred_index, gt_index)] = detail

    best: dict[str, Any] | None = None
    for scale in _candidate_scales(predicted, target):
        for pred_index, pred_view in enumerate(predicted):
            pred_center = np.asarray(pred_view["center"], dtype=float)
            for gt_index, gt_view in enumerate(target):
                translation = np.asarray(gt_view["center"], dtype=float) - scale * pred_center
                pairs: list[tuple[int, int]] = []
                center_error = np.empty((len(predicted), len(target)), dtype=float)
                cost = center_error
                for _ in range(2):
                    pairs, center_error, cost = _assignment(
                        predicted, target, shape, scale, translation, sheet_diagonal
                    )
                    offsets = [
                        np.asarray(target[gt]["center"], dtype=float)
                        - scale * np.asarray(predicted[pred]["center"], dtype=float)
                        for pred, gt in pairs
                    ]
                    if offsets:
                        translation = np.median(np.stack(offsets), axis=0)
                pairs, center_error, cost = _assignment(
                    predicted, target, shape, scale, translation, sheet_diagonal
                )
                matched_center = [min(float(center_error[pred, gt]), 1.0) for pred, gt in pairs]
                matched_shape = [float(shape[pred, gt]) for pred, gt in pairs]
                missing = len(target) - len(pairs)
                objective = (
                    0.72 * (sum(matched_center) + missing) / len(target)
                    + 0.20 * (sum(1.0 - value for value in matched_shape) + missing) / len(target)
                    + 0.08 * missing / len(target)
                )
                candidate = {
                    "objective": objective,
                    "scale": float(scale),
                    "translation": np.asarray(translation, dtype=float),
                    "pairs": pairs,
                    "center_error": center_error,
                }
                if best is None or candidate["objective"] < best["objective"]:
                    best = candidate
    assert best is not None

    # Re-estimate the shared scale from matched view envelopes and inter-view
    # distances.  Taking the median in log space prevents one mutated circle,
    # arc, or locally scaled view from setting the scale for the whole sheet.
    ratios: list[float] = []
    for pred_index, gt_index in best["pairs"]:
        pred_size = np.asarray(predicted[pred_index]["size"], dtype=float)
        gt_size = np.asarray(target[gt_index]["size"], dtype=float)
        for axis in range(2):
            ratio = _positive_ratio(float(gt_size[axis]), float(pred_size[axis]))
            if ratio is not None:
                ratios.append(ratio)
    for (pred_a, gt_a), (pred_b, gt_b) in combinations(best["pairs"], 2):
        pred_distance = float(
            np.linalg.norm(
                np.asarray(predicted[pred_a]["center"], dtype=float)
                - np.asarray(predicted[pred_b]["center"], dtype=float)
            )
        )
        gt_distance = float(
            np.linalg.norm(
                np.asarray(target[gt_a]["center"], dtype=float)
                - np.asarray(target[gt_b]["center"], dtype=float)
            )
        )
        ratio = _positive_ratio(gt_distance, pred_distance)
        if ratio is not None:
            ratios.append(ratio)
    scale = (
        float(math.exp(float(np.median(np.log(np.asarray(ratios, dtype=float))))))
        if ratios
        else float(best["scale"])
    )
    offsets = [
        np.asarray(target[gt]["center"], dtype=float)
        - scale * np.asarray(predicted[pred]["center"], dtype=float)
        for pred, gt in best["pairs"]
    ]
    translation = np.median(np.stack(offsets), axis=0) if offsets else np.zeros(2, dtype=float)
    pairs, center_error, _ = _assignment(
        predicted, target, shape, scale, translation, sheet_diagonal
    )
    accepted = [
        (pred, gt)
        for pred, gt in pairs
        if float(center_error[pred, gt]) <= ROLE_CENTER_ACCEPT_FRAC
    ]
    role_to_pred = {roles[gt]: pred for pred, gt in accepted}
    used = {pred for pred, _ in accepted}
    pair_rows = [
        {
            "role": roles[gt],
            "predicted_index": pred,
            "target_index": gt,
            "accepted": (pred, gt) in accepted,
            "center_error_fraction": _round(float(center_error[pred, gt])),
            "shape_score": _round(float(shape[pred, gt])),
            "shape": shape_details[(pred, gt)],
        }
        for pred, gt in pairs
    ]
    return {
        "eligible": True,
        "reason": "ok" if len(accepted) == len(target) else "semantic_roles_missing",
        "global_scale": scale,
        "translation": translation,
        "sheet_diagonal": sheet_diagonal,
        "role_to_pred": role_to_pred,
        "pairs": pair_rows,
        "extra_predicted_indices": sorted(set(range(len(predicted))) - used),
        "shape_details": shape_details,
        "objective": float(best["objective"]),
    }


def build_pair_context(
    pred: str | Path,
    gt: str | Path,
    *,
    sidecar: Mapping[str, Any] | None,
) -> dict[str, Any]:
    pred_path, gt_path = Path(pred), Path(gt)
    pred_meta, gt_meta = EV5._read_structure(pred_path), EV5._read_structure(gt_path)
    raw_pred = EV5._extract_entities(pred_path) if pred_meta.get("readable") else None
    raw_gt = EV5._extract_entities(gt_path) if gt_meta.get("readable") else None
    target_valid = bool(raw_gt and EV5._n_geometry(raw_gt) and EV5._safe_bbox(raw_gt) is not None)
    prediction_valid = bool(raw_pred and EV5._n_geometry(raw_pred) and EV5._safe_bbox(raw_pred) is not None)
    context: dict[str, Any] = {
        "schema_version": SCHEMA_VERSION,
        "target_valid": target_valid,
        "prediction_valid": prediction_valid,
        "pred_meta": pred_meta,
        "gt_meta": gt_meta,
        "raw_pred": raw_pred,
        "raw_gt": raw_gt,
    }
    if not target_valid:
        context.update({"eligible": False, "reason": "target_dxf_unreadable_or_degenerate"})
        return context
    canonical_gt = EV5.EV4.canonicalize_entities(raw_gt)
    gt_by_role, error = _target_views_by_role(canonical_gt, sidecar)
    if error:
        context.update(
            {
                "eligible": False,
                "reason": error,
                "canonical_gt": canonical_gt,
            }
        )
        return context
    context["canonical_gt"] = canonical_gt
    context["gt_by_role"] = gt_by_role
    if not prediction_valid:
        context.update(
            {
                "eligible": True,
                "reason": "prediction_dxf_unreadable_or_degenerate",
                "canonical_pred": _empty_entities(),
                "pred_views": [],
                "alignment": _fit_semantic_alignment([], list(gt_by_role), list(gt_by_role.values())),
            }
        )
        return context
    canonical_pred = EV5.EV4.canonicalize_entities(raw_pred)
    pred_views_all = EV5._cluster_views(canonical_pred)
    ranked = sorted(
        enumerate(pred_views_all),
        key=lambda item: (
            int(item[1].get("n_primitives", 0)),
            float(np.linalg.norm(np.asarray(item[1].get("size", (0.0, 0.0)), dtype=float))),
        ),
        reverse=True,
    )
    selected_pairs = ranked[:MAX_PREDICTED_VIEW_CANDIDATES]
    pred_views = [view for _, view in selected_pairs]
    selected_original_indices = [index for index, _ in selected_pairs]
    roles = list(gt_by_role)
    alignment = _fit_semantic_alignment(pred_views, roles, [gt_by_role[role] for role in roles])
    alignment["selected_original_indices"] = selected_original_indices
    alignment["omitted_original_indices"] = [
        index for index in range(len(pred_views_all)) if index not in selected_original_indices
    ]
    context.update(
        {
            "eligible": True,
            "reason": alignment["reason"],
            "canonical_pred": canonical_pred,
            "pred_views": pred_views,
            "pred_views_all": pred_views_all,
            "alignment": alignment,
        }
    )
    return context


def role_local_transform(
    context: Mapping[str, Any], role: str
) -> tuple[float, np.ndarray] | None:
    alignment = context.get("alignment", {})
    role_to_pred = alignment.get("role_to_pred", {}) if isinstance(alignment, Mapping) else {}
    pred_index = role_to_pred.get(role) if isinstance(role_to_pred, Mapping) else None
    gt_by_role = context.get("gt_by_role", {})
    pred_views = context.get("pred_views", [])
    if not isinstance(pred_index, int) or role not in gt_by_role or not 0 <= pred_index < len(pred_views):
        return None
    scale = float(alignment.get("global_scale", 1.0))
    translation = (
        np.asarray(gt_by_role[role]["center"], dtype=float)
        - scale * np.asarray(pred_views[pred_index]["center"], dtype=float)
    )
    return scale, translation


def _prf(matched: int, predicted: int, target: int) -> dict[str, Any]:
    eligible = bool(predicted or target)
    if not eligible:
        return {
            "eligible": False,
            "matched": 0,
            "predicted": 0,
            "target": 0,
            "precision": None,
            "recall": None,
            "f1": None,
        }
    precision = matched / predicted if predicted else 0.0
    recall = matched / target if target else 1.0
    f1 = 0.0 if precision + recall <= 0.0 else 2.0 * precision * recall / (precision + recall)
    return {
        "eligible": True,
        "matched": int(matched),
        "predicted": int(predicted),
        "target": int(target),
        "precision": _round(precision),
        "recall": _round(recall),
        "f1": _round(f1),
    }


def _line_array(line: Sequence[Any], scale: float, translation: np.ndarray) -> np.ndarray:
    points = np.asarray([[line[0], line[1]], [line[2], line[3]]], dtype=float)
    return points * scale + translation


def _line_error(first: np.ndarray, second: np.ndarray, diagonal: float) -> float:
    direct = float(np.linalg.norm(first[0] - second[0]) + np.linalg.norm(first[1] - second[1]))
    reverse = float(np.linalg.norm(first[0] - second[1]) + np.linalg.norm(first[1] - second[0]))
    return min(direct, reverse) / (2.0 * max(diagonal, 1e-9))


def _match_lines(
    predicted: Sequence[Sequence[Any]],
    target: Sequence[Sequence[Any]],
    *,
    scale: float,
    translation: np.ndarray,
    diagonal: float,
) -> dict[str, Any]:
    if not predicted or not target:
        result = _prf(0, len(predicted), len(target))
        result.update({"mean_endpoint_error": None, "worst_endpoint_error": None, "pairs": []})
        return result
    pred_arrays = [_line_array(line, scale, translation) for line in predicted]
    gt_arrays = [_line_array(line, 1.0, np.zeros(2, dtype=float)) for line in target]
    costs = np.asarray(
        [[_line_error(pred, gt, diagonal) for gt in gt_arrays] for pred in pred_arrays],
        dtype=float,
    )
    rows, columns = linear_sum_assignment(costs)
    pairs = []
    errors = []
    for row, column in zip(rows, columns):
        error = float(costs[row, column])
        if error <= 0.02:
            errors.append(error)
            pairs.append(
                {
                    "predicted_index": int(row),
                    "target_index": int(column),
                    "endpoint_error_fraction": _round(error),
                }
            )
    result = _prf(len(pairs), len(predicted), len(target))
    result.update(
        {
            "mean_endpoint_error": _round(float(np.mean(errors))) if errors else None,
            "worst_endpoint_error": _round(max(errors)) if errors else None,
            "parameter_score": _round(math.exp(-float(np.mean(errors)) / 0.01)) if errors else (0.0 if target else None),
            "pairs": pairs,
        }
    )
    return result


def _circle_record(circle: Sequence[Any], scale: float, translation: np.ndarray) -> tuple[np.ndarray, float, str]:
    center = np.asarray([circle[0], circle[1]], dtype=float) * scale + translation
    return center, abs(float(circle[2])) * scale, _visibility(circle[-1])


def _match_circles(
    predicted: Sequence[Sequence[Any]],
    target: Sequence[Sequence[Any]],
    *,
    scale: float,
    translation: np.ndarray,
    diagonal: float,
) -> dict[str, Any]:
    if not predicted or not target:
        result = _prf(0, len(predicted), len(target))
        result.update({"mean_radius_log_error": None, "worst_radius_log_error": None, "parameter_score": 0.0 if target else None, "pairs": []})
        return result
    pred_records = [_circle_record(item, scale, translation) for item in predicted]
    gt_records = [_circle_record(item, 1.0, np.zeros(2, dtype=float)) for item in target]
    costs = np.zeros((len(predicted), len(target)), dtype=float)
    raw: dict[tuple[int, int], tuple[float, float, float, bool]] = {}
    for p, (pred_center, pred_radius, pred_visibility) in enumerate(pred_records):
        for g, (gt_center, gt_radius, gt_visibility) in enumerate(gt_records):
            center_error = float(np.linalg.norm(pred_center - gt_center) / max(diagonal, 1e-9))
            log_error = abs(math.log(max(pred_radius, 1e-12) / max(gt_radius, 1e-12)))
            relative_error = abs(pred_radius / max(gt_radius, 1e-12) - 1.0)
            visibility_ok = pred_visibility == gt_visibility
            costs[p, g] = center_error + 0.35 * log_error + (0.5 if not visibility_ok else 0.0)
            raw[(p, g)] = (center_error, log_error, relative_error, visibility_ok)
    rows, columns = linear_sum_assignment(costs)
    pairs, log_errors = [], []
    for row, column in zip(rows, columns):
        center_error, log_error, relative_error, visibility_ok = raw[(int(row), int(column))]
        if center_error <= 0.08 and log_error <= math.log(2.0) and visibility_ok:
            log_errors.append(log_error)
            pairs.append(
                {
                    "predicted_index": int(row),
                    "target_index": int(column),
                    "center_error_fraction": _round(center_error),
                    "radius_log_error": _round(log_error),
                    "radius_relative_error": _round(relative_error),
                    "diameter_relative_error": _round(relative_error),
                }
            )
    result = _prf(len(pairs), len(predicted), len(target))
    result.update(
        {
            "mean_radius_log_error": _round(float(np.mean(log_errors))) if log_errors else None,
            "worst_radius_log_error": _round(max(log_errors)) if log_errors else None,
            "parameter_score": _round(math.exp(-float(np.mean(log_errors)) / 0.10)) if log_errors else (0.0 if target else None),
            "pairs": pairs,
        }
    )
    return result


def _angle_distance(first: float, second: float) -> float:
    return abs((float(first) - float(second) + 180.0) % 360.0 - 180.0)


def _arc_record(arc: Sequence[Any], scale: float, translation: np.ndarray) -> tuple[np.ndarray, float, float, float, float, str]:
    center = np.asarray([arc[0], arc[1]], dtype=float) * scale + translation
    start, end = float(arc[3]) % 360.0, float(arc[4]) % 360.0
    sweep = (end - start) % 360.0
    if sweep <= 1e-9:
        sweep = 360.0
    return center, abs(float(arc[2])) * scale, start, end, sweep, _visibility(arc[-1])


def _match_arcs(
    predicted: Sequence[Sequence[Any]],
    target: Sequence[Sequence[Any]],
    *,
    scale: float,
    translation: np.ndarray,
    diagonal: float,
) -> dict[str, Any]:
    if not predicted or not target:
        result = _prf(0, len(predicted), len(target))
        result.update({"mean_radius_log_error": None, "mean_sweep_error_fraction": None, "parameter_score": 0.0 if target else None, "pairs": []})
        return result
    pred_records = [_arc_record(item, scale, translation) for item in predicted]
    gt_records = [_arc_record(item, 1.0, np.zeros(2, dtype=float)) for item in target]
    costs = np.zeros((len(predicted), len(target)), dtype=float)
    raw: dict[tuple[int, int], tuple[float, float, float, float, bool]] = {}
    for p, pred in enumerate(pred_records):
        for g, target_item in enumerate(gt_records):
            center_error = float(np.linalg.norm(pred[0] - target_item[0]) / max(diagonal, 1e-9))
            radius_error = abs(math.log(max(pred[1], 1e-12) / max(target_item[1], 1e-12)))
            radius_relative = abs(pred[1] / max(target_item[1], 1e-12) - 1.0)
            sweep_error = abs(pred[4] - target_item[4]) / 360.0
            angle_error = (_angle_distance(pred[2], target_item[2]) + _angle_distance(pred[3], target_item[3])) / 720.0
            visibility_ok = pred[5] == target_item[5]
            costs[p, g] = center_error + 0.30 * radius_error + 0.25 * sweep_error + 0.15 * angle_error + (0.5 if not visibility_ok else 0.0)
            raw[(p, g)] = (center_error, radius_error, radius_relative, sweep_error, visibility_ok)
    rows, columns = linear_sum_assignment(costs)
    pairs, parameter_errors = [], []
    for row, column in zip(rows, columns):
        center_error, radius_error, radius_relative, sweep_error, visibility_ok = raw[(int(row), int(column))]
        if center_error <= 0.08 and radius_error <= math.log(2.0) and sweep_error <= 0.25 and visibility_ok:
            combined = radius_error + sweep_error
            parameter_errors.append(combined)
            pairs.append(
                {
                    "predicted_index": int(row),
                    "target_index": int(column),
                    "center_error_fraction": _round(center_error),
                    "radius_log_error": _round(radius_error),
                    "radius_relative_error": _round(radius_relative),
                    "sweep_error_fraction": _round(sweep_error),
                }
            )
    result = _prf(len(pairs), len(predicted), len(target))
    result.update(
        {
            "mean_radius_log_error": _round(float(np.mean([row["radius_log_error"] for row in pairs]))) if pairs else None,
            "mean_sweep_error_fraction": _round(float(np.mean([row["sweep_error_fraction"] for row in pairs]))) if pairs else None,
            "parameter_score": _round(math.exp(-float(np.mean(parameter_errors)) / 0.10)) if parameter_errors else (0.0 if target else None),
            "pairs": pairs,
        }
    )
    return result


def match_view_primitives(
    predicted_view: Mapping[str, Any] | None,
    target_view: Mapping[str, Any],
    *,
    global_scale: float,
) -> dict[str, Any]:
    target_entities = target_view["entities"]
    predicted_entities = predicted_view["entities"] if predicted_view is not None else _empty_entities()
    diagonal = max(float(np.linalg.norm(np.asarray(target_view["size"], dtype=float))), 1.0)
    if predicted_view is None:
        translation = np.zeros(2, dtype=float)
    else:
        translation = (
            np.asarray(target_view["center"], dtype=float)
            - global_scale * np.asarray(predicted_view["center"], dtype=float)
        )
    pred_visible = [line for line in predicted_entities.get("lines", []) if _visibility(line[-1]) == "visible"]
    gt_visible = [line for line in target_entities.get("lines", []) if _visibility(line[-1]) == "visible"]
    pred_hidden = [line for line in predicted_entities.get("lines", []) if _visibility(line[-1]) == "hidden"]
    gt_hidden = [line for line in target_entities.get("lines", []) if _visibility(line[-1]) == "hidden"]
    return {
        "visible_line": _match_lines(
            pred_visible, gt_visible, scale=global_scale, translation=translation, diagonal=diagonal
        ),
        "hidden_line": _match_lines(
            pred_hidden, gt_hidden, scale=global_scale, translation=translation, diagonal=diagonal
        ),
        "circle": _match_circles(
            list(predicted_entities.get("circles", [])),
            list(target_entities.get("circles", [])),
            scale=global_scale,
            translation=translation,
            diagonal=diagonal,
        ),
        "arc": _match_arcs(
            list(predicted_entities.get("arcs", [])),
            list(target_entities.get("arcs", [])),
            scale=global_scale,
            translation=translation,
            diagonal=diagonal,
        ),
        "local_translation": [float(value) for value in translation],
        "target_diagonal": diagonal,
    }


__all__ = [
    "MAX_PREDICTED_VIEW_CANDIDATES",
    "ROLE_CENTER_ACCEPT_FRAC",
    "SCHEMA_VERSION",
    "build_pair_context",
    "match_view_primitives",
    "role_local_transform",
]