Last active
November 10, 2025 08:20
-
-
Save orbeckst/e53813df6aa5b7d7a10910b2cad1cb43 to your computer and use it in GitHub Desktop.
Example for how to add a custom TopologyAttribute (for secondary structure) in MDAnalysis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import MDAnalysis as mda | |
| # (1) define the custom SecondaryStructure attribute | |
| from MDAnalysis.core.topologyattrs import ResidueAttr | |
| # Just *defining* this class registers it with MDAnalysis | |
| # and makes "ss" available for Universe.add_TopologyAttr() | |
| class SecondaryStructure(ResidueAttr): | |
| """Per-reside secondary structure identifier. | |
| - H: helix (any) | |
| - E: sheet | |
| - -: other/no structure | |
| """ | |
| attrname = "ss" | |
| singular = "ss" | |
| per_object = "residue" | |
| dtype = "U1" | |
| @staticmethod | |
| def _gen_initial_values(na, nr, ns): | |
| # initialize with "-" for each residue | |
| return np.full(nr, "-", dtype="U1") | |
| # load your universe from file "PDB"; here we are using a test file | |
| # but you just use your own filename and remove the next line | |
| from MDAnalysisTests.datafiles import PDB # REMOVE WHEN USING YOUR OWN FILE | |
| u = mda.Universe(PDB) | |
| # add the custom TopologyAttr; automatically initialize with '-' | |
| u.add_TopologyAttr("ss") | |
| # (2) get secondary structure for the protein and set the 'ss' attribute | |
| from MDAnalysis.analysis.dssp import DSSP | |
| protein = u.select_atoms("protein") | |
| # set protein secondary structure attribute to value from first frame | |
| dssp = DSSP(protein).run(frames=[0]) | |
| protein.residues.ss = dssp.results.dssp[0] | |
| # (3) We can now select on the new attribute 'ss': | |
| helices = u.select_atoms("ss == H") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment