"""Step 5: the reranker. Turns the DIAMOND hits into candidate ECs and picks the best one. Every EC of any hit is a candidate for that query. Each candidate gets a row of numbers (features) describing how well the search results support it. Two trained gradient-boosted tree models (reranker v4 and v5) each give every candidate a probability of being correct; we average the two and predict the candidate with the highest average. The training scripts in training/ build exactly the same features, so the names here must not change. """ import numpy as np import pandas as pd # The 20 search features (reranker v4 uses these plus the 2 classifier features = 22) FEATURES = ['best_bits', 'bits_ratio', 'best_pid', 'pid_gap', 'first_rank', 'n_hits', 'hit_frac', 'share1', 'share4', 'l3_share', 'vote_rank', 'best_qcov', 'best_scov', 'log_ev', 'q_best_bits', 'q_best_pid', 'q_hits', 'n_cands', 'log_qlen', 'log_freq'] # 10 extra features added in reranker v5 (v5 = 20 + 2 + 10 + 2 reliability = 34) EXTRA_FEATURES = ['share8', 'top3_hits', 'top10_hits', 'is_top_hit', 'l2_share', 'l1_share', 'mean_pid', 'bits_per_len', 'min_cov', 'inv_labels'] CLASSIFIER_FEATURES = ['clf_prob', 'clf_top'] RELIABILITY_FEATURES = ['ec_reliability', 'ec_reliability_n'] def candidate_features(hits, labels_of, log_freq): """One row per (query, candidate EC) with its features. hits: DIAMOND hits (columns q, s, pid, alen, qlen, slen, ev, bits) labels_of: {reference protein id: list of its ECs} log_freq: {EC: log(1 + number of training proteins with this EC)} """ # One row per (hit, EC of that hit), with the hit's rank for its query (1 = best bitscore) h = hits.sort_values(['q', 'bits'], ascending=[True, False]).copy() h['rank'] = h.groupby('q').cumcount() + 1 h['ec'] = h.s.map(labels_of) h['n_labels'] = h.ec.str.len() # how many ECs this hit has h = h.explode('ec') # Numbers about the query as a whole: its best bitscore, best identity and number of hits per_query = h.groupby('q').agg(q_best_bits=('bits', 'max'), q_best_pid=('pid', 'max'), q_hits=('rank', 'max')) h = h.join(per_query, on='q') # Vote weight of each hit, in three versions; a hit with several ECs splits its weight h['w1'] = h.bits / h.n_labels # plain bitscore h['w4'] = (h.bits / h.q_best_bits) ** 4 / h.n_labels # the baseline vote's weight h['w8'] = (h.bits / h.q_best_bits) ** 8 / h.n_labels # even sharper: almost only the closest hits count h['qcov'] = h.alen / h.qlen # share of the query covered by the alignment h['scov'] = h.alen / h.slen # share of the reference covered h['in_top3'] = (h['rank'] <= 3).astype(int) h['in_top10'] = (h['rank'] <= 10).astype(int) # Combine the hits of each (query, EC) pair into one candidate row c = h.groupby(['q', 'ec']).agg( best_bits=('bits', 'max'), best_pid=('pid', 'max'), first_rank=('rank', 'min'), n_hits=('rank', 'size'), w1=('w1', 'sum'), w4=('w4', 'sum'), best_qcov=('qcov', 'max'), best_scov=('scov', 'max'), min_ev=('ev', 'min'), q_best_bits=('q_best_bits', 'first'), q_best_pid=('q_best_pid', 'first'), q_hits=('q_hits', 'first'), qlen=('qlen', 'first'), w8=('w8', 'sum'), top3_hits=('in_top3', 'sum'), top10_hits=('in_top10', 'sum'), mean_pid=('pid', 'mean'), min_labels=('n_labels', 'min')).reset_index() # Share of the query's total vote that each candidate gets c['share1'] = c.w1 / c.groupby('q').w1.transform('sum') c['share4'] = c.w4 / c.groupby('q').w4.transform('sum') c['share8'] = c.w8 / c.groupby('q').w8.transform('sum') c['vote_rank'] = c.groupby('q').share4.rank(ascending=False, method='first') # How much of the vote agrees with this candidate's first 3, 2 and 1 EC digits # (e.g. for 1.1.1.1: all votes for ECs starting with 1.1.1, with 1.1, and with 1) c['l3'] = c.ec.str.rsplit('.', n=1).str[0] c['l2'] = c.ec.str.split('.').str[:2].str.join('.') c['l1'] = c.ec.str.split('.').str[0] c['l3_share'] = c.groupby(['q', 'l3']).share4.transform('sum') c['l2_share'] = c.groupby(['q', 'l2']).share4.transform('sum') c['l1_share'] = c.groupby(['q', 'l1']).share4.transform('sum') # Other comparisons c['is_top_hit'] = (c.first_rank == 1).astype(int) # does this EC hold the query's best hit? c['bits_per_len'] = c.best_bits / c.qlen c['min_cov'] = np.minimum(c.best_qcov.clip(upper=1), c.best_scov.clip(upper=1)) c['inv_labels'] = 1.0 / c.min_labels c['bits_ratio'] = c.best_bits / c.q_best_bits # 1.0 for the EC of the best hit c['pid_gap'] = c.q_best_pid - c.best_pid c['hit_frac'] = c.n_hits / c.q_hits c['n_cands'] = c.groupby('q').ec.transform('size') # how many candidates the query has c['log_ev'] = -np.log10(c.min_ev + 1e-300) c['log_qlen'] = np.log(c.qlen) c['log_freq'] = c.ec.map(log_freq).fillna(0.0) # how common the EC is in training return c def add_classifier_features(cand, classifier_output): """Add the two classifier features. classifier_output: {query id: (top 10 ECs, their probabilities)} for queries the classifier ran on. clf_prob = the probability the classifier gives this candidate EC (0 if not in its top 10) clf_top = the probability of the classifier's own first choice (how sure it is overall) Queries the classifier did not run on get NaN (empty), which the tree models treat as 'missing'. """ probability = {(q, e): p for q, (ecs, ps) in classifier_output.items() for e, p in zip(ecs, ps)} ran = cand.q.isin(set(classifier_output)) cand['clf_prob'] = [probability.get((q, e), 0.0) for q, e in zip(cand.q, cand.ec)] cand['clf_top'] = cand.q.map({q: ps[0] for q, (ecs, ps) in classifier_output.items()}) cand.loc[~ran, 'clf_prob'] = np.nan return cand def add_reliability(cand, reliability, overall_rate): """Add two features about how reliable each EC was as a candidate on the training folds (v5 only). reliability: {EC: (credit earned when it was a candidate, times it was a candidate)} The rate is pulled towards the overall rate (as if each EC had 5 extra average cases), so a rare EC does not get an extreme value from a handful of cases. """ earned = cand.ec.map({e: v[0] for e, v in reliability.items()}).fillna(0.0) proposed = cand.ec.map({e: v[1] for e, v in reliability.items()}).fillna(0.0) cand['ec_reliability'] = (earned + 5 * overall_rate) / (proposed + 5) cand['ec_reliability_n'] = np.log1p(proposed) return cand def pick_best_ec(hits, classifier_output, reranker_v4, reranker_v5, labels_of): """Score every candidate with both rerankers and return {query id: best EC}.""" if len(hits) == 0: return {} cand = candidate_features(hits, labels_of, reranker_v4['log_freq']) cand = add_classifier_features(cand, classifier_output) # Probability of being correct from each model; each model reads its own feature list p_v4 = reranker_v4['model'].predict_proba(cand[reranker_v4['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] # Average of the two models: they make different mistakes, so the average is more stable cand['p'] = (p_v4 + p_v5) / 2 best = cand.sort_values('p', ascending=False).drop_duplicates('q') return best.set_index('q').ec.to_dict()