4.18. Common functions for topology building — MDAnalysis.topology.core

The various topology parsers make use of functions and classes in this module. They are mostly of use to developers.

See also

MDAnalysis.topology.tables for some hard-coded atom information that is used by functions such as guess_atom_type() and guess_atom_mass().

class MDAnalysis.topology.core.Angle(atoms, is_guessed=False)[source]

An angle between three Atom instances. Atom 2 is the apex of the angle

New in version 0.8.

Changed in version 0.9.0: Now a subclass of TopologyObject; now uses __slots__ and stores atoms in atoms attribute

angle()[source]

Returns the angle in degrees of this Angle.

Angle between atoms 0 and 2 with apex at 1:

   2
  /
 /
1------0

Note

The numerical precision is typically not better than 4 decimals (and is only tested to 3 decimals).

New in version 0.9.0.

class MDAnalysis.topology.core.Bond(atoms, order=None, is_guessed=False)[source]

A bond between two Atom instances.

Two Bond instances can be compared with the == and != operators. A bond is equal to another if the same atom numbers are connected and they have the same bond order. The ordering of the two atom numbers is ignored as is the fact that a bond was guessed.

The presence of a particular atom can also be queried::
>>> Atom in Bond

will return either True or False.

Changed in version 0.9.0: Now a subclass of TopologyObject. Changed class to use __slots__ and stores atoms in atoms attribute.

length()[source]

Length of the bond.

partner(Atom)[source]
Returns:the other Atom in this bond
class MDAnalysis.topology.core.Improper_Torsion(atoms, is_guessed=False)[source]

Improper Torsion (improper dihedral angle) between four Atom instances.

MDAnalysis treats the improper torsion angle as the angle between the planes formed by Atoms (1, 2, 3) and (2, 3, 4).

Warning

Definitions of Atom ordering in improper torsions can change. Check the definitions here against your software.

improper()[source]

Improper dihedral angle in degrees.

Note

The numerical precision is typically not better than 4 decimals (and is only tested to 3 decimals).

class MDAnalysis.topology.core.TopologyDict(members)[source]

A customised dictionary designed for sorting the bonds, angles and torsions present in a group of atoms.

Usage:

topologydict = TopologyDict(members)
Arguments:
members

A list of TopologyObject instances

Returns:
topologydict

A specialised dictionary of the topology instances passed to it

TopologyDicts are also built lazily from a TopologyGroup.topDict attribute.

The TopologyDict collects all the selected topology type from the atoms and categorises them according to the types of the atoms within. A TopologyGroup containing all of a given bond type can be made by querying with the appropriate key. The keys to the TopologyDict are a tuple of the atom types that the bond represents and can be viewed using the keys() method.

For example, from a system containing pure ethanol

>>> td = u.bonds.topDict
>>> td.keys()
[('C', 'C'),
 ('C', 'H'),
 ('O', 'H'),
 ('C', 'O')]
>>> td['C', 'O']
< TopologyGroup containing 912 bonds >

Note

The key for a bond is taken from the type attribute of the atoms.

Getting and setting types of bonds is done smartly, so a C-C-H angle is considered identical to a H-C-C angle.

Duplicate entries are automatically removed upon creation and combination of different Dicts. This means a bond between atoms 1 and 2 will only ever appear once in a dict despite both atoms 1 and 2 having the bond in their bond attribute.

Two TopologyDict instances can be combined using addition and it will not create any duplicate bonds in the process.

New in version 0.8.

Changed in version 0.9.0: Changed initialisation to use a list of TopologyObject instances instead of list of atoms; now used from within TopologyGroup instead of accessed from AtomGroup.

keys()[source]

Returns a list of the different types of available bonds

class MDAnalysis.topology.core.TopologyGroup(bondlist)[source]

A container for a groups of bonds.

All bonds of a certain types can be retrieved from within the TopologyGroup by querying with a tuple of types:

tg2 = tg.selectBonds([key])

Where key describes the desired bond as a tuple of the involved Atom types, as defined by the .type Atom attribute). A list of available keys can be displayed using the types() method.

Alternatively, all the bonds which are in a given AtomGroup can be extracted using atomgroup_intersection():

tg2 = tg.atomgroup_intersection(ag)

This allows the keyword strict to be given, which forces all members of all bonds to be inside the AtomGroup passed to it.

Finally, a TopologyGroup can be sliced similarly to AtomGroups:

tg2 = tg[5:10]

The bonds(), angles() and torsions() methods offer a “shortcut” to the Cython distance calculation functions in MDAnalysis.core.distances.

TopologyGroups can be combined with TopologyGroups of the same bond type (ie can combine two angle containing TopologyGroups).

New in version 0.8.

Changed in version 0.9.0: Overhauled completely: (1) Added internal TopologyDict accessible by the topDict attribute. (2) selectBonds() allows the topDict to be queried with tuple of types. (3) Added atomgroup_intersection() to allow bonds which are in a given AtomGroup to be retrieved.

