Commit f220c5fa authored by Jason Swails's avatar Jason Swails

Incorporate some of quantifiedcode's suggestions, and fix mdin.py indentation

parent 3a1c3c25
GmxTests/
parmed/utils/six.py
parmed/utils/fortranformat
parmed/unit
test/
parmed/formats/pdbx/
...@@ -620,23 +620,19 @@ class AmoebaParm(AmberParm): ...@@ -620,23 +620,19 @@ class AmoebaParm(AmberParm):
""" Loads the AMOEBA chiral and multipole frames """ """ Loads the AMOEBA chiral and multipole frames """
data = self.parm_data data = self.parm_data
del self.chiral_frames[:] del self.chiral_frames[:]
try: if 'AMOEBA_CHIRAL_FRAME_LIST' in data:
it = iter(data['AMOEBA_CHIRAL_FRAME_LIST']) it = iter(data['AMOEBA_CHIRAL_FRAME_LIST'])
for i, j, k in zip(it, it, it): for i, j, k in zip(it, it, it):
self.chiral_frames.append( self.chiral_frames.append(
ChiralFrame(self.atoms[i-1], self.atoms[j-1], k) ChiralFrame(self.atoms[i-1], self.atoms[j-1], k)
) )
except KeyError:
pass
del self.multipole_frames[:] del self.multipole_frames[:]
try: if 'AMOEBA_FRAME_DEF_LIST' in data:
it = iter(data['AMOEBA_FRAME_DEF_LIST']) it = iter(data['AMOEBA_FRAME_DEF_LIST'])
for i, j, k, l, m in zip(it, it, it, it, it): for i, j, k, l, m in zip(it, it, it, it, it):
self.multipole_frames.append( self.multipole_frames.append(
MultipoleFrame(self.atoms[i-1], j, k, l, m) MultipoleFrame(self.atoms[i-1], j, k, l, m)
) )
except KeyError:
pass
#============================================= #=============================================
...@@ -645,23 +641,21 @@ class AmoebaParm(AmberParm): ...@@ -645,23 +641,21 @@ class AmoebaParm(AmberParm):
del self.adjust_types[:] del self.adjust_types[:]
del self.adjusts[:] del self.adjusts[:]
data = self.parm_data data = self.parm_data
try: # This section should always be present
for a,b,c,d,e in zip(data['AMOEBA_ADJUST_VDW_WEIGHTS_LIST'], for a,b,c,d,e in zip(data['AMOEBA_ADJUST_VDW_WEIGHTS_LIST'],
data['AMOEBA_ADJUST_MPOLE_WEIGHTS_LIST'], data['AMOEBA_ADJUST_MPOLE_WEIGHTS_LIST'],
data['AMOEBA_ADJUST_DIRECT_WEIGHTS_LIST'], data['AMOEBA_ADJUST_DIRECT_WEIGHTS_LIST'],
data['AMOEBA_ADJUST_POLAR_WEIGHTS_LIST'], data['AMOEBA_ADJUST_POLAR_WEIGHTS_LIST'],
data['AMOEBA_ADJUST_MUTUAL_WEIGHTS_LIST']): data['AMOEBA_ADJUST_MUTUAL_WEIGHTS_LIST']):
self.adjust_types.append( self.adjust_types.append(
NonbondedExceptionType(a,b,c,d,e,list=self.adjust_types) NonbondedExceptionType(a,b,c,d,e,list=self.adjust_types)
) )
it = iter(data['AMOEBA_ADJUST_LIST']) it = iter(data['AMOEBA_ADJUST_LIST'])
for i, j, k in zip(it, it, it): for i, j, k in zip(it, it, it):
self.adjusts.append( self.adjusts.append(
NonbondedException(self.atoms[i-1], self.atoms[j-1], NonbondedException(self.atoms[i-1], self.atoms[j-1],
self.adjust_types[k-1]) self.adjust_types[k-1])
) )
except KeyError:
pass
#============================================= #=============================================
......
...@@ -503,11 +503,9 @@ class AmberFormat(object): ...@@ -503,11 +503,9 @@ class AmberFormat(object):
CHARGE_SCALE = CHARMM_ELECTROSTATIC CHARGE_SCALE = CHARMM_ELECTROSTATIC
else: else:
CHARGE_SCALE = AMBER_ELECTROSTATIC CHARGE_SCALE = AMBER_ELECTROSTATIC
try: if self.charge_flag in self.parm_data:
for i, chg in enumerate(self.parm_data[self.charge_flag]): for i, chg in enumerate(self.parm_data[self.charge_flag]):
self.parm_data[self.charge_flag][i] = chg / CHARGE_SCALE self.parm_data[self.charge_flag][i] = chg / CHARGE_SCALE
except KeyError:
pass
# If we don't have a version, then read in an old-file topology # If we don't have a version, then read in an old-file topology
if self.version is None: if self.version is None:
with closing(genopen(self.name, 'r')) as f: with closing(genopen(self.name, 'r')) as f:
......
...@@ -35,7 +35,19 @@ class AmberMask(object): ...@@ -35,7 +35,19 @@ class AmberMask(object):
#====================================================== #======================================================
def Selected(self, invert=False): def Selected(self, invert=False):
""" Generator that returns the indexes of selected atoms """ """ Generator that returns the indexes of selected atoms
Parameters
----------
invert : bool, optional
If True, all atoms *not* selected by the mask will be returned
Returns
-------
generator of int
Each iteration will yield the index of the next atom that has been
selected by the mask. Atom indices are 0-based
"""
for i, v in enumerate(self.Selection(invert=invert)): for i, v in enumerate(self.Selection(invert=invert)):
if v: if v:
yield i yield i
...@@ -46,6 +58,25 @@ class AmberMask(object): ...@@ -46,6 +58,25 @@ class AmberMask(object):
""" """
Parses the mask and analyzes the result to return an atom Parses the mask and analyzes the result to return an atom
selection array selection array
Parameters
----------
prnlev : int, optional
Print debug information on the processing of the Amber mask string.
This is mainly useful if you are modifying the mask parser. Default
value is 0 (no printout), values between 1 and 8 control the level
of output (larger values produce more output). Default 0
invert : bool, optional
If True, the returned array will invert the selection of the mask
(i.e., selected atoms will not be selected and vice-versa)
Returns
-------
mask : list of int
A list with length equal to the number of atoms in the assigned
:class:`Structure <parmed.structure.Structure>` instance. Selected
atoms will have a value of 1 placed in the corresponding slot in the
return list while atoms not selected will be assigned 0.
""" """
from sys import stderr, stdout from sys import stderr, stdout
if prnlev > 2: stderr.write('In AmberMask.Selection(), debug active!\n') if prnlev > 2: stderr.write('In AmberMask.Selection(), debug active!\n')
...@@ -56,17 +87,17 @@ class AmberMask(object): ...@@ -56,17 +87,17 @@ class AmberMask(object):
return [1 for atom in self.parm.atoms] return [1 for atom in self.parm.atoms]
# 1) preprocess input expression # 1) preprocess input expression
infix = AmberMask._tokenize(self, prnlev) infix = self._tokenize(prnlev)
if prnlev > 5: stdout.write('tokenized mask: ==%s==\n' % infix) if prnlev > 5: stdout.write('tokenized mask: ==%s==\n' % infix)
# 2) construct postfix (RPN) notation # 2) construct postfix (RPN) notation
postfix = AmberMask._torpn(self, infix, prnlev) postfix = self._torpn(infix, prnlev)
if prnlev > 5: stdout.write('postfix mask: ==%s==\n' % postfix) if prnlev > 5: stdout.write('postfix mask: ==%s==\n' % postfix)
# 3) evaluate the postfix notation # 3) evaluate the postfix notation
if invert: if invert:
return [1-i for i in AmberMask._evaluate(self, postfix, prnlev)] return [1-i for i in self._evaluate(postfix, prnlev)]
return AmberMask._evaluate(self, postfix, prnlev) return self._evaluate(postfix, prnlev)
#====================================================== #======================================================
......
This diff is collapsed.
...@@ -31,15 +31,6 @@ from warnings import warn as _warn ...@@ -31,15 +31,6 @@ from warnings import warn as _warn
# Define importables via * # Define importables via *
__all__ = ['AmberFormat', 'AmberParm', 'ChamberParm', 'LoadParm', 'Rst7'] __all__ = ['AmberFormat', 'AmberParm', 'ChamberParm', 'LoadParm', 'Rst7']
# For backwards compatibility, but this will be eliminated
class rst7(Rst7):
""" Amber input coordinate (or restart coordinate) file format """
def __init__(self, filename=None):
_warn('rst7 is deprecated. Use Rst7 instead.', DeprecationWarning)
super(rst7, self).__init__(filename=filename)
# Supply a function to load a topology file in the 'correct' format # Supply a function to load a topology file in the 'correct' format
def LoadParm(parmname, rst7name=None): def LoadParm(parmname, rst7name=None):
""" """
......
...@@ -66,6 +66,9 @@ class PdbxSyntaxError(PdbxError): ...@@ -66,6 +66,9 @@ class PdbxSyntaxError(PdbxError):
def __str__(self): def __str__(self):
return "%%ERROR - [at line: %d] %s" % (self.lineNumber, self.text) return "%%ERROR - [at line: %d] %s" % (self.lineNumber, self.text)
class InputError(ParmedError):
""" When there is an error with input """
# Warnings # Warnings
class ParmedWarning(Warning): class ParmedWarning(Warning):
......
...@@ -481,10 +481,7 @@ class PDBFile(object): ...@@ -481,10 +481,7 @@ class PDBFile(object):
except (IndexError, ValueError): except (IndexError, ValueError):
A = B = C = 90.0 A = B = C = 90.0
struct.box = [a, b, c, A, B, C] struct.box = [a, b, c, A, B, C]
try: struct.space_group = line[55:66].strip()
struct.space_group = line[55:66].strip()
except IndexError:
pass
elif rec == 'EXPDTA': elif rec == 'EXPDTA':
struct.experimental = line[6:].strip() struct.experimental = line[6:].strip()
elif rec == 'AUTHOR': elif rec == 'AUTHOR':
...@@ -503,6 +500,7 @@ class PDBFile(object): ...@@ -503,6 +500,7 @@ class PDBFile(object):
try: try:
struct.year = int(line[62:66]) struct.year = int(line[62:66])
except ValueError: except ValueError:
# Shouldn't happen, but don't throw a fit
pass pass
elif part == 'PMID': elif part == 'PMID':
struct.pmid = line[19:].strip() struct.pmid = line[19:].strip()
......
...@@ -319,6 +319,7 @@ class CPreProcessor(object): ...@@ -319,6 +319,7 @@ class CPreProcessor(object):
try: try:
del self.defines[words[0]] del self.defines[words[0]]
except KeyError: except KeyError:
# Undefining an undefined variable is a no-op
pass pass
elif len(words) > 1: elif len(words) > 1:
warnings.warn('Ignored tokens in #undef: %s' % ', '.join(words[1:]), warnings.warn('Ignored tokens in #undef: %s' % ', '.join(words[1:]),
......
...@@ -159,13 +159,10 @@ def check_validity(parm, warnings): ...@@ -159,13 +159,10 @@ def check_validity(parm, warnings):
True, False, True, float) True, False, True, float)
# Check that ATOMS_PER_MOLECULE == NATOM # Check that ATOMS_PER_MOLECULE == NATOM
try: if 'ATOMS_PER_MOLECULE' in parm.parm_data:
if (sum(parm.parm_data['ATOMS_PER_MOLECULE']) != if sum(parm.parm_data['ATOMS_PER_MOLECULE']) != parm.ptr('natom'):
parm.ptr('natom')):
warnings.warn('sum(ATOMS_PER_MOLECULE) != NATOM. Use ' warnings.warn('sum(ATOMS_PER_MOLECULE) != NATOM. Use '
'"setMolecules" to fix this', FixableParmWarning) '"setMolecules" to fix this', FixableParmWarning)
except KeyError:
pass
# Duplicate pmemd's checks # Duplicate pmemd's checks
if parm.ptr('ifpert') != 0: if parm.ptr('ifpert') != 0:
......
""" Exceptions used in parmed.py """ """ Exceptions used in parmed.py """
from sys import stderr from sys import stderr
from parmed.exceptions import ParmedError, ParmedWarning from parmed.exceptions import ParmedError, ParmedWarning, InputError
class ParmError(ParmedError): class ParmError(ParmedError):
""" Base parmed error """ """ Base parmed error """
...@@ -124,9 +124,6 @@ class SimulationWarning(ParmWarning): ...@@ -124,9 +124,6 @@ class SimulationWarning(ParmWarning):
class UnhandledArgumentWarning(SeriousParmWarning): class UnhandledArgumentWarning(SeriousParmWarning):
pass pass
class InputError(ParmError):
pass
class ParmIndexError(ParmError, IndexError): class ParmIndexError(ParmError, IndexError):
pass pass
......
...@@ -2915,10 +2915,8 @@ class _CmapGrid(object): ...@@ -2915,10 +2915,8 @@ class _CmapGrid(object):
@property @property
def transpose(self): def transpose(self):
""" The transpose of the potential grid """ """ The transpose of the potential grid """
try: if hasattr(self, '_transpose'):
return self._transpose return self._transpose
except AttributeError:
pass
_transpose = [] _transpose = []
size = len(self._data) size = len(self._data)
for i in range(self.resolution): for i in range(self.resolution):
...@@ -3907,10 +3905,10 @@ class TrackedList(list): ...@@ -3907,10 +3905,10 @@ class TrackedList(list):
>>> tl.needs_indexing, tl.changed >>> tl.needs_indexing, tl.changed
(False, False) (False, False)
""" """
def __init__(self, arg=[]): def __init__(self, *args):
self.changed = False self.changed = False
self.needs_indexing = False self.needs_indexing = False
return list.__init__(self, arg) return list.__init__(self, *args)
@_changes @_changes
def __delitem__(self, item): def __delitem__(self, item):
...@@ -3924,10 +3922,12 @@ class TrackedList(list): ...@@ -3924,10 +3922,12 @@ class TrackedList(list):
try: try:
self[index]._idx = -1 self[index]._idx = -1
except AttributeError: except AttributeError:
# If we can't set _idx attribute on this object, don't fret
pass pass
try: try:
self[index].list = None self[index].list = None
except AttributeError: except AttributeError:
# If we can't set list attribute on this object, don't fret
pass pass
return list.__delitem__(self, item) return list.__delitem__(self, item)
...@@ -3941,10 +3941,12 @@ class TrackedList(list): ...@@ -3941,10 +3941,12 @@ class TrackedList(list):
try: try:
self[index]._idx = -1 self[index]._idx = -1
except AttributeError: except AttributeError:
# If we can't set _idx attribute on this object, don't fret
pass pass
try: try:
self[index].list = None self[index].list = None
except AttributeError: except AttributeError:
# If we can't set list attribute on this object, don't fret
pass pass
return list.__delslice__(self, start, stop) return list.__delslice__(self, start, stop)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment