qtot_pattern = re.compile('<STR_LIT>')<EOL>kwargs['<STR_LIT>'] = False<EOL>kwargs['<STR_LIT>'] = False<EOL>rc, output, error = grompp_warnonly(*args, **kwargs)<EOL>gmxoutput = "<STR_LIT:\n>".join([x for x in [output, error] if x is not None])<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>msg = "<STR_LIT>"<EOL>logger.error(msg)<EOL>import sys<EOL>sys.stderr.write("<STR_LIT>")<EOL>sys.stderr.write(gmxoutput)<EOL>sys.stderr.write("<STR_LIT>")<EOL>sys.stderr.flush()<EOL>raise GromacsError(rc, msg)<EOL><DEDENT>qtot = <NUM_LIT:0><EOL>for line in gmxoutput.split('<STR_LIT:\n>'):<EOL><INDENT>m = qtot_pattern.search(line)<EOL>if m:<EOL><INDENT>qtot = float(m.group('<STR_LIT>'))<EOL>break<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>".format(**vars()))<EOL>return qtot<EOL>

Run ``gromacs.grompp`` and return the total charge of the  system.

    :Arguments:
       The arguments are the ones one would pass to :func:`gromacs.grompp`.
    :Returns:
       The total charge as reported

    Some things to keep in mind:

    * The stdout output of grompp is only shown when an error occurs. For
      debugging, look at the log file or screen output and try running the
      normal :func:`gromacs.grompp` command and analyze the output if the
      debugging messages are not sufficient.

    * Check that ``qtot`` is correct. Because the function is based on pattern
      matching of the informative output of :program:`grompp` it can break when
      the output format changes. This version recognizes lines like ::

            '  System has non-zero total charge: -4.000001e+00'

      using the regular expression
      :regexp:`System has non-zero total charge: *(?P<qtot>[-+]?\d*\.\d+([eE][-+]\d+)?)`.


include_paths = [os.path.expanduser(p) for p in dirs]<EOL>return '<STR_LIT>'.join(['<STR_LIT>'] + include_paths)<EOL>

Generate a string that can be added to a mdp 'include = ' line.


if kwargs is None:<EOL><INDENT>kwargs = {}<EOL><DEDENT>include_dirs = ['<STR_LIT:.>', '<STR_LIT:..>']      <EOL>if topology is not None:<EOL><INDENT>topology_dir = os.path.dirname(topology)<EOL>include_dirs.append(topology_dir)<EOL><DEDENT>include_dirs.extend(asiterable(kwargs.pop('<STR_LIT>', [])))  <EOL>kwargs.setdefault('<STR_LIT>', _mdp_include_string(include_dirs))<EOL>return kwargs<EOL>

Set the mdp *include* key in the *kwargs* dict.

    1. Add the directory containing *topology*.
    2. Add all directories appearing under the key *includes*
    3. Generate a string of the form "-Idir1 -Idir2 ..." that
       is stored under the key *include* (the corresponding
       mdp parameter)

    By default, the directories ``.`` and ``..`` are also added to the
    *include* string for the mdp; when fed into
    :func:`gromacs.cbook.edit_mdp` it will result in a line such as ::

      include = -I. -I.. -I../topology_dir ....

    Note that the user can always override the behaviour by setting
    the *include* keyword herself; in this case this function does
    nothing.

    If no *kwargs* were supplied then a dict is generated with the
    single *include* entry.

    :Arguments:
       *topology* : top filename
          Topology file; the name of the enclosing directory is added
          to the include path (if supplied) [``None``]
       *kwargs* : dict
          Optional dictionary of mdp keywords; will be modified in place.
          If it contains the *includes* keyword with either a single string
          or a list of strings then these paths will be added to the
          include statement.
    :Returns: *kwargs* with the *include* keyword added if it did not
              exist previously; if the keyword already existed, nothing
              happens.

    .. Note:: The *kwargs* dict is **modified in place**. This
              function is a bit of a hack. It might be removed once
              all setup functions become methods in a nice class.


grompp_options = ('<STR_LIT:f>','<STR_LIT>','<STR_LIT:c>','<STR_LIT:r>','<STR_LIT:rb>','<STR_LIT:n>','<STR_LIT:p>','<STR_LIT>','<STR_LIT:o>','<STR_LIT:t>','<STR_LIT:e>',  <EOL>'<STR_LIT:h>', '<STR_LIT>', '<STR_LIT:version>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:v>', '<STR_LIT>',<EOL>'<STR_LIT:time>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>')<EOL>grompp = dict((k,v) for k,v in kwargs.items() if k in grompp_options)<EOL>other =  dict((k,v) for k,v in kwargs.items() if k not in grompp_options)<EOL>return grompp, other<EOL>

Returns one dictionary only containing valid :program:`grompp` options and everything else.

    Option list is hard coded and nased on :class:`~gromacs.tools.grompp` 4.5.3.

    :Returns: ``(grompp_dict, other_dict)``

    .. versionadded:: 0.2.4


def create_portable_topology(topol, struct, **kwargs):

