File size: 8,395 Bytes
c49f870
 
 
 
7b2bf26
 
 
 
c49f870
7b2bf26
 
 
 
 
 
 
 
c49f870
 
7b2bf26
c49f870
 
 
 
 
 
7b2bf26
 
 
 
 
 
 
 
 
c49f870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b2bf26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c49f870
7b2bf26
c49f870
7b2bf26
c49f870
 
 
7b2bf26
 
 
 
 
c49f870
 
 
 
 
7b2bf26
c49f870
 
7b2bf26
 
c49f870
 
 
 
 
 
7b2bf26
c49f870
 
 
 
 
 
 
7b2bf26
 
c49f870
 
 
 
 
 
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
184
185
186
187
"""Build local train/validation splits from the public training data.

The leaderboard hides validation labels, so model selection has to happen here.

  random   held-out reactions, every EC still seen in training (CARE "easy")
  ec4      every reaction of some EC4s held out  (CARE "medium")
  ec3      every reaction of some EC3s held out  (CARE "hard")
  matched  held-out reactions as far from training as the public val inputs

No public val input is in train.parquet, not even written backwards, and many
have no close training reaction. A random split has a third of its reactions
in training backwards, so it flatters the kNN. 'matched' keeps the reverse of
each held-out reaction out of training too, and samples the held-out
reactions so that their similarity to the nearest training reaction follows
that of the val inputs.

Run:  python dev/split.py --mode matched
"""
import argparse
import sys
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
# After dev/ itself, so that dev/train.py wins over the starter's train.py.
sys.path.insert(1, str(ROOT))

from features import Featurizer, blocks  # noqa: E402
from train import build_vocab, cached_features, soft_targets  # noqa: E402

# Bins of difference-block Tanimoto to the nearest training reaction; the last
# holds 1.0, an identical difference block.
SIMILARITY_BINS = (0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)


def unique_reactions(frame):
    return frame.rxn_smiles.drop_duplicates().to_numpy()


def split_random(frame, fraction, rng):
    reactions = unique_reactions(frame)
    rng.shuffle(reactions)
    cut = int(len(reactions) * fraction)
    return set(reactions[:cut])


def split_by_ec(frame, fraction, rng, level):
    groups = frame.ec_number.astype(str).str.split('.').str[:level].str.join('.')
    held = np.array(sorted(groups.unique()))
    rng.shuffle(held)
    chosen = set(held[:int(len(held) * fraction)])
    return set(frame.rxn_smiles[groups.isin(chosen)])


def reverse(rxn_smiles):
    return '>'.join(str(rxn_smiles).split('>')[::-1])


def nearest_similarity(queries, index, partner=None, batch=1024):
    """Each query's highest difference-block Tanimoto to any index row.

    With `partner`, the queries are the index itself and each row skips itself
    and its reverse reaction, which gives a leave-one-out similarity.
    """
    import torch

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    index = torch.from_numpy(np.ascontiguousarray(index)).to(device, torch.float32)
    popcount = index.sum(dim=1)
    best = np.empty(len(queries), dtype=np.float32)
    for start in range(0, len(queries), batch):
        query = torch.from_numpy(np.ascontiguousarray(queries[start:start + batch])).to(device, torch.float32)
        intersection = query @ index.T
        union = query.sum(dim=1, keepdim=True) + popcount[None, :] - intersection
        tanimoto = intersection / union.clamp(min=1.0)
        if partner is not None:
            rows = np.arange(len(query))
            others = partner[start:start + len(query)]
            has = others >= 0
            tanimoto[torch.from_numpy(rows), torch.from_numpy(start + rows)] = -1.0
            tanimoto[torch.from_numpy(rows[has]), torch.from_numpy(others[has])] = -1.0
        best[start:start + len(query)] = tanimoto.max(dim=1).values.cpu().numpy()
    return best


def similarity_shares(similarity):
    return np.bincount(np.digitize(similarity, SIMILARITY_BINS), minlength=len(SIMILARITY_BINS) + 1) / len(similarity)


def similarity_table(columns):
    edges = (0.0,) + SIMILARITY_BINS
    labels = [f'[{low:.1f}, {high:.1f})' for low, high in zip(edges, edges[1:])] + ['1.0']
    shares = {name: similarity_shares(similarity) for name, similarity in columns.items()}
    print('nearest training similarity ' + ''.join(f'{name:>14}' for name in columns))
    for b, label in enumerate(labels):
        print(f'  {label:<26}' + ''.join(f'{shares[name][b]:>14.1%}' for name in columns))


