Commit b7088b74 authored by peastman's avatar peastman Committed by Robert McGibbon
Browse files

Python 2/3 compatibility in single code base, plus python 3 testing on travis.

parent 4c00b312
......@@ -33,11 +33,14 @@ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from functools import wraps
from math import pi, cos, sin, sqrt
import os
import re
import sys
import simtk.openmm as mm
from simtk.openmm.vec3 import Vec3
import simtk.unit as u
......@@ -58,7 +61,8 @@ import warnings
TINY = 1e-8
WATNAMES = ('WAT', 'HOH', 'TIP3', 'TIP4', 'TIP5', 'SPCE', 'SPC')
if sys.version_info >= (3, 0):
xrange = range
def _catchindexerror(func):
"""
......@@ -70,7 +74,7 @@ def _catchindexerror(func):
""" Catch the index error """
try:
return func(*args, **kwargs)
except IndexError, e:
except IndexError as e:
raise CharmmPSFError('Array is too short: %s' % e)
return newfunc
......@@ -386,8 +390,8 @@ class CharmmPsfFile(object):
"""
try:
return type(string)
except ValueError, e:
print e
except ValueError as e:
print(e)
raise CharmmPSFError('Could not convert %s' % message)
@staticmethod
......@@ -1251,8 +1255,8 @@ class CharmmPsfFile(object):
elif implicitSolvent is GBn2:
gb = GBSAGBn2Force(solventDielectric, soluteDielectric, None,
cutoff, kappa=implicitSolventKappa)
for i, atom in enumerate(self.atom_list):
gb.addParticle([atom.charge] + list(gb_parms[i]))
for atom, gb_parm in zip(self.atom_list, gb_parms):
gb.addParticle([atom.charge] + list(gb_parm))
# Set cutoff method
if nonbondedMethod is ff.NoCutoff:
gb.setNonbondedMethod(mm.NonbondedForce.NoCutoff)
......
......@@ -28,6 +28,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Robert McGibbon"
__version__ = "1.0"
......@@ -77,7 +78,7 @@ class CheckpointReporter(object):
"""
self._reportInterval = reportInterval
if isinstance(file, basestring):
if isinstance(file, str):
self._own_handle = True
self._out = open(file, 'w+b', 0)
else:
......
......@@ -28,6 +28,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Peter Eastman"
__version__ = "1.0"
......
......@@ -28,6 +28,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Peter Eastman"
__version__ = "1.0"
......
......@@ -24,6 +24,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
import os
import math
......
......@@ -28,12 +28,18 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Christopher M. Bruns"
__version__ = "1.0"
import sys
from collections import OrderedDict
from simtk.unit import daltons, is_quantity
import copy_reg
if sys.version_info >= (3, 0):
import copyreg
else:
import copy_reg as copyreg
class Element(object):
"""An Element represents a chemical element.
......@@ -128,7 +134,7 @@ class Element(object):
diff = mass
best_guess = None
for elemmass, element in Element._elements_by_mass.iteritems():
for elemmass, element in _iteritems(Element._elements_by_mass):
massdiff = abs(elemmass - mass)
if massdiff < diff:
best_guess = element
......@@ -172,7 +178,7 @@ def get_by_symbol(symbol):
def _pickle_element(element):
return (get_by_symbol, (element.symbol,))
copy_reg.pickle(Element, _pickle_element)
copyreg.pickle(Element, _pickle_element)
# NOTE: getElementByMass assumes all masses are Quantity instances with unit
# "daltons". All elements need to obey this assumption, or that method will
......@@ -299,3 +305,10 @@ ununhexium = Element(116, "ununhexium", "Uuh", 292*daltons)
# relational operators will work with any chosen name
sulphur = sulfur
aluminium = aluminum
if sys.version_info >= (3, 0):
def _iteritems(dict):
return dict.items()
else:
def _iteritems(dict):
return dict.iteritems()
......@@ -28,6 +28,8 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
from __future__ import print_function
__author__ = "Peter Eastman"
__version__ = "1.0"
......@@ -38,7 +40,7 @@ import math
from math import sqrt, cos
import simtk.openmm as mm
import simtk.unit as unit
import element as elem
from . import element as elem
from simtk.openmm.app import Topology
def _convertParameterToNumber(param):
......@@ -1883,7 +1885,7 @@ def countConstraint(data):
if (isConstrained):
angleCount += 1
print "Constraints bond=%d angle=%d total=%d" % (bondCount, angleCount, (bondCount+angleCount))
print("Constraints bond=%d angle=%d total=%d" % (bondCount, angleCount, (bondCount+angleCount)))
## @private
class AmoebaBondGenerator:
......
......@@ -28,6 +28,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Lee-Ping Wang"
__version__ = "1.0"
......@@ -36,7 +37,7 @@ import sys
from simtk.openmm import Vec3
from re import sub, match
from simtk.unit import nanometers, angstroms, Quantity
import element as elem
from . import element as elem
try:
import numpy
except:
......
......@@ -28,14 +28,15 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
__author__ = "Peter Eastman"
__version__ = "1.0"
from simtk.openmm.app import Topology
from simtk.openmm.app import PDBFile
import forcefield as ff
import element as elem
import amberprmtopfile as prmtop
from . import forcefield as ff
from . import element as elem
from . import amberprmtopfile as prmtop
import simtk.unit as unit
import simtk.openmm as mm
import math
......@@ -601,7 +602,7 @@ class GromacsTopFile(object):
for key in self._dihedralTypes:
if key[1] == 'X' or key[2] == 'X':
wildcardDihedralTypes.append(key)
for types in dihedralTypeTable.itervalues():
for types in dihedralTypeTable.values():
types.append(key)
# Loop over molecules and create the specified number of each type.
......@@ -617,7 +618,7 @@ class GromacsTopFile(object):
try:
bondedTypes = [self._atomTypes[t][1] for t in atomTypes]
except KeyError as e:
raise ValueError('Unknown atom type: '+e.message)
raise ValueError('Unknown atom type: ' + e.message)
bondedTypes = [b if b is not None else a for a, b in zip(atomTypes, bondedTypes)]
# Add atoms.
......
......@@ -34,6 +34,8 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
from __future__ import print_function
#=============================================================================================
# GLOBAL IMPORTS
......@@ -54,7 +56,7 @@ import simtk.openmm
from simtk.openmm.app import element as elem
from simtk.openmm.app.internal.unitcell import computePeriodicBoxVectors
from simtk.openmm.vec3 import Vec3
import customgbforces as customgb
from . import customgbforces as customgb
#=============================================================================================
# AMBER parmtop loader (from 'zander', by Randall J. Radmer)
......@@ -713,7 +715,7 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
raise Exception("Cannot specify both a filename and a loader")
if prmtop_filename is not None:
# Load prmtop file.
if verbose: print "Reading prmtop file '%s'..." % prmtop_filename
if verbose: print("Reading prmtop file '%s'..." % prmtop_filename)
prmtop = PrmtopLoader(prmtop_filename)
else:
prmtop = prmtop_loader
......@@ -737,11 +739,11 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
mm = simtk.openmm
# Create OpenMM System.
if verbose: print "Creating OpenMM system..."
if verbose: print("Creating OpenMM system...")
system = mm.System()
# Populate system with atomic masses.
if verbose: print "Adding particles..."
if verbose: print("Adding particles...")
for mass in prmtop.getMasses():
system.addParticle(mass)
......@@ -759,7 +761,7 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
system.addConstraint(iAtom, jAtom, rMin)
# Add harmonic bonds.
if verbose: print "Adding bonds..."
if verbose: print("Adding bonds...")
force = mm.HarmonicBondForce()
if flexibleConstraints or (shake not in ('h-bonds', 'all-bonds', 'h-angles')):
for (iAtom, jAtom, k, rMin) in prmtop.getBondsWithH():
......@@ -771,7 +773,7 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
system.addForce(force)
# Add harmonic angles.
if verbose: print "Adding angles..."
if verbose: print("Adding angles...")
force = mm.HarmonicAngleForce()
if shake == 'h-angles':
numConstrainedBonds = system.getNumConstraints()
......@@ -809,14 +811,14 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
system.addForce(force)
# Add torsions.
if verbose: print "Adding torsions..."
if verbose: print("Adding torsions...")
force = mm.PeriodicTorsionForce()
for (iAtom, jAtom, kAtom, lAtom, forceConstant, phase, periodicity) in prmtop.getDihedrals():
force.addTorsion(iAtom, jAtom, kAtom, lAtom, periodicity, phase, forceConstant)
system.addForce(force)
# Add nonbonded interactions.
if verbose: print "Adding nonbonded interactions..."
if verbose: print("Adding nonbonded interactions...")
force = mm.NonbondedForce()
if (prmtop.getIfBox() == 0):
# System is non-periodic.
......@@ -1044,7 +1046,7 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
# Convert implicitSolventKappa to nanometers if it is a unit.
if units.is_quantity(implicitSolventKappa):
implicitSolventKappa = implicitSolventKappa.value_in_unit((1/units.nanometers).unit)
if verbose: print "Adding GB parameters..."
if verbose: print("Adding GB parameters...")
charges = prmtop.getCharges()
cutoff = None
if nonbondedMethod != 'NoCutoff':
......@@ -1071,14 +1073,15 @@ def readAmberSystem(topology, prmtop_filename=None, prmtop_loader=None, shake=No
gb = customgb.GBSAGBn2Force(solventDielectric, soluteDielectric, 'ACE', cutoff, implicitSolventKappa)
else:
raise Exception("Illegal value specified for implicit solvent model")
for iAtom in range(prmtop.getNumAtoms()):
for charge, gb_parm in zip(charges, gb_parms):
if gbmodel == 'OBC2' and implicitSolventKappa == 0:
gb.addParticle(charges[iAtom], gb_parms[iAtom][0], gb_parms[iAtom][1])
gb.addParticle(charge, gb_parm[0], gb_parm[1])
elif gbmodel == 'GBn2':
gb.addParticle([charges[iAtom], gb_parms[iAtom][0], gb_parms[iAtom][1],
gb_parms[iAtom][2], gb_parms[iAtom][3], gb_parms[iAtom][4]])
gb.addParticle([charge, gb_parm[0], gb_parm[1],
gb_parm[2], gb_parm[3], gb_parm[4]])
else:
gb.addParticle([charges[iAtom], gb_parms[iAtom][0], gb_parms[iAtom][1]])
gb.addParticle([charge, gb_parm[0], gb_parm[1]])
system.addForce(gb)
if nonbondedMethod == 'NoCutoff':
gb.setNonbondedMethod(mm.NonbondedForce.NoCutoff)
......
......@@ -33,7 +33,12 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
from simtk.openmm.app.internal.charmm.exceptions import CharmmFileError
import sys
if sys.version_info < (3, 0):
from codecs import open
class CharmmFile(object):
"""
......@@ -54,8 +59,8 @@ class CharmmFile(object):
else:
self.status = 'NEW'
try:
self._handle = open(fname, mode)
except IOError, e:
self._handle = open(fname, mode, encoding='utf-8')
except IOError as e:
raise CharmmFileError(str(e))
self.closed = False
self.line_number = 0
......
......@@ -32,6 +32,7 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
from simtk.openmm.app.internal.charmm.exceptions import (
SplitResidueWarning, BondError, ResidueError, CmapError,
MissingParameter)
......
......@@ -30,6 +30,7 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import division
from __future__ import absolute_import
from simtk.openmm import CustomGBForce, Continuous2DFunction
......@@ -369,13 +370,13 @@ def GBSAGBn2Force(solventDielectric=78.5, soluteDielectric=1, SA=None,
def convertParameters(params, gbmodel):
"""Convert the GB parameters from the file into the values expected by the appropriate CustomGBForce."""
newparams = [None]*len(params)
if gbmodel == 'GBn2':
offset = 0.0195141
else:
offset = 0.009
for i in range(len(params)):
newparams[i] = list(params[i])
newparams[i][0] -= offset
newparams[i][1] *= newparams[i][0]
return newparams
for p in params:
newParam = list(p)
newParam[0] -= offset
newParam[1] *= newParam[0]
yield newParam
#!/bin/env python
"""
pdbstructure.py: Used for managing PDB formated files.
......@@ -30,6 +28,8 @@ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import absolute_import
from __future__ import print_function
__author__ = "Christopher M. Bruns"
__version__ = "1.0"
......@@ -37,7 +37,7 @@ __version__ = "1.0"
from simtk.openmm.vec3 import Vec3
import simtk.unit as unit
from .. import element
from unitcell import computePeriodicBoxVectors
from .unitcell import computePeriodicBoxVectors
import warnings
import sys
import math
......@@ -212,11 +212,11 @@ class PdbStructure(object):
if len(model.chains) == 0:
continue
if len(self.models) > 1:
print >>output_stream, "MODEL %4d" % (model.number)
print("MODEL %4d" % (model.number), file=output_stream)
model.write(output_stream)
if len(self.models) > 1:
print >>output_stream, "ENDMDL"
print >>output_stream, "END"
print("ENDMDL", file=output_stream)
print("END", file=output_stream)
def _add_model(self, model):
if self.default_model == None:
......@@ -451,7 +451,7 @@ class Chain(object):
residue.write(next_serial_number, output_stream)
if self.has_ter_record:
r = self.residues[-1]
print >>output_stream, "TER %5d %3s %1s%4d%1s" % (next_serial_number.val, r.name_with_spaces, self.chain_id, r.number, r.insertion_code)
print("TER %5d %3s %1s%4d%1s" % (next_serial_number.val, r.name_with_spaces, self.chain_id, r.number, r.insertion_code), file=output_stream)
next_serial_number.increment()
def _add_ter_record(self):
......@@ -515,7 +515,7 @@ class Residue(object):
"""
"""
alt_loc = atom.alternate_location_indicator
if not self.locations.has_key(alt_loc):
if alt_loc not in self.locations:
self.locations[alt_loc] = Residue.Location(alt_loc, atom.residue_name_with_spaces)
assert atom.residue_number == self.number
assert atom.insertion_code == self.insertion_code
......@@ -924,7 +924,7 @@ class Atom(object):
else:
locs = list(alt_loc)
for loc_id in locs:
print >>output_stream, self._pdb_string(next_serial_number.val, loc_id)
print(self._pdb_string(next_serial_number.val, loc_id), file=output_stream)
next_serial_number.increment()
def set_name_with_spaces(self, name):
......@@ -1025,7 +1025,7 @@ if __name__=='__main__':
def parse_one_pdb(pdb_file_name):
global atom_count, residue_count, chain_count, model_count, structure_count
print pdb_file_name
print(pdb_file_name)
if pdb_file_name[-3:] == ".gz":
fh = gzip.open(pdb_file_name)
else:
......@@ -1083,10 +1083,10 @@ if __name__=='__main__':
seconds = elapsed % 60
hours = minutes / 60
minutes = minutes % 60
print "%dh:%02dm:%02ds elapsed" % (hours, minutes, seconds)
print("%dh:%02dm:%02ds elapsed" % (hours, minutes, seconds))
print "%d atoms found" % atom_count
print "%d residues found" % residue_count
print "%d chains found" % chain_count
print "%d models found" % model_count
print "%d structures found" % structure_count
print("%d atoms found" % atom_count)
print("%d residues found" % residue_count)
print("%d chains found" % chain_count)
print("%d models found" % model_count)
print("%d structures found" % structure_count)
......@@ -36,6 +36,7 @@ The DataCategory class provides base storage container for instance
data and definition meta data.
"""
from __future__ import absolute_import
__docformat__ = "restructuredtext en"
__author__ = "John Westbrook"
......@@ -99,13 +100,13 @@ class ContainerBase(object):
self.__name=name
def exists(self,name):
if self.__objCatalog.has_key(name):
if name in self.__objCatalog:
return True
else:
return False
def getObj(self,name):
if self.__objCatalog.has_key(name):
if name in self.__objCatalog:
return self.__objCatalog[name]
else:
return None
......@@ -118,7 +119,7 @@ class ContainerBase(object):
of the same name will be overwritten.
"""
if obj.getName() is not None:
if not self.__objCatalog.has_key(obj.getName()):
if obj.getName() not in self.__objCatalog:
# self.__objNameList is keeping track of object order here --
self.__objNameList.append(obj.getName())
self.__objCatalog[obj.getName()]=obj
......@@ -126,7 +127,7 @@ class ContainerBase(object):
def replace(self,obj):
""" Replace an existing object with the input object
"""
if ((obj.getName() is not None) and (self.__objCatalog.has_key(obj.getName())) ):
if ((obj.getName() is not None) and (obj.getName() in self.__objCatalog) ):
self.__objCatalog[obj.getName()]=obj
......@@ -158,7 +159,7 @@ class ContainerBase(object):
""" Revmove object by name. Return True on success or False otherwise.
"""
try:
if self.__objCatalog.has_key(curName):
if curName in self.__objCatalog:
del self.__objCatalog[curName]
i=self.__objNameList.index(curName)
del self.__objNameList[i]
......@@ -217,7 +218,7 @@ class DataContainer(ContainerBase):
def invokeDataBlockMethod(self,type,method,db):
self.__currentRow = 1
exec method.getInline()
exec(method.getInline())
def setGlobal(self):
self.__globalFlag=True
......@@ -328,7 +329,7 @@ class DataCategory(DataCategoryBase):
return self._rowList[0][ii]
except (IndexError, KeyError):
raise KeyError
raise TypeError, x
raise TypeError(x)
def getCurrentAttribute(self):
......@@ -464,7 +465,7 @@ class DataCategory(DataCategoryBase):
return self._rowList[rowI][self._attributeNameList.index(attribute)]
except (IndexError):
raise IndexError
raise IndexError, attribute
raise IndexError(attribute)
def setValue(self,value,attributeName=None,rowIndex=None):
if attributeName is None:
......@@ -544,13 +545,13 @@ class DataCategory(DataCategoryBase):
if (ind >= ll):
row.extend([None for ii in xrange(2*ind-ll)])
row[ind]=None
exec method.getInline()
exec(method.getInline())
self.__currentRowIndex+=1
currentRowIndex=self.__currentRowIndex
def invokeCategoryMethod(self,type,method,db):
self.__currentRowIndex = 0
exec method.getInline()
exec(method.getInline())
def getAttributeLengthMaximumList(self):
mList=[0 for i in len(self._attributeNameList)]
......@@ -750,7 +751,7 @@ class DataCategory(DataCategoryBase):
except (IndexError):
self.__lfh.write("attributeName %s rowI %r rowdata %r\n" % (attributeName,rowI,self._rowList[rowI]))
raise IndexError
raise TypeError, attribute
raise TypeError(attribute)
def getValueFormattedByIndex(self,attributeIndex,rowIndex):
......
......@@ -27,6 +27,7 @@ Acknowledgements:
See: http://pymmlib.sourceforge.net/
"""
from __future__ import absolute_import
__docformat__ = "restructuredtext en"
__author__ = "John Westbrook"
......@@ -137,7 +138,7 @@ class PdbxReader(object):
# Find the first reserved word and begin capturing data.
#
while True:
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
if curWord is None:
continue
reservedWord, state = self.__getState(curWord)
......@@ -194,7 +195,7 @@ class PdbxReader(object):
# Get the data for this attribute from the next token
tCat, tAtt, curQuotedString, curWord = tokenizer.next()
tCat, tAtt, curQuotedString, curWord = next(tokenizer)
if tCat is not None or (curQuotedString is None and curWord is None):
self.__syntaxError("Missing data for item _%s.%s" % (curCatName,curAttName))
......@@ -215,7 +216,7 @@ class PdbxReader(object):
else:
self.__syntaxError("Missing value in item-value pair")
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
continue
#
......@@ -225,14 +226,14 @@ class PdbxReader(object):
# The category name in the next curCatName,curAttName pair
# defines the name of the category container.
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
if curCatName is None or curAttName is None:
self.__syntaxError("Unexpected token in loop_ declaration")
return
# Check for a previous category declaration.
if categoryIndex.has_key(curCatName):
if curCatName in categoryIndex:
self.__syntaxError("Duplicate category declaration in loop_")
return
......@@ -248,7 +249,7 @@ class PdbxReader(object):
# Read the rest of the loop_ declaration
while True:
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
if curCatName is None:
break
......@@ -280,7 +281,7 @@ class PdbxReader(object):
elif curQuotedString is not None:
curRow.append(curQuotedString)
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
# loop_ data processing ends if -
......@@ -306,7 +307,7 @@ class PdbxReader(object):
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_DATA_CONTAINER":
#
......@@ -317,7 +318,7 @@ class PdbxReader(object):
containerList.append(curContainer)
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_STOP":
return
......@@ -327,7 +328,7 @@ class PdbxReader(object):
containerList.append(curContainer)
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_UNKNOWN":
self.__syntaxError("Unrecogized syntax element: " + str(curWord))
......@@ -366,7 +367,7 @@ class PdbxReader(object):
## Tokenizer loop begins here ---
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
# Dump comments
......@@ -379,7 +380,7 @@ class PdbxReader(object):
if line.startswith(";"):
mlString = [line[1:]]
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
if line.startswith(";"):
break
......@@ -451,7 +452,7 @@ class PdbxReader(object):
## Tokenizer loop begins here ---
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
# Dump comments
......@@ -464,7 +465,7 @@ class PdbxReader(object):
if line.startswith(";"):
mlString = [line[1:]]
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
if line.startswith(";"):
break
......
......@@ -10,6 +10,7 @@
##
""" Various tests caess for PDBx/mmCIF data file and dictionary reader and writer.
"""
from __future__ import absolute_import
__docformat__ = "restructuredtext en"
__author__ = "John Westbrook"
......
......@@ -22,6 +22,7 @@ Acknowledgements:
See: http://pymmlib.sourceforge.net/
"""
from __future__ import absolute_import
import re,sys
from simtk.openmm.app.internal.pdbx.reader.PdbxContainers import *
......@@ -126,7 +127,7 @@ class PdbxReader(object):
# Find the first reserved word and begin capturing data.
#
while True:
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
if curWord is None:
continue
reservedWord, state = self.__getState(curWord)
......@@ -183,7 +184,7 @@ class PdbxReader(object):
# Get the data for this attribute from the next token
tCat, tAtt, curQuotedString, curWord = tokenizer.next()
tCat, tAtt, curQuotedString, curWord = next(tokenizer)
if tCat is not None or (curQuotedString is None and curWord is None):
self.__syntaxError("Missing data for item _%s.%s" % (curCatName,curAttName))
......@@ -204,7 +205,7 @@ class PdbxReader(object):
else:
self.__syntaxError("Missing value in item-value pair")
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
continue
#
......@@ -214,14 +215,14 @@ class PdbxReader(object):
# The category name in the next curCatName,curAttName pair
# defines the name of the category container.
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
if curCatName is None or curAttName is None:
self.__syntaxError("Unexpected token in loop_ declaration")
return
# Check for a previous category declaration.
if categoryIndex.has_key(curCatName):
if curCatName in categoryIndex:
self.__syntaxError("Duplicate category declaration in loop_")
return
......@@ -237,7 +238,7 @@ class PdbxReader(object):
# Read the rest of the loop_ declaration
while True:
curCatName, curAttName, curQuotedString, curWord = tokenizer.next()
curCatName, curAttName, curQuotedString, curWord = next(tokenizer)
if curCatName is None:
break
......@@ -269,7 +270,7 @@ class PdbxReader(object):
elif curQuotedString is not None:
curRow.append(curQuotedString)
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
# loop_ data processing ends if -
......@@ -295,7 +296,7 @@ class PdbxReader(object):
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_DATA_CONTAINER":
#
......@@ -306,7 +307,7 @@ class PdbxReader(object):
containerList.append(curContainer)
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_STOP":
return
......@@ -316,7 +317,7 @@ class PdbxReader(object):
containerList.append(curContainer)
categoryIndex = {}
curCategory = None
curCatName,curAttName,curQuotedString,curWord = tokenizer.next()
curCatName,curAttName,curQuotedString,curWord = next(tokenizer)
elif state == "ST_UNKNOWN":
self.__syntaxError("Unrecogized syntax element: " + str(curWord))
......@@ -355,7 +356,7 @@ class PdbxReader(object):
## Tokenizer loop begins here ---
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
# Dump comments
......@@ -368,7 +369,7 @@ class PdbxReader(object):
if line.startswith(";"):
mlString = [line[1:]]
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
if line.startswith(";"):
break
......@@ -426,7 +427,7 @@ class PdbxReader(object):
## Tokenizer loop begins here ---
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
# Dump comments
......@@ -439,7 +440,7 @@ class PdbxReader(object):
if line.startswith(";"):
mlString = [line[1:]]
while True:
line = fileIter.next()
line = next(fileIter)
self.__curLineNumber += 1
if line.startswith(";"):
break
......
......@@ -12,6 +12,7 @@
Test cases for reading PDBx/mmCIF data files PdbxReader class -
"""
from __future__ import absolute_import
import sys, unittest, traceback
import sys, time, os, os.path, shutil
......
......@@ -11,6 +11,7 @@
Classes for writing data and dictionary containers in PDBx/mmCIF format.
"""
from __future__ import absolute_import
__docformat__ = "restructuredtext en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
......
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