_topoldir, _topol = os.path.split(topol)<EOL>processed = kwargs.pop('<STR_LIT>', os.path.join(_topoldir, '<STR_LIT>'+_topol))<EOL>grompp_kwargs, mdp_kwargs = filter_grompp_options(**kwargs)<EOL>mdp_kwargs = add_mdp_includes(topol, mdp_kwargs)<EOL>with tempfile.NamedTemporaryFile(suffix='<STR_LIT>') as mdp:<EOL><INDENT>mdp.write('<STR_LIT>'.format(**mdp_kwargs))<EOL>mdp.flush()<EOL>grompp_kwargs['<STR_LIT:p>'] = topol<EOL>grompp_kwargs['<STR_LIT>'] = processed<EOL>grompp_kwargs['<STR_LIT:f>'] =  mdp.name<EOL>grompp_kwargs['<STR_LIT:c>'] = struct<EOL>grompp_kwargs['<STR_LIT:v>'] = False<EOL>try:<EOL><INDENT>gromacs.grompp(**grompp_kwargs)<EOL><DEDENT>finally:<EOL><INDENT>utilities.unlink_gmx('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT><DEDENT>return utilities.realpath(processed)<EOL>

Create a processed topology.

    The processed (or portable) topology file does not contain any
    ``#include`` statements and hence can be easily copied around. It
    also makes it possible to re-grompp without having any special itp
    files available.

    :Arguments:
      *topol*
          topology file
      *struct*
          coordinat (structure) file

    :Keywords:
      *processed*
          name of the new topology file; if not set then it is named like
          *topol* but with ``pp_`` prepended
      *includes*
          path or list of paths of directories in which itp files are
          searched for
      *grompp_kwargs**
          other options for :program:`grompp` such as ``maxwarn=2`` can
          also be supplied

    :Returns: full path to the processed topology


fd, temp = tempfile.mkstemp('<STR_LIT>')<EOL>try:<EOL><INDENT>rc,out,err = gromacs.editconf(f=f, o=temp, stdout=False)<EOL><DEDENT>finally:<EOL><INDENT>os.unlink(temp)<EOL><DEDENT>return [float(x.split()[<NUM_LIT:1>]) for x in out.splitlines()<EOL>if x.startswith('<STR_LIT>')][<NUM_LIT:0>]<EOL>

Return the volume in nm^3 of structure file *f*.

    (Uses :func:`gromacs.editconf`; error handling is not good)


def edit_mdp(mdp, new_mdp=None, extend_parameters=None, **substitutions):

if new_mdp is None:<EOL><INDENT>new_mdp = mdp<EOL><DEDENT>if extend_parameters is None:<EOL><INDENT>extend_parameters = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>extend_parameters = list(asiterable(extend_parameters))<EOL><DEDENT>substitutions = {k: v for k,v in substitutions.items() if v is not None}<EOL>params = list(substitutions.keys())   <EOL>def demangled(p):<EOL><INDENT>"""<STR_LIT>"""<EOL>return p.replace('<STR_LIT:_>', '<STR_LIT>')  <EOL><DEDENT>patterns = {parameter:<EOL>re.compile("""<STR_LIT>""".format(demangled(parameter)), re.VERBOSE)<EOL>for parameter in substitutions}<EOL>with tempfile.TemporaryFile() as target:<EOL><INDENT>with open(mdp, '<STR_LIT:rb>') as src:<EOL><INDENT>logger.info("<STR_LIT>".format(mdp, substitutions.keys()))<EOL>for line in src:<EOL><INDENT>line = line.decode('<STR_LIT:utf-8>')<EOL>new_line = line.strip()  <EOL>for p in params[:]:<EOL><INDENT>m = patterns[p].match(new_line)<EOL>if m:<EOL><INDENT>if m.group('<STR_LIT>') is None:<EOL><INDENT>comment = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>comment = "<STR_LIT:U+0020>"+m.group('<STR_LIT>')<EOL><DEDENT>assignment = m.group('<STR_LIT>')<EOL>if not assignment.endswith('<STR_LIT:U+0020>'):<EOL><INDENT>assignment += '<STR_LIT:U+0020>'<EOL><DEDENT>new_line = assignment<EOL>if p in extend_parameters:<EOL><INDENT>new_line += str(m.group('<STR_LIT:value>')) + '<STR_LIT:U+0020>'<EOL><DEDENT>value = "<STR_LIT:U+0020>".join(map(str, asiterable(substitutions[p])))<EOL>new_line += value + comment<EOL>params.remove(p)<EOL>break<EOL><DEDENT><DEDENT>target.write((new_line+'<STR_LIT:\n>').encode('<STR_LIT:utf-8>'))<EOL><DEDENT><DEDENT>target.seek(<NUM_LIT:0>)<EOL>with open(new_mdp, '<STR_LIT:wb>') as final:<EOL><INDENT>shutil.copyfileobj(target, final)<EOL><DEDENT><DEDENT>if len(params) > <NUM_LIT:0>:<EOL><INDENT>logger.warn("<STR_LIT>".format(**vars()))<EOL><DEDENT>return {p: substitutions[p] for p in params}<EOL>

Change values in a Gromacs mdp file.

    Parameters and values are supplied as substitutions, eg ``nsteps=1000``.

    By default the template mdp file is **overwritten in place**.

    If a parameter does not exist in the template then it cannot be substituted
    and the parameter/value pair is returned. The user has to check the
    returned list in order to make sure that everything worked as expected. At
    the moment it is not possible to automatically append the new values to the
    mdp file because of ambiguities when having to replace dashes in parameter
    names with underscores (see the notes below on dashes/underscores).

    If a parameter is set to the value ``None`` then it will be ignored.

    :Arguments:
        *mdp* : filename
            filename of input (and output filename of ``new_mdp=None``)
        *new_mdp* : filename
            filename of alternative output mdp file [None]
        *extend_parameters* : string or list of strings
            single parameter or list of parameters for which the new values
            should be appended to the existing value in the mdp file. This
            makes mostly sense for a single parameter, namely 'include', which
            is set as the default. Set to ``[]`` to disable. ['include']
        *substitutions*
            parameter=value pairs, where parameter is defined by the Gromacs
            mdp file; dashes in parameter names have to be replaced by
            underscores. If a value is a list-like object then the items are
            written as a sequence, joined with spaces, e.g. ::

               ref_t=[310,310,310] --->  ref_t = 310 310 310

    :Returns:
        Dict of parameters that have *not* been substituted.

    **Example** ::

       edit_mdp('md.mdp', new_mdp='long_md.mdp', nsteps=100000, nstxtcout=1000, lincs_iter=2)

    .. Note::

       * Dashes in Gromacs mdp parameters have to be replaced by an underscore
         when supplied as python keyword arguments (a limitation of python). For example
         the MDP syntax is  ``lincs-iter = 4`` but the corresponding  keyword would be
         ``lincs_iter = 4``.
       * If the keyword is set as a dict key, eg ``mdp_params['lincs-iter']=4`` then one
         does not have to substitute.
       * Parameters *aa_bb* and *aa-bb* are considered the same (although this should
         not be a problem in practice because there are no mdp parameters that only
         differ by a underscore).
       * This code is more compact in ``Perl`` as one can use ``s///`` operators:
         ``s/^(\s*${key}\s*=\s*).*/$1${val}/``

    .. SeeAlso:: One can also load the mdp file with
                :class:`gromacs.formats.MDP`, edit the object (a dict), and save it again.


def edit_txt(filename, substitutions, newname=None):

if newname is None:<EOL><INDENT>newname = filename<EOL><DEDENT>_substitutions = [{'<STR_LIT>': re.compile(str(lRE)),<EOL>'<STR_LIT>': re.compile(str(sRE)),<EOL>'<STR_LIT>': repl}<EOL>for lRE,sRE,repl in substitutions if repl is not None]<EOL>with tempfile.TemporaryFile() as target:<EOL><INDENT>with open(filename, '<STR_LIT:rb>') as src:<EOL><INDENT>logger.info("<STR_LIT>".format(filename, len(substitutions)))<EOL>for line in src:<EOL><INDENT>line = line.decode("<STR_LIT:utf-8>")<EOL>keep_line = True<EOL>for subst in _substitutions:<EOL><INDENT>m = subst['<STR_LIT>'].match(line)<EOL>if m:              <EOL><INDENT>logger.debug('<STR_LIT>'+line.rstrip())<EOL>if subst['<STR_LIT>'] is False:   <EOL><INDENT>keep_line = False<EOL><DEDENT>else:                        <EOL><INDENT>line = subst['<STR_LIT>'].sub(str(subst['<STR_LIT>']), line)<EOL>logger.debug('<STR_LIT>'+line.rstrip())<EOL><DEDENT><DEDENT><DEDENT>if keep_line:<EOL><INDENT>target.write(line.encode('<STR_LIT:utf-8>'))<EOL><DEDENT>else:<EOL><INDENT>logger.debug("<STR_LIT>", line)<EOL><DEDENT><DEDENT><DEDENT>target.seek(<NUM_LIT:0>)<EOL>with open(newname, '<STR_LIT:wb>') as final:<EOL><INDENT>shutil.copyfileobj(target, final)<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>".format(**vars()))<EOL>

Primitive text file stream editor.

    This function can be used to edit free-form text files such as the
    topology file. By default it does an **in-place edit** of
    *filename*. If *newname* is supplied then the edited
    file is written to *newname*.

    :Arguments:
       *filename*
           input text file
       *substitutions*
           substitution commands (see below for format)
       *newname*
           output filename; if ``None`` then *filename* is changed in
           place [``None``]

    *substitutions* is a list of triplets; the first two elements are regular
    expression strings, the last is the substitution value. It mimics
    ``sed`` search and replace. The rules for *substitutions*:

    .. productionlist::
       substitutions: "[" search_replace_tuple, ... "]"
       search_replace_tuple: "(" line_match_RE "," search_RE "," replacement ")"
       line_match_RE: regular expression that selects the line (uses match)
       search_RE: regular expression that is searched in the line
       replacement: replacement string for search_RE

    Running :func:`edit_txt` does pretty much what a simple ::

         sed /line_match_RE/s/search_RE/replacement/

    with repeated substitution commands does.

    Special replacement values:
    - ``None``: the rule is ignored
    - ``False``: the line is deleted (even if other rules match)

    .. note::

       * No sanity checks are performed and the substitutions must be supplied
         exactly as shown.
       * All substitutions are applied to a line; thus the order of the substitution
         commands may matter when one substitution generates a match for a subsequent rule.
       * If replacement is set to ``None`` then the whole expression is ignored and
         whatever is in the template is used. To unset values you must provided an
         empty string or similar.
       * Delete a matching line if replacement=``False``.


marker = kwargs.pop('<STR_LIT>', None)<EOL>if marker is None:<EOL><INDENT>marker = "<STR_LIT>"<EOL><DEDENT>logger.debug("<STR_LIT>", vars())<EOL>p_marker = re.compile("<STR_LIT>".format(marker))<EOL>p_molecule = re.compile("<STR_LIT>")<EOL>with tempfile.TemporaryFile() as target:<EOL><INDENT>with open(filename, '<STR_LIT:rb>') as src:<EOL><INDENT>autogenerated = False<EOL>n_removed = <NUM_LIT:0><EOL>for line in src:<EOL><INDENT>line = line.decode('<STR_LIT:utf-8>')<EOL>if p_marker.match(line):<EOL><INDENT>autogenerated = True<EOL><DEDENT>if autogenerated and p_molecule.match(line):<EOL><INDENT>n_removed += <NUM_LIT:1><EOL>continue  <EOL><DEDENT>target.write(line.encode('<STR_LIT:utf-8>'))<EOL><DEDENT><DEDENT>if autogenerated and n_removed > <NUM_LIT:0>:<EOL><INDENT>target.seek(<NUM_LIT:0>)<EOL>with open(filename, '<STR_LIT:wb>') as final:   <EOL><INDENT>shutil.copyfileobj(target, final)<EOL><DEDENT>logger.info("<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL><DEDENT><DEDENT>return n_removed<EOL>

Remove autogenerated [ molecules ] entries from *filename*.

    Valid entries in ``[ molecules ]`` below the default *marker*
    are removed. For example, a topology file such as ::

       [ molecules ]
       Protein    1
       SOL      213
       ; The next line is the marker!
       ; Gromacs auto-generated entries follow:
       SOL            12345
       NA+     15
       CL-      16
       ; This is a comment that is NOT deleted.
       SOL            333

    would become::

       [ molecules ]
       Protein    1
       SOL      213
       ; The next line is the marker!
       ; Gromacs auto-generated entries follow:
       ; This is a comment that is NOT deleted.

    Valid molecule lines look like ``SOL 1234``, ``NA 17`` etc. The
    actual regular expression used is "\s*[\w+_-]+\s+\d+\s*(;.*)?$".

    In order to use this function, the marker line has to be manually
    added to the topology file.

    :Arguments:
      *filename*
         The topology file that includes the  ``[ molecules ]`` section.
         It is **edited in place**.
      *marker*
         Any ``[ molecules ]`` entries below this pattern (python regular
         expression) are removed. Leading white space is ignored. ``None``
         uses the default as described above.


kwargs['<STR_LIT>']=False   <EOL>user_input = kwargs.pop('<STR_LIT:input>',[])<EOL>user_input = [cmd for cmd in user_input if cmd != '<STR_LIT:q>']  <EOL>kwargs['<STR_LIT:input>'] = user_input + ['<STR_LIT>', '<STR_LIT:q>']                <EOL>return gromacs.make_ndx(**kwargs)<EOL>

make_ndx that captures all output

    Standard :func:`~gromacs.make_ndx` command with the input and
    output pre-set in such a way that it can be conveniently used for
    :func:`parse_ndxlist`.

    Example::
      ndx_groups = parse_ndxlist(make_ndx_captured(n=ndx)[0])

    Note that the convenient :func:`get_ndx_groups` function does exactly
    that and can probably used in most cases.

    :Arguments:
        keywords are passed on to :func:`~gromacs.make_ndx`
    :Returns:
        (*returncode*, *output*, ``None``)


fd, tmp_ndx = tempfile.mkstemp(suffix='<STR_LIT>')<EOL>kwargs['<STR_LIT:o>'] = tmp_ndx<EOL>try:<EOL><INDENT>g = parse_ndxlist(make_ndx_captured(n=ndx, **kwargs)[<NUM_LIT:1>])<EOL><DEDENT>finally:<EOL><INDENT>utilities.unlink_gmx(tmp_ndx)<EOL><DEDENT>return g<EOL>

Return a list of index groups in the index file *ndx*.

    :Arguments:
        - *ndx*  is a Gromacs index file.
        - kwargs are passed to :func:`make_ndx_captured`.

    :Returns:
        list of groups as supplied by :func:`parse_ndxlist`

    Alternatively, load the index file with
    :class:`gromacs.formats.NDX` for full control.


m = NDXLIST.search(output)    <EOL>grouplist = m.group('<STR_LIT>')<EOL>return parse_groups(grouplist)<EOL>

Parse output from make_ndx to build list of index groups::

      groups = parse_ndxlist(output)

    output should be the standard output from ``make_ndx``, e.g.::

       rc,output,junk = gromacs.make_ndx(..., input=('', 'q'), stdout=False, stderr=True)

    (or simply use

       rc,output,junk = cbook.make_ndx_captured(...)

    which presets input, stdout and stderr; of course input can be overriden.)

    :Returns:
       The function returns a list of dicts (``groups``) with fields

       name
           name of the groups
       nr
           number of the group (starts at 0)
       natoms
           number of atoms in the group


groups = []<EOL>for line in output.split('<STR_LIT:\n>'):<EOL><INDENT>m = NDXGROUP.match(line)<EOL>if m:<EOL><INDENT>d = m.groupdict()<EOL>groups.append({'<STR_LIT:name>': d['<STR_LIT>'],<EOL>'<STR_LIT>': int(d['<STR_LIT>']),<EOL>'<STR_LIT>': int(d['<STR_LIT>'])})<EOL><DEDENT><DEDENT>return groups<EOL>

Parse ``make_ndx`` output and return groups as a list of dicts.


def __init__(self, structure, trj, maxframes=None, format='<STR_LIT>', **kwargs):

self.structure = structure  <EOL>self.trj = trj              <EOL>self.maxframes = maxframes<EOL>if self.maxframes is not None:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>self.framedir = tempfile.mkdtemp(prefix="<STR_LIT>", suffix='<STR_LIT:_>'+format)<EOL>self.frameprefix = os.path.join(self.framedir, '<STR_LIT>')<EOL>self.frametemplate = self.frameprefix + '<STR_LIT>' + '<STR_LIT:.>' + format  <EOL>self.frameglob = self.frameprefix + '<STR_LIT:*>' + '<STR_LIT:.>' + format<EOL>kwargs['<STR_LIT>'] = True<EOL>kwargs['<STR_LIT:o>'] = self.frameprefix + '<STR_LIT:.>' + format<EOL>kwargs.setdefault('<STR_LIT:input>', ('<STR_LIT>',))<EOL>self.extractor = tools.Trjconv(s=self.structure, f=self.trj, **kwargs)<EOL>self.framenumber = <NUM_LIT:0><EOL>self.totalframes = <NUM_LIT:0><EOL>

Set up the Frames iterator.

        :Arguments:
           structure
              name of a structure file (tpr, pdb, ...)
           trj
              name of the trajectory (xtc, trr, ...)
           format
              output format for the frames, eg "pdb" or "gro" [pdb]
           maxframes : int
             maximum number of frames that are extracted to disk at
             one time; set to ``None`` to extract the whole trajectory
             at once. [``None``]
           kwargs
             All other arguments are passed to
             `class:~gromacs.tools.Trjconv`; the only options that
             cannot be changed are *sep* and the output file name *o*.


<EOL>self.extractor.run()<EOL>

Extract frames from the trajectory to the temporary directory.


return glob.glob(self.frameglob)<EOL>

Unordered list of all frames currently held on disk.


frames = self.all_frames<EOL>if len(frames) == <NUM_LIT:0>:<EOL><INDENT>self.extract()<EOL>frames = self.all_frames<EOL><DEDENT>for i in xrange(len(frames)):<EOL><INDENT>self.framenumber = i<EOL>yield self.current_framename<EOL><DEDENT>self.totalframes += len(frames)<EOL>


for frame in glob.glob(self.frameglob):<EOL><INDENT>os.unlink(frame)<EOL><DEDENT>


shutil.rmtree(self.framedir)<EOL>self.framedir = None<EOL>

Clean up all temporary frames (which can be HUGE).


def __init__(self, struct=None, selections=None, names=None, name_all=None,<EOL>ndx=None, out_ndx="<STR_LIT>", offset=<NUM_LIT:0>):

self.structure = struct<EOL>self.ndx = ndx<EOL>self.output = out_ndx<EOL>self.name_all = name_all<EOL>self.offset = offset<EOL>self._command_counter = <NUM_LIT:0><EOL>if selections is None:<EOL><INDENT>selections = []<EOL><DEDENT>if not utilities.iterable(selections):<EOL><INDENT>selections = [selections]<EOL><DEDENT>self.selections = selections<EOL>if names is None:<EOL><INDENT>names = [None] * len(selections)<EOL><DEDENT>self.make_ndx = tools.Make_ndx(f=self.structure, n=self.ndx,<EOL>stdout=False, stderr=False)<EOL>self.indexfiles = dict([self.parse_selection(selection, name)<EOL>for selection, name in zip(selections, names)])<EOL>

Build a index group from the selection arguments.

        If selections and a structure file are supplied then the individual
        selections are constructed with separate calls to
        :func:`gromacs.make_ndx`. Use :meth:`IndexBuilder.combine` to combine
        them into a joint selection or :meth:`IndexBuilder.write` to simply write
        out the individual named selections (useful with *names*).

        :Arguments:

           *struct* : filename
              Structure file (tpr, pdb, ...)

           *selections* : list
              The list must contain strings or tuples, which must be be one of
              the following constructs:

                 "<1-letter aa code><resid>[:<atom name]"

                     Selects the CA of the residue or the specified atom
                     name.

                     example: ``"S312:OA"`` or ``"A22"`` (equivalent to ``"A22:CA"``)

                 ("<1-letter aa code><resid>", "<1-letter aa code><resid>, ["<atom name>"])

                    Selects a *range* of residues. If only two residue
                    identifiers are provided then all atoms are
                    selected. With an optional third atom identifier,
                    only this atom anme is selected for each residue
                    in the range. [EXPERIMENTAL]

                 "@<make_ndx selection>"

                     The ``@`` letter introduces a verbatim ``make_ndx``
                     command. It will apply the given selection without any
                     further processing or checks.

                     example: ``"@a 6234 - 6238"`` or ``'@"SOL"'`` (note the quoting)
                     or ``"@r SER & r 312 & t OA"``.

           *names* : list
              Strings to name the selections; if not supplied or if individuals
              are ``None`` then a default name is created. When simply using
              :meth:`IndexBuilder.write` then these should be supplied.

           *name_all* : string
              Name of the group that is generated by :meth:`IndexBuilder.combine`.

           *offset* : int, dict
              This number is added to the resids in the first selection scheme; this
              allows names to be the same as in a crystal structure. If offset is a
              dict then it is used to directly look up the resids.

           *ndx* : filename or list of filenames
              Optional input index file(s).

           *out_ndx* : filename
              Output index file.


return self.indexfiles.keys()<EOL>


try:<EOL><INDENT>gmx_resid = int(self.offset[resid])<EOL><DEDENT>except (TypeError, IndexError):<EOL><INDENT>gmx_resid = resid + self.offset<EOL><DEDENT>except KeyError:<EOL><INDENT>raise KeyError("<STR_LIT>".format(resid))<EOL><DEDENT>return gmx_resid<EOL>

Returns resid in the Gromacs index by transforming with offset.


def combine(self, name_all=None, out_ndx=None, operation='<STR_LIT:|>', defaultgroups=False):

if not operation in ('<STR_LIT:|>', '<STR_LIT:&>', False):<EOL><INDENT>raise ValueError("<STR_LIT>".format(<EOL>operation))<EOL><DEDENT>if name_all is None and operation:<EOL><INDENT>name_all = self.name_all or operation.join(self.indexfiles)<EOL><DEDENT>if out_ndx is None:<EOL><INDENT>out_ndx = self.output<EOL><DEDENT>if defaultgroups:<EOL><INDENT>fd, default_ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix='<STR_LIT>')<EOL>try:<EOL><INDENT>self.make_ndx(o=default_ndx, input=['<STR_LIT:q>'])<EOL><DEDENT>except:<EOL><INDENT>utilities.unlink_gmx(default_ndx)<EOL>raise<EOL><DEDENT>ndxfiles = [default_ndx]<EOL><DEDENT>else:<EOL><INDENT>ndxfiles = []<EOL><DEDENT>ndxfiles.extend(self.indexfiles.values())<EOL>if operation:<EOL><INDENT>try:<EOL><INDENT>fd, tmp_ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix='<STR_LIT>')<EOL>operation = '<STR_LIT:U+0020>'+operation.strip()+'<STR_LIT:U+0020>'<EOL>cmd = [operation.join(['<STR_LIT>'.format(gname) for gname in self.indexfiles]),<EOL>'<STR_LIT>', '<STR_LIT:q>']<EOL>rc,out,err = self.make_ndx(n=ndxfiles, o=tmp_ndx, input=cmd)<EOL>if self._is_empty_group(out):<EOL><INDENT>warnings.warn("<STR_LIT>".format(**vars()),<EOL>category=BadParameterWarning)<EOL><DEDENT>groups = parse_ndxlist(out)<EOL>last = groups[-<NUM_LIT:1>]<EOL>name_cmd = ["<STR_LIT>".format(last['<STR_LIT>'], name_all), '<STR_LIT:q>']<EOL>rc,out,err = self.make_ndx(n=tmp_ndx, o=out_ndx, input=name_cmd)<EOL><DEDENT>finally:<EOL><INDENT>utilities.unlink_gmx(tmp_ndx)<EOL>if defaultgroups:<EOL><INDENT>utilities.unlink_gmx(default_ndx)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rc,out,err = self.make_ndx(n=ndxfiles, o=out_ndx, input=['<STR_LIT>','<STR_LIT:q>'])<EOL><DEDENT>return name_all, out_ndx<EOL>

Combine individual groups into a single one and write output.

        :Keywords:
           name_all : string
              Name of the combined group, ``None`` generates a name.  [``None``]
           out_ndx : filename
              Name of the output file that will contain the individual groups
              and the combined group. If ``None`` then default from the class
              constructor is used. [``None``]
           operation : character
              Logical operation that is used to generate the combined group from
              the individual groups: "|" (OR) or "&" (AND); if set to ``False``
              then no combined group is created and only the individual groups
              are written. ["|"]
           defaultgroups : bool
              ``True``: append everything to the default groups produced by
              :program:`make_ndx` (or rather, the groups provided in the ndx file on
              initialization --- if this was ``None`` then these are truly default groups);
              ``False``: only use the generated groups

        :Returns:
           ``(combinedgroup_name, output_ndx)``, a tuple showing the
           actual group name and the name of the file; useful when all names are autogenerated.

        .. Warning:: The order of the atom numbers in the combined group is
                     *not* guaranteed to be the same as the selections on input because
                     ``make_ndx`` sorts them ascending. Thus you should be careful when
                     using these index files for calculations of angles and dihedrals.
                     Use :class:`gromacs.formats.NDX` in these cases.

        .. SeeAlso:: :meth:`IndexBuilder.write`.


def write(self, out_ndx=None, defaultgroups=False):

name_all, out_ndx = self.combine(operation=False, out_ndx=out_ndx, defaultgroups=defaultgroups)<EOL>return out_ndx<EOL>

Write individual (named) groups to *out_ndx*.


if out_ndx is None:<EOL><INDENT>out_ndx = self.output<EOL><DEDENT>self.make_ndx(o=out_ndx, input=['<STR_LIT:q>'])<EOL>return out_ndx<EOL>

Concatenate input index files.

        Generate a new index file that contains the default Gromacs index
        groups (if a structure file was defined) and all index groups from the
        input index files.

        :Arguments:
           out_ndx : filename
              Name of the output index file; if ``None`` then use the default
              provided to the constructore. [``None``].


def parse_selection(self, selection, name=None):

if type(selection) is tuple:<EOL><INDENT>process = self._process_range<EOL><DEDENT>elif selection.startswith('<STR_LIT:@>'):<EOL><INDENT>process = self._process_command<EOL>selection = selection[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>process = self._process_residue<EOL><DEDENT>return process(selection, name)<EOL>

Retuns (groupname, filename) with index group.


def _process_command(self, command, name=None):

self._command_counter += <NUM_LIT:1><EOL>if name is None:<EOL><INDENT>name = "<STR_LIT>".format(self._command_counter)<EOL><DEDENT>try:<EOL><INDENT>fd, tmp_ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix='<STR_LIT>'+name+'<STR_LIT>')<EOL>cmd = [command, '<STR_LIT>', '<STR_LIT:q>']   <EOL>rc,out,err = self.make_ndx(o=tmp_ndx, input=cmd)<EOL>self.check_output(out, "<STR_LIT>".format(**vars()), err=err)<EOL>groups = parse_ndxlist(out)<EOL>last = groups[-<NUM_LIT:1>]<EOL>fd, ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix=name+'<STR_LIT>')<EOL>name_cmd = ["<STR_LIT>".format(last['<STR_LIT>']),<EOL>"<STR_LIT>".format(name), '<STR_LIT:q>']<EOL>rc,out,err = self.make_ndx(n=tmp_ndx, o=ndx, input=name_cmd)<EOL><DEDENT>finally:<EOL><INDENT>utilities.unlink_gmx(tmp_ndx)<EOL><DEDENT>return name, ndx<EOL>