def split_matched(frame, fraction, rng, args):
    """Held-out reactions, and the reverses of those, which leave training as well."""
    vocab = build_vocab(frame, args.vocabulary)
    reactions, _ = soft_targets(frame, {ec: i for i, ec in enumerate(vocab)})
    featurizer = Featurizer()
    _, _, change = blocks(cached_features(reactions, args.cache, featurizer))
    position = {rxn: i for i, rxn in enumerate(reactions)}
    partner = np.array([position.get(reverse(rxn), -1) for rxn in reactions])

    print('similarity of each training reaction to the rest...', flush=True)
    own = np.digitize(nearest_similarity(change, change, partner), SIMILARITY_BINS)
    queries = list(dict.fromkeys(pd.read_parquet(args.match).rxn_smiles))
    print(f'similarity of the {len(queries)} inputs in {Path(args.match).name} to training...', flush=True)
    target = nearest_similarity(blocks(featurizer.featurize_many(queries))[2], change)
    share = similarity_shares(target)
    available = np.bincount(own, minlength=len(share))

    # Hold out at most half of any bin, so training keeps reactions like the held-out ones.
    wanted = int(len(reactions) * fraction)
    size = int(min([wanted] + [available[b] / 2 / share[b] for b in range(len(share)) if share[b]]))
    if size < wanted:
        print(f'too few dissimilar reactions to hold out {wanted}; holding out {size}')
    held, dropped = [], set()
    for b in range(len(share)):
        quota = round(share[b] * size)
        for i in rng.permutation(np.flatnonzero(own == b)):
            if quota == 0:
                break
            if i in dropped:
                continue
            held.append(i)
            quota -= 1
            if partner[i] >= 0:
                dropped.add(partner[i])

    training = np.ones(len(reactions), dtype=bool)
    training[held] = False
    training[list(dropped)] = False
    similarity_table({'val inputs': target, 'held out': nearest_similarity(change[held], change[training])})
    return {reactions[i] for i in held}, {reactions[i] for i in dropped}


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--train', default=str(ROOT.parent / 'data' / 'train.parquet'))
    parser.add_argument('--mode', choices=['random', 'ec4', 'ec3', 'matched'], default='random')
    parser.add_argument('--fraction', type=float, default=0.1)
    parser.add_argument('--seed', type=int, default=0)
    parser.add_argument('--out', default=str(ROOT / 'dev' / 'splits'))
    parser.add_argument('--match', default=str(ROOT.parent / 'data' / 'val_inputs.parquet'),
                        help='matched: the inputs whose similarity to training the split copies')
    parser.add_argument('--vocabulary', default=str(ROOT / 'ec_vocabulary.json'))
    parser.add_argument('--cache', default=str(ROOT / 'dev' / 'cache' / 'full_features.npy'),
                        help='matched: default fingerprints of every training reaction, as dev/train.py caches them')
    args = parser.parse_args()

    frame = pd.read_parquet(args.train)
    rng = np.random.default_rng(args.seed)

    dropped = set()
    if args.mode == 'random':
        held = split_random(frame, args.fraction, rng)
    elif args.mode == 'matched':
        held, dropped = split_matched(frame, args.fraction, rng, args)
    else:
        held = split_by_ec(frame, args.fraction, rng, 4 if args.mode == 'ec4' else 3)

    mask = frame.rxn_smiles.isin(held)
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    train, val = frame[~mask & ~frame.rxn_smiles.isin(dropped)], frame[mask]
    train.to_parquet(out / f'{args.mode}_train.parquet', index=False)
    val.to_parquet(out / f'{args.mode}_val.parquet', index=False)

    seen = set(train.ec_number)
    unseen = sum(1 for ec in val.ec_number.unique() if ec not in seen)
    print(f'mode={args.mode}  train={len(train)} rows / {train.rxn_smiles.nunique()} reactions')
    print(f'              val={len(val)} rows / {val.rxn_smiles.nunique()} reactions')
    if dropped:
        print(f'reverses of held-out reactions left out of both: {len(dropped)}')
    print(f'val ECs never seen in training: {unseen} of {val.ec_number.nunique()}')
    print(f'wrote {out}/{args.mode}_{{train,val}}.parquet')


if __name__ == '__main__':
    main()