def _read_vdw(self, f): """ Reads the van der Waals parameters """ if not hasattr(self, 'atom_list'): raise AttributeError('Atom definitions must be loaded ' 'prior to vdW!') # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['natom']): try: int(line[0:6]) atnum = int(line[9:15]) self.atom_list[i].add_vdw( line[22:32], line[32:42], line[43:53], line[53:63], line[64:74], ) except ValueError: raise TinkerError('Error parsing van der Waals term') line = f.readline() if atnum != i + 1: raise TinkerError('Atom number mismatch in vdW [%d vs %d]' % (i + 1, atnum))
def _read_tortors(self, f): """ Read the Torsion-Torsion parameters """ self.tortor_list = TorsionTorsionList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['ntortor']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 at3 = int(line[21:27]) - 1 at4 = int(line[27:33]) - 1 at5 = int(line[33:39]) - 1 dim1 = int(line[49:55]) dim2 = int(line[55:61]) self.tortor_list.add(self.atom_list[at1], self.atom_list[at2], self.atom_list[at3], self.atom_list[at4], self.atom_list[at5], dim1, dim2) except ValueError: raise TinkerError('Error parsing torsion-torsion term') line = f.readline() # The CMAP section was adjusted to print out the entire torsion # grid under each tor-tor definition. If this line has 3 words, we # need to eat the next dim1*dim2 lines if len(line.split()) == 3: gridvals = [] for j in range(dim1 * dim2): gridvals.append(tuple([float(x) for x in line.split()])) line = f.readline() self.tortor_list[-1].type = TorsionTorsionGrid.new(gridvals)
def _read_torang(self, f): """ Read the torsion-angle parameters """ self.torangle_list = TorsionAngleList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['ntors']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 at3 = int(line[21:27]) - 1 at4 = int(line[27:33]) - 1 # Get the rest of the terms (replace / with ' ' so we can do a # simple string split on whitespace) terms = line[33:].replace('/', ' ').split() self.torangle_list.add(self.atom_list[at1], self.atom_list[at2], self.atom_list[at3], self.atom_list[at4], terms) except ValueError: raise TinkerError('Error parsing torsion angle term') line = f.readline()
def _read_ureybrad(self, f): """ Reads the urey-bradley terms """ self.ureybrad_list = UreyBradleyList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['nurey']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 # Support older-style analyze output that had all 3 atoms # involved in the angle. Newer analyze output contains only the # first and 3rd atoms, so that is all we pass into the # UreyBradleyList function try: at3 = int(line[21:27]) - 1 except ValueError: at3 = at2 self.ureybrad_list.add(self.atom_list[at1], self.atom_list[at3], line[34:50], line[50:60]) except ValueError: raise TinkerError('Error parsing Urey-Bradley term') line = f.readline()
def __init__(self, fname): # The currently recognized/parsed keywords (these are the only ones # necessary for running Amoeba in Amber) self.keywords = { 'PARAMETERS': None, 'A-AXIS': None, 'B-AXIS': None, 'C-AXIS': None, 'ALPHA': None, 'BETA': None, 'GAMMA': None } # Parse the file for line in open(fname, 'r'): # Skip over any blank lines if not line.strip(): continue words = line.split() key = words[0].upper() # Get rid of the keyword and all whitespace result = line.replace(words[0], '').strip() try: self.keywords[key] = self._datatypes[key](result) except KeyError: pass # All non-keyword lines are ignored comments except ValueError: raise TinkerError('Malformed keyword control file! Could not ' 'convert the value of %s into type %s' % (key, self._datatypes[key]))
def _read_multipoles(self, f): """ Read the atomic multipoles """ self.multipole_list = AtomicMultipoleList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['npole']): try: int(line[0:6]) at = int(line[9:15]) - 1 # Collect the rest of the arguments, kept as strings frame = [line[16:23], line[23:30], line[30:37]] typestr = line[40:48] moments = [line[50:59]] # Next numbers are on the next line line = f.readline() moments.extend([line[50:59], line[59:68], line[68:77]]) line = f.readline() moments.append(line[50:59]) line = f.readline() moments.extend([line[50:59], line[59:68]]) line = f.readline() moments.extend([line[50:59], line[59:68], line[68:77]]) self.multipole_list.add(self.atom_list[at], frame, typestr, moments) except ValueError: raise TinkerError('Error parsing multipole term') line = f.readline()
def __init__(self, fname, seq=None): super(XyzFile, self).__init__() if isinstance(fname, string_types): fxyz = genopen(fname, 'r') own_handle_xyz = True else: fxyz = fname own_handle_xyz = False if seq is not None: seqstruct = load_file(seq) # Now parse the file try: natom = int(fxyz.readline().split()[0]) except (ValueError, IndexError): raise TinkerError('Bad XYZ file format; first line') if seq is not None and natom != len(seqstruct.atoms): raise ValueError( 'Sequence file %s # of atoms does not match the # ' 'of atoms in the XYZ file' % seq) words = fxyz.readline().split() if len(words) == 6 and not XyzFile._check_atom_record(words): self.box = [float(w) for w in words] words = fxyz.readline().split() atom = Atom(atomic_number=AtomicNum[element_by_name(words[1])], name=words[1], type=words[5]) atom.xx, atom.xy, atom.xz = [float(w) for w in words[2:5]] residue = Residue('SYS') residue.number = 1 residue._idx = 0 if seq is not None: residue = seqstruct.residues[0] self.add_atom(atom, residue.name, residue.number, residue.chain, residue.insertion_code, residue.segid) bond_ids = [[int(w) for w in words[6:]]] for i, line in enumerate(fxyz): words = line.split() atom = Atom(atomic_number=AtomicNum[element_by_name(words[1])], name=words[1], type=words[5]) atom.xx, atom.xy, atom.xz = [float(w) for w in words[2:5]] if seq is not None: residue = seqstruct.atoms[i + 1].residue self.add_atom(atom, residue.name, residue.number, residue.chain, residue.insertion_code, residue.segid) bond_ids.append([int(w) for w in words[6:]]) # All of the bonds are stored now -- go ahead and make them now for atom, bonds in zip(self.atoms, bond_ids): i = atom.idx + 1 for idx in bonds: if idx > i: self.bonds.append(Bond(atom, self.atoms[idx - 1])) if own_handle_xyz: fxyz.close()
def _read_atom_definitions(self, f): # Make an atom list self.atom_list = AtomList() # Eat 3 lines, then begin f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['natom']): try: atnum = int(line[:6]) self.atom_list.add(line[11:14], line[14:21], line[21:28], line[28:34], line[34:44], line[44:49], line[54:].strip()) except ValueError: raise TinkerError('Error parsing atomic properties\n\t' '[%s]' % line.rstrip()) line = f.readline() if atnum != i + 1: raise TinkerError('Atom number mismatch [%d vs %d]' % (i + 1, atnum))
def _read_section(f, container, natom): """ Reads a section of an open file into the passed container. The container should be a 2-dimensional list of length natom x 3 """ for i in range(natom): words = f.readline().upper().split() try: container[i][0] = float(words[0].replace('D', 'E')) container[i][1] = float(words[1].replace('D', 'E')) container[i][2] = float(words[2].replace('D', 'E')) except (IndexError, ValueError): raise TinkerError('Could not parse values from dyn file')
def _read_interactions(self, f): """ Reads the number of interactions present in the system """ # Eat the next line (1 only) f.readline() line = f.readline() while line.strip(): try: key = TinkerAnalout.atom_inter_flags[line[1:20]] except KeyError: raise TinkerError('Unrecognized token in interaction count ' '[%s]' % line[1:20].strip()) self.pointers[key] = int(line[21:]) line = f.readline()
def _read_dipoles(self, f): """ Read atomic dipole polarizabilities """ self.dipole_list = DipolePolarizabilityList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['npole']): try: int(line[0:6]) at = int(line[9:15]) - 1 self.dipole_list.add(self.atom_list[at], line[25:35], line[40:].split()) except ValueError: raise TinkerError('Error parsing dipole polarizabilities') line = f.readline()
def _read_pitors(self, f): """ Read the Pi-Orbital Torsion parameters """ self.pitors_list = PiTorsionList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['npitors']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 self.pitors_list.add(self.atom_list[at1], self.atom_list[at2], line[40:50]) except ValueError: raise TinkerError('Error parsing pi-torsion term') line = f.readline()
def _read_bonds(self, f): """ Reads the bond stretching terms """ self.bond_list = BondList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['nbond']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 self.bond_list.add(self.atom_list[at1], self.atom_list[at2], line[40:50], line[50:60]) except ValueError: raise TinkerError('Error parsing bonded term') line = f.readline()
def _read_angs(self, f): """ Reads the angle stretching terms """ self.angle_list = AngleList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['nangle']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 at3 = int(line[21:27]) - 1 self.angle_list.add(self.atom_list[at1], self.atom_list[at2], self.atom_list[at3], line[40:50], line[50:60], line[60:67], line[69:]) except ValueError: raise TinkerError('Error parsing angle term') line = f.readline()
def _read_opdist(self, f): """ Read the out-of-plane distance parameters """ self.oopdist_list = OutOfPlaneDistList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['nopdist']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 at3 = int(line[21:27]) - 1 at4 = int(line[27:33]) - 1 self.oopdist_list.add(self.atom_list[at1], self.atom_list[at2], self.atom_list[at3], self.atom_list[at4], line[42:52]) except ValueError: raise TinkerError('Error parsing out-of-plane distance term') line = f.readline()
def _read_strbnd(self, f): """ Reads the stretch-bend terms """ self.stretchbend_list = StretchBendList() # Eat the next 3 lines f.readline() f.readline() f.readline() line = f.readline() for i in range(self.pointers['nstrbnd']): try: int(line[0:6]) at1 = int(line[9:15]) - 1 at2 = int(line[15:21]) - 1 at3 = int(line[21:27]) - 1 self.stretchbend_list.add(self.atom_list[at1], self.atom_list[at2], self.atom_list[at3], line[27:40], line[40:50], line[50:60], line[60:70]) except ValueError: raise TinkerError('Error parsing stretch-bend term') line = f.readline()
def read(self, fname): """ Parses the .dyn file """ f = open(fname, 'r') try: if f.readline().strip() != 'Number of Atoms and Title :': raise TinkerError('%s is not a recognized TINKER .dyn file' % fname) line = f.readline() self.natom, self.title = int(line[0:8].strip()), line[8:].strip() if f.readline().strip() != 'Periodic Box Dimensions :': raise TinkerError('No periodic box dimension line') self.box = [0.0 for i in range(6)] words = f.readline().upper().split() self.box[0] = float(words[0].replace('D', 'E')) self.box[1] = float(words[1].replace('D', 'E')) self.box[2] = float(words[2].replace('D', 'E')) words = f.readline().upper().split() self.box[3] = float(words[0].replace('D', 'E')) self.box[4] = float(words[1].replace('D', 'E')) self.box[5] = float(words[2].replace('D', 'E')) if f.readline().strip() != 'Current Atomic Positions :': raise TinkerError('No atomic positions in .dyn file') self.positions = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.positions, self.natom) line = f.readline().strip() if line == 'Current Translational Velocities :': self.rigidbody = True self.translational_velocities = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.translational_velocities, self.natom) if f.readline().strip() != 'Current Angular Velocities :': raise TinkerError('Could not find Angular velocity ' 'section in .dyn file') self.angular_velocities = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.angular_velocities, self.natom) if f.readline().strip() != 'Current Angular Momenta :': raise TinkerError('Could not find angular momenta section ' 'in .dyn file') self.angular_momenta = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.angular_momenta, self.natom) elif line == 'Current Atomic Velocities :': self.rigidbody = False self.velocities = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.velocities, self.natom) if f.readline().strip() != 'Current Atomic Accelerations :': raise TinkerError('Could not find accelerations in %s ' % fname) self.accelerations = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.accelerations, self.natom) if f.readline().strip() != 'Alternate Atomic Accelerations :': raise TinkerError( 'Could not find old accelerations in %s' % fname) self.old_accelerations = [[0.0, 0.0, 0.0] for i in range(self.natom)] DynFile._read_section(f, self.old_accelerations, self.natom) else: raise TinkerError('No velocities in %s' % fname) finally: f.close()
def read(self, fname): """ Reads the analout file """ self.pointers = dict(natom=0, norbit=0, nbond=0, nbpi=0, nangle=0, nstrbnd=0, nurey=0, nangang=0, nopbend=0, nopdist=0, niprop=0, nitors=0, ntors=0, npitors=0, nstrtor=0, ntortor=0, nion=0, ndipole=0, npole=0, pair12=0, pair13=0, pair14=0, pair15=0) self.fname = fname f = open(self.fname, 'r') try: line = f.readline() # Look for the TINKER watermark while True: if not line: raise TinkerError('Could not find the TINKER watermark ' 'in %s' % fname) if line.lstrip().startswith('### TINKER'): break line = f.readline() # Get the numbers of all parameters while not line.lstrip().startswith( 'Total Numbers of Atoms and Interactions'): if not line: raise TinkerError('Could not find the atom/ixn count') line = f.readline() # Eat the next line f.readline() line = f.readline() # Get all of the pointers while line.strip(): try: key = TinkerAnalout.atom_inter_flags[line[:27].strip()] except KeyError: raise TinkerError('Unrecognized pointer keyword %s' % key) try: self.pointers[key] = int(line[27:].strip()) except ValueError: raise TinkerError('Could not convert pointer %s to int ' '[%s]' % (key, line.rstrip())) except KeyError: raise Exception('Should not be here -- internal error') line = f.readline() # Check that we read in some pointers s = 0 for key in self.pointers: s += self.pointers[key] if s <= 0: raise TinkerError('All pointers are 0') # Get the atoms in the next section while line.strip() != 'Atom Type Definition Parameters :': if not line: raise TinkerError('Unexpected EOF when looking for atom ' 'definitions') line = f.readline() TinkerAnalout._read_atom_definitions(self, f) # Get all of the sections defined in _functionmap -- see bottom of # this file while True: line = f.readline() try: self._functionmap[line.strip()](self, f) except KeyError: break finally: f.close()
def load_parameter_file(self, fname): """ Parses a parameter file and loads all of the parameters found into data structures. """ self.attributes = dict() # First load the attributes from the header f = BookmarkedFile(fname, 'r') done_with_attributes = False line = f.readline().replace('\t', ' ') while line and not done_with_attributes: if 'Literature References' in line: done_with_attributes = True break line = (line + '#').strip() line = line[:line.index('#')].strip() if not line: line = f.readline().replace('\t', ' ') continue words = line.split() if len(words) != 2: continue # Now extract the property if _IS_INT(words[1]): self.attributes[words[0].lower()] = int(words[1]) elif _IS_FLOAT(words[1]): self.attributes[words[0].lower()] = float(words[1]) else: self.attributes[words[0].lower()] = words[1] line = f.readline().replace('\t', ' ') if not done_with_attributes: raise TinkerError('Could not find force field attributes.') # Now get the atom types while line.lstrip()[:5].lower() != 'atom ': line = f.readline().replace('\t', ' ') # Now loop through all atoms while line.lstrip()[:5].lower() == 'atom ': rematch = self.atomre.match(line) num, typenum, name, descrip, anum, mass, val = rematch.groups() self.atoms[int(num)] = _Atom(typenum, name, descrip, anum, mass, val) line = f.readline().replace('\t', ' ') # Now parse out the van der waals terms while line.lstrip()[:4].lower() != 'vdw ': line = f.readline().replace('\t', ' ') while line.lstrip()[:4].lower() == 'vdw ': _AtomType.set_vdw_params(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Now parse out the bonds while line.lstrip()[:5].lower() != 'bond ': line = f.readline().replace('\t', ' ') while line.lstrip()[:5].lower() == 'bond ': _BondType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Now parse out the angles. Handle iring and Fourier terms rematch = self.anglere.match(line) while not rematch: line = f.readline().replace('\t', ' ') rematch = self.anglere.match(line) while rematch: try: get_angle_type(rematch.groups()[0], *line.split()[1:]) except TypeError as err: print(repr(rematch.groups()[0]), line.split()[1:]) raise err line = f.readline().replace('\t', ' ') rematch = self.anglere.match(line) # Now parse out the stretch-bend parameters while line.lstrip()[:7].lower() != 'strbnd ': line = f.readline().replace('\t', ' ') while line.lstrip()[:7].lower() == 'strbnd ': _StretchBendType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Get the Urey-Bradley term(s). From here on out, some of the terms may # not exist in all versions of the force field, so protect for EOF and # make sure we rewind to avoid missing any terms f.mark() while line.lstrip()[:9].lower() != 'ureybrad ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:9].lower() == 'ureybrad ' and line: f.mark() _UreyBradleyType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Get the out-of-plane bending f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:7].lower() != 'opbend ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:7].lower() == 'opbend ' and line: f.mark() _OPBendType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Get the torsion parameters f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:8].lower() != 'torsion ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:8].lower() == 'torsion ' and line: f.mark() _DihedralType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Get the pitorsions f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:7] != 'pitors ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:7] == 'pitors ' and line: f.mark() _PiTorsionType(*line.split()[1:]) line = f.readline().replace('\t', ' ') # Get the coupled torsions f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:8] != 'tortors ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:8] == 'tortors ' and line: words = line.split() tortor = _TorsionTorsionType(words[1:6], words[6], words[7]) line = f.readline().replace('\t', ' ') while line.strip(): tortor.add_point(*line.split()) line = f.readline().replace('\t', ' ') line = f.readline().replace('\t', ' ') f.mark() # Get the multipole terms f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:10].lower() != 'multipole ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:10].lower() == 'multipole ' and line: words = line.split() multipole = _MultipoleType(words[1:-1], words[-1]) multipole.add_terms(f.readline().split()) multipole.add_terms(f.readline().split()) multipole.add_terms(f.readline().split()) multipole.add_terms(f.readline().split()) line = f.readline().replace('\t', ' ') f.mark() # Get the dipole polarizabilities f.rewind(); line = f.readline().replace('\t', ' ') while line.lstrip()[:9] != 'polarize ' and line: line = f.readline().replace('\t', ' ') while line.lstrip()[:9] == 'polarize ' and line: words = line.split() index = int(words[1]) try: self.atoms[index].set_polarizability( words[2], words[3], words[4:] ) except IndexError: self.atoms[index].set_polarizability(words[2], words[3], []) line = f.readline().replace('\t', ' ') f.close() # Now clean up so we can load another parameter set reset() return