File size: 4,444 Bytes
7f9a652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared generators reused across Lilambd ledgers."""
import pandas as pd
import pycountry
from evallib import fmt, select

_ISO3 = {}


def cname(iso3):
    if iso3 in _ISO3:
        return _ISO3[iso3]
    c = pycountry.countries.get(alpha_3=iso3)
    n = getattr(c, 'common_name', None) or (c.name if c else None)
    _ISO3[iso3] = f'{n} ({iso3})' if n else iso3
    return _ISO3[iso3]


def cname2(iso2):
    c = pycountry.countries.get(alpha_2=iso2)
    n = getattr(c, 'common_name', None) or (c.name if c else None)
    return f'{n} ({iso2})' if n else iso2


def long_features(B, file, unit_col='unit', key='iso3', label=cname, n_lookup=40, n_rank=12, n_cmp=15, n_count=8, n_absent=10, scope='country', ds_short=''):
    """Questions over a long table (key, feature, value, year, unit)."""
    df = B.store[file]
    feats = sorted(df['feature'].dropna().unique())
    units = df.groupby('feature')[unit_col].first().to_dict()
    years = df.groupby('feature')['year'].first().to_dict()
    keys_all = sorted(df[key].unique())
    per = max(1, n_lookup // max(1, len(feats)))
    for ft in feats:
        sub = df[df.feature == ft]
        u = units[ft]
        for _, r in sub.loc[B.sample(sub.index, per)].iterrows():
            B.add('lookup', f'In {ds_short} `{file}`, what is the value of `{ft}` ({u}) for {label(r[key])}?',
                  {'op': 'lookup', 'file': file, 'where': [[key, '==', r[key]], ['feature', '==', ft]], 'col': 'value'},
                  unit=u, skills=['table_lookup', 'code_resolution'])
    for ft in B.sample(feats, n_rank):
        u = units[ft]
        for op, word in (('argmax', 'highest'), ('argmin', 'lowest')):
            B.add('rank', f'In {ds_short} `{file}`, which {scope} has the {word} `{ft}` ({u})? Answer with its {key} code.',
                  {'op': op, 'file': file, 'where': [['feature', '==', ft]], 'col': 'value', 'return': key},
                  difficulty=2, skills=['ranking', 'full_scan'])
        B.add('rank', f'In {ds_short} `{file}`, list the 3 {scope} codes ({key}) with the highest `{ft}` ({u}), highest first.',
              {'op': 'topk', 'k': 3, 'file': file, 'where': [['feature', '==', ft]], 'col': 'value', 'return': key},
              difficulty=2, skills=['ranking', 'full_scan'], answer_format='JSON list of codes')
    for _ in range(n_cmp):
        ft = B.rng.choice(feats)
        sub = df[df.feature == ft]
        if len(sub) < 2:
            continue
        a, b = sub.sample(2, random_state=B.rng.randint(0, 1 << 30))[key]
        B.add('compare', f'In {ds_short} `{file}`, which has the larger `{ft}` ({units[ft]}): {label(a)} or {label(b)}? Answer with the {key} code.',
              {'op': 'compare', 'labels': [a, b], 'parts': [
                  {'op': 'lookup', 'file': file, 'where': [[key, '==', a], ['feature', '==', ft]], 'col': 'value'},
                  {'op': 'lookup', 'file': file, 'where': [[key, '==', b], ['feature', '==', ft]], 'col': 'value'}]},
              difficulty=2, skills=['comparison'])
    for ft in B.sample(feats, n_count):
        sub = pd.to_numeric(df[df.feature == ft]['value'], errors='coerce').dropna()
        if len(sub) < 10:
            continue
        thr = float(f'{sub.quantile(B.rng.choice([0.5, 0.75, 0.9])):.3g}')
        B.add('count', f'In {ds_short} `{file}`, how many {scope} rows have `{ft}` greater than {fmt(thr)} ({units[ft]})?',
              {'op': 'count', 'file': file, 'where': [['feature', '==', ft], ['value', '>', thr]]},
              difficulty=2, skills=['filter', 'count', 'full_scan'])
    # unanswerable: key exists for other features but not this one
    tries = 0
    made = 0
    while made < n_absent and tries < 200:
        tries += 1
        ft = B.rng.choice(feats)
        have = set(df[df.feature == ft][key])
        missing = [k for k in keys_all if k not in have]
        if not missing:
            continue
        k = B.rng.choice(missing)
        if B.add('unanswerable', f'In {ds_short} `{file}`, what is the value of `{ft}` ({units[ft]}) for {label(k)}? If the dataset has no such row, answer null.',
                 {'op': 'absent', 'file': file, 'where': [[key, '==', k], ['feature', '==', ft]]},
                 difficulty=2, skills=['abstention'],
                 note='No row exists for this key and feature; a grounded system must abstain.'):
            made += 1