CPPStructurePlot.map_structure

CPPStructurePlot.map_structure(df_feat, pdb=None, uniprot=None, col_imp='feat_impact', tmd_len=20, start=1, chain=None, sequence=None, mode='impact', focus='whole', focus_region=None, size_by_impact=True, normalize_by_span=False, highlight=None)[source]

Paint per-residue CPP feature impact onto an interactive 3D protein structure.

Each feature in df_feat is mapped to the residue positions it spans (shifted to absolute residue numbers by start) and its col_imp value is aggregated per position. By default (normalize_by_span=False) each feature’s full signed impact is added to every residue it spans, reproducing the deployed app’s per-residue colouring; set normalize_by_span=True for the span-normalized sum used by CPPPlot.profile(). The per-residue signed impact is then painted onto the structure cartoon.

Parameters:
  • df_feat (pd.DataFrame, shape (n_features, n_feature_info)) – Feature DataFrame with a feature column and the signed per-feature impact column col_imp (e.g. from ShapModel.add_feat_impact() or CPP.run()).

  • pdb (str, optional) – Path to a .pdb / .cif structure file. Exactly one of pdb or uniprot must be given.

  • uniprot (str, optional) – UniProt accession; the AlphaFold model is fetched from AlphaFold DB into a temporary folder via StructurePreprocessor.fetch_alphafold(). Exactly one of pdb or uniprot must be given.

  • col_imp (str, default='feat_impact') – Column of df_feat holding the signed per-feature impact to paint.

  • tmd_len (int, default=20) – Length of the TMD (>=1). Must match the value used when the features were generated.

  • start (int, default=1) – Absolute residue number of the first JMD-N residue in the structure (>=0); shifts window-relative feature positions onto the structure’s residue numbering.

  • chain (str, optional) – Chain id to render. Default selects the best-matching chain when sequence is given, otherwise the first amino-acid chain.

  • sequence (str, optional) – Full protein sequence; enables best-matching-chain selection (reusing the structure backend’s alignment) and a sanity check that start lines up with the structure.

  • mode ({'impact', 'plddt'}, default='impact') – 'impact' paints the red-white-blue feature-impact ramp; 'plddt' paints the AlphaFold pLDDT confidence palette.

  • focus ({'whole', 'fade', 'zoom'}, default='whole') – 'whole' styles every residue equally; 'fade' ghosts residues outside the window; 'zoom' points the camera at the window.

  • focus_region (tuple or list of tuples, optional) – (start, stop) residue range (or list of ranges) defining the focus window. Default derives the window from the union of df_feat positions.

  • size_by_impact (bool, default=True) – If True, draw a stick whose radius is proportional to |impact| (impact mode only).

  • normalize_by_span (bool, default=False) – If False (default), add each feature’s full impact to every residue it spans (app-fidelity colouring). If True, divide each feature’s impact by its span count first (the span-normalized sum of CPPPlot.profile() and the CPPPlot.feature_map() top per-position bar).

  • highlight (tuple or list of tuple, optional) – One or more (start, stop) residue ranges (1-based, inclusive, absolute structure numbering) whose residues are all painted in COLOR_LINK_HIGHLIGHT (cyan) on top of the impact colouring. This is the same highlight shape as AAPredPlot.predict_sample(), so a region marked cyan on the sequence plot can be mirrored on the structure with the identical argument. Distinct from focus_region, which frames (zoom / fade) rather than colours; each start / stop must be an integer with start <= stop.

Returns:

view – A thin wrapper over the interactive py3Dmol view exposing show(), write_html(path), and _repr_html_ for inline display, plus the mapped dict_impact / max_abs for inspection.

Return type:

StructureView

Notes

tmd_len, start, jmd_n_len and jmd_c_len must match the geometry used when the features were generated, otherwise the impact lands on the wrong residues.

See also

  • AAPredPlot.predict_sample(): shades the same highlight (start, stop) regions cyan on the sequence viewer; pass the identical highlight here to mirror the selection in 3D (shared COLOR_LINK_HIGHLIGHT).

Raises:
  • ValueError – On invalid arguments (e.g. an unknown mode / focus, neither or both of pdb / uniprot, a df_feat missing col_imp, or an unknown chain).

  • RuntimeError – If py3Dmol is not installed, or an AlphaFold model for uniprot cannot be fetched.

Examples

Paint per-residue CPP / CPP-SHAP feature impact onto an interactive 3D protein structure. Each feature in a df_feat is mapped to the residues it spans and its signed impact is painted residue-by-residue onto the protein cartoon, rendered with py3Dmol. A red-white-blue ramp shows where features raise (red) or lower (blue) the prediction; a plddt mode shows AlphaFold confidence instead. The view is interactive — rotate/zoom it, and export it with write_html.

This is a pro feature (needs biopython + py3Dmol).

import pandas as pd
import aaanalysis as aa
import aaanalysis.utils as ut

aa.options["verbose"] = False

