9.1.1. Core object: Universe — MDAnalysis.core.universe

The Universe class ties a topology and a trajectory together. Almost all code in MDAnalysis starts with a Universe.

Normally, a Universe is created from files:

import MDAnalysis as mda
u = mda.Universe("topology.psf", "trajectory.dcd")

In order to construct new simulation system it is also convenient to construct a Universe from existing AtomGroup instances with the Merge() function.

9.1.1.1. Working with Universes

9.1.1.1.1. Quick segid selection

Deprecated since version 0.16.2: Instant selectors will be removed in the 1.0 release. See issue #1377 for more details.

If the loaded topology provided segids, then these are made accessible as attributes of the Universe. If the segid starts with a number such as ‘4AKE’, the letter ‘s’ will be prepended to the segid. For example:

import MDAnalysis as mda
from MDAnalysisTests.datafiles import PSF, DCD

u = mda.Universe(PSF, DCD)
u.s4AKE  # selects all segments with segid 4AKE

If only a single segment has that segid then a Segment object will be returned, otherwise a SegmentGroup will be returned.

9.1.1.2. Classes

class MDAnalysis.core.universe.Universe(*args, **kwargs)[source]

The MDAnalysis Universe contains all the information describing the system.

The system always requires a topology file — in the simplest case just a list of atoms. This can be a CHARMM/NAMD PSF file or a simple coordinate file with atom informations such as XYZ, PDB, Gromacs GRO, or CHARMM CRD. See Table of Supported Topology Formats for what kind of topologies can be read.

A trajectory provides coordinates; the coordinates have to be ordered in the same way as the list of atoms in the topology. A trajectory can be a single frame such as a PDB, CRD, or GRO file, or it can be a MD trajectory (in CHARMM/NAMD/LAMMPS DCD, Gromacs XTC/TRR, or generic XYZ format). See Table of supported coordinate formats for what can be read as a “trajectory”.

As a special case, when the topology is a file that contains atom information and coordinates (such as XYZ, PDB, GRO or CRD, see Table of supported coordinate formats) then the coordinates are immediately loaded from the “topology” file unless a trajectory is supplied.

Examples for setting up a universe:

u = Universe(topology, trajectory)          # read system from file(s)
u = Universe(pdbfile)                       # read atoms and coordinates from PDB or GRO
u = Universe(topology, [traj1, traj2, ...]) # read from a list of trajectories
u = Universe(topology, traj1, traj2, ...)   # read from multiple trajectories

Load new data into a universe (replaces old trajectory and does not append):

u.load_new(trajectory)                      # read from a new trajectory file

Select atoms, with syntax similar to CHARMM (see select_atoms for details):

u.select_atoms(...)
Parameters:
  • topology (str, Topology object or stream) – A CHARMM/XPLOR PSF topology file, PDB file or Gromacs GRO file; used to define the list of atoms. If the file includes bond information, partial charges, atom masses, … then these data will be available to MDAnalysis. A “structure” file (PSF, PDB or GRO, in the sense of a topology) is always required. Alternatively, an existing MDAnalysis.core.topology.Topology instance may also be given.
  • topology_format – Provide the file format of the topology file; None guesses it from the file extension [None] Can also pass a subclass of MDAnalysis.topology.base.TopologyReaderBase to define a custom reader to be used on the topology file.
  • format – Provide the file format of the coordinate or trajectory file; None guesses it from the file extension. Note that this keyword has no effect if a list of file names is supplied because the “chained” reader has to guess the file format for each individual list member. [None] Can also pass a subclass of MDAnalysis.coordinates.base.ProtoReader to define a custom reader to be used on the trajectory file.
  • guess_bonds (bool, optional) – Once Universe has been loaded, attempt to guess the connectivity between atoms. This will populate the .bonds .angles and .dihedrals attributes of the Universe.
  • vdwradii (dict, optional) – For use with guess_bonds. Supply a dict giving a vdwradii for each atom type which are used in guessing bonds.
  • is_anchor (bool, optional) – When unpickling instances of MDAnalysis.core.groups.AtomGroup existing Universes are searched for one where to anchor those atoms. Set to False to prevent this Universe from being considered. [True]
  • anchor_name (str, optional) – Setting to other than None will cause MDAnalysis.core.groups.AtomGroup instances pickled from the Universe to only unpickle if a compatible Universe with matching anchor_name is found. Even if anchor_name is set is_anchor will still be honored when unpickling.
  • in_memory – After reading in the trajectory, transfer it to an in-memory representations, which allow for manipulation of coordinates.
  • in_memory_step – Only read every nth frame into in-memory representation.
trajectory

currently loaded trajectory reader;

dimensions

current system dimensions (simulation unit cell, if set in the trajectory)

atoms, residues, segments

master Groups for each topology level

bonds, angles, dihedrals

master ConnectivityGroups for each connectivity type

add_Residue(segment=None, **attrs)[source]

Add a new Residue to this Universe

New Residues will not contain any Atoms, but can be assigned to Atoms as per usual. If the Universe contains multiple segments, this must be specified as a keyword.

Parameters:
  • segment (MDAnalysis.Segment) – If there are multiple segments, then the Segment that the new Residue will belong in must be specified.
  • attrs (dict) – For each Residue attribute, the value for the new Residue must be specified
