htmd.molecule.molecule module

class htmd.molecule.molecule.Molecule(filename=None, name=None, **kwargs)

Bases: object

Class to manipulate molecular structures.

Molecule contains all the fields of a PDB and it is independent of any force field. It can contain multiple conformations and trajectories, however all operations are done on the current frame. The following PDB fields are accessible as attributes (record, serial, name, altloc, resname, chain, resid, insertion, coords, occupancy, beta, segid, element, charge). The coordinates are accessible via the coords attribute ([number of atoms x 3 x number of frames] where [x,y,z] are the second dimension.

Parameters:
  • filename (str or list of str) – Optionally load a PDB file from the specified file. If there’s no file and the value is four characters long assume it is a PDB accession code and try to download from the RCSB web server.
  • name (str) – Give a name to the Molecule that will be used for visualization
  • kwargs – Accepts any further arguments that should be passed to the Molecule.read method.

Examples

>>> mol = Molecule( './test/data/dhfr/dhfr.pdb' )  
>>> mol = Molecule( '3PTB', name='Trypsin' )
>>> print(mol)                                     
Molecule with 1701 atoms and 1 frames
Atom field - altloc shape: (1701,)
Atom field - atomtype shape: (1701,)
...

Methods

align(sel[, refmol, refsel, frames]) Align the molecule to a reference structure
alignBySequence(ref[, molseg, refseg, …]) Aligns the Molecule to a reference Molecule by their longests sequences alignment
append(mol[, collisions, coldist]) Append a molecule at the end of the current molecule
appendFrames(mol) Appends the frames of a Molecule to the current Molecule.
atomselect(sel[, indexes, strict, …]) Select a set of atoms based on a selection text
center([loc, sel]) Moves the geometric center of the Molecule to a given location
copy() Create a copy of the molecule object
deleteBonds(sel[, inter]) Deletes all bonds that contain atoms in sel or between atoms in sel.
dropFrames([keep, drop]) Removes trajectory frames from the Molecule
empty(numAtoms) Creates an empty molecule of N atoms.
filter(sel[, _logger]) Removes all atoms not included in the selection
get(field[, sel]) Retrieve a specific PDB field based on the selection
getDihedral(atom_quad) Gets a dihedral angle.
insert(mol, index[, collisions, coldist]) Insert the contents of one molecule into another at a specific index.
moveBy(vector[, sel]) Move a selection of molecule atoms by a given vector
mutateResidue(sel, newres) Mutates a residue by deleting it’s sidechain and renaming it
read(filename[, type, skip, frames, append, …]) Read any supported file.
remove(selection[, _logger]) Remove atoms from the Molecule
renumberResidues([returnMapping]) Renumbers residues incrementally.
rotateBy(M[, center, sel]) Rotate a selection of atoms by a given rotation around a center
sequence([oneletter, noseg]) Return the AA sequence of the Molecule.
set(field, value[, sel]) Set a specific PDB field based on the selection
setDihedral(atom_quad, radians[, bonds]) Sets the angle of a dihedral.
view([sel, style, color, guessBonds, …]) Visualizes the molecule in a molecular viewer
viewCrystalPacking() If the Molecule was read from a crystallographic PDB structure it shows the crystal packing of the molecule.
wrap([wrapsel, fileBonds, guessBonds]) Wraps coordinates of the molecule into the simulation box
write(filename[, sel, type]) Writes any of the supported formats (pdb, coor, psf, xtc, xyz, mol2, gro) and any formats supported by MDtraj

Attributes

frame
fstep
numAtoms Number of atoms in the molecule
numFrames Number of coordinate frames in the molecule
numResidues
x Get the x coordinates at the current frame
y Get the y coordinates at the current frame
z Get the z coordinates at the current frame
record

np.ndarray – The record field of a PDB file if the topology was read from a PDB.

serial

np.ndarray – The serial number of each atom.

name

np.ndarray – The name of each atom.

altloc

np.ndarray – The alternative location flag of the atoms if read from a PDB.

resname

np.ndarray – The residue name of each atom.

chain

np.ndarray – The chain name of each atom.

resid

np.ndarray – The residue ID of each atom.

insertion

np.ndarray – The insertion flag of the atoms if read from a PDB.

occupancy

np.ndarray – The occupancy value of each atom if read from a PDB.

beta

np.ndarray – The beta factor value of each atom if read from a PDB.

segid

np.ndarray – The segment ID of each atom.

element

np.ndarray – The element of each atom.

charge

np.ndarray – The charge of each atom.

masses

np.ndarray – The mass of each atom.

atomtype

np.ndarray – The atom type of each atom.

coords

np.ndarray – A float32 array with shape (natoms, 3, nframes) containing the coordinates of the Molecule.

box

np.ndarray – A float32 array with shape (3, nframes) containing the periodic box dimensions of an MD trajectory.

boxangles

np.ndarray – The angles of the box. If none are set they are assumed to be 90 degrees.

bonds

np.ndarray – Atom pairs corresponding to bond terms.

bondtype

np.ndarray – The type of each bond in Molecule.bonds if available.

angles

np.ndarray – Atom triplets corresponding to angle terms.

dihedrals

np.ndarray – Atom quadruplets corresponding to dihedral terms.

impropers

np.ndarray – Atom quadruplets corresponding to improper dihedral terms.

crystalinfo

dict – A dictionary containing crystallographic information. It has fields [‘sGroup’, ‘numcopies’, ‘rotations’, ‘translations’]

frame

int – The current frame. atomselection and get commands will be calculated on this frame.

fileloc

list – The location of the files used to read this Molecule

time

list – The time for each frame of the simulation

step

list – The step for each frame of the simulation

reps

Representations object – A list of representations that is used when visualizing the molecule

viewname

str – The name used for the molecule in the viewer

align(sel, refmol=None, refsel=None, frames=None)

Align the molecule to a reference structure

Parameters:
  • sel (str) – Atom selection string for aligning. See more here
  • refmol (Molecule, optional) – Optionally pass a reference Molecule on which to align. If None is given, it will align on the first frame of the same Molecule
  • refsel (str, optional) – Atom selection for the refmol if one is given. Default: same as sel. See more here
  • frames (list or range) – A list of frames which to align. By default it will align all frames of the Molecule

Examples

>>> mol=tryp.copy()
>>> mol.align('protein')
>>> mol.align('name CA', refmol=Molecule('3PTB'))
alignBySequence(ref, molseg=None, refseg=None, nalignfragment=1, returnAlignments=False, maxalignments=1)

Aligns the Molecule to a reference Molecule by their longests sequences alignment

Parameters:
  • ref (Molecule object) – The reference Molecule to which we want to align
  • molseg (str) – The segment of this Molecule we want to align
  • refseg (str) – The segment of ref we want to align to
  • nalignfragments (int) – The number of fragments used for the alignment.
  • returnAlignments (bool) – Return all alignments as a list of Molecules
  • maxalignments (int) – The maximum number of alignments we want to produce
Returns:

mols – If returnAlignments is True it returns a list of Molecules each containing a different alignment. Otherwise it modifies the current Molecule with the best single alignment.

Return type:

list

append(mol, collisions=False, coldist=1.3)

Append a molecule at the end of the current molecule

Parameters:
  • mol (Molecule) – Target Molecule which to append to the end of the current Molecule
  • collisions (bool) – If set to True it will remove residues of mol which collide with atoms of this Molecule object.
  • coldist (float) – Collision distance in Angstrom between atoms of the two molecules. Anything closer will be considered a collision.

Example

>>> mol=tryp.copy()
>>> mol.filter("not resname BEN")
>>> lig=tryp.copy()
>>> lig.filter("resname BEN")
>>> mol.append(lig)
appendFrames(mol)

Appends the frames of a Molecule to the current Molecule.

Parameters:mol (Molecule) – A Molecule object.
atomselect(sel, indexes=False, strict=False, fileBonds=True, guessBonds=True)

Select a set of atoms based on a selection text

Parameters:
  • sel (str) – Atom selection string. See more here
  • indexes (bool) – If True returns the indexes instead of a bitmap
  • strict (bool) – If True it will raise an error if no atoms were selected.
  • fileBonds (bool) – If True will use bonds read from files.
  • guessBonds (bool) – If True will use guessed bonds.
Returns:

asel – Either a bitmap of selected atoms or their indexes

Return type:

np.ndarray

Examples

>>> mol=tryp.copy()
>>> mol.atomselect('resname MOL')
array([False, False, False, ..., False, False, False], dtype=bool)
center(loc=(0, 0, 0), sel='all')

Moves the geometric center of the Molecule to a given location

Parameters:
  • loc (list, optional) – The location to which to move the geometric center
  • sel (str) – Atom selection string of the atoms whose geometric center we want to center on the loc position. See more here

Examples

>>> mol=tryp.copy()
>>> mol.center()
>>> mol.center([10, 10, 10], 'name CA')
copy()

Create a copy of the molecule object

Returns:newmol – A copy of the object
Return type:Molecule
deleteBonds(sel, inter=True)

Deletes all bonds that contain atoms in sel or between atoms in sel.

Parameters:
  • sel (str) – Atom selection string of atoms whose bonds will be deleted. See more here
  • inter (bool) – When True it will delete also bonds between atoms in sel with bonds to atoms outside of sel. When False it will only delete bonds between atoms in sel.
dropFrames(keep='all', drop=None)

Removes trajectory frames from the Molecule

Parameters:
  • keep (int or list of ints) – Index of frame, or list of frame indexes which we want to keep (and drop all others).
  • drop (int or list of ints) – Index of frame, or list of frame indexes which we want to drop (and keep all others).

Examples

>>> mol = Molecule('1sb0')
>>> mol.dropFrames(keep=[1,2])
>>> mol.numFrames == 2
>>> mol.dropFrames(drop=[0])
>>> mol.numFrames == 1
empty(numAtoms)

Creates an empty molecule of N atoms.

Parameters:numAtoms (int) – Number of atoms to create in the molecule.

Example

>>> newmol = Molecule()
>>> newmol.empty(100)
filter(sel, _logger=True)

Removes all atoms not included in the selection

Parameters:sel (str) – Atom selection string. See more here

Examples

>>> mol=tryp.copy()
>>> mol.filter('protein')
frame
fstep
get(field, sel=None)

Retrieve a specific PDB field based on the selection

Parameters:
  • field (str) – The field we want to get. To see a list of all available fields do print(Molecule._atom_and_coord_fields).
  • sel (str) – Atom selection string for which atoms we want to get the field from. Default all. See more here
Returns:

vals – Array of values of field for all atoms in the selection.

Return type:

np.ndarray

Examples

>>> mol=tryp.copy()
>>> mol.get('resname')
array(['ILE', 'ILE', 'ILE', ..., 'HOH', 'HOH', 'HOH'], dtype=object)
>>> mol.get('resname', sel='resid 158')
array(['LEU', 'LEU', 'LEU', 'LEU', 'LEU', 'LEU', 'LEU', 'LEU'], dtype=object)
getDihedral(atom_quad)

Gets a dihedral angle.

Parameters:atom_quad (list) – Four atom indexes corresponding to the atoms defining the dihedral
Returns:angle – The angle in radians
Return type:float

Examples

>>> mol.getDihedral([0, 5, 8, 12])
insert(mol, index, collisions=0, coldist=1.3)

Insert the contents of one molecule into another at a specific index.

Parameters:
  • mol (Molecule) – Molecule to be inserted
  • index (integer) – The atom index at which the passed molecule will be inserted
  • collisions (bool) – If set to True it will remove residues of mol which collide with atoms of this Molecule object.
  • coldist (float) – Collision distance in Angstrom between atoms of the two molecules. Anything closer will be considered a collision.

Example

>>> mol=tryp.copy()
>>> mol.numAtoms
1701
>>> mol.insert(tryp, 0)
>>> mol.numAtoms
3402
moveBy(vector, sel=None)

Move a selection of molecule atoms by a given vector

Parameters:
  • vector (list) – 3D coordinates to add to the Molecule coordinates
  • sel (str) – Atom selection string of atoms which we want to move. See more here

Examples

>>> mol=tryp.copy()
>>> mol.moveBy([3, 45 , -8])
mutateResidue(sel, newres)

Mutates a residue by deleting it’s sidechain and renaming it

Parameters:
  • sel (str) – Atom selection string for the residue we want to mutate. The selection needs to include all atoms of the residue. See more here
  • newres (str) – The name of the new residue

Examples

>>> mol=tryp.copy()
>>> mol.mutateResidue('resid 158', 'ARG')
numAtoms

Number of atoms in the molecule

numFrames

Number of coordinate frames in the molecule

numResidues
read(filename, type=None, skip=None, frames=None, append=False, overwrite='all', keepaltloc='A', guess=None, guessNE=None, _logger=True, **kwargs)

Read any supported file. Currently supported files include pdb, psf, prmtop, prm, pdbqt, xtc, coor, xyz, mol2, gjf, mae, and crd, as well as all others supported by MDTraj.

Detects from the extension the file type and loads it into Molecule

Parameters:
  • filename (str) – Name of the file we want to read
  • type (str, optional) – File type of the file. If None, it’s automatically determined by the extension
  • skip (int, optional) – If the file is a trajectory, skip every skip frames
  • frames (list, optional) – If the file is a trajectory, read only the given frames
  • append (bool, optional) – If the file is a trajectory or coor file, append the coordinates to the previous coordinates. Note append is slow.
  • overwrite (str, list of str) – A list of the existing fields in Molecule that we wish to overwrite when reading this file. Set to None if you don’t want to overwrite any existing fields.
  • keepaltloc (str) – Set to any string to only keep that specific altloc. Set to ‘all’ if you want to keep all alternative atom positions.
  • guess (list of str) – Properties of the molecule to guess. Can be any combination of (‘bonds’, ‘angles’, ‘dihedrals’)
  • guessNE (list of str) – Properties of the molecule to guess if it’s Non-Existent. Can be any combination of (‘bonds’, ‘angles’, ‘dihedrals’)
remove(selection, _logger=True)

Remove atoms from the Molecule

Parameters:selection (str) – Atom selection string of the atoms we want to remove. See more here
Returns:removed – The list of atoms removed
Return type:np.array

Example

>>> mol=tryp.copy()
>>> mol.remove('name CA')               
array([   1,    9,   16,   20,   24,   36,   43,   49,   53,   58,...
renumberResidues(returnMapping=False)

Renumbers residues incrementally.

It checks for changes in either of the resid, insertion, chain or segid fields and in case of a change it creates a new residue number.

Parameters:returnMapping (bool) – If set to True, the method will also return the mapping between the old and new residues

Examples

>>> mapping = mol.renumberResidues(returnMapping=True)
rotateBy(M, center=(0, 0, 0), sel='all')

Rotate a selection of atoms by a given rotation around a center

Parameters:
  • M (np.ndarray) – The rotation matrix
  • center (list) – The rotation center
  • sel (str) – Atom selection string for atoms to rotate. See more here

Examples

>>> mol = tryp.copy()
>>> mol.rotateBy(rotationMatrix([0, 1, 0], 1.57))
sequence(oneletter=True, noseg=False)

Return the AA sequence of the Molecule.

Parameters:
  • oneletter (bool) – Whether to return one-letter or three-letter AA codes. There should be only one atom per residue.
  • noseg (bool) – Ignore segments and return the whole sequence as single string.
Returns:

sequence – The primary sequence as a dictionary segid - string (if oneletter is True) or segid - list of strings (otherwise).

Return type:

str

Examples

>>> mol=tryp.copy()
>>> mol.sequence()
{'0': 'IVGGYTCGANTVPYQVSLNSGYHFCGGSLINSQWVVSAAHCYKSGIQVRLGEDNINVVEGNEQFISASKSIVHPSYNSNTLNNDIMLIKLKSAASLNSRVASISLPTSCASAGTQCLISGWGNTKSSGTSYPDVLKCLKAPILSDSSCKSAYPGQITSNMFCAGYLEGGKDSCQGDSGGPVVCSGKLQGIVSWGSGCAQKNKPGVYTKVCNYVSWIKQTIASN'}
>>> sh2 = Molecule("1LKK")
>>> pYseq = sh2.sequence(oneletter=False)
>>> pYseq['1']
['PTR', 'GLU', 'GLU', 'ILE']
>>> pYseq = sh2.sequence(oneletter=True)
>>> pYseq['1']
'?EEI'
set(field, value, sel=None)

Set a specific PDB field based on the selection

Parameters:
  • field (str) – The field we want to set. To see a list of all available fields do print(Molecule._atom_and_coord_fields).
  • value (string or integer) – All atoms that match the atom selection will have the PDB field field set to this scalar value (or 3-vector if setting the coordinates)
  • sel (str) – Atom selection string for atom which to set. See more here

Examples

>>> mol=tryp.copy()
>>> mol.set('segid', 'P', sel='protein')
setDihedral(atom_quad, radians, bonds=None)

Sets the angle of a dihedral.

Parameters:
  • atom_quad (list) – Four atom indexes corresponding to the atoms defining the dihedral
  • radians (float) – The angle in radians to which we want to set the dihedral
  • bonds (np.ndarray) – An array containing all bonds of the molecule. This is needed if multiple modifications are done as the bond guessing can get messed up if atoms come very close after the rotation.

Examples

>>> mol.setDihedral([0, 5, 8, 12], 0.16)
>>> # If we perform multiple modifications, calculate bonds first and pass them as argument to be safe
>>> bonds = mol._getBonds()
>>> mol.setDihedral([0, 5, 8, 12], 0.16, bonds=bonds)
>>> mol.setDihedral([18, 20, 24, 30], -1.8, bonds=bonds)
view(sel=None, style=None, color=None, guessBonds=True, viewer=None, hold=False, name=None, viewerhandle=None, gui=False)

Visualizes the molecule in a molecular viewer

Parameters:
  • sel (str) – Atom selection string for the representation. See more here
  • style (str) – Representation style. See more here.
  • color (str or int) – Coloring mode (str) or ColorID (int). See more here.
  • guessBonds (bool) – Allow VMD to guess bonds for the molecule
  • viewer (str ('vmd', 'webgl')) – Choose viewer backend. Default is taken from htmd.config
  • hold (bool) – If set to True, it will not visualize the molecule but instead collect representations until set back to False.
  • name (str, optional) – A name to give to the molecule in VMD
  • viewerhandle (VMD object, optional) – A specific viewer in which to visualize the molecule. If None it will use the current default viewer.
viewCrystalPacking()

If the Molecule was read from a crystallographic PDB structure it shows the crystal packing of the molecule.

wrap(wrapsel=None, fileBonds=True, guessBonds=True)

Wraps coordinates of the molecule into the simulation box

Parameters:wrapsel (str) – Atom selection string of atoms on which to center the wrapping box. See more here

Examples

>>> mol=tryp.copy()
>>> mol.wrap()
>>> mol.wrap('protein')
write(filename, sel=None, type=None, **kwargs)

Writes any of the supported formats (pdb, coor, psf, xtc, xyz, mol2, gro) and any formats supported by MDtraj

Parameters:
  • filename (str) – The filename of the file we want to write to disk
  • sel (str, optional) – Atom selection string of the atoms we want to write. If None, it will write all atoms. See more here
  • type (str, optional) – The filetype we want to write. By default, detected from the file extension
x

Get the x coordinates at the current frame

y

Get the y coordinates at the current frame

z

Get the z coordinates at the current frame

class htmd.molecule.molecule.Representations(mol)

Bases: object

Class that stores representations for Molecule.

Examples

>>> from htmd.molecule.molecule import Molecule
>>> mol = tryp.copy()
>>> mol.reps.add('protein', 'NewCartoon')
>>> print(mol.reps)                     
rep 0: sel='protein', style='NewCartoon', color='Name'
>>> mol.view() 
>>> mol.reps.remove() 
add(sel=None, style=None, color=None)

Adds a new representation for Molecule.

Parameters:
  • sel (str) – Atom selection string for the representation. See more here
  • style (str) – Representation style. See more here.
  • color (str or int) – Coloring mode (str) or ColorID (int). See more here.
append(reps)
list()

Lists all representations. Equivalent to using print.

remove(index=None)

Removed one or all representations.

Parameters:index (int) – The index of the representation to delete. If none is given it deletes all.
class htmd.molecule.molecule.TestMolecule(methodName='runTest')

Bases: unittest.case.TestCase

addCleanup(function, *args, **kwargs)

Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

addTypeEqualityFunc(typeobj, function)

Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

Parameters:
  • typeobj – The data type to call this function on when both values are of the same type in assertEqual().
  • function – The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.
assertAlmostEqual(first, second, places=None, msg=None, delta=None)

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertAlmostEquals(*args, **kwargs)
assertCountEqual(first, second, msg=None)

An unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times.

self.assertEqual(Counter(list(first)),
Counter(list(second)))
Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.
  • [0, 0, 1] and [0, 1] compare unequal.
assertDictContainsSubset(subset, dictionary, msg=None)

Checks whether dictionary is a superset of subset.

assertDictEqual(d1, d2, msg=None)
assertEqual(first, second, msg=None)

Fail if the two objects are unequal as determined by the ‘==’ operator.

assertEquals(*args, **kwargs)
assertFalse(expr, msg=None)

Check that the expression is false.

assertGreater(a, b, msg=None)

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIn(member, container, msg=None)

Just like self.assertTrue(a in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsInstance(obj, cls, msg=None)

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertIsNone(obj, msg=None)

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNot(expr1, expr2, msg=None)

Just like self.assertTrue(a is not b), but with a nicer default message.

assertIsNotNone(obj, msg=None)

Included for symmetry with assertIsNone.

assertLess(a, b, msg=None)

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)

Just like self.assertTrue(a <= b), but with a nicer default message.

assertListEqual(list1, list2, msg=None)

A list-specific equality assertion.

Parameters:
  • list1 – The first list to compare.
  • list2 – The second list to compare.
  • msg – Optional message to use on failure instead of a list of differences.
assertLogs(logger=None, level=None)

Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger.

This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects.

Example:

with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
assertMultiLineEqual(first, second, msg=None)

Assert that two multi-line strings are equal.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertNotAlmostEquals(*args, **kwargs)
assertNotEqual(first, second, msg=None)

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertNotEquals(*args, **kwargs)
assertNotIn(member, container, msg=None)

Just like self.assertTrue(a not in b), but with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)

Included for symmetry with assertIsInstance.

assertNotRegex(text, unexpected_regex, msg=None)

Fail the test if the text matches the regular expression.

assertNotRegexpMatches(*args, **kwargs)
assertRaises(expected_exception, *args, **kwargs)

Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertRaises(SomeException):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertRaises is used as a context object.

The context manager keeps a reference to the exception as the ‘exception’ attribute. This allows you to inspect the exception after the assertion:

with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
assertRaisesRegex(expected_exception, expected_regex, *args, **kwargs)

Asserts that the message in a raised exception matches a regex.

Parameters:
  • expected_exception – Exception class expected to be raised.
  • expected_regex – Regex (re pattern object or string) expected to be found in error message.
  • args – Function to be called and extra positional args.
  • kwargs – Extra kwargs.
  • msg – Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager.
assertRaisesRegexp(*args, **kwargs)
assertRegex(text, expected_regex, msg=None)

Fail the test unless the text matches the regular expression.

assertRegexpMatches(*args, **kwargs)
assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Parameters:
  • seq1 – The first sequence to compare.
  • seq2 – The second sequence to compare.
  • seq_type – The expected datatype of the sequences, or None if no datatype should be enforced.
  • msg – Optional message to use on failure instead of a list of differences.
assertSetEqual(set1, set2, msg=None)

A set-specific equality assertion.

Parameters:
  • set1 – The first set to compare.
  • set2 – The second set to compare.
  • msg – Optional message to use on failure instead of a list of differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertTrue(expr, msg=None)

Check that the expression is true.

assertTupleEqual(tuple1, tuple2, msg=None)

A tuple-specific equality assertion.

Parameters:
  • tuple1 – The first tuple to compare.
  • tuple2 – The second tuple to compare.
  • msg – Optional message to use on failure instead of a list of differences.
assertWarns(expected_warning, *args, **kwargs)

Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception.

If called with the callable and arguments omitted, will return a context object used like this:

with self.assertWarns(SomeWarning):
    do_something()

An optional keyword argument ‘msg’ can be provided when assertWarns is used as a context object.

The context manager keeps a reference to the first matching warning as the ‘warning’ attribute; similarly, the ‘filename’ and ‘lineno’ attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:

with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
assertWarnsRegex(expected_warning, expected_regex, *args, **kwargs)

Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

Parameters:
  • expected_warning – Warning class expected to be triggered.
  • expected_regex – Regex (re pattern object or string) expected to be found in error message.
  • args – Function to be called and extra positional args.
  • kwargs – Extra kwargs.
  • msg – Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager.
assert_(*args, **kwargs)
countTestCases()
debug()

Run the test without collecting errors in a TestResult

defaultTestResult()
doCleanups()

Execute all cleanup functions. Normally called for you after tearDown.

fail(msg=None)

Fail immediately, with the given message.

failIf(*args, **kwargs)
failIfAlmostEqual(*args, **kwargs)
failIfEqual(*args, **kwargs)
failUnless(*args, **kwargs)
failUnlessAlmostEqual(*args, **kwargs)
failUnlessEqual(*args, **kwargs)
failUnlessRaises(*args, **kwargs)
failureException

alias of AssertionError

id()
longMessage = True
maxDiff = 640
run(result=None)
setUp()

Hook method for setting up the test fixture before exercising it.

setUpClass()

Hook method for setting up class fixture before running tests in the class.

shortDescription()

Returns a one-line description of the test, or None if no description has been provided.

The default implementation of this method returns the first line of the specified test method’s docstring.

skipTest(reason)

Skip this test.

subTest(msg=<object object>, **params)

Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed.

tearDown()

Hook method for deconstructing the test fixture after testing it.

tearDownClass()

Hook method for deconstructing the class fixture after running all tests in the class.

test_appendingBondsBondtypes()
test_guessBonds()
test_mdtrajWriter()
test_setDihedral()
test_trajReadingAppending()
test_uniqueAtomID()
test_uniqueResidueID()
test_updateBondsAnglesDihedrals()
exception htmd.molecule.molecule.TopologyInconsistencyError(value)

Bases: Exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class htmd.molecule.molecule.UniqueAtomID(**kwargs)

Bases: object

static fromMolecule(mol, sel=None, idx=None)
selectAtom(mol, indexes=True, ignore=None)
class htmd.molecule.molecule.UniqueResidueID(**kwargs)

Bases: object

static fromMolecule(mol, sel=None, idx=None)
selectAtoms(mol, indexes=True, ignore=None)
htmd.molecule.molecule.mol_equal(mol1, mol2, checkFields=('record', 'serial', 'name', 'altloc', 'resname', 'chain', 'resid', 'insertion', 'occupancy', 'beta', 'segid', 'element', 'charge', 'masses', 'atomtype', 'coords'), exceptFields=None)