File size: 9,135 Bytes
85097f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Seeded version × source-half quotas with catalog-nearest refill in each half."""
import hashlib
import random
from collections import Counter, defaultdict
from embodied_pipeline.prover import final_balance, pose_balance


def _rng(seed, key):
    return random.Random(hashlib.sha256(f'{seed}:{key}'.encode()).digest())


def _shares(weights, total, rng):
    keys = sorted(weights)
    rng.shuffle(keys)
    denominator = sum(weights.values())
    shares = {k: weights[k] * total // denominator for k in keys}
    for k in sorted(keys, key=lambda k: -(weights[k] * total % denominator))[:total-sum(shares.values())]:
        shares[k] += 1
    return shares


def tree(families):
    """Family → subject → form → version, in the same order as quota_defaults."""
    result = {}
    for family in families:
        subjects = result.setdefault(family['id'], {})
        for version in family['versions']:
            vid = version['id']
            form = vid.split('/')[0]
            subject = '.'.join(form.split('.')[:2])
            subjects.setdefault(subject, {}).setdefault(form, {})[vid] = vid
    return result


def select(rows, quotas, families, *, seed=0, pool_of=None):
    """Sample PASS rows within each source half. Old unlabeled rows cannot fill either half.

    pool_of reads the segment's fixed generator config in production; tags.pool is useful
    for already exported items. Odd quotas give the seeded first half the extra slot.
    """
    root = tree(families)

    def leaves(node):
        if isinstance(node, str):
            return [node]
        return [vid for child in node.values() for vid in leaves(child)]

    versions = leaves(root)
    pool_of = pool_of or (lambda row: (row.get('tags') or {}).get('pool'))
    chosen, details, remaining = {}, {}, {}
    for vid in versions:
        quota = quotas.get(vid, 0)
        if not isinstance(quota, int) or isinstance(quota, bool) or quota < 0:
            raise ValueError(f'{vid}: quota must be a nonnegative integer')
        buckets = {p: [] for p in ('anti_shortcut', 'natural', 'unlabeled')}
        for row in rows.get(vid, []):
            if row.get('decision', {}).get('result') != 'PASS':
                continue
            pool = pool_of(row) or 'unlabeled'
            if pool not in buckets:
                raise ValueError(f'{vid}: unknown source pool {pool!r}')
            buckets[pool].append(row)
        rng = _rng(seed, vid)
        halves = ['anti_shortcut', 'natural']
        rng.shuffle(halves)
        chosen[vid], strata, remaining[vid] = [], {}, {}
        for i, pool in enumerate(halves):
            need = quota // 2 + int(quota % 2 and i == 0)
            values = pose_balance.packets(buckets[pool], seed)
            unit = all(len(packet) == 1 for packet in values)
            draws = rng.sample(values, min(need, len(values)) if unit else len(values))
            kept, kept_packets = [], set()
            for packet in draws:
                if len(kept) + len(packet) <= need:
                    kept.extend(packet)
                    kept_packets.add(id(packet))
            chosen[vid].extend(kept)
            available = sum(map(len, values))
            strata[pool] = dict(quota=need, available=available, taken=len(kept), unfilled=need-len(kept))
            if vid in pose_balance.VERSIONS:
                strata[pool]['balance_dropped'] = len(buckets[pool]) - available
            spare = [packet for packet in values if id(packet) not in kept_packets]
            rng.shuffle(spare)
            remaining[vid][pool] = spare
        details[vid] = dict(quota=quota, available=sum(map(len, buckets.values())), taken=len(chosen[vid]),
                            received=0, pools=strata, unlabeled=len(buckets['unlabeled']))
    def refill(node, pool):
        if isinstance(node, str):
            return [node] * details[node]['pools'][pool]['unfilled']
        gaps = [vid for child in node.values() for vid in refill(child, pool)]
        candidates = leaves(node)
        while gaps:
            spare = [vid for vid in candidates if any(len(p) <= len(gaps) for p in remaining[vid][pool])]
            if not spare:
                break
            for vid in spare:
                values = remaining[vid][pool]
                index = next((i for i in range(len(values)-1, -1, -1) if len(values[i]) <= len(gaps)), None)
                if index is None:
                    continue
                packet = values.pop(index)
                chosen[vid].extend(packet)
                details[vid]['taken'] += len(packet)
                details[vid]['received'] += len(packet)
                details[vid]['pools'][pool]['taken'] += len(packet)
                for _ in packet:
                    details[gaps.pop(0)]['pools'][pool]['unfilled'] -= 1
                if not gaps:
                    break
        return gaps

    for pool in ('anti_shortcut', 'natural'):
        refill(root, pool)
    shortages = [dict(version=vid, pool=pool, missing=s['unfilled'])
                 for vid in versions for pool, s in details[vid]['pools'].items() if s['unfilled']]
    report = dict(seed=seed, versions=details, shortages=shortages, unfilled=sum(s['missing'] for s in shortages))
    unknown = [vid for vid in quotas if vid not in details]
    if unknown:
        report['unknown'] = unknown
    return chosen, report


def select_groups(rows, *, seed=0, versions=()):
    """Balance abilities using complete 3+3 packs, preserving input row order.

    rows maps script IDs to grouped question rows. Version-composition strata get
    proportional integer shares (largest remainder) seed the preference; joint
    answer and pose constraints may change shares. No row or pack is repeated.
    Missing counts compare with the larger original ability supply, not new demand.
    """
    packets = defaultdict(list)
    for sid, values in rows.items():
        for row in values:
            g = row['scope']['group']
            if g['unit'].split('.')[0] not in ('1', '2', '3', '4', '5'):
                raise ValueError(f"unknown ability unit: {g['unit']}")
            packets[sid, g['unit'], g['id']].append(row)
    pools = {'1-4': [], '5': []}
    invalid = []
    before = Counter(dict.fromkeys(versions, 0))
    for key, packet in sorted(packets.items()):
        slots = [(r['scope']['group']['set'], r['scope']['group']['slot']) for r in packet]
        if (len(packet) != 6 or set(slots) != {(s, f'{s}{i}') for s in range(2) for i in range(3)}
                or any(r.get('decision', {}).get('result') != 'PASS' for r in packet)):
            invalid.append(dict(script_id=key[0], unit=key[1], id=key[2], rows=len(packet)))
            continue
        pools['5' if key[1].startswith('5.') else '1-4'].append((key, packet))
        before.update(r['public']['version_id'] for r in packet)
    target = min(map(len, pools.values()))
    demand = max(map(len, pools.values()))
    selected = set()
    for ability, pool in pools.items():
        strata = defaultdict(list)
        for key, packet in pool:
            composition = tuple(sorted(Counter(r['public']['version_id'] for r in packet).items()))
            strata[composition].append((key, packet))
        rng = _rng(seed, ability)
        shares = _shares({k: len(v) for k, v in strata.items()}, target, rng)
        for k, count in shares.items():
            selected.update(key for key, _ in rng.sample(strata[k], count))
    selected, balance = final_balance.select(sorted(pools['1-4']+pools['5']), selected)
    taken = {g: sum(key in selected for key, _ in p) for g, p in pools.items()}
    chosen = {sid: [r for r in values if (sid, r['scope']['group']['unit'], r['scope']['group']['id']) in selected]
              for sid, values in rows.items()}
    after = Counter(r['public']['version_id'] for values in chosen.values() for r in values)
    report = dict(seed=seed, unit='complete_3+3_pack', ratio=1.0 if selected else None,
                  invalid_packs=len(invalid), invalid=invalid,
                  balance=balance,
                  groups={g: dict(available=len(p), target=demand, taken=taken[g],
                                  missing=demand-len(p), dropped=len(p)-taken[g],
                                  questions_before=6*len(p), questions_after=6*taken[g])
                          for g, p in pools.items()},
                  versions={v: dict(available=before[v], taken=after[v], missing=before[v]-after[v])
                            for v in sorted(before)})
    for ability, pool in pools.items():
        available = Counter(r['public']['version_id'] for _, packet in pool for r in packet)
        taken = Counter(r['public']['version_id'] for key, packet in pool if key in selected for r in packet)
        wanted = _shares(available, 6*demand, _rng(seed, ability + ':shortage')) if pool else {}
        report['groups'][ability]['versions'] = {
            v: dict(available=available[v], target=wanted[v], taken=taken[v], missing=wanted[v]-taken[v],
                    dropped=available[v]-taken[v]) for v in sorted(available)}
    return chosen, report