File size: 4,553 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
"""The paper's fixed-population ten-column aggregation for offline DXF scores."""
import math

COMPONENTS = {'SV': 'structure', 'VC': 'view', 'GF': 'geometry',
              'DF': 'physical', 'AQ': 'annotation', 'LC': 'layout'}
THRESHOLDS = {'structure': 1., 'view': 1., 'geometry': .9,
              'physical': .9, 'annotation': .9, 'layout': .85}


def parse_atoms(result, gt):
    """Frozen CAMR atomic checks from unify_annotation_columns_20260924_v1.py."""
    if result is None:
        return None, "missing_result"
    ann = result.get("components", {}).get("annotation", {})
    d = ann.get("details", {})
    items = d.get("items")
    if d.get("scope") != "full_gt" or not isinstance(items, list):
        return None, "no_full_gt_items:" + str(ann.get("reason"))
    want = sorted((x["id"], x["gt_dimension_index"]) for x in gt["specs"])
    got = sorted((x.get("id"), x.get("gt_dimension_index")) for x in items)
    if want != got or d.get("n_selected_target") != len(want):
        return None, "target_inventory_mismatch:" + str(ann.get("reason"))
    if "n_matched_predicted_native" not in d:
        return None, "missing_native_matching_counters"
    n = len(want)
    tp = int(d["n_matched_predicted_native"])
    assert n > 0 and 0 <= tp <= n
    assert tp == sum(float(x["presence"]) for x in items)
    assert n == int(d["n_total_gt_dimension_targets"])
    assert len({x["pred_dimension_index"] for x in items if x["pred_dimension_index"] is not None}) == tp
    return {"native_target_count": n, "native_matched_count": tp, "all_targets_matched": tp == n,
            "matching_policy": d.get("matching_policy")}, "observed"


def make_record(sid, contract, result=None, status='scored', error=None):
    eligible = bool(contract['full_gt']['annotation_eligible'])
    row = {'id': sid, 'status': status, 'annotation_eligible': eligible,
           'components': {k: 0.0 for k in COMPONENTS},
           'view_pass': False, 'layout_pass': False, 'camr_complete': False,
           'annotation_unknown': False, 'error': error}
    if status != 'scored':
        if result is not None:
            raise ValueError('A failed output must not contribute a scored result')
        return row
    if result is None:
        raise ValueError('A scored record requires a result')
    assert result['metric_version'] == 'v5.2-rc5k-final'
    benchmark = result['benchmark']
    assert benchmark['thresholds'] == THRESHOLDS
    for column, key in COMPONENTS.items():
        component = result['components'][key]
        value = component['score']
        row['components'][column] = float(value) if value is not None else 0.0
        assert math.isfinite(row['components'][column]) and 0 <= row['components'][column] <= 1
        if key in {'view', 'layout'}:
            inferred = bool(value >= THRESHOLDS[key]) if component['eligible'] and value is not None else None
            assert benchmark[key + '_pass'] is inferred
            row[key + '_pass'] = inferred
    if eligible:
        atoms, reason = parse_atoms(result, contract)
        row['annotation_unknown'] = atoms is None
        row['annotation_evidence_status'] = reason
        row['annotation_atoms'] = atoms
        row['camr_complete'] = atoms is not None and atoms['all_targets_matched']
    return row


def aggregate(rows):
    if not rows:
        raise ValueError('Cannot aggregate an empty population')
    if len({r['id'] for r in rows}) != len(rows):
        raise ValueError('Duplicate sample IDs')
    n = len(rows)
    eligible = [r for r in rows if r['annotation_eligible']]
    scored = sum(r['status'] == 'scored' for r in rows)
    camr_count = sum(r['camr_complete'] is True for r in eligible)
    metrics = {'SDR': 100 * scored / n}
    metrics.update({k: 100 * math.fsum(r['components'][k] for r in rows) / n for k in COMPONENTS})
    metrics.update(CAMR=(100 * camr_count / len(eligible) if eligible else None),
                   CVR=100 * sum(r['view_pass'] is True for r in rows) / n,
                   LAR=100 * sum(r['layout_pass'] is True for r in rows) / n)
    return {'sample_count': n, 'scorable_count': scored,
            'camr_denominator': len(eligible), 'camr_confirmed_count': camr_count,
            'annotation_unknown_count': sum(r['annotation_unknown'] for r in eligible),
            'metrics': metrics, 'scale': '0--100; rate columns are percentages',
            'failed_outputs': 'retained in fixed denominators with zero component scores',
            'optional_inapplicable_components': 'fixed-column zero filling'}