Returns:

Return type:

A reference to the new Residue

Raises:

NoDataError – If any information was missing. This happens before any changes have been made, ie the change is rolled back.

Example

Adding a new GLY residue, then placing atoms within it:

>>> newres = u.add_Residue(segment=u.segments[0], resid=42, resname='GLY')
>>> u.atoms[[1, 2, 3]].residues = newres
>>> u.select_atoms('resname GLY and resid 42')
<AtomGroup with 3 atoms>
add_Segment(**attrs)[source]

Add a new Segment to this Universe

Parameters:attrs (dict) – For each Segment attribute as a key, give the value in the new Segment
Returns:
Return type:A reference to the new Segment
Raises:NoDataError – If any attributes were not specified as a keyword.
add_TopologyAttr(topologyattr)[source]

Add a new topology attribute.

angles

Angles between atoms

bonds

Bonds between atoms

coord

Reference to current timestep and coordinates of universe.

The raw trajectory coordinates are Universe.coord.positions, represented as a numpy.float32 array.

Because coord is a reference to a Timestep, it changes its contents while one is stepping through the trajectory.

Note

In order to access the coordinates it is better to use the AtomGroup.positions() method; for instance, all coordinates of the Universe as a numpy array: Universe.atoms.positions().

dihedrals

Dihedral angles between atoms

dimensions

Current dimensions of the unitcell

impropers

Improper dihedral angles between atoms

is_anchor

Is this Universe an anchoring for unpickling AtomGroups

kwargs

keyword arguments used to initialize this universe

load_new(filename, format=None, in_memory=False, **kwargs)[source]

Load coordinates from filename.

The file format of filename is autodetected from the file name suffix or can be explicitly set with the format keyword. A sequence of files can be read as a single virtual trajectory by providing a list of filenames.

Parameters:
  • filename (str or list) – the coordinate file (single frame or trajectory) or a list of filenames, which are read one after another.
  • format (str or list or object (optional)) – provide the file format of the coordinate or trajectory file; None guesses it from the file extension. Note that this keyword has no effect if a list of file names is supplied because the “chained” reader has to guess the file format for each individual list member [None]. Can also pass a subclass of MDAnalysis.coordinates.base.ProtoReader to define a custom reader to be used on the trajectory file.
  • in_memory (bool (optional)) –

    Directly load trajectory into memory with the MemoryReader

    New in version 0.16.0.

  • **kwargs (dict) – Other kwargs are passed to the trajectory reader (only for advanced use)
Returns:

  • filename (str or list)
  • trajectory_format (str)

Raises:

TypeError if trajectory format can not be – determined or no appropriate trajectory reader found

Changed in version 0.8: If a list or sequence that is provided for filename only contains a single entry then it is treated as single coordinate file. This has the consequence that it is not read by the ChainReader but directly by its specialized file format reader, which typically has more features than the ChainReader.

remove_anchor()[source]

Remove this Universe from the possible anchor list for unpickling

select_atoms(*args, **kwargs)[source]

Select atoms.

trajectory

Reference to trajectory reader object containing trajectory data.

transfer_to_memory(start=None, stop=None, step=None, verbose=None, quiet=None)[source]

Transfer the trajectory to in memory representation.

Replaces the current trajectory reader object with one of type MDAnalysis.coordinates.memory.MemoryReader to support in-place editing of coordinates.

Parameters:
  • start (int, optional) – start reading from the nth frame.
  • stop (int, optional) – read upto and excluding the nth frame.
  • step (int, optional) – Read in every nth frame. [1]
  • verbose (bool, optional) – Will print the progress of loading trajectory to memory, if set to True. Default value is False.

New in version 0.16.0.

9.1.1.3. Functions

MDAnalysis.core.universe.Merge(*args)[source]

Create a new new Universe from one or more AtomGroup instances.

Parameters:

*args (AtomGroup) – One or more AtomGroups.

Returns:

universe

Return type:

Universe

Raises:
  • ValueError – Too few arguments or an AtomGroup is empty and
  • TypeError – Arguments are not AtomGroup instances.

Notes

The resulting Universe will only inherit the common topology attributes that all merged universes share.

AtomGroup instances can come from different Universes, or can come directly from a select_atoms() call.

Merge can also be used with a single AtomGroup if the user wants to, for example, re-order the atoms in the Universe.

If multiple AtomGroup instances from the same Universe are given, the merge will first simply “add” together the AtomGroup instances.

Merging does not create a full trajectory but only a single structure even if the input consists of one or more trajectories. However, one can use the MemoryReader to construct a trajectory for the new Universe as described under Creating an in-memory trajectory of a sub-system.

Example

In this example, protein, ligand, and solvent were externally prepared in three different PDB files. They are loaded into separate Universe objects (where they could be further manipulated, e.g. renumbered, relabeled, rotated, …) The Merge() command is used to combine all of them together:

u1 = Universe("protein.pdb")
u2 = Universe("ligand.pdb")
u3 = Universe("solvent.pdb")
u = Merge(u1.select_atoms("protein"), u2.atoms, u3.atoms)
u.atoms.write("system.pdb")

The complete system is then written out to a new PDB file.

Changed in version 0.9.0: Raises exceptions instead of assertion errors.

Changed in version 0.16.0: The trajectory is now a MemoryReader.