File size: 3,853 Bytes
8af9600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build the homology "weights": a DIAMOND database of reference sequences and their EC labels.

Reference sequences are the competition training set plus (optionally) every Swiss-Prot entry
(reviewed UniProt) with an EC number that is not already in training. Swiss-Prot ECs are filtered
to the pinned EC vocabulary. Swiss-Prot also gives an exact-sequence lookup table: a query whose
sequence is a Swiss-Prot entry gets that entry's EC directly.
Swiss-Prot file: reviewed UniProt entries with EC numbers (columns accession, ec, sequence), from
https://rest.uniprot.org/uniprotkb/stream?query=(reviewed:true) AND (ec:*)&fields=accession,ec,sequence&format=tsv"""
import argparse
import json
import subprocess
from collections import Counter
from pathlib import Path

import pandas as pd

ROOT = Path(__file__).parent
DIAMOND = str(ROOT / 'bin' / 'diamond')


def train(train_path, swissprot_path=None):
    valid = set(json.loads((ROOT / 'ec_vocabulary.json').read_text()))
    frame = pd.read_parquet(train_path)
    if not set(frame.ec_number) <= valid:
        raise ValueError('Training data contains ECs outside the pinned vocabulary.')

    # A sequence can appear on several rows with different ECs, so group them into one entry
    groups = frame.groupby('sequence', sort=False).ec_number.apply(lambda s: ';'.join(sorted(set(s))))
    labels = pd.DataFrame({'seq_id': ['t%d' % i for i in range(len(groups))], 'ecs': groups.values,
                           'sequence': groups.index})
    weights = ROOT / 'weights'
    weights.mkdir(exist_ok=True)

    # Fallback for queries with no hit: the most frequent EC among unique training sequences
    counts = labels.ecs.str.split(';').explode().value_counts()
    (weights / 'fallback.json').write_text(json.dumps({'prediction': [counts.index[0]]}) + '\n')

    if swissprot_path:
        sprot = pd.read_parquet(swissprot_path)
        sprot = sprot[~sprot.sequence.isin(set(groups.index))]
        # Keep only full ECs from the competition vocabulary, in the entry's own order, merging
        # entries that share a sequence
        ecs = sprot.groupby('sequence', sort=False).ec.apply(
            lambda s: list(dict.fromkeys(e for x in s for e in x.split(';') if e in valid)))
        ecs = ecs[ecs.str.len() > 0]
        # Exact lookup: put the EC most common in training first (ties keep Swiss-Prot's order).
        # On training proteins that are also in Swiss-Prot this rule scores 0.919 L4.
        train_count = Counter(frame.ec_number)
        ordered = [sorted(e, key=lambda x: -train_count.get(x, 0)) for e in ecs]
        pd.DataFrame({'sequence': ecs.index, 'ec': [e[0] for e in ordered]}).to_parquet(
            weights / 'swissprot_lookup.parquet', index=False)
        extra = pd.DataFrame({'seq_id': ['s%d' % i for i in range(len(ecs))], 'ecs': [';'.join(e) for e in ordered],
                              'sequence': ecs.index})
        labels = pd.concat([labels, extra], ignore_index=True)
        print('Swiss-Prot entries added:', len(extra))

    labels[['seq_id', 'ecs']].to_parquet(weights / 'train_labels.parquet', index=False)
    fasta = weights / 'train.fasta'
    with fasta.open('w') as f:
        for sid, seq in zip(labels.seq_id, labels.sequence):
            f.write('>%s\n%s\n' % (sid, seq))
    subprocess.run([DIAMOND, 'makedb', '--in', str(fasta), '-d', str(weights / 'train'), '--quiet'], check=True)
    fasta.unlink()  # the .dmnd file already holds the sequences
    print('Database built from', len(labels), 'unique reference sequences')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--train', required=True)
    parser.add_argument('--swissprot', help='optional parquet of Swiss-Prot entries with EC numbers')
    args = parser.parse_args()
    train(args.train, args.swissprot)