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 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Topology-aware v3 geometry helpers for indexed EDP DSL evaluation.

V3 deliberately lives beside eval_geometric02.py.  The legacy endpoint metric
is retained as a diagnostic, while the headline line metric matches complete,
undirected segments one-to-one.  This makes a missing or duplicated segment
visible to both reporting and the dense reward.

Alignment is translation and isotropic-scale invariant, with no rotation.  A
coordinate-wise median and median radial scale replace the unstable nearest-
neighbour ICP initialisation used by v2.  Absolute page placement and relative
three-view layout are reported separately and do not affect the invariant shape
score.
"""

from __future__ import annotations

from collections import Counter
from typing import Any, Iterable

import numpy as np
from scipy.optimize import linear_sum_assignment

import eval_geometric02 as V2


TAU_FRACS = V2.TAU_FRACS
TAU_HEADLINE_IDX = V2.TAU_HEADLINE_IDX
DENSE_SIGMA_FRAC = V2.DENSE_SIGMA_FRAC
DENSE_LENGTH_RHO = 0.25
USABLE_BASE = V2.USABLE_BASE

# Re-export stable v2 helpers used by the reward/evaluator.
extract_entities = V2.extract_entities
n_entities = V2.n_entities
bbox_diagonal = V2.bbox_diagonal
score_annotation = V2.score_annotation
geometry_soft_gate = V2.geometry_soft_gate
compute_overall = V2.compute_overall
transform_points = V2.transform_points


def collect_alignment_points(entities: dict[str, Any]) -> np.ndarray:
    """Collect unique visible support points without sampling line interiors."""

    points: set[tuple[float, float]] = set()
    for x1, y1, x2, y2, layer in entities["lines"]:
        if "hidden" not in layer.lower():
            points.add((round(float(x1), 6), round(float(y1), 6)))
            points.add((round(float(x2), 6), round(float(y2), 6)))
    for cx, cy, radius, layer in entities["circles"]:
        if "hidden" not in layer.lower():
            points.add((round(float(cx), 6), round(float(cy), 6)))
            points.add((round(float(cx + radius), 6), round(float(cy), 6)))
            points.add((round(float(cx - radius), 6), round(float(cy), 6)))
            points.add((round(float(cx), 6), round(float(cy + radius), 6)))
            points.add((round(float(cx), 6), round(float(cy - radius), 6)))
    for cx, cy, radius, start, end, layer in entities["arcs"]:
        if "hidden" not in layer.lower():
            for x, y in V2._arc_geometry_points(
                cx, cy, radius, start, end, midpoint=True
            ):
                points.add((round(float(x), 6), round(float(y), 6)))
    if not points:
        return np.empty((0, 2), dtype=float)
    return np.asarray(sorted(points), dtype=float)


def _robust_location_scale(points: np.ndarray) -> tuple[np.ndarray, float]:
    if len(points) == 0:
        return np.zeros(2, dtype=float), 1.0
    center = np.median(points, axis=0)
    radial = np.linalg.norm(points - center, axis=1)
    positive = radial[radial > 1e-12]
    if len(positive):
        radius = float(np.median(positive))
    else:
        radius = 1.0
    return center.astype(float), max(radius, 1e-12)


def shared_alignment(
    ent_pred: dict[str, Any], ent_gt: dict[str, Any]
) -> tuple[np.ndarray, np.ndarray, float]:
    """Return one robust translate+scale transform shared by all submetrics."""

    source = collect_alignment_points(ent_pred)
    target = collect_alignment_points(ent_gt)
    if len(source) == 0 or len(target) == 0:
        return np.zeros(2), np.zeros(2), 1.0
    source_center, source_radius = _robust_location_scale(source)
    target_center, target_radius = _robust_location_scale(target)
    scale = target_radius / source_radius
    if not np.isfinite(scale) or scale <= 0:
        scale = 1.0
    return source_center, target_center, float(scale)


def _segments(lines: Iterable[tuple[Any, ...]]) -> np.ndarray:
    values = [
        [[float(line[0]), float(line[1])], [float(line[2]), float(line[3])]]
        for line in lines
    ]
    if not values:
        return np.empty((0, 2, 2), dtype=float)
    return np.asarray(values, dtype=float)


def _transform_segments(
    segments: np.ndarray,
    source_center: np.ndarray,
    target_center: np.ndarray,
    scale: float,
) -> np.ndarray:
    if not len(segments):
        return segments
    flattened = segments.reshape((-1, 2))
    return transform_points(
        flattened, source_center, target_center, scale
    ).reshape((-1, 2, 2))


def _endpoint_error_matrix(predicted: np.ndarray, target: np.ndarray) -> np.ndarray:
    """Mean endpoint distance for undirected segment pairs."""

    direct = 0.5 * (
        np.linalg.norm(predicted[:, None, 0] - target[None, :, 0], axis=2)
        + np.linalg.norm(predicted[:, None, 1] - target[None, :, 1], axis=2)
    )
    reverse = 0.5 * (
        np.linalg.norm(predicted[:, None, 0] - target[None, :, 1], axis=2)
        + np.linalg.norm(predicted[:, None, 1] - target[None, :, 0], axis=2)
    )
    return np.minimum(direct, reverse)


def _f1(precision: float, recall: float) -> float:
    if precision + recall <= 0:
        return 0.0
    return float(2.0 * precision * recall / (precision + recall))


def _canonical_line(line: tuple[Any, ...]) -> tuple[Any, ...]:
    first = (round(float(line[0]), 6), round(float(line[1]), 6))
    second = (round(float(line[2]), 6), round(float(line[3]), 6))
    visibility = "H" if "hidden" in str(line[4]).lower() else "V"
    low, high = sorted((first, second))
    return visibility, low, high


def _duplicate_count(lines: Iterable[tuple[Any, ...]]) -> int:
    counts = Counter(_canonical_line(line) for line in lines)
    return int(sum(max(0, count - 1) for count in counts.values()))


def _segment_f1_block(
    pred_lines: list[tuple[Any, ...]],
    gt_lines: list[tuple[Any, ...]],
    src_c: np.ndarray,
    dst_c: np.ndarray,
    scale: float,
    gt_diag: float,
) -> dict[str, Any]:
    predicted = _segments(pred_lines)
    target = _segments(gt_lines)
    n_pred, n_gt = len(predicted), len(target)
    legacy = V2._line_f1_block(
        pred_lines, gt_lines, src_c, dst_c, scale, gt_diag
    )
    if n_pred == 0 and n_gt == 0:
        return {
            "present": False,
            "f1": 1.0,
            "precision": 1.0,
            "recall": 1.0,
            "matched": 0,
            "n_pred": 0,
            "n_gt": 0,
            "f1_at": {},
            "headline_tau_mm": None,
            "endpoint_error_mean_mm": None,
            "duplicate_pred": 0,
            "duplicate_gt": 0,
            "legacy_vertex": legacy,
        }
    if n_pred == 0 or n_gt == 0:
        return {
            "present": True,
            "f1": 0.0,
            "precision": 0.0,
            "recall": 0.0,
            "matched": 0,
            "n_pred": n_pred,
            "n_gt": n_gt,
            "f1_at": {f"{frac:.3f}": 0.0 for frac in TAU_FRACS},
            "headline_tau_mm": round(
                TAU_FRACS[TAU_HEADLINE_IDX] * max(gt_diag, 1.0), 4
            ),
            "endpoint_error_mean_mm": None,
            "duplicate_pred": _duplicate_count(pred_lines),
            "duplicate_gt": _duplicate_count(gt_lines),
            "legacy_vertex": legacy,
        }

    aligned = _transform_segments(predicted, src_c, dst_c, scale)
    errors = _endpoint_error_matrix(aligned, target)
    row_indices, column_indices = linear_sum_assignment(errors)
    assigned = errors[row_indices, column_indices]
    diagonal = gt_diag if gt_diag > 1e-6 else 1.0
    f1_at: dict[str, float] = {}
    details: dict[float, tuple[int, float, float, float]] = {}
    for fraction in TAU_FRACS:
        matched = int(np.count_nonzero(assigned <= fraction * diagonal))
        precision = matched / n_pred
        recall = matched / n_gt
        value = _f1(precision, recall)
        details[fraction] = (matched, precision, recall, value)
        f1_at[f"{fraction:.3f}"] = round(value, 4)
    headline = TAU_FRACS[TAU_HEADLINE_IDX]
    matched, precision, recall, value = details[headline]
    accepted = assigned[assigned <= headline * diagonal]
    return {
        "present": True,
        "f1": round(value, 4),
        "precision": round(float(precision), 4),
        "recall": round(float(recall), 4),
        "matched": matched,
        "n_pred": n_pred,
        "n_gt": n_gt,
        "f1_at": f1_at,
        "headline_tau_mm": round(headline * diagonal, 4),
        "endpoint_error_mean_mm": (
            round(float(np.mean(accepted)), 4) if len(accepted) else None
        ),
        "duplicate_pred": _duplicate_count(pred_lines),
        "duplicate_gt": _duplicate_count(gt_lines),
        "legacy_vertex": legacy,
    }


def _dense_segments(
    pred_lines: list[tuple[Any, ...]],
    gt_lines: list[tuple[Any, ...]],
    src_c: np.ndarray,
    dst_c: np.ndarray,
    scale: float,
    gt_diag: float,
) -> float:
    predicted = _segments(pred_lines)
    target = _segments(gt_lines)
    n_pred, n_gt = len(predicted), len(target)
    if n_pred == 0 and n_gt == 0:
        return 1.0
    if n_pred == 0 or n_gt == 0:
        return 0.0
    aligned = _transform_segments(predicted, src_c, dst_c, scale)
    errors = _endpoint_error_matrix(aligned, target)
    pred_lengths = np.linalg.norm(aligned[:, 1] - aligned[:, 0], axis=1)
    gt_lengths = np.linalg.norm(target[:, 1] - target[:, 0], axis=1)
    length_error = np.abs(
        np.log(
            (pred_lengths[:, None] + 1e-9)
            / (gt_lengths[None, :] + 1e-9)
        )
    )
    sigma = max(1e-6, DENSE_SIGMA_FRAC * max(gt_diag, 1.0))
    quality = np.exp(-errors / sigma) * np.exp(-length_error / DENSE_LENGTH_RHO)
    row_indices, column_indices = linear_sum_assignment(-quality)
    matched_quality = float(quality[row_indices, column_indices].sum())
    return _f1(matched_quality / n_pred, matched_quality / n_gt)


def _split_lines(entities: dict[str, Any]) -> tuple[list[Any], list[Any]]:
    visible = [
        line for line in entities["lines"] if "hidden" not in line[-1].lower()
    ]
    hidden = [
        line for line in entities["lines"] if "hidden" in line[-1].lower()
    ]
    return visible, hidden


def _primitive_key(entity: tuple[Any, ...], family: str) -> tuple[Any, ...]:
    visibility = "H" if "hidden" in str(entity[-1]).lower() else "V"
    if family == "lines":
        return _canonical_line(entity)
    values = tuple(round(float(value), 6) for value in entity[:-1])
    return (family, visibility, *values)


def topology_count_diagnostics(
    ent_pred: dict[str, Any], ent_gt: dict[str, Any]
) -> dict[str, Any]:
    pred_counter: Counter[tuple[Any, ...]] = Counter()
    gt_counter: Counter[tuple[Any, ...]] = Counter()
    for family in ("lines", "circles", "arcs"):
        pred_counter.update(_primitive_key(item, family) for item in ent_pred[family])
        gt_counter.update(_primitive_key(item, family) for item in ent_gt[family])
    n_pred = sum(pred_counter.values())
    n_gt = sum(gt_counter.values())
    duplicate_pred = sum(max(0, count - 1) for count in pred_counter.values())
    duplicate_gt = sum(max(0, count - 1) for count in gt_counter.values())
    # Compare excess multiplicity, not untranslated absolute entity keys.
    # This keeps global translation/scale semantically invariant.
    excess_duplicate = max(0, duplicate_pred - duplicate_gt)
    return {
        "n_pred": int(n_pred),
        "n_gt": int(n_gt),
        "count_precision": round(min(1.0, n_gt / max(n_pred, 1)), 6),
        "count_recall": round(min(1.0, n_pred / max(n_gt, 1)), 6),
        "duplicate_pred": int(duplicate_pred),
        "duplicate_gt": int(duplicate_gt),
        "excess_duplicate": int(excess_duplicate),
        "excess_duplicate_ratio": round(
            excess_duplicate / max(n_pred, 1), 6
        ),
    }


def score_geometry(
    ent_pred: dict[str, Any],
    ent_gt: dict[str, Any],
    src_c: np.ndarray,
    dst_c: np.ndarray,
    scale: float,
    gt_diag: float,
) -> dict[str, Any]:
    vis_pred, hid_pred = _split_lines(ent_pred)
    vis_gt, hid_gt = _split_lines(ent_gt)
    lines = _segment_f1_block(
        vis_pred, vis_gt, src_c, dst_c, scale, gt_diag
    )
    hidden = _segment_f1_block(
        hid_pred, hid_gt, src_c, dst_c, scale, gt_diag
    )
    circles = V2._match_circles(
        ent_pred, ent_gt, src_c, dst_c, scale, gt_diag
    )
    arcs = V2._match_arcs(ent_pred, ent_gt, src_c, dst_c, scale, gt_diag)
    parts = [(lines["f1"], 1.0)]
    if hid_pred or hid_gt:
        parts.append((hidden["f1"], 0.5))
    if circles["n_pred"] or circles["n_gt"]:
        parts.append((circles["match_f1"], 1.0))
    if arcs["n_pred"] or arcs["n_gt"]:
        parts.append((arcs["match_f1"], 1.0))
    denominator = sum(weight for _, weight in parts)
    score = sum(value * weight for value, weight in parts) / denominator
    return {
        "lines": lines,
        "hidden": hidden,
        "circles": circles,
        "arcs": arcs,
        "topology": topology_count_diagnostics(ent_pred, ent_gt),
        "score": round(float(score), 4),
    }


def dense_geometry_score(
    ent_pred: dict[str, Any],
    ent_gt: dict[str, Any],
    src_c: np.ndarray,
    dst_c: np.ndarray,
    scale: float,
    gt_diag: float,
) -> float:
    vis_pred, hid_pred = _split_lines(ent_pred)
    vis_gt, hid_gt = _split_lines(ent_gt)
    parts = [(
        _dense_segments(vis_pred, vis_gt, src_c, dst_c, scale, gt_diag),
        1.0,
    )]
    if hid_pred or hid_gt:
        parts.append((
            _dense_segments(hid_pred, hid_gt, src_c, dst_c, scale, gt_diag),
            0.5,
        ))
    if V2._has_family(ent_pred, ent_gt, "circles"):
        parts.append((
            V2._dense_circles(
                ent_pred, ent_gt, src_c, dst_c, scale, gt_diag, "circles"
            ),
            1.0,
        ))
    if V2._has_family(ent_pred, ent_gt, "arcs"):
        parts.append((
            V2._dense_circles(
                ent_pred, ent_gt, src_c, dst_c, scale, gt_diag, "arcs"
            ),
            1.0,
        ))
    denominator = sum(weight for _, weight in parts)
    return float(sum(value * weight for value, weight in parts) / denominator)


def _support_points(entities: dict[str, Any]) -> np.ndarray:
    return collect_alignment_points(entities)


def _bbox(points: np.ndarray) -> tuple[np.ndarray, np.ndarray] | None:
    if len(points) == 0:
        return None
    return points.min(axis=0), points.max(axis=0)


def _deterministic_centroids(points: np.ndarray, count: int = 3) -> np.ndarray:
    unique = np.unique(points, axis=0)
    if len(unique) <= count:
        return unique
    order = np.lexsort((unique[:, 1], unique[:, 0]))
    seeds = [unique[order[0]]]
    while len(seeds) < count:
        distances = np.stack(
            [np.linalg.norm(unique - seed, axis=1) for seed in seeds], axis=1
        )
        seeds.append(unique[int(np.argmax(distances.min(axis=1)))])
    centroids = np.asarray(seeds, dtype=float)
    for _ in range(30):
        distances = np.stack(
            [np.linalg.norm(unique - center, axis=1) for center in centroids],
            axis=1,
        )
        labels = distances.argmin(axis=1)
        updated = np.asarray(
            [
                unique[labels == index].mean(axis=0)
                if np.any(labels == index)
                else centroids[index]
                for index in range(count)
            ]
        )
        if np.allclose(updated, centroids, atol=1e-10, rtol=0):
            break
        centroids = updated
    return centroids


def _normalise_points(points: np.ndarray) -> np.ndarray:
    center, radius = _robust_location_scale(points)
    return (points - center) / radius


def layout_diagnostics(
    ent_pred: dict[str, Any],
    ent_gt: dict[str, Any],
    *,
    page: tuple[float, float] | None = None,
) -> dict[str, Any]:
    """Report absolute placement and relative three-cluster layout separately."""

    predicted = _support_points(ent_pred)
    target = _support_points(ent_gt)
    containment = None
    if page is not None and len(predicted):
        width, height = page
        inside = (
            (predicted[:, 0] >= 0)
            & (predicted[:, 0] <= width)
            & (predicted[:, 1] >= 0)
            & (predicted[:, 1] <= height)
        )
        containment = round(float(inside.mean()), 6)

    absolute_center_error = absolute_scale_log_error = None
    pred_box, gt_box = _bbox(predicted), _bbox(target)
    if pred_box is not None and gt_box is not None:
        pred_min, pred_max = pred_box
        gt_min, gt_max = gt_box
        pred_center = 0.5 * (pred_min + pred_max)
        gt_center = 0.5 * (gt_min + gt_max)
        gt_diagonal = max(float(np.linalg.norm(gt_max - gt_min)), 1e-9)
        pred_diagonal = max(float(np.linalg.norm(pred_max - pred_min)), 1e-9)
        absolute_center_error = round(
            float(np.linalg.norm(pred_center - gt_center) / gt_diagonal), 6
        )
        absolute_scale_log_error = round(
            float(abs(np.log(pred_diagonal / gt_diagonal))), 6
        )

    relative_error = None
    relative_score = None
    pred_clusters = gt_clusters = 0
    if len(predicted) and len(target):
        pred_centroids = _deterministic_centroids(_normalise_points(predicted))
        gt_centroids = _deterministic_centroids(_normalise_points(target))
        pred_clusters, gt_clusters = len(pred_centroids), len(gt_centroids)
        distances = np.linalg.norm(
            pred_centroids[:, None] - gt_centroids[None, :], axis=2
        )
        rows, columns = linear_sum_assignment(distances)
        matched = float(distances[rows, columns].sum())
        precision = len(rows) / pred_clusters
        recall = len(rows) / gt_clusters
        count_f1 = _f1(precision, recall)
        relative_error = matched / max(len(rows), 1)
        relative_score = count_f1 * np.exp(-relative_error / 0.15)

    return {
        "page_containment": containment,
        "absolute_center_error_frac": absolute_center_error,
        "absolute_scale_log_error": absolute_scale_log_error,
        "relative_view_layout_error": (
            round(float(relative_error), 6) if relative_error is not None else None
        ),
        "relative_view_layout_score": (
            round(float(relative_score), 6) if relative_score is not None else None
        ),
        "pred_view_clusters": int(pred_clusters),
        "gt_view_clusters": int(gt_clusters),
    }