Download predict.py from RohanTheZ/enzyme-viva: direct link, hf CLI and curl.
- Browser
- Download file 5.42 kB
-
https://huggingface.co/RohanTheZ/enzyme-viva/resolve/main/predict.py
- Command line
-
hf download hf://RohanTheZ/enzyme-viva/predict.py
-
curl -L -o predict.py https://huggingface.co/RohanTheZ/enzyme-viva/resolve/main/predict.py
5.42 kB
| """Predict one EC number for every protein sequence in the input file (runs on CPU, offline). | |
| How a query is predicted, in order: | |
| 1. Exact lookups (lookups.py): if the sequence is in Swiss-Prot, BRENDA, TrEMBL or PDB, take that | |
| entry's EC. This answers about 99.6% of validation queries. | |
| 2. First search (search.py): DIAMOND finds similar reference proteins ("hits") for the rest. | |
| 3. Second search (search.py): queries with no hit get a slower, more sensitive search and a vote. | |
| 4. Classifier (classifier.py): the ESM2-8M model reads the sequence of weak queries | |
| (best hit below 40% identity) and gives its own EC probabilities. | |
| 5. Rerankers (rerank.py): every EC of the hits is a candidate; two trained models score the | |
| candidates and the best one is predicted. | |
| 6. Final checks (checks.py): NCBIfam family check, then Rhea reaction check. | |
| 7. Write one line per input: {"id": ..., "prediction": [EC]}. | |
| Usage: python predict.py --input INPUT.parquet --output OUTPUT.jsonl | |
| """ | |
| import os | |
| # Use one maths thread per process: the classifier runs in two processes on the two CPUs. | |
| # This must be set before numpy is imported (all the modules below import numpy). | |
| os.environ['OPENBLAS_NUM_THREADS'] = '1' | |
| os.environ['OMP_NUM_THREADS'] = '1' | |
| os.environ['MKL_NUM_THREADS'] = '1' | |
| import argparse | |
| import json | |
| import pickle | |
| import tempfile | |
| import time | |
| from collections import Counter | |
| from pathlib import Path | |
| import pandas as pd | |
| from checks import family_check, rhea_check | |
| from classifier import run_classifier | |
| from inputs import prepare_inputs | |
| from lookups import exact_lookups | |
| from rerank import pick_best_ec | |
| from search import first_search, second_search | |
| WEIGHTS = Path(__file__).parent / 'weights' | |
| def load_reference_labels(): | |
| """ECs of every reference protein in the DIAMOND database, and how often each EC appears in training. | |
| Reference ids starting with 't' are competition training proteins; ids starting with 's' are the | |
| extra Swiss-Prot enzymes. Only training proteins are counted. | |
| """ | |
| labels = pd.read_parquet(WEIGHTS / 'train_labels.parquet') # columns seq_id, ecs ('a;b') | |
| labels_of = dict(zip(labels.seq_id, labels.ecs.str.split(';'))) | |
| train_count = Counter() | |
| for seq_id, ecs in zip(labels.seq_id, labels.ecs): | |
| if seq_id.startswith('t'): | |
| train_count.update(ecs.split(';')) | |
| return labels_of, train_count | |
| def load_pickle(file_name): | |
| with open(WEIGHTS / file_name, 'rb') as f: | |
| return pickle.load(f) | |
| def predict_file(input_path, output_path): | |
| start = time.time() | |
| inputs = prepare_inputs(pd.read_parquet(input_path)) # unique sequences only | |
| # Step 1: exact lookups | |
| looked_up = exact_lookups(inputs) | |
| queries = inputs[~inputs.id.isin(looked_up)].reset_index(drop=True) # the rest go to the search | |
| labels_of, train_count = load_reference_labels() | |
| fallback = json.loads((WEIGHTS / 'fallback.json').read_text())['prediction'][0] # most common training EC | |
| reranker_v4 = load_pickle('reranker.pkl') | |
| reranker_v5 = load_pickle('reranker_v5.pkl') | |
| # Steps 2 and 3: first search, then the second search for queries with no hit | |
| with tempfile.TemporaryDirectory(dir='/tmp') as workdir: | |
| hits, slowdown = first_search(queries, workdir, start) | |
| second_votes = second_search(queries, hits, workdir, start, slowdown, labels_of) | |
| # Step 4: classifier on weak queries (best identity below 40%, or no hit), weakest first so the | |
| # time goes where it helps most. Queries already answered by the second search are skipped. | |
| best_identity = hits.groupby('q').pid.max() | |
| weak = [(best_identity.get(q, 0.0), q) for q in queries.id if best_identity.get(q, 0.0) < reranker_v4['pid_cut']] | |
| weak = [q for _, q in sorted(weak) if q not in second_votes] | |
| sequence_of = dict(zip(queries.id, queries.sequence)) | |
| classifier_output = run_classifier(weak, sequence_of, start) | |
| print('classifier ran on %d of %d weak queries, %.0f s' % (len(classifier_output), len(weak), time.time() - start), flush=True) | |
| # Step 5: rerankers pick the best candidate EC for every query that has hits | |
| with_hits = {q: v for q, v in classifier_output.items() if q in best_identity.index} | |
| best_ec = pick_best_ec(hits, with_hits, reranker_v4, reranker_v5, labels_of) | |
| # Queries with no hit in the first search: the second-search vote, otherwise the classifier's top EC | |
| for q, ec in second_votes.items(): | |
| if q not in best_ec: | |
| best_ec[q] = ec | |
| for q, (ecs, probabilities) in classifier_output.items(): | |
| if q not in best_ec: | |
| best_ec[q] = str(ecs[0]) | |
| # Step 6: final checks on the searched queries | |
| best_ec.update(family_check(queries, best_ec, train_count)) | |
| best_ec.update(rhea_check(queries, best_ec, train_count)) | |
| # Step 7: lookup answers always win; anything still without a prediction gets the fallback EC | |
| best_ec.update(looked_up) | |
| with Path(output_path).open('w') as output: | |
| for query_id in inputs.id: | |
| output.write(json.dumps({'id': query_id, 'prediction': [best_ec.get(query_id, 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) | |