enzyme-viva / train.py
RohanTheZ's picture
Readable version of v16b with training code
508a59e verified
Raw History Blame Contribute Delete
3.85 kB
"""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)