We use a small real AlphaFold model — human lysozyme C (UniProt P61626) — fetched automatically by passing uniprot=. (You can equally pass pdb='path/to/model.pdb'.) The df_feat here carries a few illustrative features with a signed feat_impact; in practice it comes from CPP.run + ShapModel.

df_cat = aa.load_scales(name='scales_cat').head(5).reset_index(drop=True)
splits = ['Segment(1,2)', 'Segment(2,2)', 'Segment(1,1)', 'Pattern(C,1)', 'Segment(1,4)']
parts = ['TMD', 'TMD', 'JMD_N', 'TMD', 'JMD_C']
df_feat = pd.DataFrame({
    ut.COL_FEATURE: [f"{parts[i]}-{splits[i]}-{r[ut.COL_SCALE_ID]}" for i, r in df_cat.iterrows()],
    'category': df_cat[ut.COL_CAT], 'subcategory': df_cat[ut.COL_SUBCAT],
    'scale_name': df_cat[ut.COL_SCALE_NAME],
    'abs_auc': [0.2, 0.15, 0.3, 0.1, 0.25], 'abs_mean_dif': [0.3, 0.2, 0.5, 0.4, 0.35],
    'mean_dif': [0.3, -0.2, 0.5, -0.4, 0.25], 'std_test': 0.1, 'std_ref': 0.1,
    'feat_impact': [0.8, -0.5, 1.2, -0.3, 0.6]})
aa.display_df(df_feat, n_rows=10, show_shape=True)
DataFrame shape: (5, 10)
  feature category subcategory scale_name abs_auc abs_mean_dif mean_dif std_test std_ref feat_impact
1 TMD-Segment(1,2)-LINS030110 ASA/Volume Accessible surface area (ASA) ASA (folded coil/turn) 0.200000 0.300000 0.300000 0.100000 0.100000 0.800000
2 TMD-Segment(2,2)-LINS030113 ASA/Volume Accessible surface area (ASA) ASA (folded coil/turn) 0.150000 0.200000 -0.200000 0.100000 0.100000 -0.500000
3 JMD_N-Segment(1,1)-JANJ780101 ASA/Volume Accessible surface area (ASA) ASA (folded protein) 0.300000 0.500000 0.500000 0.100000 0.100000 1.200000
4 TMD-Pattern(C,1)-JANJ780103 ASA/Volume Accessible surface area (ASA) ASA (folded protein) 0.100000 0.400000 -0.400000 0.100000 0.100000 -0.300000
5 JMD_C-Segment(1,4)-LINS030104 ASA/Volume Accessible surface area (ASA) ASA (folded protein) 0.250000 0.350000 0.250000 0.100000 0.100000 0.600000

mode="impact" paints the white→red / white→blue ramp; focus="fade" ghosts residues outside the feature window; size_by_impact scales each residue’s stick by |impact|. start is the absolute residue number of the first JMD-N residue (here the window covers residues 40–69).

csp = aa.CPPStructurePlot(jmd_n_len=10, jmd_c_len=10, verbose=False)
view = csp.map_structure(df_feat=df_feat, uniprot='P61626', col_imp='feat_impact',
                         tmd_len=10, start=40, mode='impact', focus='fade')
view

3Dmol.js failed to load for some reason. Please check your browser console for error messages.

By default each feature’s full impact is painted on every residue it spans (app-fidelity colouring). The per-residue values are on view.dict_impact; pass normalize_by_span=True for the span-normalized sum used by the CPPPlot.feature_map top bar.

df_imp = pd.DataFrame({'residue': list(view.dict_impact),
                       'impact': [round(v, 3) for v in view.dict_impact.values()]})
aa.display_df(df_imp, n_rows=10, show_shape=True)
DataFrame shape: (30, 2)
  residue impact
1 40 1.200000
2 41 1.200000
3 42 1.200000
4 43 1.200000
5 44 1.200000
6 45 1.200000
7 46 1.200000
8 47 1.200000
9 48 1.200000
10 49 1.200000

focus="zoom" points the camera at the window (override it with focus_region); highlight paints one or more (start, stop) residue ranges in bright cyan (here (42, 45)), the same colour AAPredPlot.predict_sample shades on the sequence viewer, so a selection there mirrors here. mode="plddt" paints the AlphaFold confidence palette (blue = high, orange = low) instead of the impact ramp.

view_zoom = csp.map_structure(df_feat=df_feat, uniprot='P61626', tmd_len=10, start=40,
                              mode='impact', focus='zoom', focus_region=(40, 49),
                              highlight=(42, 45))
view_zoom

3Dmol.js failed to load for some reason. Please check your browser console for error messages.

view_plddt = csp.map_structure(df_feat=df_feat, uniprot='P61626', tmd_len=10, start=40,
                               mode='plddt', focus='whole')
view_plddt

3Dmol.js failed to load for some reason. Please check your browser console for error messages.

Export the interactive view as a self-contained page with view.write_html('structure.html'). For the structure next to the feature map use CPPStructurePlot.plot_combined; for a live, re-predicting explorer use CPPStructurePlot.interactive.