Changed in version 0.10.0: Added from_indices() constructor, allowing class to be created from indices. Can now create empty Group. Renamed dump_contents() to to_indices()

angles(result=None, pbc=False)[source]

Calculates the angle in radians formed between a bond between atoms 1 and 2 and a bond between atoms 2 & 3

Keywords:
result

allows a predefined results array to be used, note that this will be overwritten

pbc

apply periodic boundary conditions when calculating angles [False] this is important when connecting vectors between atoms might require minimum image convention

Uses cython implementation

Changed in version 0.9.0: Added pbc option (default False)

atomgroup_intersection(ag, **kwargs)[source]

Retrieve all bonds from within this TopologyGroup that are within the AtomGroup which is passed.

Keywords:
strict

Only retrieve bonds which are completely contained within the AtomGroup. [False]

New in version 0.9.0.

bonds(pbc=False, result=None)[source]

Calculates the distance between all bonds in this TopologyGroup

Keywords:
pbc

apply periodic boundary conditions when calculating distance [False]

result

allows a predefined results array to be used, note that this will be overwritten

Uses cython implementation

dump_contents()

Return a tuple of tuples which define the contents of this TopologyGroup in terms of the atom numbers, (0 based index within u.atoms)

This format should be identical to the original contents of the entries in universe._topology. Note that because bonds are sorted as they are initialised, the order that atoms are defined in each entry might be reversed.

New in version 0.9.0.

Changed in version 0.10.0: Renamed from “dump_contents” to “to_indices”

classmethod from_indices(bondlist, atomgroup, bondclass=None, guessed=True, remove_duplicates=False)[source]

Initiate from a list of indices.

Arguments:
bondlist

A list of list of indices.

atomgroup

An AtomGroup which the indices from bondlist will be used on.

Keywords:
bond

The Class of the topology object to be made. If missing this will try and be guessed according to the number of indices in each record. This will only work for Bonds and Angles.

guessed

Whether or not the bonds were guessed. [True]

remove_duplicates

Sort through items and make sure that no duplicates are created [False]

New in version 0.10.0.

selectBonds(selection)[source]

Retrieves a selection from this topology group based on types.

to_indices()[source]

Return a tuple of tuples which define the contents of this TopologyGroup in terms of the atom numbers, (0 based index within u.atoms)

This format should be identical to the original contents of the entries in universe._topology. Note that because bonds are sorted as they are initialised, the order that atoms are defined in each entry might be reversed.

New in version 0.9.0.

Changed in version 0.10.0: Renamed from “dump_contents” to “to_indices”

topDict

Returns the TopologyDict for this topology group.

This is used for the selectBonds method when fetching a certain type of bond.

This is a cached property so will be generated the first time it is accessed.

torsions(result=None, pbc=False)[source]

Calculate the torsional angle in radians for this topology group.

Defined as the angle between a plane formed by atoms 1, 2 and 3 and a plane formed by atoms 2, 3 and 4.

Keywords:
result

allows a predefined results array to be used, note that this will be overwritten

pbc

apply periodic boundary conditions when calculating angles [False] this is important when connecting vectors between atoms might require minimum image convention

Uses cython implementation.

Changed in version 0.9.0: Added pbc option (default False)

types()[source]

Return a list of the bond types in this TopologyGroup

class MDAnalysis.topology.core.TopologyObject(atoms, is_guessed=False)[source]

Base class for all Topology items.

Defines the behaviour by which Bonds/Angles/etc in MDAnalysis should behave.

New in version 0.9.0.

Changed in version 0.10.0: All TopologyObject now keep track of if they were guessed or not via the is_guessed managed property.

indices

Tuple of indices describing this object

New in version 0.10.0.

is_guessed

True if the bond was guessed.

type

Type of the bond as a tuple

When comparing types, it is important to consider the reverse of the type too, ie:

a.type == b.type or a.type == b.type[::-1]
class MDAnalysis.topology.core.Torsion(atoms, is_guessed=False)[source]

Torsion (dihedral angle) between four Atom instances.

The torsion is defined as the angle between the planes formed by Atoms (1, 2, 3) and (2, 3, 4).

New in version 0.8.

Changed in version 0.9.0: Now a subclass of TopologyObject; now uses __slots__ and stores atoms in atoms attribute.

torsion()[source]

Calculate the dihedral angle in degrees.

Dihedral angle around axis connecting atoms 1 and 2 (i.e. the angle between the planes spanned by atoms (0,1,2) and (1,2,3)):

        3
        |
  1-----2
 /
0

Note

The numerical precision is typically not better than 4 decimals (and is only tested to 3 decimals).

New in version 0.9.0.

MDAnalysis.topology.core.build_residues(atoms)[source]

Create a list Residue instances from a list of Atom instances.

Updating residues also changes the underlying Atom instances, which record to which residue an atom belongs.

Returns:List of Residue instances

