"""Step 6: two final checks on the predictions of the searched queries. Both checks are optional: if their files are missing or anything fails, no prediction changes. Family check (NCBIfam): NCBIfam has 5,078 family models (profile HMMs). Each describes a protein family whose members all have the same EC. If a query matches a family above the family's "trusted" score, and our prediction is not that family's EC, the prediction becomes the family's EC. On 1,000 weak training proteins this changed 86 predictions and raised their credit from 5 to 76. Rhea check: Some Swiss-Prot entries have no full EC (none at all, or a partial one like 7.1.1.-), so the Swiss-Prot lookup skips them. Many still list the reactions they carry out as Rhea IDs, and each Rhea reaction has a full EC. On training proteins found in this table, the label was one of these reaction ECs 98% of the time. So if a query's sequence is such an entry and our prediction is not one of its reaction ECs, we switch to a reaction EC: the one the entry's GO labels also name, otherwise the one most common in training. """ import gzip import json from pathlib import Path import pandas as pd ROOT = Path(__file__).parent WEIGHTS = ROOT / 'weights' def most_common(ecs, train_count): """The EC that appears most often in training (ties go to the first in sorted order).""" return max(sorted(ecs), key=lambda e: train_count.get(e, 0)) def clean_sequence(sequence, allowed_letters): # pyhmmer accepts only standard amino-acid letters; anything else becomes X (unknown) return ''.join(c if c in allowed_letters else 'X' for c in sequence.upper()) def family_check(queries, current, train_count): """Returns {query id: new ec} for the predictions the family check changes.""" try: import pyhmmer families = json.loads((WEIGHTS / 'ncbifam_ec.json').read_text()) # family name -> its ECs vocab = set(json.loads((ROOT / 'ec_vocabulary.json').read_text())) if len(queries) == 0: return {} with pyhmmer.plan7.HMMFile(gzip.open(WEIGHTS / 'ncbifam_ec.hmm.gz', 'rb')) as f: hmms = list(f) alphabet = pyhmmer.easel.Alphabet.amino() allowed = set(alphabet.symbols) - set('-*~') sequences = pyhmmer.easel.TextSequenceBlock([ pyhmmer.easel.TextSequence(name=str(q).encode(), sequence=clean_sequence(s, allowed)) for q, s in zip(queries.id, queries.sequence)]).digitize(alphabet) # For each query, its best family hit above that family's trusted cutoffs best = {} # query id -> (score, family name) for hmm, hits in zip(hmms, pyhmmer.hmmsearch(hmms, sequences, cpus=2)): full_cutoff, domain_cutoff = hmm.cutoffs.trusted family = hmm.name.decode() if isinstance(hmm.name, bytes) else hmm.name for hit in hits: if hit.score >= full_cutoff and hit.best_domain.score >= domain_cutoff: 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, family) changes = {} for q, (score, family) in best.items(): family_ecs = [e for e in families[family]['ecs'] if e in vocab] if family_ecs and current.get(q) not in family_ecs: changes[q] = most_common(family_ecs, train_count) 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_check(queries, current, train_count): """Returns {query id: new ec} for the predictions the Rhea check changes.""" try: table = pd.read_parquet(WEIGHTS / 'sprot_rhea.parquet') # sequence, rhea_ecs, go_ecs (only vocabulary ECs) reaction_ecs = {} for seq, rhea_text, go_text in zip(table.sequence, table.rhea_ecs, table.go_ecs): rhea = sorted(set(rhea_text.split(';')) - {''}) go = set(go_text.split(';')) - {''} reaction_ecs[seq] = (rhea, go) changes = {} for q, seq in zip(queries.id, queries.sequence): if seq not in reaction_ecs: continue rhea, go = reaction_ecs[seq] if rhea and current.get(q) not in rhea: # Prefer a reaction EC that GO also names, then the one most common in training changes[q] = max(rhea, key=lambda e: (e in go, train_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 {}