Search is not available for this dataset
text
stringlengths
75
104k
def delete_frames(self): """Delete all frames.""" for frame in glob.glob(self.frameglob): os.unlink(frame)
def gmx_resid(self, resid): """Returns resid in the Gromacs index by transforming with offset.""" try: gmx_resid = int(self.offset[resid]) except (TypeError, IndexError): gmx_resid = resid + self.offset except KeyError: raise KeyError("offset must be a...
def combine(self, name_all=None, out_ndx=None, operation='|', defaultgroups=False): """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 ...
def write(self, out_ndx=None, defaultgroups=False): """Write individual (named) groups to *out_ndx*.""" name_all, out_ndx = self.combine(operation=False, out_ndx=out_ndx, defaultgroups=defaultgroups) return out_ndx
def cat(self, out_ndx=None): """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 Nam...
def parse_selection(self, selection, name=None): """Retuns (groupname, filename) with index group.""" if type(selection) is tuple: # range process = self._process_range elif selection.startswith('@'): # verbatim make_ndx command process = self._pr...
def _process_command(self, command, name=None): """Process ``make_ndx`` command and return name and temp index file.""" self._command_counter += 1 if name is None: name = "CMD{0:03d}".format(self._command_counter) # Need to build it with two make_ndx calls because I cannot...
def _process_residue(self, selection, name=None): """Process residue/atom selection and return name and temp index file.""" if name is None: name = selection.replace(':', '_') # XXX: use _translate_residue() .... m = self.RESIDUE.match(selection) if not m: ...
def _process_range(self, selection, name=None): """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='CA'): """Translate selection for a single res to make_ndx syntax.""" m = self.RESIDUE.match(selection) if not m: errmsg = "Selection {selection!r} is not valid.".format(**vars()) logger.error(errmsg) ra...
def check_output(self, make_ndx_output, message=None, err=None): """Simple tests to flag problems with a ``make_ndx`` run.""" if message is None: message = "" else: message = '\n' + message def format(output, w=60): hrule = "====[ GromacsError (diagnos...
def outfile(self, p): """Path for an output file. If :attr:`outdir` is set then the path is ``outdir/basename(p)`` else just ``p`` """ if self.outdir is not None: return os.path.join(self.outdir, os.path.basename(p)) else: return p
def rp(self, *args): """Return canonical path to file under *dirname* with components *args* If *args* form an absolute path then just return it as the absolute path. """ try: p = os.path.join(*args) if os.path.isabs(p): return p except ...
def center_fit(self, **kwargs): """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 on...
def fit(self, xy=False, **kwargs): """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 defau...
def strip_water(self, os=None, o=None, on=None, compact=False, resn="SOL", groupname="notwater", **kwargs): """Write xtc and tpr with water (by resname) removed. :Keywords: *os* Name of the output tpr file; by default use the original but inser...
def strip_fit(self, **kwargs): """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 gro...
def _join_dirname(self, *args): """return os.path.join(os.path.dirname(args[0]), *args[1:])""" # extra function because I need to use it in a method that defines # the kwarg 'os', which collides with os.path... return os.path.join(os.path.dirname(args[0]), *args[1:])
def create(logger_name, logfile='gromacs.log'): """Create a top level logger. - The file logger logs everything (including DEBUG). - The console logger only logs INFO and above. Logging to a file and the console. See http://docs.python.org/library/logging.html?#logging-to-multiple-destination...
def _generate_template_dict(dirname): """Generate a list of included files *and* extract them to a temp space. Templates have to be extracted from the egg because they are used by external code. All template filenames are stored in :data:`config.templates`. """ return dict((resource_basename(fn...
def resource_basename(resource): """Last component of a resource (which always uses '/' as sep).""" if resource.endswith('/'): resource = resource[:-1] parts = resource.split('/') return parts[-1]
def get_template(t): """Find template file *t* and return its real path. *t* can be a single string or a list of strings. A string should be one of 1. a relative or absolute path, 2. a file in one of the directories listed in :data:`gromacs.config.path`, 3. a filename in the package template d...
def _get_template(t): """Return a single template *t*.""" if os.path.exists(t): # 1) Is it an accessible file? pass else: _t = t _t_found = False for d in path: # 2) search config.path p = os.path.join(d, _t) if os.path.e...
def get_configuration(filename=CONFIGNAME): """Reads and parses the configuration file. Default values are loaded and then replaced with the values from ``~/.gromacswrapper.cfg`` if that file exists. The global configuration instance :data:`gromacswrapper.config.cfg` is updated as are a number of g...
def setup(filename=CONFIGNAME): """Prepare a default GromacsWrapper global environment. 1) Create the global config file. 2) Create the directories in which the user can store template and config files. This function can be run repeatedly without harm. """ # setup() must be separate and ...
def check_setup(): """Check if templates directories are setup and issue a warning and help. Set the environment variable :envvar:`GROMACSWRAPPER_SUPPRESS_SETUP_CHECK` skip the check and make it always return ``True`` :return ``True`` if directories were found and ``False`` otherwise .. versio...
def set_gmxrc_environment(gmxrc): """Set the environment from ``GMXRC`` provided in *gmxrc*. Runs ``GMXRC`` in a subprocess and puts environment variables loaded by it into this Python environment. If *gmxrc* evaluates to ``False`` then nothing is done. If errors occur then only a warning will be ...
def get_tool_names(): """ Get tool names from all configured groups. :return: list of tool names """ names = [] for group in cfg.get('Gromacs', 'groups').split(): names.extend(cfg.get('Gromacs', group).split()) return names
def configuration(self): """Dict of variables that we make available as globals in the module. Can be used as :: globals().update(GMXConfigParser.configuration) # update configdir, templatesdir ... """ configuration = { 'configfilename': self....
def getpath(self, section, option): """Return option as an expanded path.""" return os.path.expanduser(os.path.expandvars(self.get(section, option)))
def getLogLevel(self, section, option): """Return the textual representation of logging level 'option' or the number. Note that option is always interpreted as an UPPERCASE string and hence integer log levels will not be recognized. .. SeeAlso: :mod:`logging` and :func:`logging...
def save(self, filename): """Pickle the whole collection to *filename*. If no extension is provided, ".collection" is appended. """ cPickle.dump(self, open(self._canonicalize(filename), 'wb'), protocol=cPickle.HIGHEST_PROTOCOL)
def load(self, filename, append=False): """Load collection from pickled file *filename*. *append* determines if the saved collection is added to the current one or if it replaces the current content. If no extension is provided, ".collection" is appended. """ tmp = cPic...
def _canonicalize(self, filename): """Use .collection as extension unless provided""" path, ext = os.path.splitext(filename) if not ext: ext = ".collection" return path + ext
def register(self,flag): """Register a new :class:`Flag` instance with the Flags registry.""" super(Flags,self).__setitem__(flag.name,flag)
def update(self,*flags): """Update Flags registry with a list of :class:`Flag` instances.""" super(Flags,self).update([(flag.name,flag) for flag in flags])
def scale_dihedrals(mol, dihedrals, scale, banned_lines=None): """Scale dihedral angles""" if banned_lines is None: banned_lines = [] new_dihedrals = [] for dh in mol.dihedrals: atypes = dh.atom1.get_atomtype(), dh.atom2.get_atomtype(), dh.atom3.get_atomt...
def scale_impropers(mol, impropers, scale, banned_lines=None): """Scale improper dihedrals""" if banned_lines is None: banned_lines = [] new_impropers = [] for im in mol.impropers: atypes = (im.atom1.get_atomtype(), im.atom2.get_atomtype(), ...
def partial_tempering(topfile="processed.top", outfile="scaled.top", banned_lines='', scale_lipids=1.0, scale_protein=1.0): """Set up topology for partial tempering (REST2) replica exchange. .. versionchanged:: 0.7.0 Use keyword arguments instead of an `args` Namespace...
def to_unicode(obj): """Convert obj to unicode (if it can be be converted). Conversion is only attempted if `obj` is a string type (as determined by :data:`six.string_types`). .. versionchanged:: 0.7.0 removed `encoding keyword argument """ if not isinstance(obj, six.string_types): ...
def besttype(x): """Convert string x to the most useful type, i.e. int, float or unicode string. If x is a quoted string (single or double quotes) then the quotes are stripped and the enclosed string returned. .. Note:: Strings will be returned as Unicode strings (using :func:`to_unicode`). ...
def to_int64(a): """Return view of the recarray with all int32 cast to int64.""" # build new dtype and replace i4 --> i8 def promote_i4(typestr): if typestr[1:] == 'i4': typestr = typestr[0]+'i8' return typestr dtype = [(name, promote_i4(typestr)) for name,typestr in a.dtype...
def irecarray_to_py(a): """Slow conversion of a recarray into a list of records with python types. Get the field names from :attr:`a.dtype.names`. :Returns: iterator so that one can handle big input arrays """ pytypes = [pyify(typestr) for name,typestr in a.dtype.descr] def convert_record(r): ...
def _convert_fancy(self, field): """Convert to a list (sep != None) and convert list elements.""" if self.sep is False: x = self._convert_singlet(field) else: x = tuple([self._convert_singlet(s) for s in field.split(self.sep)]) if len(x) == 0: ...
def parse(self): """Parse the xpm file and populate :attr:`XPM.array`.""" with utilities.openany(self.real_filename) as xpm: # Read in lines until we find the start of the array meta = [xpm.readline()] while not meta[-1].startswith("static char *gromacs_xpm[]"): ...
def col(self, c): """Parse colour specification""" m = self.COLOUR.search(c) if not m: self.logger.fatal("Cannot parse colour specification %r.", c) raise ParseError("XPM reader: Cannot parse colour specification {0!r}.".format(c)) value = m.group('value') ...
def run(self, *args, **kwargs): """Run the command; args/kwargs are added or replace the ones given to the constructor.""" _args, _kwargs = self._combine_arglist(args, kwargs) results, p = self._run_command(*_args, **_kwargs) return results
def _combine_arglist(self, args, kwargs): """Combine the default values and the supplied values.""" _args = self.args + args _kwargs = self.kwargs.copy() _kwargs.update(kwargs) return _args, _kwargs
def _run_command(self, *args, **kwargs): """Execute the command; see the docs for __call__. :Returns: a tuple of the *results* tuple ``(rc, stdout, stderr)`` and the :class:`Popen` instance. """ # hack to run command WITHOUT input (-h...) even though user defined ...
def _commandline(self, *args, **kwargs): """Returns the command line (without pipes) as a list.""" # transform_args() is a hook (used in GromacsCommand very differently!) return [self.command_name] + self.transform_args(*args, **kwargs)
def commandline(self, *args, **kwargs): """Returns the commandline that run() uses (without pipes).""" # this mirrors the setup in run() _args, _kwargs = self._combine_arglist(args, kwargs) return self._commandline(*_args, **_kwargs)
def Popen(self, *args, **kwargs): """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 com...
def transform_args(self, *args, **kwargs): """Transform arguments and return them as a list suitable for Popen.""" options = [] for option,value in kwargs.items(): if not option.startswith('-'): # heuristic for turning key=val pairs into options # (fai...
def help(self, long=False): """Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.""" print("\ncommand: {0!s}\n\n".format(self.command_name)) print(self.__doc__) if long: print("\ncall method: command():\n") print(self.__call__.__d...
def _combine_arglist(self, args, kwargs): """Combine the default values and the supplied values.""" gmxargs = self.gmxargs.copy() gmxargs.update(self._combineargs(*args, **kwargs)) return (), gmxargs
def _combineargs(self, *args, **kwargs): """Add switches as 'options' with value True to the options dict.""" d = {arg: True for arg in args} # switches are kwargs with value True d.update(kwargs) return d
def _build_arg_list(self, **kwargs): """Build list of arguments from the dict; keys must be valid gromacs flags.""" arglist = [] for flag, value in kwargs.items(): # XXX: check flag against allowed values flag = str(flag) if flag.startswith('_'): ...
def _run_command(self,*args,**kwargs): """Execute the gromacs command; see the docs for __call__.""" result, p = super(GromacsCommand, self)._run_command(*args, **kwargs) self.check_failure(result, command_string=p.command_string) return result, p
def _commandline(self, *args, **kwargs): """Returns the command line (without pipes) as a list. Inserts driver if present""" if(self.driver is not None): return [self.driver, self.command_name] + self.transform_args(*args, **kwargs) return [self.command_name] + self.transform_args(*a...
def transform_args(self,*args,**kwargs): """Combine arguments and turn them into gromacs tool arguments.""" newargs = self._combineargs(*args, **kwargs) return self._build_arg_list(**newargs)
def _get_gmx_docs(self): """Extract standard gromacs doc Extract by running the program and chopping the header to keep from 'DESCRIPTION' onwards. """ if self._doc_cache is not None: return self._doc_cache try: logging.disable(logging.CRITICAL) ...
def communicate(self, use_input=True): """Run the command, using the input that was set up on __init__ (for *use_input* = ``True``)""" if use_input: return super(PopenWithInput, self).communicate(self.input) else: return super(PopenWithInput, self).communicate()
def autoconvert(s): """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. """ if type(s) is not str: return s for converter in int, float, str: # try them in increasing order of lenience try: ...
def openany(datasource, mode='rt', reset=True): """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 :me...
def anyopen(datasource, mode='rt', reset=True): """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.res...
def _get_stream(filename, openfunction=open, mode='r'): """Return open stream if *filename* can be opened with *openfunction* or else ``None``.""" try: stream = openfunction(filename, mode=mode) except (IOError, OSError) as err: # An exception might be raised due to two reasons, first the op...
def hasmethod(obj, m): """Return ``True`` if object *obj* contains the method *m*. .. versionadded:: 0.7.1 """ return hasattr(obj, m) and callable(getattr(obj, m))
def isstream(obj): """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 ...
def convert_aa_code(x): """Converts between 3-letter and 1-letter amino acid codes.""" if len(x) == 1: return amino_acid_codes[x.upper()] elif len(x) == 3: return inverse_aa_codes[x.upper()] else: raise ValueError("Can only convert 1-letter or 3-letter amino acid codes, " ...
def in_dir(directory, create=True): """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 ...
def realpath(*args): """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. """ if None in args: return None return os.path.realpath( os.path.expandvars(os.path.expand...
def find_first(filename, suffices=None): """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 separat...
def withextsep(extensions): """Return list in which each element is guaranteed to start with :data:`os.path.extsep`.""" def dottify(x): if x.startswith(os.path.extsep): return x return os.path.extsep + x return [dottify(x) for x in asiterable(extensions)]
def iterable(obj): """Returns ``True`` if *obj* can be iterated over and is *not* a string.""" if isinstance(obj, string_types): return False # avoid iterating over characters of a string if hasattr(obj, 'next'): return True # any iterator will do try: len(obj) # any...
def unlink_f(path): """Unlink path but do not complain if file does not exist.""" try: os.unlink(path) except OSError as err: if err.errno != errno.ENOENT: raise
def unlink_gmx_backups(*args): """Unlink (rm) all backup files corresponding to the listed files.""" for path in args: dirname, filename = os.path.split(path) fbaks = glob.glob(os.path.join(dirname, '#'+filename+'.*#')) for bak in fbaks: unlink_f(bak)
def mkdir_p(path): """Create a directory *path* with subdirs but do not complain if it exists. This is like GNU ``mkdir -p path``. """ try: os.makedirs(path) except OSError as err: if err.errno != errno.EEXIST: raise
def cat(f=None, o=None): """Concatenate files *f*=[...] and write to *o*""" # need f, o to be compatible with trjcat and eneconv if f is None or o is None: return target = o infiles = asiterable(f) logger.debug("cat {0!s} > {1!s} ".format(" ".join(infiles), target)) with open(target,...
def activate_subplot(numPlot): """Make subplot *numPlot* active on the canvas. Use this if a simple ``subplot(numRows, numCols, numPlot)`` overwrites the subplot instead of activating it. """ # see http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg07156.html from pylab impor...
def remove_legend(ax=None): """Remove legend for axes or gca. See http://osdir.com/ml/python.matplotlib.general/2005-07/msg00285.html """ from pylab import gca, draw if ax is None: ax = gca() ax.legend_ = None draw()
def number_pdbs(*args, **kwargs): """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"] """ format = kwargs.pop('format', "%(num)04d") nam...
def _init_filename(self, filename=None, ext=None): """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` ...
def filename(self,filename=None,ext=None,set_default=False,use_my_ext=False): """Supply a file name for the class object. Typical uses:: fn = filename() ---> <default_filename> fn = filename('name.ext') ---> 'name' fn = filename(ext='pickle') ---> <defaul...
def check_file_exists(self, filename, resolve='exception', force=None): """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 "w...
def infix_filename(self, name, default, infix, ext=None): """Unless *name* is provided, insert *infix* before the extension *ext* of *default*.""" if name is None: p, oldext = os.path.splitext(default) if ext is None: ext = oldext if ext.startswith(os....
def strftime(self, fmt="%d:%H:%M:%S"): """Primitive string formatter. The only directives understood are the following: ============ ========================== Directive meaning ============ ========================== %d day as integer ...
def start_logging(logfile="gromacs.log"): """Start logging of messages to file and console. The default logfile is named ``gromacs.log`` and messages are logged with the tag *gromacs*. """ from . import log log.create("gromacs", logfile=logfile) logging.getLogger("gromacs").info("GromacsWra...
def stop_logging(): """Stop logging to logfile and console.""" from . import log logger = logging.getLogger("gromacs") logger.info("GromacsWrapper %s STOPPED logging", get_version()) log.clear_handlers(logger)
def filter_gromacs_warnings(action, categories=None): """Set the :meth:`warnings.simplefilter` to *action*. *categories* must be a list of warning classes or strings. ``None`` selects the defaults, :data:`gromacs.less_important_warnings`. """ if categories is None: categories = less_impor...
def tool_factory(clsname, name, driver, base=GromacsCommand): """ Factory for GromacsCommand derived types. """ clsdict = { 'command_name': name, 'driver': driver, '__doc__': property(base._get_gmx_docs) } return type(clsname, (base,), clsdict)
def find_executables(path): """ 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 """ execs = [] for exe in os.listdir(path): fullexe = os.pa...
def load_v5_tools(): """ 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 too...
def load_v4_tools(): """ 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: ...
def merge_ndx(*args): """ 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 """ ndxs = [] struct = None for fname in args: ...
def read(self, filename=None): """Read and parse index file *filename*.""" self._init_filename(filename) data = odict() with open(self.real_filename) as ndx: current_section = None for line in ndx: line = line.strip() if len(line) ...
def write(self, filename=None, ncol=ncol, format=format): """Write index file to *filename* (or overwrite the file that the index was read from)""" with open(self.filename(filename, ext='ndx'), 'w') as ndx: for name in self: atomnumbers = self._getarray(name) # allows overri...
def ndxlist(self): """Return a list of groups in the same format as :func:`gromacs.cbook.get_ndx_groups`. Format: [ {'name': group_name, 'natoms': number_atoms, 'nr': # group_number}, ....] """ return [{'name': name, 'natoms': len(atomnumbers), 'nr': nr+1} for ...
def join(self, *groupnames): """Return an index group that contains atoms from all *groupnames*. The method will silently ignore any groups that are not in the index. **Example** Always make a solvent group from water and ions, even if not all ions are present in all ...
def break_array(a, threshold=numpy.pi, other=None): """Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to ...
def write(self, filename=None): """Write array to xvg file *filename* in NXY format. .. Note:: Only plain files working at the moment, not compressed. """ self._init_filename(filename) with utilities.openany(self.real_filename, 'w') as xvg: xvg.write("# xmgrace compa...