File size: 7,496 Bytes
268c55e
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Independent annotation-export checks; does not call its metric functions.

Uses explicit coincidence matrices for alpha and a separate augmenting-path
cardinality matcher for the headline instance counts.
"""
from __future__ import annotations

import argparse
import json
import math
from collections import Counter
from itertools import combinations
from pathlib import Path

import numpy as np


def reference_alpha(values, levels, squared, *, ordinal=False):
    coincidence = np.zeros((len(levels), len(levels)))
    pairable = [v for v in values if len(v) >= 2]
    if len(pairable) < 2: return None
    for ratings in pairable:
        counts=Counter(ratings)
        for i,a in enumerate(levels):
            for j,b in enumerate(levels):
                coincidence[i,j] += counts[a]*(counts[b]-(a==b))/(len(ratings)-1)
    marginals=coincidence.sum(axis=1); n=marginals.sum()
    expected=np.outer(marginals,marginals)-np.diag(marginals)
    distance=np.array([[(a-b)**2 if squared else float(a!=b) for b in levels] for a in levels], dtype=float)
    if ordinal:
        for i in range(len(levels)):
            for j in range(len(levels)):
                lo,hi=sorted((i,j))
                distance[i,j]=(sum(marginals[lo:hi+1])-(marginals[lo]+marginals[hi])/2)**2
    do=(coincidence*distance).sum()/n
    de=(expected*distance).sum()/(n*(n-1))
    return None if de<=0 else float(1-do/de)


def overlap(a,b):
    ix=max(0,min(a[0]+a[2],b[0]+b[2])-max(a[0],b[0]))
    iy=max(0,min(a[1]+a[3],b[1]+b[3])-max(a[1],b[1]))
    intersection=ix*iy
    return intersection/(a[2]*a[3]+b[2]*b[3]-intersection)


def maximum_pairs(a,b):
    edges=[[j for j,y in enumerate(b) if x['use_case_id']==y['use_case_id'] and overlap(x['bbox'],y['bbox'])>=.5] for x in a]
    owners={}
    def visit(i,seen):
        for j in edges[i]:
            if j in seen: continue
            seen.add(j)
            if j not in owners or visit(owners[j],seen):
                owners[j]=i
                return True
        return False
    for i in range(len(a)): visit(i,set())
    return [(i,j) for j,i in owners.items()]


def equal(actual,expected):
    assert (actual is None and expected is None) or (actual is not None and expected is not None and math.isclose(actual,expected,abs_tol=1e-11)),(actual,expected)


def verify(artifact_path, gold_path, iaa_path, manifest_path):
    artifact=json.loads(artifact_path.read_text()); gold=json.loads(gold_path.read_text()); raw=json.loads(iaa_path.read_text())
    gold_ids={r['image_id']:{v['use_case_id'] for v in r['gold']['violations']} for r in gold}
    categories={r['image_id']:r['category'] for r in map(json.loads,manifest_path.read_text().splitlines())}
    prepared={}
    for r in raw:
        labels=r['first_pass']
        ratings={k:[a[k] for a in labels if not a.get('reported') and type(a.get(k)) is int and 1<=a[k]<=5] for k in ('plausibility','naturalness')}
        usable=[a for a in labels if not a.get('reported') and bool(a['no_violation_detected']) != bool(a['violations'])]
        sets=[{v['use_case_id'] for v in a['violations']} for a in usable]
        pairs=list(combinations(usable,2))
        matches=Counter(); endpoints=Counter(); raw_matches=raw_endpoints=0
        for a,b in pairs:
            m=maximum_pairs(a['violations'],b['violations'])
            for v in a['violations']+b['violations']: endpoints[v['use_case_id']]+=1/len(pairs)
            for i,j in m: matches[a['violations'][i]['use_case_id']]+=1/len(pairs)
            raw_matches+=len(m);raw_endpoints+=len(a['violations'])+len(b['violations'])
        prepared[r['image_id']]={'ratings':ratings,'sets':sets,'matches':matches,'endpoints':endpoints,
                                'raw_matches':raw_matches,'raw_endpoints':raw_endpoints}
    checks=0
    for group in artifact['groups'].values():
        selected=[(i,p) for i,p in prepared.items() if (group['population']=='all' or i in gold_ids) and (group['source']=='all' or categories[i]==group['source'])]
        for row in group['rows']:
            ids=set(c for cs in artifact['domains'].values() for c in cs) if row['kind']=='overall' else set(artifact['domains'].get(row['id'],[row['id']]))
            qrows=[p for i,p in selected if row['kind']=='overall' or gold_ids.get(i,set())&ids]
            for k in ('plausibility','naturalness'):
                values=[p['ratings'][k] for p in qrows if len(p['ratings'][k])>=2]
                q=row['quality'][k]
                assert q['eligible']==len(values)
                equal(q['alpha']['value'],reference_alpha(values,list(range(1,6)),True,ordinal=True))
                equal(q['interval_alpha']['value'],reference_alpha(values,list(range(1,6)),True))
                equal(q['exact']['value'],sum(len(set(v))==1 for v in values)/len(values) if values else None)
                equal(q['within_one']['value'],sum(max(v)-min(v)<=1 for v in values)/len(values) if values else None)
                checks+=5
            label_rows=[[s&ids for s in p['sets']] for _,p in selected if len(p['sets'])>=2]
            a=dis=0
            for sets in label_rows:
                comparisons=list(combinations(sets,2))
                for x,y in comparisons:
                    a+=len(x&y)/len(comparisons);dis+=len(x^y)/len(comparisons)
            agreement=row['agreement']
            equal(agreement['exact']['value'],sum(len({tuple(sorted(s)) for s in sets})==1 for sets in label_rows)/len(label_rows) if label_rows else None)
            equal(agreement['positive_agreement']['value'],2*a/(2*a+dis) if a or dis else None)
            if row['kind']=='class':
                equal(agreement['alpha']['value'],reference_alpha([[int(bool(s)) for s in sets] for sets in label_rows],[0,1],False))
                checks+=1
            matches=sum(sum(p['matches'][c] for c in ids) for _,p in selected)
            endpoints=sum(sum(p['endpoints'][c] for c in ids) for _,p in selected)
            equal(agreement['instance_f1']['value'],2*matches/endpoints if endpoints else None)
            equal(agreement['support']['match_5'],matches)
            equal(agreement['support']['box_endpoints'],endpoints)
            assert agreement['support']['label_n']==len(label_rows)
            checks+=6
        print(f"Verified {group['population']} / {group['source']}",flush=True)
    result={'status':'passed','checks':checks,'images':len(raw),'groups':len(artifact['groups']),
            'source_hashes':{k:v['sha256'] for k,v in artifact['sources'].items()},
            'methods':['Independent explicit coincidence matrices for ordinal/interval/nominal alpha',
                       'Raw first-pass exact/within-one and class-set aggregation',
                       'Independent augmenting-path instance cardinality at IoU 0.50'],
            'limits':['Point estimates verified; bootstrap distribution and optimal-IoU tie cases are tested separately.']}
    print(json.dumps(result,indent=2))
    return result


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--artifact',type=Path,required=True)
    parser.add_argument('--gold',type=Path,required=True)
    parser.add_argument('--iaa',type=Path,required=True)
    parser.add_argument('--manifest',type=Path,required=True)
    parser.add_argument('--output',type=Path)
    a=parser.parse_args()
    result=verify(a.artifact,a.gold,a.iaa,a.manifest)
    if a.output: a.output.write_text(json.dumps(result,indent=2)+'\n')