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() and SeqOpt.run() all return sequences, whereas predict() 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 its features reference (reusing the wild-type TMD coordinates from df_seq), builds the matrix with SequenceFeature.feature_matrix(), and hands it to predict(). 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_status and ad_nearest_train say which candidates the model can still be trusted on, and reliable is 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 entry column naming the wild-type each candidate derives from, plus the candidate sequence in the col_seq column. SeqMut.mutate(), SeqMut.combine() and SeqOpt.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 entry column with unique protein identifiers, in the position-based format (sequence, tmd_start, tmd_stop). See SequenceFeature.get_df_parts() for the full df_seq format specification. It supplies the wild-type TMD coordinates reused for every candidate of an entry.

  • features (array-like, shape (n_features,) or pd.DataFrame) – Feature ids ('PART-SPLIT-SCALE'), or a df_feat whose 'feature' column holds them. Pass the same feature set, in the same order, that produced the training X of fit(); 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. If None, the default scale set from load_scales() is used.

  • col_seq (str, default='sequence_mut') – Name of the df_cand column carrying the candidate sequence. 'sequence_mut' is the column SeqMut.mutate(), SeqMut.combine() and SeqOpt.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 per df_cand row, in df_cand order and carrying its index, with exactly the columns predict() returns (score … reliable, ad_status, ad_nearest_train). Attach it to the candidates with df_cand.join(df_rel).

Return type:

pd.DataFrame, shape (n_candidates, 16)

Raises:
  • RuntimeError – If called before fit().

  • ValueError – If df_cand is not a DataFrame, is empty, or lacks an entry / col_seq column; if a candidate entry is absent from df_seq or its sequence is not a string; if df_seq is not position-based or its entries are not unique; if features is empty or a feature id does not follow the 'PART-SPLIT-SCALE' grammar; if col_seq is not a string, jmd_n_len / jmd_c_len are not non-negative integers, or n_jobs is invalid; or if the rebuilt matrix has a different number of features than the training X.

Notes

  • Substitutions only. A substituted candidate keeps the wild-type length, so the wild-type tmd_start / tmd_stop still locate its TMD. Insertions or deletions shift those coordinates: score such candidates by passing a df_seq whose coordinates are already corrected for them.

  • The result equals building the matrix yourself with SequenceFeature.feature_matrix() and calling predict() on it; both routes give the same ood_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. SeqMut and SeqOpt return sequences, while predict takes 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 the features reference (reusing the wild-type TMD coordinates from df_seq), the matrix is built with SequenceFeature.feature_matrix, and the result is handed to predict.

Designed candidates are pushed away from the training data by construction, so the applicability-domain columns are the point: ood_score, ad_status and ad_nearest_train say 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.suggest proposes the mutations that move one wild-type most strongly toward the test-class profile, and SeqMut.mutate turns them into candidate sequences. The candidate column is sequence_mut (SeqMut.combine and SeqOpt.run emit the same entry + sequence_mut shape).

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_cand is the candidate table, df_seq the wild-type it derives from (it supplies tmd_start / tmd_stop), and features the feature set the model was fitted on (a df_feat or a plain list of feature ids). The result has the columns of predict, 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_scales pins the amino acid scales (use the ones the training matrix was built with), col_seq names the sequence column of df_cand, jmd_n_len / jmd_c_len set the JMD flank lengths used to slice the parts, and n_jobs spreads 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_seq also scores a column of unmutated sequences: pointing it at sequence runs 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_score climbs above 1, ad_status turns outside, and reliable is False whatever 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