Process ``make_ndx`` command and  return name and temp index file.


def _process_residue(self, selection, name=None):

if name is None:<EOL><INDENT>name = selection.replace('<STR_LIT::>', '<STR_LIT:_>')<EOL><DEDENT>m = self.RESIDUE.match(selection)<EOL>if not m:<EOL><INDENT>raise ValueError("<STR_LIT>".format(**vars()))<EOL><DEDENT>gmx_resid = self.gmx_resid(int(m.group('<STR_LIT>')))<EOL>residue = m.group('<STR_LIT>')<EOL>if len(residue) == <NUM_LIT:1>:<EOL><INDENT>gmx_resname = utilities.convert_aa_code(residue) <EOL><DEDENT>else:<EOL><INDENT>gmx_resname = residue                            <EOL><DEDENT>gmx_atomname = m.group('<STR_LIT>')<EOL>if gmx_atomname is None:<EOL><INDENT>gmx_atomname = '<STR_LIT>'<EOL><DEDENT>_selection = '<STR_LIT>'.format(**vars())<EOL>cmd = ['<STR_LIT>', '<STR_LIT>',<EOL>_selection,<EOL>'<STR_LIT>'.format(**vars()),<EOL>'<STR_LIT:q>']<EOL>fd, ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix=name+'<STR_LIT>')<EOL>rc,out,err = self.make_ndx(n=self.ndx, o=ndx, input=cmd)<EOL>self.check_output(out, "<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL>return name, ndx<EOL>

Process residue/atom selection and return name and temp index file.


def _process_range(self, selection, name=None):

try:<EOL><INDENT>first, last, gmx_atomname = selection<EOL><DEDENT>except ValueError:<EOL><INDENT>try:<EOL><INDENT>first, last = selection<EOL>gmx_atomname = '<STR_LIT:*>'<EOL><DEDENT>except:<EOL><INDENT>logger.error("<STR_LIT>", selection)<EOL>raise<EOL><DEDENT><DEDENT>if name is None:<EOL><INDENT>name = "<STR_LIT>".format(**vars())<EOL><DEDENT>_first = self._translate_residue(first, default_atomname=gmx_atomname)<EOL>_last = self._translate_residue(last, default_atomname=gmx_atomname)<EOL>_selection = '<STR_LIT>'.format(_first['<STR_LIT>'], _last['<STR_LIT>'], gmx_atomname)<EOL>cmd = ['<STR_LIT>', '<STR_LIT>',<EOL>_selection,<EOL>'<STR_LIT>'.format(**vars()),<EOL>'<STR_LIT:q>']<EOL>fd, ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix=name+'<STR_LIT>')<EOL>rc,out,err = self.make_ndx(n=self.ndx, o=ndx, input=cmd)<EOL>self.check_output(out, "<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL>return name, ndx<EOL>

Process a range selection.

        ("S234", "A300", "CA")   --> selected all CA in this range
        ("S234", "A300")         --> selected all atoms in this range

        .. Note:: Ignores residue type, only cares about the resid (but still required)


def _translate_residue(self, selection, default_atomname='<STR_LIT>'):

m = self.RESIDUE.match(selection)<EOL>if not m:<EOL><INDENT>errmsg = "<STR_LIT>".format(**vars())<EOL>logger.error(errmsg)<EOL>raise ValueError(errmsg)<EOL><DEDENT>gmx_resid = self.gmx_resid(int(m.group('<STR_LIT>')))    <EOL>residue = m.group('<STR_LIT>')<EOL>if len(residue) == <NUM_LIT:1>:<EOL><INDENT>gmx_resname = utilities.convert_aa_code(residue) <EOL><DEDENT>else:<EOL><INDENT>gmx_resname = residue                            <EOL><DEDENT>gmx_atomname = m.group('<STR_LIT>')<EOL>if gmx_atomname is None:<EOL><INDENT>gmx_atomname = default_atomname<EOL><DEDENT>return {'<STR_LIT>':gmx_resname, '<STR_LIT>':gmx_resid, '<STR_LIT>':gmx_atomname}<EOL>

Translate selection for a single res to make_ndx syntax.


def check_output(self, make_ndx_output, message=None, err=None):

if message is None:<EOL><INDENT>message = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>message = '<STR_LIT:\n>' + message<EOL><DEDENT>def format(output, w=<NUM_LIT>):<EOL><INDENT>hrule = "<STR_LIT>".ljust(w,"<STR_LIT:=>")<EOL>return hrule + '<STR_LIT:\n>' + str(output) + hrule<EOL><DEDENT>rc = True<EOL>if self._is_empty_group(make_ndx_output):<EOL><INDENT>warnings.warn("<STR_LIT>".format(**vars()), category=GromacsValueWarning)<EOL>rc = False<EOL><DEDENT>if self._has_syntax_error(make_ndx_output):<EOL><INDENT>rc = False<EOL>out_formatted = format(make_ndx_output)<EOL>raise GromacsError("<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL><DEDENT>if make_ndx_output.strip() == "<STR_LIT>":<EOL><INDENT>rc = False<EOL>out_formatted = format(err)<EOL>raise GromacsError("<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL><DEDENT>return rc<EOL>

Simple tests to flag problems with a ``make_ndx`` run.


def __init__(self, s="<STR_LIT>", f="<STR_LIT>", n=None, force=None,<EOL>dirname=os.path.curdir, outdir=None):

self.tpr = self.filename(s, ext="<STR_LIT>", use_my_ext=True)<EOL>self.xtc = self.filename(f, ext="<STR_LIT>", use_my_ext=True)<EOL>self.ndx = n<EOL>self.dirname = dirname<EOL>self.outdir = utilities.realpath(outdir) if outdir is not None else None<EOL>self.force = force<EOL>self.nowater = {}     <EOL>self.proteinonly = {} <EOL>with utilities.in_dir(self.dirname, create=False):<EOL><INDENT>for f in (self.tpr, self.xtc, self.ndx):<EOL><INDENT>if f is None:<EOL><INDENT>continue<EOL><DEDENT>if not os.path.exists(f):<EOL><INDENT>msg = "<STR_LIT>".format(**vars())<EOL>warnings.warn(msg, category=MissingDataWarning)<EOL>logger.warn(msg)<EOL><DEDENT><DEDENT><DEDENT>logger.info("<STR_LIT>", self)<EOL>

Set up Transformer with structure and trajectory.

        Supply *n* = tpr, *f* = xtc (and *n* = ndx) relative to dirname.

        :Keywords:
           *s*
              tpr file (or similar); note that this should not contain
              position restraints if it is to be used with a reduced
              system (see :meth:`~Transformer.strip_water`)
           *f*
              trajectory (xtc, trr, ...)
           *n*
              index file (it is typically safe to leave this as ``None``; in
              cases where a trajectory needs to be centered on non-standard
              groups this should contain those groups)
           *force*
              Set the default behaviour for handling existing files:
                - ``True``: overwrite existing trajectories
                - ``False``: throw a IOError exception
                - ``None``: skip existing and log a warning [default]
           *dirname*
              directory in which all operations are performed, relative paths
              are interpreted relative to *dirname* [.]
           *outdir*
              directory under which output files are placed; by default
              the same directory where the input files live


if self.outdir is not None:<EOL><INDENT>return os.path.join(self.outdir, os.path.basename(p))<EOL><DEDENT>else:<EOL><INDENT>return p<EOL><DEDENT>

Path for an output file.

        If :attr:`outdir` is set then the path is
        ``outdir/basename(p)`` else just ``p``


try:<EOL><INDENT>p = os.path.join(*args)<EOL>if os.path.isabs(p):<EOL><INDENT>return p<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT>return utilities.realpath(self.dirname, *args)<EOL>

Return canonical path to file under *dirname* with components *args*

         If *args* form an absolute path then just return it as the absolute path.


kwargs.setdefault('<STR_LIT:s>', self.tpr)<EOL>kwargs.setdefault('<STR_LIT:n>', self.ndx)<EOL>kwargs['<STR_LIT:f>'] = self.xtc<EOL>kwargs.setdefault('<STR_LIT:o>', self.outfile(self.infix_filename(None, self.xtc, '<STR_LIT>', '<STR_LIT>')))<EOL>force = kwargs.pop('<STR_LIT>', self.force)<EOL>logger.info("<STR_LIT>".format(**kwargs))<EOL>with utilities.in_dir(self.dirname):<EOL><INDENT>if not self.check_file_exists(kwargs['<STR_LIT:o>'], resolve="<STR_LIT>", force=force):<EOL><INDENT>trj_fitandcenter(**kwargs)<EOL><DEDENT>logger.info("<STR_LIT>".format(**kwargs))<EOL><DEDENT>return {'<STR_LIT>': self.rp(kwargs['<STR_LIT:s>']), '<STR_LIT>': self.rp(kwargs['<STR_LIT:o>'])}<EOL>

Write compact xtc that is fitted to the tpr reference structure.

        See :func:`gromacs.cbook.trj_fitandcenter` for details and
        description of *kwargs* (including *input*, *input1*, *n* and
        *n1* for how to supply custom index groups). The most important ones are listed
        here but in most cases the defaults should work.

        :Keywords:
           *s*
             Input structure (typically the default tpr file but can be set to
             some other file with a different conformation for fitting)
           *n*
             Alternative index file.
           *o*
             Name of the output trajectory.
           *xy* : Boolean
             If ``True`` then only fit in xy-plane (useful for a membrane normal
             to z). The default is ``False``.
           *force*
             - ``True``: overwrite existing trajectories
             - ``False``: throw a IOError exception
             - ``None``: skip existing and log a warning [default]

        :Returns:
              dictionary with keys *tpr*, *xtc*, which are the names of the
              the new files


kwargs.setdefault('<STR_LIT:s>', self.tpr)<EOL>kwargs.setdefault('<STR_LIT:n>', self.ndx)<EOL>kwargs['<STR_LIT:f>'] = self.xtc<EOL>force = kwargs.pop('<STR_LIT>', self.force)<EOL>if xy:<EOL><INDENT>fitmode = '<STR_LIT>'<EOL>kwargs.pop('<STR_LIT>', None)<EOL>infix_default = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>fitmode = kwargs.pop('<STR_LIT>', '<STR_LIT>')  <EOL>infix_default = '<STR_LIT>'<EOL><DEDENT>dt = kwargs.get('<STR_LIT>')<EOL>if dt:<EOL><INDENT>infix_default += '<STR_LIT>'.format(int(dt))    <EOL><DEDENT>kwargs.setdefault('<STR_LIT:o>', self.outfile(self.infix_filename(None, self.xtc, infix_default, '<STR_LIT>')))<EOL>fitgroup = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>kwargs.setdefault('<STR_LIT:input>', [fitgroup, "<STR_LIT>"])<EOL>if kwargs.get('<STR_LIT>', False):<EOL><INDENT>logger.warn("<STR_LIT>", kwargs)<EOL>if len(kwargs['<STR_LIT>']) != <NUM_LIT:3>:<EOL><INDENT>logger.error("<STR_LIT>")<EOL>raise ValuError("<STR_LIT>")<EOL><DEDENT><DEDENT>logger.info("<STR_LIT>", kwargs['<STR_LIT:f>'], xy)<EOL>logger.info("<STR_LIT>", vars())<EOL>with utilities.in_dir(self.dirname):<EOL><INDENT>if self.check_file_exists(kwargs['<STR_LIT:o>'], resolve="<STR_LIT>", force=force):<EOL><INDENT>logger.warn("<STR_LIT>", kwargs['<STR_LIT:o>'])<EOL><DEDENT>else:<EOL><INDENT>gromacs.trjconv(fit=fitmode, **kwargs)<EOL>logger.info("<STR_LIT>", fitmode, kwargs['<STR_LIT:o>'])<EOL><DEDENT><DEDENT>return {'<STR_LIT>': self.rp(kwargs['<STR_LIT:s>']), '<STR_LIT>': self.rp(kwargs['<STR_LIT:o>'])}<EOL>

Write xtc that is fitted to the tpr reference structure.

        Runs :class:`gromacs.tools.trjconv` with appropriate arguments
        for fitting. The most important *kwargs* are listed
        here but in most cases the defaults should work.

        Note that the default settings do *not* include centering or
        periodic boundary treatment as this often does not work well
        with fitting. It is better to do this as a separate step (see
        :meth:`center_fit` or :func:`gromacs.cbook.trj_fitandcenter`)

        :Keywords:
           *s*
             Input structure (typically the default tpr file but can be set to
             some other file with a different conformation for fitting)
           *n*
             Alternative index file.
           *o*
             Name of the output trajectory. A default name is created.
             If e.g. *dt* = 100  is one of the *kwargs* then the default name includes
             "_dt100ps".
          *xy* : boolean
             If ``True`` then only do a rot+trans fit in the xy plane
             (good for membrane simulations); default is ``False``.
          *force*
            ``True``: overwrite existing trajectories
            ``False``: throw a IOError exception
            ``None``: skip existing and log a warning [default]
          *fitgroup*
            index group to fit on ["backbone"]

            .. Note:: If keyword *input* is supplied then it will override
                      *fitgroup*; *input* = ``[fitgroup, outgroup]``
          *kwargs*
             kwargs are passed to :func:`~gromacs.cbook.trj_xyfitted`

        :Returns:
              dictionary with keys *tpr*, *xtc*, which are the names of the
              the new files


def strip_water(self, os=None, o=None, on=None, compact=False,<EOL>resn="<STR_LIT>", groupname="<STR_LIT>", **kwargs):

force = kwargs.pop('<STR_LIT>', self.force)<EOL>newtpr = self.outfile(self.infix_filename(os, self.tpr, '<STR_LIT>'))<EOL>newxtc = self.outfile(self.infix_filename(o, self.xtc, '<STR_LIT>'))<EOL>newndx = self.outfile(self.infix_filename(on, self.tpr, '<STR_LIT>', '<STR_LIT>'))<EOL>nowater_ndx = self._join_dirname(newtpr, "<STR_LIT>")    <EOL>if compact:<EOL><INDENT>TRJCONV = trj_compact<EOL>if kwargs.get('<STR_LIT>') is not None and '<STR_LIT:input>' in kwargs:<EOL><INDENT>logger.warn("<STR_LIT>", kwargs['<STR_LIT>'], kwargs['<STR_LIT:input>'][<NUM_LIT:0>])<EOL><DEDENT>_input = kwargs.get('<STR_LIT:input>', [kwargs.get('<STR_LIT>', '<STR_LIT>')])<EOL>kwargs['<STR_LIT:input>'] = [_input[<NUM_LIT:0>], groupname]  <EOL>del _input<EOL>logger.info("<STR_LIT>", kwargs['<STR_LIT:input>'][<NUM_LIT:0>])<EOL>logger.info("<STR_LIT>", kwargs['<STR_LIT:input>'][<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>TRJCONV = gromacs.trjconv<EOL>kwargs['<STR_LIT:input>'] = [groupname]<EOL>logger.info("<STR_LIT>", kwargs['<STR_LIT:input>'][<NUM_LIT:0>])<EOL><DEDENT>kwargs.pop("<STR_LIT>", None)<EOL>NOTwater = "<STR_LIT>".format(**vars())  <EOL>with utilities.in_dir(self.dirname):<EOL><INDENT>if not self.check_file_exists(newxtc, resolve="<STR_LIT>", force=force):<EOL><INDENT>B = IndexBuilder(struct=self.tpr, selections=['<STR_LIT:@>'+NOTwater],<EOL>ndx=self.ndx, out_ndx=nowater_ndx)<EOL>B.combine(name_all=groupname, operation="<STR_LIT:|>", defaultgroups=True)<EOL>logger.debug("<STR_LIT>", nowater_ndx)<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>gromacs.tpbconv(s=self.tpr, o=newtpr, n=nowater_ndx, input=[groupname])<EOL>logger.info("<STR_LIT>", newndx)<EOL>gromacs.make_ndx(f=newtpr, o=newndx, input=['<STR_LIT:q>'], stderr=False, stdout=False)<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>kwargs['<STR_LIT:s>'] = self.tpr<EOL>kwargs['<STR_LIT:f>'] = self.xtc<EOL>kwargs['<STR_LIT:n>'] = nowater_ndx<EOL>kwargs['<STR_LIT:o>'] = newxtc<EOL>TRJCONV(**kwargs)<EOL>logger.info("<STR_LIT>")<EOL>for ext in '<STR_LIT>', '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>kwargs['<STR_LIT:o>'] = self.filename(newtpr, ext=ext)<EOL>TRJCONV(dump=<NUM_LIT:0>, stdout=False, stderr=False, **kwargs)  <EOL><DEDENT>except:<EOL><INDENT>logger.exception("<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL><DEDENT><DEDENT><DEDENT>logger.info("<STR_LIT>")<EOL><DEDENT>self.nowater[self.rp(newxtc)] = Transformer(dirname=self.dirname, s=newtpr,<EOL>f=newxtc, n=newndx, force=force)<EOL>return {'<STR_LIT>':self.rp(newtpr), '<STR_LIT>':self.rp(newxtc), '<STR_LIT>':self.rp(newndx)}<EOL>

Write xtc and tpr with water (by resname) removed.

        :Keywords:
           *os*
              Name of the output tpr file; by default use the original but
              insert "nowater" before suffix.
           *o*
              Name of the output trajectory; by default use the original name but
              insert "nowater" before suffix.
           *on*
              Name of a new index file (without water).
           *compact*
              ``True``: write a compact and centered trajectory
              ``False``: use trajectory as it is [``False``]
           *centergroup*
              Index group used for centering ["Protein"]

              .. Note:: If *input* is provided (see below under *kwargs*)
                        then *centergroup* is ignored and the group for
                        centering is taken as the first entry in *input*.

           *resn*
              Residue name of the water molecules; all these residues are excluded.
           *groupname*
              Name of the group that is generated by subtracting all waters
              from the system.
           *force* : Boolean
             - ``True``: overwrite existing trajectories
             - ``False``: throw a IOError exception
             - ``None``: skip existing and log a warning [default]
           *kwargs*
              are passed on to :func:`gromacs.cbook.trj_compact` (unless the
              values have to be set to certain values such as s, f, n, o
              keywords). The *input* keyword is always mangled: Only the first
              entry (the group to centre the trajectory on) is kept, and as a
              second group (the output group) *groupname* is used.

        :Returns:
              dictionary with keys *tpr*, *xtc*, *ndx* which are the names of the
              the new files

        .. warning:: The input tpr file should *not* have *any position restraints*;
                     otherwise Gromacs will throw a hissy-fit and say

                     *Software inconsistency error: Position restraint coordinates are
                     missing*

                     (This appears to be a bug in Gromacs 4.x.)


def keep_protein_only(self, os=None, o=None, on=None, compact=False,<EOL>groupname="<STR_LIT>", **kwargs):

force = kwargs.pop('<STR_LIT>', self.force)<EOL>suffix = '<STR_LIT>'<EOL>newtpr = self.outfile(self.infix_filename(os, self.tpr, '<STR_LIT:_>'+suffix))<EOL>newxtc = self.outfile(self.infix_filename(o, self.xtc, '<STR_LIT:_>'+suffix))<EOL>newndx = self.outfile(self.infix_filename(on, self.tpr, '<STR_LIT:_>'+suffix, '<STR_LIT>'))<EOL>selection_ndx = suffix+"<STR_LIT>"    <EOL>if compact:<EOL><INDENT>TRJCONV = trj_compact<EOL>_input = kwargs.get('<STR_LIT:input>', ['<STR_LIT>'])<EOL>kwargs['<STR_LIT:input>'] = [_input[<NUM_LIT:0>], groupname]  <EOL>del _input<EOL><DEDENT>else:<EOL><INDENT>TRJCONV = gromacs.trjconv<EOL>kwargs['<STR_LIT:input>'] = [groupname]<EOL><DEDENT>selections = ['<STR_LIT:@>'+sel for sel in ['<STR_LIT>'] + kwargs.pop('<STR_LIT>',[])]<EOL>with utilities.in_dir(self.dirname):<EOL><INDENT>if not self.check_file_exists(newxtc, resolve="<STR_LIT>", force=force):<EOL><INDENT>B = IndexBuilder(struct=self.tpr, selections=selections,<EOL>ndx=self.ndx, out_ndx=selection_ndx)<EOL>B.combine(name_all=groupname, operation="<STR_LIT:|>", defaultgroups=True)<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>gromacs.tpbconv(s=self.tpr, o=newtpr, n=selection_ndx, input=[groupname])<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>gromacs.make_ndx(f=newtpr, o=newndx, input=['<STR_LIT:q>'], stderr=False, stdout=False)<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>kwargs['<STR_LIT:s>'] = self.tpr<EOL>kwargs['<STR_LIT:f>'] = self.xtc<EOL>kwargs['<STR_LIT:n>'] = selection_ndx<EOL>kwargs['<STR_LIT:o>'] = newxtc<EOL>TRJCONV(**kwargs)<EOL>logger.info("<STR_LIT>")<EOL>for ext in '<STR_LIT>', '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>kwargs['<STR_LIT:o>'] = self.filename(newtpr, ext=ext)<EOL>TRJCONV(dump=<NUM_LIT:0>, stdout=False, stderr=False, **kwargs)  <EOL><DEDENT>except:<EOL><INDENT>logger.exception("<STR_LIT>"<EOL>"<STR_LIT>" % vars())<EOL><DEDENT><DEDENT><DEDENT>logger.info("<STR_LIT>")<EOL><DEDENT>self.proteinonly[self.rp(newxtc)] = Transformer(dirname=self.dirname, s=newtpr,<EOL>f=newxtc, n=newndx, force=force)<EOL>return {'<STR_LIT>':self.rp(newtpr), '<STR_LIT>':self.rp(newxtc), '<STR_LIT>':self.rp(newndx)}<EOL>

Write xtc and tpr only containing the protein.

        :Keywords:
           *os*
              Name of the output tpr file; by default use the original but
              insert "proteinonly" before suffix.
           *o*
              Name of the output trajectory; by default use the original name but
              insert "proteinonly" before suffix.
           *on*
              Name of a new index file.
           *compact*
              ``True``: write a compact and centered trajectory
              ``False``: use trajectory as it is [``False``]
           *groupname*
              Name of the protein-only group.
           *keepalso*
              List of literal make_ndx selections of additional groups that should
              be kept, e.g. ['resname DRUG', 'atom 6789'].
           *force* : Boolean
             - ``True``: overwrite existing trajectories
             - ``False``: throw a IOError exception
             - ``None``: skip existing and log a warning [default]
           *kwargs*
              are passed on to :func:`gromacs.cbook.trj_compact` (unless the
              values have to be set to certain values such as s, f, n, o
              keywords). The *input* keyword is always mangled: Only the first
              entry (the group to centre the trajectory on) is kept, and as a
              second group (the output group) *groupname* is used.

        :Returns:
              dictionary with keys *tpr*, *xtc*, *ndx* which are the names of the
              the new files

        .. warning:: The input tpr file should *not* have *any position restraints*;
                     otherwise Gromacs will throw a hissy-fit and say

                     *Software inconsistency error: Position restraint coordinates are
                     missing*

                     (This appears to be a bug in Gromacs 4.x.)


kwargs.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>kw_fit = {}<EOL>for k in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:input>'):<EOL><INDENT>if k in kwargs:<EOL><INDENT>kw_fit[k] = kwargs.pop(k)<EOL><DEDENT><DEDENT>kwargs['<STR_LIT:input>'] = kwargs.pop('<STR_LIT>', ['<STR_LIT>'])<EOL>kwargs['<STR_LIT>'] = kw_fit['<STR_LIT>'] = kwargs.pop('<STR_LIT>', self.force)<EOL>paths = self.strip_water(**kwargs)    <EOL>transformer_nowater = self.nowater[paths['<STR_LIT>']]  <EOL>return transformer_nowater.fit(**kw_fit)          <EOL>

Strip water and fit to the remaining system.

        First runs :meth:`strip_water` and then :meth:`fit`; see there
        for arguments.

        - *strip_input* is used for :meth:`strip_water` (but is only useful in
          special cases, e.g. when there is no Protein group defined. Then set
          *strip_input* = ``['Other']``.

        - *input* is passed on to :meth:`fit` and can contain the
          ``[center_group, fit_group, output_group]``

        - *fitgroup* is only passed to :meth:`fit` and just contains
          the group to fit to ("backbone" by default)

          .. warning:: *fitgroup* can only be a Gromacs default group and not
                       a custom group (because the indices change after stripping)

        - By default *fit* = "rot+trans" (and *fit* is passed to :meth:`fit`,
          together with the *xy* = ``False`` keyword)

        .. Note:: The call signature of :meth:`strip_water` is somewhat different from this one.


<EOL>return os.path.join(os.path.dirname(args[<NUM_LIT:0>]), *args[<NUM_LIT:1>:])<EOL>


self.args = args<EOL>self.kwargs = kwargs<EOL>

Set up the command class.

        The arguments can always be provided as standard positional
        arguments such as

          ``"-c", "config.conf", "-o", "output.dat", "--repeats=3", "-v", "input.dat"``

        In addition one can also use keyword arguments such as

          ``c="config.conf", o="output.dat", repeats=3, v=True``

        These are automatically transformed appropriately according to
        simple rules:

        * Any single-character keywords are assumed to be POSIX-style
          options and will be prefixed with a single dash and the value
          separated by a space.

        * Any other keyword is assumed to be a GNU-style long option
          and thus will be prefixed with two dashes and the value will
          be joined directly with an equals sign and no space.

        If this does not work (as for instance for the options of the
        UNIX ``find`` command) then provide options and values in the
        sequence of positional arguments.

        *Example*

        Create a ``Ls`` class whose instances execute the ``ls`` command::

          LS = type("LS", (gromacs.core.Command,), {'command_name': 'ls'})
          ls = LS()
          ls()        # lists directory like ls
          ls(l=True)  # lists directory like ls -l

        Now create an instance that performs a long directory listing by
        default::

          lslong = LS(l=True)
          lslong()    # like ls -l


_args, _kwargs = self._combine_arglist(args, kwargs)<EOL>results, p = self._run_command(*_args, **_kwargs)<EOL>return results<EOL>

Run the command; args/kwargs are added or replace the ones given to the constructor.


def _combine_arglist(self, args, kwargs):

_args = self.args + args<EOL>_kwargs = self.kwargs.copy()<EOL>_kwargs.update(kwargs)<EOL>return _args, _kwargs<EOL>

Combine the default values and the supplied values.


def _run_command(self, *args, **kwargs):

<EOL>use_input = kwargs.pop('<STR_LIT>', True)<EOL>capturefile = None<EOL>if environment.flags['<STR_LIT>'] is True:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', PIPE)<EOL>kwargs.setdefault('<STR_LIT>', PIPE)<EOL><DEDENT>elif environment.flags['<STR_LIT>'] == "<STR_LIT:file>":<EOL><INDENT>if '<STR_LIT>' in kwargs and '<STR_LIT>' in kwargs:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>fn = environment.flags['<STR_LIT>']<EOL>capturefile = file(fn, "<STR_LIT:w>")   <EOL>if '<STR_LIT>' in kwargs and '<STR_LIT>' not in kwargs:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', capturefile)<EOL><DEDENT>else:<EOL><INDENT>kwargs.setdefault('<STR_LIT>', STDOUT)<EOL>kwargs.setdefault('<STR_LIT>', capturefile)<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>p = self.Popen(*args, **kwargs)<EOL>out, err = p.communicate(use_input=use_input) <EOL><DEDENT>except:<EOL><INDENT>if capturefile is not None:<EOL><INDENT>logger.error("<STR_LIT>", capturefile)<EOL><DEDENT>raise<EOL><DEDENT>finally:<EOL><INDENT>if capturefile is not None:<EOL><INDENT>capturefile.close()<EOL><DEDENT><DEDENT>rc = p.returncode<EOL>return (rc, out, err), p<EOL>

Execute the command; see the docs for __call__.

        :Returns: a tuple of the *results* tuple ``(rc, stdout, stderr)`` and
                  the :class:`Popen` instance.


def _commandline(self, *args, **kwargs):

<EOL>return [self.command_name] + self.transform_args(*args, **kwargs)<EOL>

Returns the command line (without pipes) as a list.


<EOL>_args, _kwargs = self._combine_arglist(args, kwargs)<EOL>return self._commandline(*_args, **_kwargs)<EOL>

Returns the commandline that run() uses (without pipes).


stderr = kwargs.pop('<STR_LIT>', None)     <EOL>if stderr is False:                     <EOL><INDENT>stderr = PIPE<EOL><DEDENT>elif stderr is True:<EOL><INDENT>stderr = None                       <EOL><DEDENT>stdout = kwargs.pop('<STR_LIT>', None)     <EOL>if stdout is False:                     <EOL><INDENT>stdout = PIPE<EOL><DEDENT>elif stdout is True:<EOL><INDENT>stdout = None                       <EOL><DEDENT>stdin = kwargs.pop('<STR_LIT>', None)<EOL>input = kwargs.pop('<STR_LIT:input>', None)<EOL>use_shell = kwargs.pop('<STR_LIT>', False)<EOL>if input:<EOL><INDENT>stdin = PIPE<EOL>if isinstance(input, six.string_types) and not input.endswith('<STR_LIT:\n>'):<EOL><INDENT>input = six.text_type(input) + '<STR_LIT:\n>'<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>input = '<STR_LIT:\n>'.join(map(six.text_type, input)) + '<STR_LIT:\n>'<EOL><DEDENT>except TypeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT>cmd = self._commandline(*args, **kwargs)   <EOL>try:<EOL><INDENT>p = PopenWithInput(cmd, stdin=stdin, stderr=stderr, stdout=stdout,<EOL>universal_newlines=True, input=input, shell=use_shell)<EOL><DEDENT>except OSError as err:<EOL><INDENT>logger.error("<STR_LIT:U+0020>".join(cmd))            <EOL>if err.errno == errno.ENOENT:<EOL><INDENT>errmsg = "<STR_LIT>".format(self.command_name)<EOL>logger.fatal(errmsg)<EOL>raise OSError(errmsg)<EOL><DEDENT>else:<EOL><INDENT>logger.exception("<STR_LIT>".format(self.command_name))<EOL>raise<EOL><DEDENT><DEDENT>logger.debug(p.command_string)<EOL>return p<EOL>

Returns a special Popen instance (:class:`PopenWithInput`).

        The instance has its input pre-set so that calls to
        :meth:`~PopenWithInput.communicate` will not need to supply
        input. This is necessary if one wants to chain the output from
        one command to an input from another.

        :TODO:
          Write example.


def transform_args(self, *args, **kwargs):

options = []<EOL>for option,value in kwargs.items():<EOL><INDENT>if not option.startswith('<STR_LIT:->'):<EOL><INDENT>if len(option) == <NUM_LIT:1>:<EOL><INDENT>option = '<STR_LIT:->' + option         <EOL><DEDENT>else:<EOL><INDENT>option = '<STR_LIT>' + option        <EOL><DEDENT><DEDENT>if value is True:<EOL><INDENT>options.append(option)<EOL>continue<EOL><DEDENT>elif value is False:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(option))<EOL><DEDENT>if option[:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>options.append(option + '<STR_LIT:=>' + str(value))    <EOL><DEDENT>else:<EOL><INDENT>options.extend((option, str(value)))         <EOL><DEDENT><DEDENT>return options + list(args)<EOL>

Transform arguments and return them as a list suitable for Popen.


print("<STR_LIT>".format(self.command_name))<EOL>print(self.__doc__)<EOL>if long:<EOL><INDENT>print("<STR_LIT>")<EOL>print(self.__call__.__doc__)<EOL><DEDENT>

Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.


return self.run(*args, **kwargs)<EOL>

Run command with the given arguments::

           rc,stdout,stderr = command(*args, input=None, **kwargs)

        All positional parameters *args* and all gromacs *kwargs* are passed on
        to the Gromacs command. input and output keywords allow communication
        with the process via the python subprocess module.

        :Arguments:
          *input* : string, sequence
             to be fed to the process' standard input;
             elements of a sequence are concatenated with
             newlines, including a trailing one    [``None``]
          *stdin*
             ``None`` or automatically set to ``PIPE`` if input given [``None``]
          *stdout*
             how to handle the program's stdout stream [``None``]

             filehandle
                    anything that behaves like a file object
             ``None`` or ``True``
                    to see  output on screen
             ``False`` or ``PIPE``
                     returns the output as a string in  the stdout parameter

          *stderr*
             how to handle the stderr stream [``None``]

             ``STDOUT``
                     merges standard error with the standard out stream
             ``False`` or ``PIPE``
                     returns the output as a string in the stderr return parameter
             ``None`` or ``True``
                     keeps it on stderr (and presumably on screen)

        Depending on the value of the GromacsWrapper flag
        :data:`gromacs.environment.flags```['capture_output']`` the above
        default behaviour can be different.

        All other kwargs are passed on to the Gromacs tool.

        :Returns:

           The shell return code rc of the command is always returned. Depending
           on the value of output, various strings are filled with output from the
           command.

        :Notes:

           In order to chain different commands via pipes one must use the special
           :class:`PopenWithInput` object (see :meth:`GromacsCommand.Popen` method) instead of the simple
           call described here and first construct the pipeline explicitly and then
           call the :meth:`PopenWithInput.communicate` method.

           ``STDOUT`` and ``PIPE`` are objects provided by the :mod:`subprocess` module. Any
           python stream can be provided and manipulated. This allows for chaining
           of commands. Use ::

              from subprocess import PIPE, STDOUT

           when requiring these special streams (and the special boolean
           switches ``True``/``False`` cannot do what you need.)

           (TODO: example for chaining commands)


doc = kwargs.pop('<STR_LIT>', None)  <EOL>self.__failuremode = None<EOL>self.failuremode = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>self.gmxargs = self._combineargs(*args, **kwargs)<EOL>self._doc_cache = None<EOL>

Set up the command with gromacs flags as keyword arguments.

        The following  are generic instructions; refer  to the Gromacs
        command  usage information  that should  have  appeared before
        this generic documentation.

        As an example, a generic Gromacs command could use the following flags::

          cmd = GromacsCommand('v', f=['md1.xtc','md2.xtc'], o='processed.xtc', t=200, ...)

        which would correspond to running the command in the shell as ::

          GromacsCommand -v -f md1.xtc md2.xtc -o processed.xtc -t 200

        **Gromacs command line arguments**

           Gromacs boolean switches (such as ``-v``) are given as python
           positional arguments (``'v'``) or as keyword argument (``v=True``);
           note the quotes in the first case. Negating a boolean switch can be
           done with ``'nov'``, ``nov=True`` or ``v=False`` (and even ``nov=False``
           works as expected: it is the same as ``v=True``).

           Any Gromacs options that take parameters are handled as keyword
           arguments. If an option takes multiple arguments (such as the
           multi-file input ``-f file1 file2 ...``) then the list of files must be
           supplied as a python list.

           If a keyword has the python value ``None`` then it will *not* be
           added to the Gromacs command line; this allows for flexible
           scripting if it is not known in advance if an input file is
           needed. In this case the default value of the gromacs tool
           is used.

           Keywords must be legal python keywords or the interpreter raises a
           :exc:`SyntaxError` but of course Gromacs commandline arguments are
           not required to be legal python. In this case "quote" the option
           with an underscore (``_``) and the underscore will be silently
           stripped. For instance, ``-or`` translates to the illegal keyword
           ``or`` so it must be underscore-quoted::

              cmd(...., _or='mindistres.xvg')

        **Command execution**

           The command is executed with the :meth:`~GromacsCommand.run` method or by
           calling it as a function. The two next lines are equivalent::

             cmd(...)
             cmd.run(...)

           When the command is run one can override options that were given at
           initialization or one can add additional ones. The same rules for
           supplying Gromacs flags apply as described above.

        **Non-Gromacs keyword arguments**

           The other keyword arguments (listed below) are not passed on to the
           Gromacs tool but determine how the command class behaves. *They are
           only useful when instantiating a class*, i.e. they determine how
           this tool behaves during all future invocations although it can be
           changed by setting :attr:`failuremode`. This is mostly of interest
           to developers.

        :Keywords:
           *failure*
              determines how a failure of the gromacs command is treated; it
              can be one of the following:

              'raise'
                   raises GromacsError if command fails
              'warn'
                   issue a :exc:`GromacsFailureWarning`
              ``None``
                   just continue silently

           *doc* : string
              additional documentation (*ignored*) []

        .. versionchanged:: 0.6.0
           The *doc* keyword is now ignored (because it was not worth the effort to
           make it work with the lazy-loading of docs).


gmxargs = self.gmxargs.copy()<EOL>gmxargs.update(self._combineargs(*args, **kwargs))<EOL>return (), gmxargs<EOL>


def _combineargs(self, *args, **kwargs):

d = {arg: True for arg in args}   <EOL>d.update(kwargs)<EOL>return d<EOL>

Add switches as 'options' with value True to the options dict.


arglist = []<EOL>for flag, value in kwargs.items():<EOL><INDENT>flag = str(flag)<EOL>if flag.startswith('<STR_LIT:_>'):<EOL><INDENT>flag = flag[<NUM_LIT:1>:]                 <EOL><DEDENT>if not flag.startswith('<STR_LIT:->'):<EOL><INDENT>flag = '<STR_LIT:->' + flag               <EOL><DEDENT>if value is True:<EOL><INDENT>arglist.append(flag)            <EOL><DEDENT>elif value is False:<EOL><INDENT>if flag.startswith('<STR_LIT>'):<EOL><INDENT>arglist.append('<STR_LIT:->' + flag[<NUM_LIT:3>:])<EOL><DEDENT>else:<EOL><INDENT>arglist.append('<STR_LIT>' + flag[<NUM_LIT:1>:])  <EOL><DEDENT><DEDENT>elif value is None:<EOL><INDENT>pass                            <EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>arglist.extend([flag] + value) <EOL><DEDENT>except TypeError:<EOL><INDENT>arglist.extend([flag, value])  <EOL><DEDENT><DEDENT><DEDENT>return list(map(str, arglist))<EOL>

Build list of arguments from the dict; keys must be valid  gromacs flags.


result, p = super(GromacsCommand, self)._run_command(*args, **kwargs)<EOL>self.check_failure(result, command_string=p.command_string)<EOL>return result, p<EOL>

Execute the gromacs command; see the docs for __call__.


if(self.driver is not None):<EOL><INDENT>return [self.driver, self.command_name] + self.transform_args(*args, **kwargs)<EOL><DEDENT>return [self.command_name] + self.transform_args(*args, **kwargs)<EOL>

Returns the command line (without pipes) as a list. Inserts driver if present


newargs = self._combineargs(*args, **kwargs)<EOL>return self._build_arg_list(**newargs)<EOL>

Combine arguments and turn them into gromacs tool arguments.


if self._doc_cache is not None:<EOL><INDENT>return self._doc_cache<EOL><DEDENT>try:<EOL><INDENT>logging.disable(logging.CRITICAL)<EOL>rc, header, docs = self.run('<STR_LIT:h>', stdout=PIPE, stderr=PIPE, use_input=False)<EOL><DEDENT>except:<EOL><INDENT>logging.critical("<STR_LIT>".format(self.command_name))<EOL>self._doc_cache = "<STR_LIT>"<EOL>return self._doc_cache<EOL><DEDENT>finally:<EOL><INDENT>logging.disable(logging.NOTSET)<EOL><DEDENT>m = re.match(self.doc_pattern, docs, re.DOTALL)<EOL>if m is None:<EOL><INDENT>m = re.match(self.doc_pattern, header, re.DOTALL)<EOL>if m is None:<EOL><INDENT>self._doc_cache = "<STR_LIT>"<EOL>return self._doc_cache<EOL><DEDENT><DEDENT>self._doc_cache = m.group('<STR_LIT>')<EOL>return self._doc_cache<EOL>

Extract standard gromacs doc

        Extract by running the program and chopping the header to keep from
        'DESCRIPTION' onwards.


kwargs.setdefault('<STR_LIT>', True)   <EOL>self.input = kwargs.pop('<STR_LIT:input>', None)<EOL>if six.PY2 and self.input is not None:<EOL><INDENT>self.input = self.input.encode('<STR_LIT:utf-8>')<EOL><DEDENT>self.command = args[<NUM_LIT:0>]<EOL>try:<EOL><INDENT>input_string = '<STR_LIT>' +self.input.replace('<STR_LIT:\n>','<STR_LIT>') + '<STR_LIT>'  <EOL><DEDENT>except (TypeError, AttributeError):<EOL><INDENT>input_string = "<STR_LIT>"<EOL><DEDENT>self.command_string = input_string + "<STR_LIT:U+0020>".join(self.command)<EOL>super(PopenWithInput,self).__init__(*args, **kwargs)<EOL>

Initialize with the standard :class:`subprocess.Popen` arguments.

        :Keywords:
           *input*
               string that is piped into the command


if use_input:<EOL><INDENT>return super(PopenWithInput, self).communicate(self.input)<EOL><DEDENT>else:<EOL><INDENT>return super(PopenWithInput, self).communicate()<EOL><DEDENT>

Run the command, using the input that was set up on __init__ (for *use_input* = ``True``)


def tool_factory(clsname, name, driver, base=GromacsCommand):

clsdict = {<EOL>'<STR_LIT>': name,<EOL>'<STR_LIT>': driver,<EOL>'<STR_LIT>': property(base._get_gmx_docs)<EOL>}<EOL>return type(clsname, (base,), clsdict)<EOL>

Factory for GromacsCommand derived types.


return name.replace('<STR_LIT:->', '<STR_LIT:_>').capitalize()<EOL>

Turns tool names into valid identifiers.

    :param name: tool name
    :return: valid identifier


execs = []<EOL>for exe in os.listdir(path):<EOL><INDENT>fullexe = os.path.join(path, exe)<EOL>if (os.access(fullexe, os.X_OK) and not os.path.isdir(fullexe) and<EOL>exe not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>']):<EOL><INDENT>execs.append(exe)<EOL><DEDENT><DEDENT>return execs<EOL>

Find executables in a path.

    Searches executables in a directory excluding some know commands
    unusable with GromacsWrapper.

    :param path: dirname to search for
    :return: list of executables


logger.debug("<STR_LIT>")<EOL>drivers = config.get_tool_names()<EOL>if len(drivers) == <NUM_LIT:0> and '<STR_LIT>' in os.environ:<EOL><INDENT>drivers = find_executables(os.environ['<STR_LIT>'])<EOL><DEDENT>if len(drivers) == <NUM_LIT:0> or len(drivers) > <NUM_LIT:4>:<EOL><INDENT>drivers = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>append = config.cfg.getboolean('<STR_LIT>', '<STR_LIT>', fallback=True)<EOL>tools = {}<EOL>for driver in drivers:<EOL><INDENT>suffix = driver.partition('<STR_LIT:_>')[<NUM_LIT:2>]<EOL>try:<EOL><INDENT>out = subprocess.check_output([driver, '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>'])<EOL>for line in out.splitlines()[<NUM_LIT:5>:-<NUM_LIT:1>]:<EOL><INDENT>line = str(line.decode('<STR_LIT:ascii>'))   <EOL>if line[<NUM_LIT:4>] != '<STR_LIT:U+0020>':<EOL><INDENT>name = line[<NUM_LIT:4>:line.index('<STR_LIT:U+0020>', <NUM_LIT:4>)]<EOL>fancy = make_valid_identifier(name)<EOL>if suffix and append:<EOL><INDENT>fancy = '<STR_LIT>'.format(fancy, suffix)<EOL><DEDENT>tools[fancy] = tool_factory(fancy, name, driver)<EOL><DEDENT><DEDENT><DEDENT>except (subprocess.CalledProcessError, OSError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not tools:<EOL><INDENT>errmsg = "<STR_LIT>".format(drivers)<EOL>logger.debug(errmsg)<EOL>raise GromacsToolLoadingError(errmsg)<EOL><DEDENT>logger.debug("<STR_LIT>".format(len(tools)))<EOL>return tools<EOL>

Load Gromacs 2018/2016/5.x tools automatically using some heuristic.

    Tries to load tools (1) using the driver from configured groups (2) and
    falls back to automatic detection from ``GMXBIN`` (3) then to rough guesses.

    In all cases the command ``gmx help`` is ran to get all tools available.

    :return: dict mapping tool names to GromacsCommand classes


logger.debug("<STR_LIT>")<EOL>names = config.get_tool_names()<EOL>if len(names) == <NUM_LIT:0> and '<STR_LIT>' in os.environ:<EOL><INDENT>names = find_executables(os.environ['<STR_LIT>'])<EOL><DEDENT>if len(names) == <NUM_LIT:0> or len(names) > len(V4TOOLS) * <NUM_LIT:4>:<EOL><INDENT>names = list(V4TOOLS)<EOL><DEDENT>names.extend(config.get_extra_tool_names())<EOL>tools = {}<EOL>for name in names:<EOL><INDENT>fancy = make_valid_identifier(name)<EOL>tools[fancy] = tool_factory(fancy, name, None)<EOL><DEDENT>if not tools:<EOL><INDENT>errmsg = "<STR_LIT>"<EOL>logger.debug(errmsg)<EOL>raise GromacsToolLoadingError(errmsg)<EOL><DEDENT>logger.debug("<STR_LIT>".format(len(tools)))<EOL>return tools<EOL>

Load Gromacs 4.x tools automatically using some heuristic.

    Tries to load tools (1) in configured tool groups (2) and fails back  to
    automatic detection from ``GMXBIN`` (3) then to a prefilled list.

    Also load any extra tool configured in ``~/.gromacswrapper.cfg``

    :return: dict mapping tool names to GromacsCommand classes


ndxs = []<EOL>struct = None<EOL>for fname in args:<EOL><INDENT>if fname.endswith('<STR_LIT>'):<EOL><INDENT>ndxs.append(fname)<EOL><DEDENT>else:<EOL><INDENT>if struct is not None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>struct = fname<EOL><DEDENT><DEDENT>fd, multi_ndx = tempfile.mkstemp(suffix='<STR_LIT>', prefix='<STR_LIT>')<EOL>os.close(fd)<EOL>atexit.register(os.unlink, multi_ndx)<EOL>if struct:<EOL><INDENT>make_ndx = registry['<STR_LIT>'](f=struct, n=ndxs, o=multi_ndx)<EOL><DEDENT>else:<EOL><INDENT>make_ndx = registry['<STR_LIT>'](n=ndxs, o=multi_ndx)<EOL><DEDENT>_, _, _ = make_ndx(input=['<STR_LIT:q>'], stdout=False, stderr=False)<EOL>return multi_ndx<EOL>

Takes one or more index files and optionally one structure file and
    returns a path for a new merged index file.

    :param args: index files and zero or one structure file
    :return: path for the new merged index file


if type(s) is not str:<EOL><INDENT>return s<EOL><DEDENT>for converter in int, float, str:   <EOL><INDENT>try:<EOL><INDENT>s = [converter(i) for i in s.split()]<EOL>if len(s) == <NUM_LIT:1>:<EOL><INDENT>return s[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return numpy.array(s)<EOL><DEDENT><DEDENT>except (ValueError, AttributeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>".format(s))<EOL>

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.


@contextmanager<EOL>def openany(datasource, mode='<STR_LIT>', reset=True):

stream = anyopen(datasource, mode=mode, reset=reset)<EOL>try:<EOL><INDENT>yield stream<EOL><DEDENT>finally:<EOL><INDENT>stream.close()<EOL><DEDENT>

Context manager for :func:`anyopen`.

    Open the `datasource` and close it when the context of the :keyword:`with`
    statement exits.

    `datasource` can be a filename or a stream (see :func:`isstream`). A stream
    is reset to its start if possible (via :meth:`~io.IOBase.seek` or
    :meth:`~cString.StringIO.reset`).

    The advantage of this function is that very different input sources
    ("streams") can be used for a "file", ranging from files on disk (including
    compressed files) to open file objects to sockets and strings---as long as
    they have a file-like interface.

    :Arguments:
      *datasource*
           a file or a stream
      *mode*
           {'r', 'w'} (optional), open in r(ead) or w(rite) mode
      *reset*
           bool (optional) try to read (`mode` 'r') the stream from the
           start [``True``]

    **Example**

    Open a gzipped file and process it line by line::

        with openany("input.pdb.gz") as pdb:
            for line in pdb:
                if line.startswith('ATOM'):
                    print(line)

    Open a URL and read it::

       import urllib2
       with openany(urllib2.urlopen("https://www.mdanalysis.org/")) as html:
           print(html.read())

    .. SeeAlso::
       :func:`anyopen`


def anyopen(datasource, mode='<STR_LIT>', reset=True):

handlers = {'<STR_LIT>': bz2_open, '<STR_LIT>': gzip.open, '<STR_LIT>': open}<EOL>if mode.startswith('<STR_LIT:r>'):<EOL><INDENT>if isstream(datasource):<EOL><INDENT>stream = datasource<EOL>try:<EOL><INDENT>filename = str(stream.name)  <EOL><DEDENT>except AttributeError:<EOL><INDENT>filename = "<STR_LIT>"<EOL><DEDENT>if reset:<EOL><INDENT>try:<EOL><INDENT>stream.reset()<EOL><DEDENT>except (AttributeError, IOError):<EOL><INDENT>try:<EOL><INDENT>stream.seek(<NUM_LIT:0>)<EOL><DEDENT>except (AttributeError, IOError):<EOL><INDENT>warnings.warn("<STR_LIT>"<EOL>"<STR_LIT>".format(filename),<EOL>category=StreamWarning)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>stream = None<EOL>filename = datasource<EOL>for ext in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):  <EOL><INDENT>openfunc = handlers[ext]<EOL>stream = _get_stream(datasource, openfunc, mode=mode)<EOL>if stream is not None:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if stream is None:<EOL><INDENT>raise IOError(errno.EIO, "<STR_LIT>".format(**vars()), repr(filename))<EOL><DEDENT><DEDENT><DEDENT>elif mode.startswith('<STR_LIT:w>') or mode.startswith('<STR_LIT:a>'):  <EOL><INDENT>if isstream(datasource):<EOL><INDENT>stream = datasource<EOL>try:<EOL><INDENT>filename = str(stream.name)  <EOL><DEDENT>except AttributeError:<EOL><INDENT>filename = "<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>stream = None<EOL>filename = datasource<EOL>name, ext = os.path.splitext(filename)<EOL>if ext.startswith('<STR_LIT:.>'):<EOL><INDENT>ext = ext[<NUM_LIT:1>:]<EOL><DEDENT>if not ext in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>ext = '<STR_LIT>'  <EOL><DEDENT>openfunc = handlers[ext]<EOL>stream = openfunc(datasource, mode=mode)<EOL>if stream is None:<EOL><INDENT>raise IOError(errno.EIO, "<STR_LIT>".format(**vars()), repr(filename))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise NotImplementedError("<STR_LIT>".format(**vars()))<EOL><DEDENT>try:<EOL><INDENT>stream.name = filename<EOL><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>pass  <EOL><DEDENT>return stream<EOL>

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

    `datasource` can be a filename or a stream (see :func:`isstream`). By
    default, a stream is reset to its start if possible (via
    :meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.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 :class:`file` or :func:`open`) or a stream (e.g. from
        :func:`urllib2.urlopen` or :class:`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

    .. SeeAlso::
       :func:`openany` to be used with the :keyword:`with` statement.


def _get_stream(filename, openfunction=open, mode='<STR_LIT:r>'):

try:<EOL><INDENT>stream = openfunction(filename, mode=mode)<EOL><DEDENT>except (IOError, OSError) as err:<EOL><INDENT>if errno.errorcode[err.errno] in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>six.reraise(*sys.exc_info())<EOL><DEDENT>return None<EOL><DEDENT>if mode.startswith('<STR_LIT:r>'):<EOL><INDENT>try:<EOL><INDENT>stream.readline()<EOL><DEDENT>except IOError:<EOL><INDENT>stream.close()<EOL>stream = None<EOL><DEDENT>except:<EOL><INDENT>stream.close()<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>stream.close()<EOL>stream = openfunction(filename, mode=mode)<EOL><DEDENT><DEDENT>return stream<EOL>

Return open stream if *filename* can be opened with *openfunction* or else ``None``.


return hasattr(obj, m) and callable(getattr(obj, m))<EOL>

Return ``True`` if object *obj* contains the method *m*.

    .. versionadded:: 0.7.1


signature_methods = ("<STR_LIT>",)<EOL>alternative_methods = (<EOL>("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"),<EOL>("<STR_LIT>", "<STR_LIT>", "<STR_LIT>"))<EOL>for m in signature_methods:<EOL><INDENT>if not hasmethod(obj, m):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>alternative_results = [<EOL>numpy.all([hasmethod(obj, m) for m in alternatives])<EOL>for alternatives in alternative_methods]<EOL>return numpy.any(alternative_results)<EOL>

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

    .. SeeAlso::
       :mod:`io`

    .. versionadded:: 0.7.1


if len(x) == <NUM_LIT:1>:<EOL><INDENT>return amino_acid_codes[x.upper()]<EOL><DEDENT>elif len(x) == <NUM_LIT:3>:<EOL><INDENT>return inverse_aa_codes[x.upper()]<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>" % x)<EOL><DEDENT>

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


startdir = os.getcwd()<EOL>try:<EOL><INDENT>try:<EOL><INDENT>os.chdir(directory)<EOL>logger.debug("<STR_LIT>".format(**vars()))<EOL><DEDENT>except OSError as err:<EOL><INDENT>if create and err.errno == errno.ENOENT:<EOL><INDENT>os.makedirs(directory)<EOL>os.chdir(directory)<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL><DEDENT>else:<EOL><INDENT>logger.exception("<STR_LIT>".format(**vars()))<EOL>raise<EOL><DEDENT><DEDENT>yield os.getcwd()<EOL><DEDENT>finally:<EOL><INDENT>os.chdir(startdir)<EOL><DEDENT>

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.


if None in args:<EOL><INDENT>return None<EOL><DEDENT>return os.path.realpath(<EOL>os.path.expandvars(os.path.expanduser(os.path.join(*args))))<EOL>

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

    Expands ``~`` and environment variables such as :envvar:`$HOME`.

    Returns ``None`` if any of the args is none.


<EOL>root,extension = os.path.splitext(filename)<EOL>if suffices is None:<EOL><INDENT>suffices = []<EOL><DEDENT>else:<EOL><INDENT>suffices = withextsep(suffices)<EOL><DEDENT>extensions = [extension] + suffices  <EOL>for ext in extensions:<EOL><INDENT>fn = root + ext<EOL>if os.path.exists(fn):<EOL><INDENT>return fn<EOL><DEDENT><DEDENT>return None<EOL>

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 (:data:`os.path.extsep`) or not

    :Returns: The first match or ``None``.


def dottify(x):<EOL><INDENT>if x.startswith(os.path.extsep):<EOL><INDENT>return x<EOL><DEDENT>return os.path.extsep + x<EOL><DEDENT>return [dottify(x) for x in asiterable(extensions)]<EOL>

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


for root, dirs, files in os.walk(directory):<EOL><INDENT>for basename in files:<EOL><INDENT>if fnmatch.fnmatch(basename, pattern):<EOL><INDENT>filename = os.path.join(root, basename)<EOL>yield filename<EOL><DEDENT><DEDENT><DEDENT>

Find files recursively under *directory*, matching *pattern* (generator).

    *pattern* is a UNIX-style glob pattern as used ny :func:`fnmatch.fnmatch`.

    Recipe by Bruno Oliveira from
    http://stackoverflow.com/questions/2186525/use-a-glob-to-find-files-recursively-in-python


def is_exe(fpath):<EOL><INDENT>return os.path.isfile(fpath) and os.access(fpath, os.X_OK)<EOL><DEDENT>fpath, fname = os.path.split(program)<EOL>if fpath:<EOL><INDENT>real_program = realpath(program)<EOL>if is_exe(real_program):<EOL><INDENT>return real_program<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for path in os.environ["<STR_LIT>"].split(os.pathsep):<EOL><INDENT>exe_file = os.path.join(path, program)<EOL>if is_exe(exe_file):<EOL><INDENT>return exe_file<EOL><DEDENT><DEDENT><DEDENT>return None<EOL>

Determine full path of executable *program* on :envvar:`PATH`.

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

    .. versionadded:: 0.5.1


if isinstance(obj, string_types):<EOL><INDENT>return False    <EOL><DEDENT>if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>return True    <EOL><DEDENT>try:<EOL><INDENT>len(obj)       <EOL><DEDENT>except TypeError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>

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


if not iterable(obj):<EOL><INDENT>obj = [obj]<EOL><DEDENT>return obj<EOL>

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


return asiterable(obj)[<NUM_LIT:0>]<EOL>

Returns the first entry of a sequence or the obj.

    Treats strings as single objects.


try:<EOL><INDENT>os.unlink(path)<EOL><DEDENT>except OSError as err:<EOL><INDENT>if err.errno != errno.ENOENT:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>

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


for path in args:<EOL><INDENT>unlink_f(path)<EOL><DEDENT>unlink_gmx_backups(*args)<EOL>

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


for path in args:<EOL><INDENT>dirname, filename = os.path.split(path)<EOL>fbaks = glob.glob(os.path.join(dirname, '<STR_LIT:#>'+filename+'<STR_LIT>'))<EOL>for bak in fbaks:<EOL><INDENT>unlink_f(bak)<EOL><DEDENT><DEDENT>

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


try:<EOL><INDENT>os.makedirs(path)<EOL><DEDENT>except OSError as err:<EOL><INDENT>if err.errno != errno.EEXIST:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>

Create a directory *path* with subdirs but do not complain if it exists.

    This is like GNU ``mkdir -p path``.


<EOL>if f is None or o is None:<EOL><INDENT>return<EOL><DEDENT>target = o<EOL>infiles = asiterable(f)<EOL>logger.debug("<STR_LIT>".format("<STR_LIT:U+0020>".join(infiles), target))<EOL>with open(target, '<STR_LIT:w>') as out:<EOL><INDENT>rc = subprocess.call(['<STR_LIT>'] + infiles, stdout=out)<EOL><DEDENT>if rc != <NUM_LIT:0>:<EOL><INDENT>msg = "<STR_LIT>".format(rc, "<STR_LIT:U+0020>".join(infiles), target)<EOL>logger.exception(msg)<EOL>raise OSError(errno.EIO, msg, target)<EOL><DEDENT>

Concatenate files *f*=[...] and write to *o*


<EOL>from pylab import gcf, axes<EOL>numPlot -= <NUM_LIT:1>  <EOL>return axes(gcf().get_axes()[numPlot])<EOL>

Make subplot *numPlot* active on the canvas.

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


from pylab import gca, draw<EOL>if ax is None:<EOL><INDENT>ax = gca()<EOL><DEDENT>ax.legend_ = None<EOL>draw()<EOL>

Remove legend for axes or gca.

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


format = kwargs.pop('<STR_LIT>', "<STR_LIT>")<EOL>name_format = "<STR_LIT>" + format +"<STR_LIT>"<EOL>for f in itertools.chain.from_iterable(map(glob.glob, args)):<EOL><INDENT>m = NUMBERED_PDB.search(f)<EOL>if m is None:<EOL><INDENT>continue<EOL><DEDENT>num = int(m.group('<STR_LIT>'))<EOL>prefix = m.group('<STR_LIT>')<EOL>suffix = m.group('<STR_LIT>')<EOL>newname = name_format % vars()<EOL>logger.info("<STR_LIT>".format(**vars()))<EOL>try:<EOL><INDENT>os.rename(f, newname)<EOL><DEDENT>except OSError:<EOL><INDENT>logger.exception("<STR_LIT>")<EOL><DEDENT><DEDENT>

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"]


def _init_filename(self, filename=None, ext=None):

extension = ext or self.default_extension<EOL>filename = self.filename(filename, ext=extension, use_my_ext=True, set_default=True)<EOL>self.real_filename = os.path.realpath(filename)<EOL>

Initialize the current filename :attr:`FileUtils.real_filename` of the object.

        Bit of a hack.

        - The first invocation must have ``filename != None``; this will set a
          default filename with suffix :attr:`FileUtils.default_extension`
          unless another one was supplied.

        - Subsequent invocations either change the filename accordingly or
          ensure that the default filename is set with the proper suffix.


if filename is None:<EOL><INDENT>if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>self._filename = None        <EOL><DEDENT>if self._filename:<EOL><INDENT>filename = self._filename<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>my_ext = None<EOL><DEDENT>else:<EOL><INDENT>filename, my_ext = os.path.splitext(filename)<EOL>if set_default:                  <EOL><INDENT>self._filename = filename<EOL><DEDENT><DEDENT>if my_ext and use_my_ext:<EOL><INDENT>ext = my_ext<EOL><DEDENT>if ext is not None:<EOL><INDENT>if ext.startswith(os.extsep):<EOL><INDENT>ext = ext[<NUM_LIT:1>:]  <EOL><DEDENT>if ext != "<STR_LIT>":<EOL><INDENT>filename = filename + os.extsep + ext<EOL><DEDENT><DEDENT>return filename<EOL>

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.

        .. versionchanged:: 0.3.1
           An empty string as *ext* = "" will suppress appending an extension.


def check_file_exists(self, filename, resolve='<STR_LIT>', force=None):

def _warn(x):<EOL><INDENT>msg = "<STR_LIT>".format(x)<EOL>logger.warn(msg)<EOL>warnings.warn(msg)<EOL>return True<EOL><DEDENT>def _raise(x):<EOL><INDENT>msg = "<STR_LIT>".format(x)<EOL>logger.error(msg)<EOL>raise IOError(errno.EEXIST, x, msg)<EOL><DEDENT>solutions = {'<STR_LIT:ignore>': lambda x: False,      <EOL>'<STR_LIT>': lambda x: True,     <EOL>'<STR_LIT>': _warn,<EOL>'<STR_LIT>': _warn,<EOL>'<STR_LIT>': _raise,<EOL>'<STR_LIT>': _raise,<EOL>}<EOL>if force is True:<EOL><INDENT>resolve = '<STR_LIT:ignore>'<EOL><DEDENT>elif force is False:<EOL><INDENT>resolve = '<STR_LIT>'<EOL><DEDENT>if not os.path.isfile(filename):<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return solutions[resolve](filename)<EOL><DEDENT>

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 :exc:`UserWarning`
        "exception"
              raise :exc:`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


def infix_filename(self, name, default, infix, ext=None):

if name is None:<EOL><INDENT>p, oldext = os.path.splitext(default)<EOL>if ext is None:<EOL><INDENT>ext = oldext<EOL><DEDENT>if ext.startswith(os.extsep):<EOL><INDENT>ext = ext[<NUM_LIT:1>:]<EOL><DEDENT>name = self.filename(p+infix, ext=ext)<EOL><DEDENT>return name<EOL>

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


return self.seconds // <NUM_LIT><EOL>


return self.seconds // <NUM_LIT> - <NUM_LIT>*self.dhours<EOL>


return self.seconds - <NUM_LIT>*self.dhours - <NUM_LIT>*self.dminutes<EOL>


return <NUM_LIT>*self.days + self.seconds / <NUM_LIT><EOL>


substitutions = {<EOL>"<STR_LIT>": str(self.days),<EOL>"<STR_LIT>": "<STR_LIT>".format(self.dhours),<EOL>"<STR_LIT>": str(<NUM_LIT>*self.days + self.dhours),<EOL>"<STR_LIT>": "<STR_LIT>".format(self.dminutes),<EOL>"<STR_LIT>": "<STR_LIT>".format(self.dseconds),<EOL>}<EOL>s = fmt<EOL>for search, replacement in substitutions.items():<EOL><INDENT>s = s.replace(search, replacement)<EOL><DEDENT>return s<EOL>

Primitive string formatter.

        The only directives understood are the following:
          ============   ==========================
          Directive      meaning
          ============   ==========================
          %d             day as integer
          %H             hour  [00-23]
          %h             hours including days
          %M             minute as integer [00-59]
          %S             second as integer [00-59]
          ============   ==========================


def topology(struct=None, protein='<STR_LIT>',<EOL>top='<STR_LIT>',  dirname='<STR_LIT>',<EOL>posres="<STR_LIT>",<EOL>ff="<STR_LIT>", water="<STR_LIT>",<EOL>**pdb2gmx_args):

structure = realpath(struct)<EOL>new_struct = protein + '<STR_LIT>'<EOL>if posres is None:<EOL><INDENT>posres = protein + '<STR_LIT>'<EOL><DEDENT>pdb2gmx_args.update({'<STR_LIT:f>': structure, '<STR_LIT:o>': new_struct, '<STR_LIT:p>': top, '<STR_LIT:i>': posres,<EOL>'<STR_LIT>': ff, '<STR_LIT>': water})<EOL>with in_dir(dirname):<EOL><INDENT>logger.info("<STR_LIT>".format(**vars()))<EOL>gromacs.pdb2gmx(**pdb2gmx_args)<EOL><DEDENT>return {'<STR_LIT>': realpath(dirname, top),'<STR_LIT>': realpath(dirname, new_struct),'<STR_LIT>' : realpath(dirname, posres) }<EOL>

Build Gromacs topology files from pdb.

    :Keywords:
       *struct*
           input structure (**required**)
       *protein*
           name of the output files
       *top*
           name of the topology file
       *dirname*
           directory in which the new topology will be stored
       *ff*
           force field (string understood by ``pdb2gmx``); default
           "oplsaa"
       *water*
           water model (string), default "tip4p"
       *pdb2gmxargs*
           other arguments for ``pdb2gmx``

    .. note::
       At the moment this function simply runs ``pdb2gmx`` and uses
       the resulting topology file directly. If you want to create
       more complicated topologies and maybe also use additional itp
       files or make a protein itp file then you will have to do this
       manually.


def make_main_index(struct, selection='<STR_LIT>', ndx='<STR_LIT>', oldndx=None):

logger.info("<STR_LIT>".format(**vars()))<EOL>_,out,_ = gromacs.make_ndx(f=struct, n=oldndx, o=ndx, stdout=False,<EOL>input=("<STR_LIT>", "<STR_LIT:q>"))<EOL>groups = cbook.parse_ndxlist(out)<EOL>selection = selection.strip("<STR_LIT>")<EOL>selected_groups = [g for g in groups if g['<STR_LIT:name>'].lower() == selection.lower()]<EOL>if len(selected_groups) > <NUM_LIT:1>:<EOL><INDENT>logging.warn("<STR_LIT>")<EOL><DEDENT>if len(selected_groups) <= <NUM_LIT:0>:<EOL><INDENT>msg = "<STR_LIT>".format(selection, groups)<EOL>logging.error(msg)<EOL>raise ValueError(msg)<EOL><DEDENT>last = len(groups) - <NUM_LIT:1><EOL>assert last == groups[-<NUM_LIT:1>]['<STR_LIT>']<EOL>group = selected_groups[<NUM_LIT:0>]<EOL>_,out,_ = gromacs.make_ndx(f=struct, n=ndx, o=ndx,<EOL>stdout=False,<EOL>input=("<STR_LIT>".format(group['<STR_LIT>']),<EOL>"<STR_LIT>".format(last+<NUM_LIT:1>),<EOL>"<STR_LIT>",<EOL>"<STR_LIT>".format(last+<NUM_LIT:2>),<EOL>"<STR_LIT>",<EOL>"<STR_LIT:q>"))<EOL>return cbook.parse_ndxlist(out)<EOL>

Make index file with the special groups.

    This routine adds the group __main__ and the group __environment__
    to the end of the index file. __main__ contains what the user
    defines as the *central* and *most important* parts of the
    system. __environment__ is everything else.

    The template mdp file, for instance, uses these two groups for T-coupling.

    These groups are mainly useful if the default groups "Protein" and "Non-Protein"
    are not appropriate. By using symbolic names such as __main__ one
    can keep scripts more general.

    :Returns:
      *groups* is a list of dictionaries that describe the index groups. See
      :func:`gromacs.cbook.parse_ndxlist` for details.

    :Arguments:
      *struct* : filename
        structure (tpr, pdb, gro)
      *selection* : string
        is a ``make_ndx`` command such as ``"Protein"`` or ``r DRG`` which
        determines what is considered the main group for centering etc. It is
        passed directly to ``make_ndx``.
      *ndx* : string
         name of the final index file
      *oldndx* : string
         name of index file that should be used as a basis; if None
         then the ``make_ndx`` default groups are used.

    This routine is very dumb at the moment; maybe some heuristics will be
    added later as could be other symbolic groups such as __membrane__.