ReliabilityModel.predict_candidates
- ReliabilityModel.predict_candidates(df_cand, df_seq, features, *, df_scales=None, col_seq='sequence_mut', jmd_n_len=10, jmd_c_len=10, n_jobs=1)[source]
Score a set of design candidates for reliability, rebuilding their feature matrix first.
The one-call entry point from the design tier.
SeqMut.mutate(),SeqMut.combine()andSeqOpt.run()all return sequences, whereaspredict()takes a feature matrix, so scoring a candidate set used to mean rebuilding that matrix by hand. This method does it: it slices every candidate sequence into the parts itsfeaturesreference (reusing the wild-type TMD coordinates fromdf_seq), builds the matrix withSequenceFeature.feature_matrix(), and hands it topredict(). No scoring logic is duplicated.Designed candidates are pushed away from the training data by construction, which is exactly what the applicability-domain columns measure:
ood_score,ad_statusandad_nearest_trainsay which candidates the model can still be trusted on, andreliableis the headline verdict.Added in version 1.2.0.
- Parameters:
df_cand (pd.DataFrame, shape (n_candidates, n_cand_info)) – Candidate table from the design tier: an
entrycolumn naming the wild-type each candidate derives from, plus the candidate sequence in thecol_seqcolumn.SeqMut.mutate(),SeqMut.combine()andSeqOpt.run()all emit this shape (entry+sequence_mut); every other column is ignored and kept out of the result.df_seq (pd.DataFrame, shape (n_samples, n_seq_info)) – DataFrame containing an
entrycolumn with unique protein identifiers, in the position-based format (sequence,tmd_start,tmd_stop). SeeSequenceFeature.get_df_parts()for the fulldf_seqformat specification. It supplies the wild-type TMD coordinates reused for every candidate of anentry.features (array-like, shape (n_features,) or pd.DataFrame) – Feature ids (
'PART-SPLIT-SCALE'), or adf_featwhose'feature'column holds them. Pass the same feature set, in the same order, that produced the trainingXoffit(); a different number of features raises.df_scales (pd.DataFrame, shape (n_letters, n_scales), optional) – DataFrame of amino acid scales (index = amino acids, columns = scale ids). Pass the scales used to build the training
X. IfNone, the default scale set fromload_scales()is used.col_seq (str, default='sequence_mut') – Name of the
df_candcolumn carrying the candidate sequence.'sequence_mut'is the columnSeqMut.mutate(),SeqMut.combine()andSeqOpt.run()emit; pass'sequence'to score wild-type sequences with the same call.jmd_n_len (int, default=10) – Length of JMD-N in number of amino acids (a non-negative integer). Use the value the training matrix was built with, or the candidate parts will not match it.
jmd_c_len (int, default=10) – Length of JMD-C in number of amino acids (a non-negative integer). Use the value the training matrix was built with, or the candidate parts will not match it.
n_jobs (int, None, or -1, default=1) – Number of CPU cores (>=1) used to build the candidate feature matrix. If
None, the number is optimized automatically; if-1, all available cores are used. It changes speed only, never the returned values.
- Returns:
df_rel – The
predict()table for the rebuilt candidate matrix: one row perdf_candrow, indf_candorder and carrying its index, with exactly the columnspredict()returns (score…reliable,ad_status,ad_nearest_train). Attach it to the candidates withdf_cand.join(df_rel).- Return type:
pd.DataFrame, shape (n_candidates, 16)
- Raises:
RuntimeError – If called before
fit().ValueError – If
df_candis not a DataFrame, is empty, or lacks anentry/col_seqcolumn; if a candidateentryis absent fromdf_seqor its sequence is not a string; ifdf_seqis not position-based or its entries are not unique; iffeaturesis empty or a feature id does not follow the'PART-SPLIT-SCALE'grammar; ifcol_seqis not a string,jmd_n_len/jmd_c_lenare not non-negative integers, orn_jobsis invalid; or if the rebuilt matrix has a different number of features than the trainingX.
Notes
Substitutions only. A substituted candidate keeps the wild-type length, so the wild-type
tmd_start/tmd_stopstill locate its TMD. Insertions or deletions shift those coordinates: score such candidates by passing adf_seqwhose coordinates are already corrected for them.The result equals building the matrix yourself with
SequenceFeature.feature_matrix()and callingpredict()on it; both routes give the sameood_score.Duplicate candidate rows are kept and scored independently, so the output never collapses rows and stays row-aligned with
df_cand.
Examples
ReliabilityModel().predict_candidates()scores a design-candidate set in one call.SeqMutandSeqOptreturn sequences, whilepredicttakes a feature matrix, so a candidate set used to be scored by rebuilding that matrix by hand. This method does it: the candidate sequences are sliced into the parts thefeaturesreference (reusing the wild-type TMD coordinates fromdf_seq), the matrix is built withSequenceFeature.feature_matrix, and the result is handed topredict.Designed candidates are pushed away from the training data by construction, so the applicability-domain columns are the point:
ood_score,ad_statusandad_nearest_trainsay which candidates the model can still be trusted on.import aaanalysis as aa aa.options["verbose"] = False # Training data: the feature matrix the reliability reference is fitted on. df_seq = aa.load_dataset(name="DOM_GSEC", n=25) df_feat = aa.load_features().head(30) sf = aa.SequenceFeature() X = sf.feature_matrix(features=df_feat, df_seq=df_seq) labels = df_seq["label"].to_list() rm = aa.ReliabilityModel(random_state=42).fit(X=X, labels=labels, ad_borderline=0.25) print(f"fitted on {len(X)} samples; ad_threshold_ = {rm.ad_threshold_:.3f} ({rm.ad_method_})")
fitted on 50 samples; ad_threshold_ = 5.568 (knn)
The candidate set.
SeqMut.suggestproposes the mutations that move one wild-type most strongly toward the test-class profile, andSeqMut.mutateturns them into candidate sequences. The candidate column issequence_mut(SeqMut.combineandSeqOpt.runemit the sameentry+sequence_mutshape).df_wt = df_seq.head(1) # one wild-type to design around seqm = aa.SeqMut() df_sug = seqm.suggest(df_seq=df_wt, df_feat=df_feat, n=8, region="tmd") df_mut = seqm.mutate(df_seq=df_wt, mutations=df_sug[["entry", "pos", "to_aa"]], df_feat=df_feat) aa.display_df(df_mut, n_rows=10, show_shape=True)
DataFrame shape: (8, 8)
entry pos to_aa from_aa mutation sequence_mut delta_cpp shift_score 1 Q14802 59 R A A59R MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 1.248970 1.212690 2 Q14802 59 K A A59K MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 1.219060 1.122200 3 Q14802 59 Q A A59Q MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.565060 0.387340 4 Q14802 59 Y A A59Y MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.501020 0.293580 5 Q14802 59 M A A59M MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.320380 0.258420 6 Q14802 58 R S S58R MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.223860 0.223860 7 Q14802 57 I M M57I MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.313850 0.218710 8 Q14802 59 N A A59N MQKVTLGLLVFLAGF...PGETPPLITPGSAQS 0.638060 0.208340 One call.
df_candis the candidate table,df_seqthe wild-type it derives from (it suppliestmd_start/tmd_stop), andfeaturesthe feature set the model was fitted on (adf_feator a plain list of feature ids). The result has the columns ofpredict, one row per candidate, in candidate order.df_rel = rm.predict_candidates(df_cand=df_mut, df_seq=df_wt, features=df_feat) aa.display_df(df_rel, n_rows=10, show_shape=True)
DataFrame shape: (8, 16)
score score_std ci_low ci_high ood_score in_domain ad_knn ad_mahalanobis ad_leverage score_calibrated margin entropy conformal_set reliable ad_status ad_nearest_train 1 0.409000 0.170906 0.127884 0.690116 0.850316 True 4.734768 7.708792 1.213349 0.447090 0.105820 0.991907 both False inside 0 2 0.397000 0.175445 0.108418 0.685582 0.854408 True 4.757554 8.417703 1.446891 0.449735 0.100529 0.992698 both False inside 0 3 0.322500 0.181270 0.024338 0.620662 0.702199 True 3.910020 5.974393 0.728622 0.344444 0.311111 0.929008 neg True inside 0 4 0.331000 0.178883 0.036764 0.625236 0.721058 True 4.015032 6.292646 0.809101 0.311111 0.377778 0.894452 neg True inside 0 5 0.357500 0.183708 0.055327 0.659673 0.747114 True 4.160117 6.827822 0.951631 0.416402 0.167196 0.979740 neg True inside 0 6 0.370500 0.187896 0.061439 0.679561 0.726865 True 4.047367 6.986730 0.996517 0.288360 0.423280 0.866593 both False inside 0 7 0.299500 0.191767 0.000000 0.614929 0.695324 True 3.871738 5.671605 0.656831 0.111111 0.777778 0.503258 neg True inside 0 8 0.301500 0.179730 0.005871 0.597129 0.726475 True 4.045192 6.752306 0.930891 0.111111 0.777778 0.503258 neg True inside 0 The table keeps the candidates’ index, so it attaches to them with a plain join: the design score (
delta_cpp/shift_score) and the trust verdict end up side by side.cols = ["score", "ood_score", "in_domain", "ad_status", "ad_nearest_train", "reliable"] df_scored = df_mut[["mutation", "delta_cpp", "shift_score"]].join(df_rel[cols]) aa.display_df(df_scored, n_rows=10, show_shape=True)
DataFrame shape: (8, 9)
mutation delta_cpp shift_score score ood_score in_domain ad_status ad_nearest_train reliable 1 A59R 1.248970 1.212690 0.409000 0.850316 True inside 0 False 2 A59K 1.219060 1.122200 0.397000 0.854408 True inside 0 False 3 A59Q 0.565060 0.387340 0.322500 0.702199 True inside 0 True 4 A59Y 0.501020 0.293580 0.331000 0.721058 True inside 0 True 5 A59M 0.320380 0.258420 0.357500 0.747114 True inside 0 True 6 S58R 0.223860 0.223860 0.370500 0.726865 True inside 0 False 7 M57I 0.313850 0.218710 0.299500 0.695324 True inside 0 True 8 A59N 0.638060 0.208340 0.301500 0.726475 True inside 0 True Further parameters.
df_scalespins the amino acid scales (use the ones the training matrix was built with),col_seqnames the sequence column ofdf_cand,jmd_n_len/jmd_c_lenset the JMD flank lengths used to slice the parts, andn_jobsspreads the matrix build over CPU cores (speed only, identical values).df_rel_kws = rm.predict_candidates(df_cand=df_mut, df_seq=df_wt, features=df_feat, df_scales=aa.load_scales(), col_seq="sequence_mut", jmd_n_len=10, jmd_c_len=10, n_jobs=1) print("identical to the defaults:", df_rel_kws.equals(df_rel)) aa.display_df(df_rel_kws[cols], n_rows=10, show_shape=True)
identical to the defaults: True DataFrame shape: (8, 6)
score ood_score in_domain ad_status ad_nearest_train reliable 1 0.409000 0.850316 True inside 0 False 2 0.397000 0.854408 True inside 0 False 3 0.322500 0.702199 True inside 0 True 4 0.331000 0.721058 True inside 0 True 5 0.357500 0.747114 True inside 0 True 6 0.370500 0.726865 True inside 0 False 7 0.299500 0.695324 True inside 0 True 8 0.301500 0.726475 True inside 0 True col_seqalso scores a column of unmutated sequences: pointing it atsequenceruns the wild-types of the training set through the same path, a useful in-domain reference point.df_rel_wt = rm.predict_candidates(df_cand=df_seq, df_seq=df_seq, features=df_feat, col_seq="sequence") aa.display_df(df_rel_wt[cols], n_rows=10, show_shape=True)
DataFrame shape: (50, 6)
score ood_score in_domain ad_status ad_nearest_train reliable 1 0.298000 0.639066 True inside 0 True 2 0.066500 0.793419 True inside 1 True 3 0.134500 0.611198 True inside 2 True 4 0.338500 0.772372 True inside 3 True 5 0.137500 0.562242 True inside 4 True 6 0.109500 0.661339 True inside 5 True 7 0.138500 0.660566 True inside 6 False 8 0.239000 0.762832 True inside 7 False 9 0.375000 0.575392 True inside 8 False 10 0.366000 0.528925 True inside 9 True How far is too far. The point mutations above all stay
inside: they move the sequence a little, not out of the space the model was trained on. Rewriting the whole TMD to poly-W does not leave it either, because hydrophobic TMDs are exactly what the training set is made of. Rewriting the entire JMD-TMD-JMD window to poly-D does:ood_scoreclimbs above1,ad_statusturnsoutside, andreliableisFalsewhatever the score says.import pandas as pd wt_seq = df_wt["sequence"].iloc[0] start, stop = int(df_wt["tmd_start"].iloc[0]), int(df_wt["tmd_stop"].iloc[0]) n_tmd = stop - start + 1 seq_tmd = wt_seq[:start - 1] + "W" * n_tmd + wt_seq[stop:] seq_window = wt_seq[:start - 11] + "D" * (n_tmd + 20) + wt_seq[stop + 10:] df_far = pd.DataFrame({"entry": list(df_wt["entry"]) * 2, "sequence_mut": [seq_tmd, seq_window]}, index=["TMD to poly-W", "window to poly-D"]) aa.display_df(rm.predict_candidates(df_cand=df_far, df_seq=df_wt, features=df_feat)[cols], n_rows=10, show_shape=True)
DataFrame shape: (2, 6)
score ood_score in_domain ad_status ad_nearest_train reliable TMD to poly-W 0.164500 0.796861 True inside 0 True window to poly-D 0.131500 1.896677 False outside 13 False