"""Offline CPU inference (v15). 0. A query whose sequence is a Swiss-Prot entry (reviewed UniProt, with an EC number) takes that entry's EC directly. Otherwise, a query whose sequence BRENDA links to an EC takes that EC, and otherwise a query whose sequence is an unreviewed UniProt (TrEMBL) entry with an EC takes that EC (looked up by sequence fingerprint). All other queries go through the steps below. 1. DIAMOND finds similar reference sequences (competition training set plus Swiss-Prot enzymes); every EC among the hits is a candidate. 2. Queries with no hit at all are searched again (ultra-sensitive, E-value < 100) and get a plain bitscore vote over those weaker hits. 3. For queries with only weak hits, a fine-tuned ESM2-8M classifier (NumPy) adds its own EC probabilities. 4. Two trained rerankers (the v4 and v5 models) score the candidates; their probabilities are averaged and the best EC is predicted. """ import os # One BLAS thread per process: the classifier runs in two processes on the two CPUs. # Set before numpy is imported (the evaluator sandbox blocks the /proc files that threadpoolctl reads). os.environ['OPENBLAS_NUM_THREADS'] = '1' os.environ['OMP_NUM_THREADS'] = '1' os.environ['MKL_NUM_THREADS'] = '1' import argparse import hashlib import json from collections import defaultdict import pickle import subprocess import tempfile import time from multiprocessing import Pool from pathlib import Path import numpy as np import pandas as pd from inputs import prepare_inputs from esm_numpy import ECClassifierNumpy from rerank import add_classifier_features, add_reliability, candidate_features ROOT = Path(__file__).parent DIAMOND = str(ROOT / 'bin' / 'diamond') HIT_COLUMNS = ['q', 's', 'pid', 'alen', 'qlen', 'slen', 'ev', 'bits'] # The evaluator kills any process that writes a file larger than 16 MiB and allows 256 open files. # With --bin 128 DIAMOND spreads its temporary seed hits over 128 files, and --compress 1 gzips the # hit table; a batch of 10,000 queries / 5 M residues stays near 5-6 MiB, far below 16 MiB. # The evaluator's speed varies a lot between runs (the same search took 165 s once and over 540 s # another time), so the search goes in batches and adapts: # - the first batch is a small probe that measures how fast very-sensitive mode runs on this machine # - before each later batch, if the remaining queries cannot finish in very-sensitive mode by # SENSITIVE_UNTIL_SECONDS, the rest use DIAMOND's default mode (about 5x faster) # - finished batches are always kept, so a slow machine gives weaker hits, never zero hits PROBE_QUERIES = 2_000 CHUNK_QUERIES = 10_000 CHUNK_RESIDUES = 5_000_000 SENSITIVE_UNTIL_SECONDS = 450 # Time of one very-sensitive batch on our test machine: fixed start-up cost + cost per residue # (fitted on our runs: one 5.5 M-residue batch 183 s, four batches totalling 5.5 M residues 299 s) BATCH_FIXED_SECONDS = 40.0 BATCH_SECONDS_PER_RESIDUE = 2.6e-5 def expected_batch_seconds(residues): return BATCH_FIXED_SECONDS + BATCH_SECONDS_PER_RESIDUE * residues # Hard stop for DIAMOND: a running search is killed here, its queries go to the classifier/fallback STOP_AFTER_SECONDS = 540 # The second search (queries with no hit) only starts if the first search finished by this point SECOND_PASS_IF_DONE_BY = 300 # ...and only on a machine that is not slow (on a slow machine the classifier needs the time), # and for at most this many seconds SECOND_PASS_MAX_SLOWDOWN = 1.2 SECOND_PASS_MAX_SECONDS = 200 # The classifier runs on weak-hit queries (weakest first) until this point, then stops CLASSIFIER_UNTIL_SECONDS = 500 classifier = None # loaded in the main process before the worker processes are forked def classify(seq): return classifier.predict(seq) def run_classifier(queries, sequence_of, start): """Top 10 ECs and probabilities for each query, in the given order, until the time budget ends. This stage is optional: if anything goes wrong (error, crashed worker, stall), it stops and returns what it has. Queries without classifier output are handled by the reranker as 'missing'. """ global classifier results = {} if not queries: return results pool = None try: classifier = ECClassifierNumpy(str(ROOT / 'weights' / 'ec_classifier.npz'), str(ROOT / 'weights' / 'ec_classes.json')) pool = Pool(2) # workers are forked copies of this process, so they already have the model answers = pool.imap(classify, [sequence_of[q] for q in queries]) # chunksize 1 keeps next(timeout=...) for q in queries: time_left = CLASSIFIER_UNTIL_SECONDS - (time.time() - start) if time_left <= 0: break # Wait at most until the deadline for the next answer; a stalled pool raises TimeoutError results[q] = answers.next(timeout=time_left) except Exception as error: print('classifier stage stopped early:', repr(error), flush=True) finally: if pool is not None: pool.terminate() return results def make_chunks(frame): """A small first batch (the speed probe), then batches of at most CHUNK_QUERIES queries / CHUNK_RESIDUES residues.""" chunks, current, residues = [], [], 0 for qid, seq in zip(frame.id, frame.sequence): limit = PROBE_QUERIES if not chunks else CHUNK_QUERIES if current and (residues + len(seq) > CHUNK_RESIDUES or len(current) == limit): chunks.append(current) current, residues = [], 0 current.append((qid, seq)) residues += len(seq) if current: chunks.append(current) return chunks def run_diamond(chunk, workdir, sensitive, time_left, mode=None, evalue='1e-3'): """Align one chunk of queries against the training database and return its hit table. Returns None if there are no hits or the search had to be stopped at the time limit.""" query_fasta = Path(workdir) / 'queries.fasta' hits_path = Path(workdir) / 'hits.tsv' # DIAMOND writes hits.tsv.gz because of --compress 1 with query_fasta.open('w') as f: for qid, seq in chunk: f.write('>%s\n%s\n' % (qid, seq)) if mode is None: mode = '--very-sensitive' if sensitive else None # None = DIAMOND's default mode mode_args = [mode] if mode else [] try: subprocess.run([DIAMOND, 'blastp', '-q', str(query_fasta), '-d', str(ROOT / 'weights' / 'train'), '-o', str(hits_path), '--compress', '1', '--bin', '128', '--threads', '2', '--max-target-seqs', '50', '--evalue', evalue, '--tmpdir', str(workdir), '--quiet', *mode_args, '--outfmt', '6', 'qseqid', 'sseqid', 'pident', 'length', 'qlen', 'slen', 'evalue', 'bitscore'], check=True, timeout=max(1, time_left)) except subprocess.TimeoutExpired: print('DIAMOND stopped at the time limit; these queries continue without hits', flush=True) return None try: return pd.read_csv(str(hits_path) + '.gz', sep='\t', names=HIT_COLUMNS, dtype={'q': str, 's': str}) except pd.errors.EmptyDataError: return None def vote(g, ecs_of): """Plain bitscore vote (top 25 hits within 80% of the best bitscore, weight bitscore^4).""" g = g.head(25) best, votes = g.bits.iloc[0], defaultdict(float) for s, b in zip(g.s, g.bits): if b < 0.8 * best: break for ec in ecs_of[s]: votes[ec] += b ** 4 / len(ecs_of[s]) return max(votes, key=votes.get) def fingerprint(sequence): """First 8 bytes of the MD5 of the sequence as an unsigned 64-bit number (same as the Kaggle download).""" return int.from_bytes(hashlib.md5(sequence.encode()).digest()[:8], 'little') def trembl_lookup(queries): """EC for each query whose exact sequence is an unreviewed UniProt entry with an EC. The fingerprints are sorted, so each query is one binary search. Optional: if the files are missing or unreadable, no query is looked up and everything goes to the search.""" try: hashes = np.load(ROOT / 'weights' / 'trembl_hashes.npy') ec_ids = np.load(ROOT / 'weights' / 'trembl_ec_ids.npy') ec_list = json.loads((ROOT / 'weights' / 'trembl_ecs.json').read_text()) except Exception as error: print('TrEMBL lookup unavailable:', repr(error), flush=True) return {} if len(queries) == 0 or len(hashes) == 0: return {} keys = np.array([fingerprint(s) for s in queries.sequence], dtype=np.uint64) pos = np.minimum(np.searchsorted(hashes, keys), len(hashes) - 1) found = hashes[pos] == keys return {qid: ec_list[ec_ids[p]] for qid, p, f in zip(queries.id, pos, found) if f} def family_hmm_override(queries, current): """New predictions from trusted NCBIfam family hits; optional (any failure changes nothing).""" try: import gzip import pyhmmer info = json.loads((ROOT / 'weights' / 'ncbifam_ec.json').read_text()) vocab = set(json.loads((ROOT / 'ec_vocabulary.json').read_text())) labels = pd.read_parquet(ROOT / 'weights' / 'train_labels.parquet') count = {} for sid, ecs in zip(labels.seq_id, labels.ecs): if sid.startswith('t'): for e in ecs.split(';'): count[e] = count.get(e, 0) + 1 if len(queries) == 0: return {} with pyhmmer.plan7.HMMFile(gzip.open(ROOT / 'weights' / 'ncbifam_ec.hmm.gz', 'rb')) as f: hmms = list(f) alphabet = pyhmmer.easel.Alphabet.amino() allowed = set(alphabet.symbols) - set('-*~') block = pyhmmer.easel.TextSequenceBlock([ pyhmmer.easel.TextSequence(name=str(q).encode(), sequence=''.join(c if c in allowed else 'X' for c in s.upper())) for q, s in zip(queries.id, queries.sequence)]).digitize(alphabet) best = {} # query -> (score, family) of its best trusted hit for hmm, hits in zip(hmms, pyhmmer.hmmsearch(hmms, block, cpus=2)): full_cut, domain_cut = hmm.cutoffs.trusted name = hmm.name.decode() if isinstance(hmm.name, bytes) else hmm.name for hit in hits: if hit.score >= full_cut and hit.best_domain.score >= domain_cut: q = hit.name.decode() if isinstance(hit.name, bytes) else hit.name if q not in best or hit.score > best[q][0]: best[q] = (hit.score, name) changes = {} for q, (score, name) in best.items(): ecs = [e for e in info[name]['ecs'] if e in vocab] if ecs and current.get(q) not in ecs: changes[q] = max(sorted(ecs), key=lambda e: count.get(e, 0)) print('family HMMs: %d of %d searched queries with a trusted hit, %d predictions changed' % ( len(best), len(queries), len(changes)), flush=True) return changes except Exception as error: print('family HMM step skipped:', repr(error), flush=True) return {} def rhea_override(queries, current): """Reviewed UniProt entries with no full EC number (none at all, or a partial one like 7.1.1.-) still list the reactions they catalyse as Rhea IDs, and each Rhea reaction maps to an EC. On the 613 training proteins found in this table, the label was one of the Rhea ECs 98% of the time, so a prediction outside the Rhea set is almost always wrong. Only such predictions are replaced: by the Rhea EC that the entry's GO terms also name, else the one most common in training. Optional: a missing table or any failure changes nothing.""" try: table = pd.read_parquet(ROOT / 'weights' / 'sprot_rhea.parquet') labels = pd.read_parquet(ROOT / 'weights' / 'train_labels.parquet') count = {} for sid, ecs in zip(labels.seq_id, labels.ecs): if sid.startswith('t'): for e in ecs.split(';'): count[e] = count.get(e, 0) + 1 sets_of = {seq: (sorted(set(r.split(';')) - {''}), set(g.split(';')) - {''}) for seq, r, g in zip(table.sequence, table.rhea_ecs, table.go_ecs)} changes = {} for q, seq in zip(queries.id, queries.sequence): if seq not in sets_of: continue rhea, go = sets_of[seq] # the table holds only vocabulary ECs if rhea and current.get(q) not in rhea: changes[q] = max(rhea, key=lambda e: (e in go, count.get(e, 0))) print('Rhea step: %d predictions changed' % len(changes), flush=True) return changes except Exception as error: print('Rhea step skipped:', repr(error), flush=True) return {} def predict_file(input_path, output_path): start = time.time() all_inputs = prepare_inputs(pd.read_parquet(input_path)) # Exact lookup: a query whose sequence is a Swiss-Prot entry takes that entry's EC and needs no search lookup = pd.read_parquet(ROOT / 'weights' / 'swissprot_lookup.parquet') ec_of_sequence = dict(zip(lookup.sequence, lookup.ec)) looked_up = {qid: ec_of_sequence[seq] for qid, seq in zip(all_inputs.id, all_inputs.sequence) if seq in ec_of_sequence} n_swissprot = len(looked_up) # Second exact lookup: BRENDA (literature-curated; covers many unreviewed entries with no UniProt EC) brenda = pd.read_parquet(ROOT / 'weights' / 'brenda_lookup.parquet') ec_of_brenda = dict(zip(brenda.sequence, brenda.ec)) for qid, seq in zip(all_inputs.id, all_inputs.sequence): if qid not in looked_up and seq in ec_of_brenda: looked_up[qid] = ec_of_brenda[seq] n_brenda = len(looked_up) - n_swissprot # Third exact lookup: unreviewed UniProt (TrEMBL) entries with an EC, stored as sequence fingerprints trembl = trembl_lookup(all_inputs[~all_inputs.id.isin(looked_up)]) # Learned remap for TrEMBL: a few ECs where TrEMBL's annotation and the competition labels disagree # consistently on training proteins (e.g. 1.2.1.27 is labelled 1.2.1.18) remap = json.loads((ROOT / 'weights' / 'remap.json').read_text()).get('tr', {}) trembl = {qid: remap.get(ec, ec) for qid, ec in trembl.items()} looked_up.update(trembl) # Fourth exact lookup: PDB structure chains with an EC (SIFTS), for queries no UniProt source covers pdb = pd.read_parquet(ROOT / 'weights' / 'pdb_lookup.parquet') ec_of_pdb = dict(zip(pdb.sequence, pdb.ec)) n_pdb = 0 for qid, seq in zip(all_inputs.id, all_inputs.sequence): if qid not in looked_up and seq in ec_of_pdb: looked_up[qid] = ec_of_pdb[seq] n_pdb += 1 frame = all_inputs[~all_inputs.id.isin(looked_up)].reset_index(drop=True) print('lookup: %d Swiss-Prot, %d BRENDA, %d TrEMBL, %d PDB, of %d queries; %d left for the search' % ( n_swissprot, n_brenda, len(trembl), n_pdb, len(all_inputs), len(frame)), flush=True) labels = pd.read_parquet(ROOT / 'weights' / 'train_labels.parquet') ecs_of = dict(zip(labels.seq_id, labels.ecs.str.split(';'))) fallback = json.loads((ROOT / 'weights' / 'fallback.json').read_text())['prediction'][0] with open(ROOT / 'weights' / 'reranker.pkl', 'rb') as f: reranker = pickle.load(f) with open(ROOT / 'weights' / 'reranker_v5.pkl', 'rb') as f: reranker_v5 = pickle.load(f) all_hits = [] chunks = make_chunks(frame) batch_residues = [sum(len(seq) for _, seq in chunk) for chunk in chunks] # How much slower (>1) or faster (<1) this machine is than our test machine, measured on # the very-sensitive batches run so far slowdown = None actual_seconds, expected_seconds = 0.0, 0.0 with tempfile.TemporaryDirectory(dir='/tmp') as workdir: for i, chunk in enumerate(chunks): elapsed = time.time() - start if elapsed > STOP_AFTER_SECONDS: print('time limit near, %d batches left without hits' % (len(chunks) - i), flush=True) break # Very-sensitive only if everything left is expected to finish by SENSITIVE_UNTIL_SECONDS sensitive = True if slowdown is not None: still_needed = slowdown * sum(expected_batch_seconds(r) for r in batch_residues[i:]) sensitive = elapsed + still_needed < SENSITIVE_UNTIL_SECONDS batch_start = time.time() hits = run_diamond(chunk, workdir, sensitive, STOP_AFTER_SECONDS - elapsed) if hits is not None: all_hits.append(hits) if sensitive and hits is not None: actual_seconds += time.time() - batch_start expected_seconds += expected_batch_seconds(batch_residues[i]) slowdown = actual_seconds / expected_seconds print('batch %d/%d done (%s mode, %d queries), %.0f s, machine speed factor %s' % ( i + 1, len(chunks), 'very-sensitive' if sensitive else 'default', len(chunk), time.time() - start, 'n/a' if slowdown is None else '%.2f' % slowdown), flush=True) hits = pd.concat(all_hits) if all_hits else pd.DataFrame(columns=HIT_COLUMNS) # Second search for queries with no hit at all: ultra-sensitive with a loose E-value. # On held-out training folds this gets the full EC right about twice as often as our # classifier does for these queries (0.048 vs 0.025). second_vote = {} have_hits = set(hits.q) no_hit = [(qid, seq) for qid, seq in zip(frame.id, frame.sequence) if qid not in have_hits] elapsed = time.time() - start fast_enough = slowdown is not None and slowdown < SECOND_PASS_MAX_SLOWDOWN if no_hit and elapsed < SECOND_PASS_IF_DONE_BY and fast_enough: second = run_diamond(no_hit, workdir, True, min(STOP_AFTER_SECONDS - elapsed, SECOND_PASS_MAX_SECONDS), '--ultra-sensitive', '100') if second is not None: second = second.sort_values(['q', 'bits'], ascending=[True, False]) second_vote = {q: vote(g, ecs_of) for q, g in second.groupby('q', sort=False)} print('second search: %d of %d no-hit queries now have hits, %.0f s' % ( len(second_vote), len(no_hit), time.time() - start), flush=True) else: print('second search skipped (%d no-hit queries, %.0f s, speed factor %s)' % ( len(no_hit), elapsed, 'n/a' if slowdown is None else '%.2f' % slowdown), flush=True) # Weak queries: no hit at all, or best identity below the cut. Weakest first, so the time budget # is spent where the classifier helps most. best_pid = hits.groupby('q').pid.max() weak = [(best_pid.get(q, 0.0), q) for q in frame.id if best_pid.get(q, 0.0) < reranker['pid_cut']] weak = [q for _, q in sorted(weak) if q not in second_vote] # queries solved by the second search skip the classifier sequence_of = dict(zip(frame.id, frame.sequence)) clf = run_classifier(weak, sequence_of, start) print('classifier ran on %d of %d weak queries, %.0f s' % (len(clf), len(weak), time.time() - start), flush=True) # Each EC seen among a query's hits is a candidate; the reranker scores how likely it is correct best_ec = {} if len(hits): cand = candidate_features(hits, ecs_of, reranker['log_freq']) cand = add_classifier_features(cand, {q: v for q, v in clf.items() if q in best_pid.index}) # Ensemble: each candidate's score is the average of two rerankers' probabilities of being # correct, the v4 model and the v5 model (v5 also uses out-of-fold EC reliability). # Averaging two models that make different mistakes lowers the variance of the pick. p_v4 = reranker['model'].predict_proba(cand[reranker['features']])[:, 1] cand = add_reliability(cand, reranker_v5['reliability'], reranker_v5['overall_rate']) p_v5 = reranker_v5['model'].predict_proba(cand[reranker_v5['features']])[:, 1] cand['p'] = (p_v4 + p_v5) / 2 best_ec = cand.sort_values('p', ascending=False).drop_duplicates('q').set_index('q').ec.to_dict() # Queries with no first-search hit: the second-search vote, otherwise the classifier's top EC for q, ec in second_vote.items(): if q not in best_ec: best_ec[q] = ec for q, (ecs, ps) in clf.items(): if q not in best_ec: best_ec[q] = str(ecs[0]) # Curated protein-family HMMs (NCBIfam/TIGRFAM "equivalog" families: every member has the same # specific function) for the searched queries. A hit above the family's trusted cutoffs whose EC set # does not contain the current prediction replaces it with the family's EC most common in training. # On 1,000 weak training proteins this changed 86 predictions, raising their credit from 5 to 76. best_ec.update(family_hmm_override(frame, best_ec)) # Reviewed UniProt entries without a full EC number still name their reactions (Rhea IDs). A searched # query whose exact sequence is such an entry, and whose prediction is not one of the Rhea ECs, is # switched to a Rhea EC (see rhea_override). best_ec.update(rhea_override(frame, best_ec)) best_ec.update(looked_up) with Path(output_path).open('w') as output: for key in all_inputs.id: output.write(json.dumps({'id': key, 'prediction': [best_ec.get(key, fallback)]}) + '\n') if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', required=True) parser.add_argument('--output', required=True) args = parser.parse_args() predict_file(args.input, args.output)