5.1.5. gromacs.utilities – Helper functions and classes

The module defines some convenience functions and classes that are used in other modules; they do not make use of gromacs.tools or gromacs.cbook and can be safely imported at any time.

5.1.5.1. Classes

FileUtils provides functions related to filename handling. It can be used as a base or mixin class. The gromacs.analysis.Simulation class is derived from it.

class gromacs.utilities.FileUtils[source]

Mixin class to provide additional file-related capabilities.

check_file_exists(filename, resolve='exception', force=None)[source]

If a file exists then continue with the action specified in resolve.

resolve must be one of

“ignore”

always return False

“indicate”

return True if it exists

“warn”

indicate and issue a UserWarning

“exception”

raise IOError if it exists

Alternatively, set force for the following behaviour (which ignores resolve):

True

same as resolve = “ignore” (will allow overwriting of files)

False

same as resolve = “exception” (will prevent overwriting of files)

None

ignored, do whatever resolve says

default_extension = None

Default extension for files read/written by this class.

filename(filename=None, ext=None, set_default=False, use_my_ext=False)[source]

Supply a file name for the class object.

Typical uses:

fn = filename()             ---> <default_filename>
fn = filename('name.ext')   ---> 'name'
fn = filename(ext='pickle') ---> <default_filename>'.pickle'
fn = filename('name.inp','pdf') --> 'name.pdf'
fn = filename('foo.pdf',ext='png',use_my_ext=True) --> 'foo.pdf'

The returned filename is stripped of the extension (use_my_ext=False) and if provided, another extension is appended. Chooses a default if no filename is given.

Raises a ValueError exception if no default file name is known.

If set_default=True then the default filename is also set.

use_my_ext=True lets the suffix of a provided filename take priority over a default ext tension.

Changed in version 0.3.1: An empty string as ext = “” will suppress appending an extension.

infix_filename(name, default, infix, ext=None)[source]

Unless name is provided, insert infix before the extension ext of default.

class gromacs.utilities.AttributeDict[source]

A dictionary with pythonic access to keys as attributes — useful for interactive work.

class gromacs.utilities.Timedelta[source]

Extension of datetime.timedelta.

Provides attributes ddays, dhours, dminutes, dseconds to measure the delta in normal time units.

ashours gives the total time in fractional hours.

5.1.5.2. Functions

Some additional convenience functions that deal with files and directories:

gromacs.utilities.openany(directory[, mode='r'])[source]

Context manager to open a compressed (bzip2, gzip) or plain file (uses anyopen()).

gromacs.utilities.anyopen(datasource, mode='rt', reset=True)[source]

Open datasource (gzipped, bzipped, uncompressed) and return a stream.

datasource can be a filename or a stream (see isstream()). By default, a stream is reset to its start if possible (via seek() or reset()).

If possible, the attribute stream.name is set to the filename or “<stream>” if no filename could be associated with the datasource.

Arguments:
datasource

a file (from file or open()) or a stream (e.g. from urllib2.urlopen() or cStringIO.StringIO)

mode

{‘r’, ‘w’, ‘a’} (optional), Open in r(ead), w(rite) or a(ppen) mode. More complicated modes (‘r+’, ‘w+’, …) are not supported; only the first letter of mode is used and thus any additional modifiers are silently ignored.

reset

bool (optional), try to read (mode ‘r’) the stream from the start

Returns:

file-like object

See also

openany() to be used with the with statement.

gromacs.utilities.isstream(obj)[source]

Detect if obj is a stream.

We consider anything a stream that has the methods

  • close()

and either set of the following

  • read(), readline(), readlines()

  • write(), writeline(), writelines()

Arguments:
obj

stream or str

Returns:

bool, True if obj is a stream, False otherwise

See also

io

New in version 0.7.1.

gromacs.utilities.realpath(*args)[source]

Join all args and return the real path, rooted at /.

Expands ~ and environment variables such as $HOME.

Returns None if any of the args is none.

gromacs.utilities.in_dir(directory[, create=True])[source]

Context manager to execute a code block in a directory.

  • The directory is created if it does not exist (unless create = False is set)

  • At the end or after an exception code always returns to the directory that was the current directory before entering the block.

gromacs.utilities.find_first(filename, suffices=None)[source]

Find first filename with a suffix from suffices.

Arguments:
filename

base filename; this file name is checked first

suffices

list of suffices that are tried in turn on the root of filename; can contain the ext separator (os.path.extsep) or not

Returns:

The first match or None.

gromacs.utilities.withextsep(extensions)[source]

Return list in which each element is guaranteed to start with os.path.extsep.

gromacs.utilities.which(program)[source]

Determine full path of executable program on PATH.

(Jay at http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python)

New in version 0.5.1.

Functions that improve list processing and which do not treat strings as lists:

gromacs.utilities.iterable(obj)[source]

Returns True if obj can be iterated over and is not a string.

gromacs.utilities.asiterable(obj)[source]

Returns obj so that it can be iterated over; a string is not treated as iterable

gromacs.utilities.firstof(obj)[source]

Returns the first entry of a sequence or the obj.

Treats strings as single objects.

Functions that help handling Gromacs files:

Unlink path but do not complain if file does not exist.

Unlink (remove) Gromacs file(s) and all corresponding backups.

Unlink (rm) all backup files corresponding to the listed files.

gromacs.utilities.number_pdbs(*args, **kwargs)[source]

Rename pdbs x1.pdb … x345.pdb –> x0001.pdb … x0345.pdb

Arguments:
  • args: filenames or glob patterns (such as “pdb/md*.pdb”)

  • format: format string including keyword num [“%(num)04d”]

Functions that make working with matplotlib easier:

gromacs.utilities.activate_subplot(numPlot)[source]

Make subplot numPlot active on the canvas.

Use this if a simple subplot(numRows, numCols, numPlot) overwrites the subplot instead of activating it.

gromacs.utilities.remove_legend(ax=None)[source]

Remove legend for axes or gca.

See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html

Miscellaneous functions:

gromacs.utilities.convert_aa_code(x)[source]

Converts between 3-letter and 1-letter amino acid codes.

gromacs.utilities.autoconvert(s)[source]

Convert input to a numerical type if possible.

  1. A non-string object is returned as it is

  2. Try conversion to int, float, str.

gromacs.utilities.hasmethod(obj, m)[source]

Return True if object obj contains the method m.

New in version 0.7.1.

5.1.5.3. Data

gromacs.utilities.amino_acid_codes = {'A': 'ALA', 'C': 'CYS', 'D': 'ASP', 'E': 'GLU', 'F': 'PHE', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE', 'K': 'LYS', 'L': 'LEU', 'M': 'MET', 'N': 'ASN', 'P': 'PRO', 'Q': 'GLN', 'R': 'ARG', 'S': 'SER', 'T': 'THR', 'V': 'VAL', 'W': 'TRP', 'Y': 'TYR'}

translation table for 1-letter codes –> 3-letter codes .. Note: This does not work for HISB and non-default charge state aa!