Package gromacs
[hide private]
[frames] | no frames]

Source Code for Package gromacs

  1  # GromacsWrapper 
  2  # Copyright (c) 2009-2010 Oliver Beckstein <orbeckst@gmail.com> 
  3  # Released under the GNU Public License 3 (or higher, your choice) 
  4  # See the file COPYING for details. 
  5   
  6  """ 
  7  :mod:`gromacs` -- GromacsWrapper Package Overview 
  8  ================================================= 
  9   
 10  **GromacsWrapper** (package :mod:`gromacs`) is a thin shell around the `Gromacs`_ 
 11  tools for light-weight integration into python scripts or interactive use in 
 12  `ipython`_. 
 13   
 14  .. _`Gromacs`: http://www.gromacs.org 
 15  .. _`ipython`: http://ipython.scipy.org 
 16   
 17   
 18  Modules 
 19  ------- 
 20   
 21  :mod:`gromacs` 
 22       The top level module contains all gromacs tools; each tool can be 
 23       run directly or queried for its documentation. It also defines 
 24       the root logger class (name *gromacs* by default). 
 25   
 26  :mod:`gromacs.config` 
 27       Configuration options. Not really used much at the moment. 
 28   
 29  :mod:`gromacs.cbook` 
 30       The Gromacs cook book contains typical applications of the tools. In many 
 31       cases this not more than just an often-used combination of parameters for 
 32       a tool. 
 33   
 34  :mod:`gromacs.tools` 
 35       Contains classes that wrap the gromacs tools. They are automatically 
 36       generated from the list of tools in :data:`gromacs.tools.gmx_tools`. 
 37   
 38  :mod:`gromacs.formats` 
 39       Classes to represent data files in various formats such as 
 40       xmgrace graphs. The classes allow reading and writing and for 
 41       graphs, also plotting of the data. 
 42   
 43  :mod:`gromacs.utilities` 
 44       Convenience functions and mixin-classes that are used as helpers 
 45       in other modules. 
 46   
 47  :mod:`gromacs.setup` 
 48       Functions to set up a MD simulation, containing tasks such as solvation 
 49       and adding ions, energy minimizqtion, MD with position-restraints, and 
 50       equilibrium MD. 
 51   
 52  :mod:`gromacs.qsub` 
 53       Functions to handle batch submission queuing systems. 
 54   
 55  :mod:`gromacs.run` 
 56       Classes to run :program:`mdrun` in various way, including on 
 57       multiprocessor systems. 
 58   
 59  :mod:`gromacs.analysis` 
 60       A package that collects whole analysis tasks. It uses the gromacs but is 
 61       otherwise only loosely coupled with the rest. At the moment it only 
 62       contains the infrastructure and an example application. See the package 
 63       documentation. 
 64   
 65   
 66  Examples 
 67  -------- 
 68   
 69  The following examples should simply convey the flavour of using the 
 70  package. See the individual modules for more examples. 
 71   
 72  Getting help 
 73  ............ 
 74   
 75  In python:: 
 76   
 77     help(gromacs.g_dist) 
 78     gromacs.g_dist.help() 
 79     gromacs.g_dist.help(long=True) 
 80   
 81  In ``ipython``:: 
 82   
 83     gromacs.g_dist ? 
 84   
 85   
 86  Simple usage 
 87  ............ 
 88   
 89  Gromacs flags are given as python keyword arguments:: 
 90   
 91     gromacs.g_dist(v=True, s='topol.tpr', f='md.xtc', o='dist.xvg', dist=1.2) 
 92   
 93  Input to stdin of the command can be supplied:: 
 94   
 95     gromacs.make_ndx(f='topol.tpr', o='md.ndx',  
 96                      input=('keep "SOL"', '"SOL" | r NA | r CL', 'name 2 solvent', 'q')) 
 97   
 98  Output of the command can be caught in a variable and analyzed:: 
 99   
100     rc, output, junk = gromacs.grompp(..., stdout=False)        # collects command output 
101     for line in output.split('\\n'): 
102         line = line.strip() 
103         if line.startswith('System has non-zero total charge:'): 
104               qtot = float(line[34:]) 
105               break 
106   
107  (See :func:`gromacs.cbook.grompp_qtot` for a more robust implementation of this 
108  application.) 
109   
110   
111  Warnings and Exceptions 
112  ----------------------- 
113   
114  A number of package-specific exceptions (:exc:`GromacsError`) and 
115  warnings (:exc:`Gromacs*Warning`, :exc:`AutoCorrectionWarning`, 
116  :exc:`BadParameterWarning`) can be raised. 
117   
118  If you want to stop execution at, for instance, a :exc:`AutoCorrectionWarning` or 
119  :exc:`BadParameterWarning` then use the python :mod:`warnings` filter:: 
120    
121    import warnings 
122    warnings.simplefilter('error', gromacs.AutoCorrectionWarning) 
123    warnings.simplefilter('error', gromacs.BadParameterWarning) 
124   
125  This will make python raise an exception instead of moving on. The default is 
126  to always report, eg:: 
127   
128    warnings.simplefilter('always', gromacs.BadParameterWarning) 
129   
130  The following *exceptions* are defined: 
131   
132  .. autoexception:: GromacsError 
133  .. autoexception:: MissingDataError 
134  .. autoexception:: ParseError 
135   
136  The following *warnings* are defined: 
137   
138  .. autoexception:: GromacsFailureWarning 
139  .. autoexception:: GromacsImportWarning 
140  .. autoexception:: GromacsValueWarning 
141  .. autoexception:: AutoCorrectionWarning 
142  .. autoexception:: BadParameterWarning 
143  .. autoexception:: MissingDataWarning 
144  .. autoexception:: UsageWarning 
145  .. autoexception:: LowAccuracyWarning 
146   
147   
148  Logging 
149  ------- 
150   
151  The library uses python's logging_ module to keep a history of what it has been 
152  doing. In particular, every wrapped Gromacs command logs its command line 
153  (including piped input) to the log file (configured in 
154  :data:`gromacs.config.logfilename`). This facilitates debugging or simple 
155  re-use of command lines for very quick and dirty work. The logging facilty 
156  appends to the log file and time-stamps every entry. See :mod:`gromacs.config` 
157  for more details on configuration. 
158   
159  .. _logging: http://docs.python.org/library/logging.html 
160   
161  Version 
162  ------- 
163   
164  The package version can be queried with the :func:`gromacs.get_version` function. 
165   
166  .. autofunction:: get_version 
167  .. autofunction:: get_version_tuple 
168   
169  """ 
170  __docformat__ = "restructuredtext en" 
171   
172  #: Package version; this is the only place where it is set. 
173  VERSION = 0,1,12 
174   
175 -def get_version():
176 """Return current package version as a string.""" 177 return ".".join(map(str,VERSION))
178
179 -def get_version_tuple():
180 """Return current package version as a tuple (*MAJOR*, *MINOR*, *PATCHLEVEL*).""" 181 return tuple(VERSION)
182 183 # __all__ is extended with all gromacs command instances later 184 __all__ = ['config', 'tools', 'cbook'] 185 186 # Note: analysis not imported by default (requires additional pre-requisites) 187
188 -class GromacsError(EnvironmentError):
189 """Error raised when a gromacs tool fails. 190 191 Returns error code in the errno attribute and a string in strerror. 192 # TODO: return status code and possibly error message 193 """
194
195 -class MissingDataError(Exception):
196 """Error raised when prerequisite data are not available. 197 198 For analysis with :class:`gromacs.analysis.core.Simulation` this typically 199 means that the :meth:`~gromacs.analysis.core.Simulation.analyze` method has 200 to be run first. 201 """
202
203 -class ParseError(Exception):
204 """Error raised when parsing of a file failed."""
205
206 -class GromacsFailureWarning(Warning):
207 """Warning about failure of a Gromacs tool."""
208
209 -class GromacsImportWarning(ImportWarning):
210 """Warns about problems with using a gromacs tool."""
211
212 -class GromacsValueWarning(Warning):
213 """Warns about problems with the value of an option or variable."""
214
215 -class AutoCorrectionWarning(Warning):
216 """Warns about cases when the code is choosing new values automatically."""
217
218 -class BadParameterWarning(Warning):
219 """Warns if some parameters or variables are unlikely to be appropriate or correct."""
220
221 -class MissingDataWarning(Warning):
222 """Warns when prerequisite data/files are not available."""
223
224 -class UsageWarning(Warning):
225 """Warns if usage is unexpected/documentation ambiguous."""
226
227 -class LowAccuracyWarning(Warning):
228 """Warns that results may possibly have low accuracy."""
229 230 import warnings 231 # These warnings should always be displayed because other parameters 232 # can have changed, eg during interactive use. 233 for w in (AutoCorrectionWarning, BadParameterWarning, UsageWarning, 234 GromacsFailureWarning, GromacsValueWarning, LowAccuracyWarning): 235 warnings.simplefilter('always', category=w) 236 del w 237 238 239 # Import configuration before anything else 240 import config 241 242 243 import logging 244 # NOTE: logging is still iffy; when I reload I add a new logger each 245 # time and output is repeated for each reload. Probably should heed 246 # the advice on logging and libraries in 247 # http://docs.python.org/library/logging.html?#configuring-logging-for-a-library
248 -class NullHandler(logging.Handler):
249 - def emit(self, record):
250 pass
251 252 # default silent logger --- just here for illustration; below we 253 # we get a proper logger from log.create() 254 h = NullHandler() 255 logging.getLogger("gromacs").addHandler(h) 256 del h 257 258 # The top level logger of the library is named 'gromacs'. 259 # Note that we are configuring this logger with console output. If the root logger also 260 # does this then we will get two output lines to the console. We'll live with this because 261 # this is a simple convenience library and most people will not bother 262 # with a logger (I think...) 263 # 264 # In modules that use loggers get a logger like so: 265 # import logging 266 # logger = logging.getLogger('gromacs.MODULENAME') 267 268 # add standard logging -- remove when integrating in a library?? 269 import log 270 logger = log.create('gromacs', logfile='gromacs.log') 271 del log 272 273 274 # Add gromacs command **instances** to the top level. 275 # These serve as the equivalence of running commands in the shell. 276 # (Note that each gromacs command is actually run when the instance is 277 # created in order to gather the documentation string.) 278 import tools 279 280 # Ignore warnings from a few programs that do not produce 281 # documentation when run with '-h' (only applies when the default for 282 # failuremode of core.GromacsCommand is changed to 'warn') 283 warnings.simplefilter("ignore", GromacsFailureWarning) 284 _have_g_commands = [] 285 _missing_g_commands = [] 286 for clsname, cls in tools.registry.items(): 287 name = clsname[0].lower() + clsname[1:] # instances should start with lower case 288 try: 289 globals()[name] = cls() # add instance of command for immediate use 290 _have_g_commands.append(name) 291 except GromacsError: # ignore missing -h for doc extraction 292 pass 293 except OSError: 294 _missing_g_commands.append(name) 295 warnings.simplefilter("always", GromacsFailureWarning) 296 warnings.simplefilter("always", GromacsImportWarning) 297 298 _have_g_commands.sort() 299 _missing_g_commands.sort() 300 if len(_missing_g_commands) > 0: 301 warnings.warn("Some Gromacs commands were NOT found; " 302 "maybe source GMXRC first? The following are missing:\n%r\n" % _missing_g_commands, 303 category=GromacsImportWarning) 304 305 del name, cls, clsname 306 307 # get ALL active command instances with 'from gromacs import *' 308 __all__.extend(_have_g_commands) 309 310 311 # cbook should come after the whole of init as it relies on command 312 # instances in the top level name space 313 try: 314 import cbook 315 except OSError, err: 316 warnings.warn("Some Gromacs commands were NOT found when importing gromacs.cbook:\n"+str(err), 317 category=GromacsImportWarning) 318 319 # convenience functions for warnings 320 321 less_important_warnings = ['AutoCorrectionWarning', 'UsageWarning'] 322
323 -def filter_gromacs_warnings(action, categories=None):
324 """Set the :meth:`warnings.simplefilter` to *action*. 325 326 *categories* must be a list of warning classes or strings. 327 ``None`` selects the defaults, :data:`gromacs.less_important_warnings`. 328 """ 329 330 if categories is None: 331 categories = less_important_warnings 332 for c in categories: 333 try: 334 w = globals()[c] 335 except KeyError: 336 w = c 337 if not issubclass(w, Warning): 338 raise TypeError("%r is neither a Warning nor the name of a Gromacs warning." % c) 339 warnings.simplefilter(action, category=w)
340
341 -def disable_gromacs_warnings(categories=None):
342 """Disable ("ignore") specified warnings from the gromacs package. 343 344 *categories* must be a list of warning classes or strings. 345 ``None`` selects the defaults. 346 347 """ 348 filter_gromacs_warnings('ignore', categories=categories)
349
350 -def enable_gromacs_warnings(categories=None):
351 """Enable ("always") specified warnings from the gromacs package. 352 353 *categories* must be a list of warning classes or strings. 354 ``None`` selects the defaults, :data:`gromacs._less_important_warnings`. 355 356 """ 357 filter_gromacs_warnings('always', categories=categories)
358