File size: 6,016 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
#!/usr/bin/env python3
"""Metric-v4.3 frozen DISK-pilot helpers.

V4.3 keeps v4.2 geometry and balances dimension-scale consistency by semantic
dimension groups.  Repeating the same diameter DIMENSION therefore cannot
outvote one incorrect thickness DIMENSION.
"""

from __future__ import annotations

import math
from typing import Any

import numpy as np

try:
    from . import eval_geometric04 as CORE
    from . import eval_geometric042 as GEOMETRY
except ImportError:
    import eval_geometric04 as CORE
    import eval_geometric042 as GEOMETRY


canonicalize_entities = GEOMETRY.canonicalize_entities
extract_entities = GEOMETRY.extract_entities
legacy_dimension_entities = GEOMETRY.legacy_dimension_entities
representation_quality = GEOMETRY.representation_quality
score_disk_semantics = GEOMETRY.score_disk_semantics


def _semantic_family(family: str) -> str:
    if family in {"diameter", "radius"}:
        return "circular"
    if family in {"linear", "aligned"}:
        return "linear"
    return family


def _equivalent_value(first: dict[str, Any], second: dict[str, Any]) -> bool:
    if _semantic_family(str(first.get("family"))) != _semantic_family(str(second.get("family"))):
        return False
    first_value = first.get("display_value")
    second_value = second.get("display_value")
    if not isinstance(first_value, (int, float)) or not isinstance(second_value, (int, float)):
        return first_value is None and second_value is None
    if str(first.get("family")) == "radius":
        first_value = 2.0 * float(first_value)
    if str(second.get("family")) == "radius":
        second_value = 2.0 * float(second_value)
    tolerance = max(0.01, 0.001 * max(abs(float(first_value)), abs(float(second_value)), 1.0))
    return abs(float(first_value) - float(second_value)) <= tolerance


def _group_items(items: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
    groups: list[list[dict[str, Any]]] = []
    for item in items:
        for group in groups:
            if _equivalent_value(item, group[0]):
                group.append(item)
                break
        else:
            groups.append([item])
    return groups


def _consensus(log_ratios: list[float]) -> tuple[float | None, float]:
    if not log_ratios:
        return None, 0.0
    threshold = math.log1p(CORE.DIMENSION_SCALE_INLIER_REL)
    global_median = float(np.median(log_ratios))
    candidates: list[tuple[int, float, list[float]]] = []
    for candidate in log_ratios:
        inliers = [value for value in log_ratios if abs(value - candidate) <= threshold]
        centre = float(np.median(inliers))
        candidates.append((len(inliers), -abs(centre - global_median), inliers))
    _, _, inliers = max(candidates, key=lambda value: (value[0], value[1]))
    centre = float(np.median(inliers))
    score = float(
        np.mean(
            [
                math.exp(-abs(value - centre) / CORE.DIMENSION_SCALE_DECAY)
                for value in log_ratios
            ]
        )
    )
    return centre, score


def score_dimension_consistency(entities: dict[str, Any]) -> dict[str, Any]:
    """Return dimension consistency with one vote per semantic dimension."""

    raw = CORE.score_dimension_consistency(entities)
    items = list(raw.get("items", []))
    if not items:
        result = dict(raw)
        result.update({"raw_score": raw["score"], "n_groups": 0, "duplicate_dimensions": 0, "groups": []})
        return result
    groups = _group_items(items)
    group_details: list[dict[str, Any]] = []
    log_ratios: list[float] = []
    for group in groups:
        ratios = [
            float(item["scale_ratio"])
            for item in group
            if isinstance(item.get("scale_ratio"), (int, float))
            and float(item["scale_ratio"]) > 0
        ]
        group_ratio = float(np.median(ratios)) if ratios else None
        if group_ratio is not None:
            log_ratios.append(math.log(group_ratio))
        group_details.append(
            {
                "family": _semantic_family(str(group[0].get("family"))),
                "display_value": group[0].get("display_value"),
                "count": len(group),
                "scale_ratio": round(group_ratio, 8) if group_ratio is not None else None,
                "binding_quality": round(
                    float(np.median([float(item.get("binding_quality", 0.0)) for item in group])),
                    6,
                ),
                "valid": group_ratio is not None,
            }
        )
    centre, scale_consistency = _consensus(log_ratios)
    for group in group_details:
        ratio = group["scale_ratio"]
        group["scale_quality"] = (
            round(
                math.exp(-abs(math.log(float(ratio)) - centre) / CORE.DIMENSION_SCALE_DECAY),
                6,
            )
            if ratio is not None and centre is not None
            else 0.0
        )
    binding_quality = float(np.mean([group["binding_quality"] for group in group_details]))
    n_valid = len(log_ratios)
    n_invalid = len(groups) - n_valid
    completeness = n_valid / max(len(groups), 1)
    score = scale_consistency * binding_quality * completeness
    return {
        "score": round(float(score), 6),
        "raw_score": float(raw["score"]),
        "n_dimensions": len(items),
        "n_groups": len(groups),
        "duplicate_dimensions": len(items) - len(groups),
        "n_valid": n_valid,
        "n_invalid": n_invalid,
        "drawing_scale": round(math.exp(centre), 8) if centre 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),
        "groups": group_details,
        "items": items,
    }


__all__ = [
    "canonicalize_entities",
    "extract_entities",
    "legacy_dimension_entities",
    "representation_quality",
    "score_dimension_consistency",
    "score_disk_semantics",
]