New in version 0.8.

Changed in version 0.9.0: Now allows resids to be given in non sequential order

MDAnalysis.topology.core.build_segments(atoms)[source]

Create all Segment instancess from a list of Atom instances.

The function also builds the Residue instances by tracking residue numbers.

Updating segments also changes the underlying Atom instances, which record to which residue and segment an atom belongs.

Returns:structure dict, which associates a segname with a Segment

Changed in version 0.9.0: Now allows resids in a given Segment to be given in non sequential order.

MDAnalysis.topology.core.get_atom_mass(element)[source]

Return the atomic mass in u for element.

Masses are looked up in MDAnalysis.topology.tables.masses.

Warning

Unknown masses are set to 0.00

MDAnalysis.topology.core.get_parser_for(filename, permissive=False, tformat=None)[source]

Return the appropriate topology parser for filename.

Automatic detection is disabled when an explicit format is provided.

MDAnalysis.topology.core.guess_angles(bonds)[source]

Given a list of Bonds, find all angles that exist between atoms.

Works by assuming that if atoms 1 & 2 are bonded, and 2 & 3 are bonded, then (1,2,3) must be an angle.

Returns:List of tuples defining the angles. Suitable for use in u._topology

See also

guess_bonds()

MDAnalysis.topology.core.guess_atom_charge(atomname)[source]

Guess atom charge from the name.

Warning

Not implemented; simply returns 0.

MDAnalysis.topology.core.guess_atom_element(atomname)[source]

Guess the element of the atom from the name.

Looks in dict to see if element is found, otherwise it uses the first character in the atomname. The table comes from CHARMM and AMBER atom types, where the first character is not sufficient to determine the atom type. Some GROMOS ions have also been added.

See also

guess_atom_type() and MDAnalysis.topology.tables (where the data are stored)

MDAnalysis.topology.core.guess_atom_mass(atomname)[source]

Guess a mass based on the atom name.

guess_atom_element() is used to determine the kind of atom.

Warning

Anything not recognized is simply set to 0; if you rely on the masses you might want to double check.

MDAnalysis.topology.core.guess_atom_type(atomname)[source]

Guess atom type from the name.

At the moment, this function simply returns the element, as guessed by guess_atom_element().

MDAnalysis.topology.core.guess_bonds(atoms, coords, **kwargs)[source]

Guess if bonds exist between two atoms based on their distance.

Bond between two atoms is created, if the two atoms are within

\[\begin{split}d < f * (R_1 + R_2)\end{split}\]

of each other, where \(R_1\) and \(R_2\) are the VdW radii of the atoms and \(f\) is an ad-hoc fudge_factor. This is the same algorithm that VMD uses.

Keywords:
fudge_factor

The factor by which atoms must overlap eachother to be considered a bond. Larger values will increase the number of bonds found. [0.72]

vdwradii

To supply custom vdwradii for atoms in the algorithm. Must be a dict of format {type:radii}. The default table of van der Waals radii is hard-coded as MDAnalysis.topology.tables.vdwradii. Any user defined vdwradii passed as an argument will supercede the table values. [None]

lower_bound

The minimum bond length. All bonds found shorter than this length will be ignored. This is useful for parsing PDB with altloc records where atoms with altloc A and B maybe very close together and there should be no chemical bond between them. [0.1]

box

Bonds are found using a distance search, if unit cell information is given, periodic boundary conditions will be considered in the distance search. [None]

Returns:

List of tuples suitable for use in Universe topology building.

Warning

No check is done after the bonds are guessed to see if Lewis structure is correct. This is wrong and will burn somebody.

Raises:ValueError if inputs are malformed or vdwradii data is missing.

New in version 0.7.7.

Changed in version 0.9.0: Updated method internally to use more numpy, should work faster. Should also use less memory, previously scaled as \(O(n^2)\). vdwradii argument now augments table list rather than replacing entirely.

MDAnalysis.topology.core.guess_format(filename, format=None)[source]

Returns the type of topology file filename.

The current heuristic simply looks at the filename extension but more complicated probes could be implemented here or in the individual packages (e.g. as static methods).

If format is supplied then it overrides the auto detection.

MDAnalysis.topology.core.guess_improper_torsions(angles)[source]

Given a list of Angles, find all improper torsions that exist between atoms.

Works by assuming that if (1,2,3) is an angle, and 2 & 4 are bonded, then (2, 1, 3, 4) must be an improper torsion. ie the improper torsion is the angle between the planes formed by (1, 2, 3) and (1, 3, 4)

Returns:List of tuples defining the improper torsions. Suitable for use in u._topology
MDAnalysis.topology.core.guess_torsions(angles)[source]

Given a list of Angles, find all torsions that exist between atoms.

Works by assuming that if (1,2,3) is an angle, and 3 & 4 are bonded, then (1,2,3,4) must be a torsion.

Returns:List of tuples defining the torsions. Suitable for use in u._topology