gromacsgrofile.py 7.37 KB
Newer Older
1
"""
Peter Eastman's avatar
Peter Eastman committed
2
grofile.py: Used for loading Gromacs GRO files.
3
4
5
6
7
8
9

This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, grant U54 GM072970. See https://simtk.org.

Portions copyright (c) 2012 Stanford University and the Authors.
Peter Eastman's avatar
Peter Eastman committed
10
Authors: Lee-Ping Wang, Peter Eastman
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Contributors:

Permission is hereby granted, free of charge, to any person obtaining a 
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
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.
"""
__author__ = "Lee-Ping Wang"
__version__ = "1.0"

import os
import sys
from simtk.openmm import Vec3
from re import sub, match
Peter Eastman's avatar
Peter Eastman committed
38
39
from simtk.unit import nanometers, angstroms
import element as elem
40
41
42
43
44
try:
    import numpy
except:
    pass

Peter Eastman's avatar
Peter Eastman committed
45
def _isint(word):
46
47
48
49
50
51
52
53
    """ONLY matches integers! If you have a decimal point? None shall pass!

    @param[in] word String (for instance, '123', '153.0', '2.', '-354')
    @return answer Boolean which specifies whether the string is an integer (only +/- sign followed by digits)
    
    """
    return match('^[-+]?[0-9]+$',word)

Peter Eastman's avatar
Peter Eastman committed
54
def _isfloat(word):
55
56
57
58
59
60
61
62
63
    """Matches ANY number; it can be a decimal, scientific notation, what have you
    CAUTION - this will also match an integer.

    @param[in] word String (for instance, '123', '153.0', '2.', '-354')
    @return answer Boolean which specifies whether the string is any number
    
    """
    return match('^[-+]?[0-9]*\.?[0-9]*([eEdD][-+]?[0-9]+)?$',word)

Peter Eastman's avatar
Peter Eastman committed
64
def _is_gro_coord(line):
65
66
67
68
69
70
71
    """ Determines whether a line contains GROMACS data or not

    @param[in] line The line to be tested
    
    """
    sline = line.split()
    if len(sline) == 6 or len(sline) == 9:
Peter Eastman's avatar
Peter Eastman committed
72
        return all([_isint(sline[2]), _isfloat(sline[3]), _isfloat(sline[4]), _isfloat(sline[5])])
73
    elif len(sline) == 5 or len(sline) == 8:
Peter Eastman's avatar
Peter Eastman committed
74
        return all([_isint(line[15:20]), _isfloat(sline[2]), _isfloat(sline[3]), _isfloat(sline[4])])
75
76
77
    else:
        return 0

Peter Eastman's avatar
Peter Eastman committed
78
def _is_gro_box(line):
79
80
81
82
83
84
    """ Determines whether a line contains a GROMACS box vector or not

    @param[in] line The line to be tested
    
    """
    sline = line.split()
Peter Eastman's avatar
Peter Eastman committed
85
    if len(sline) == 9 and all([_isfloat(i) for i in sline]):
86
        return 1
Peter Eastman's avatar
Peter Eastman committed
87
    elif len(sline) == 3 and all([_isfloat(i) for i in sline]):
88
89
90
91
        return 1
    else:
        return 0

Peter Eastman's avatar
Peter Eastman committed
92
93
94
95
96
97
class GromacsGroFile(object):
    """GromacsGroFile parses a Gromacs .gro file and constructs a set of atom positions from it.
    
    A .gro file also contains some topological information, such as elements and residue names,
    but not enough to construct a full Topology object.  This information is recorded and stored
    in the object's public fields."""
98
99
    
    def __init__(self, file):
Peter Eastman's avatar
Peter Eastman committed
100
        """Load a .gro file.
101
102
103
104
105
106
107
108
        
        The atom positions can be retrieved by calling getPositions().
        
        Parameters:
         - file (string) the name of the file to load
        """

        xyzs     = []
Peter Eastman's avatar
Peter Eastman committed
109
        elements = [] # The element, most useful for quantum chemistry calculations
110
111
112
113
114
115
116
117
118
119
120
121
122
123
        atomname = [] # The atom name, for instance 'HW1'
        comms    = []
        resid    = []
        resname  = []
        boxes    = []
        xyz      = []
        ln       = 0
        frame    = 0
        for line in open(file):
            sline = line.split()
            if ln == 0:
                comms.append(line.strip())
            elif ln == 1:
                na = int(line.strip())
Peter Eastman's avatar
Peter Eastman committed
124
            elif _is_gro_coord(line):
125
126
127
128
129
130
131
132
133
                if frame == 0: # Create the list of residues, atom names etc. only if it's the first frame.
                    # Name of the residue, for instance '153SOL1 -> SOL1' ; strips leading numbers
                    thisresname = sub('^[0-9]*','',sline[0])
                    resname.append(thisresname)
                    resid.append(int(sline[0].replace(thisresname,'')))
                    atomname.append(sline[1])
                    thiselem = sline[1]
                    if len(thiselem) > 1:
                        thiselem = thiselem[0] + sub('[A-Z0-9]','',thiselem[1:])
Peter Eastman's avatar
Peter Eastman committed
134
135
136
137
                        try:
                            elements.append(elem.get_by_symbol(thiselem))
                        except KeyError:
                            elements.append(None)
138
139
                pos = [float(i) for i in sline[-3:]]
                xyz.append(Vec3(pos[0], pos[1], pos[2]))
Peter Eastman's avatar
Peter Eastman committed
140
            elif _is_gro_box(line) and ln == na + 2:
141
142
143
144
145
146
                boxes.append([float(i) for i in sline]*nanometers)
                xyzs.append(xyz*nanometers)
                xyz = []
                ln = -1
                frame += 1
            else:
Peter Eastman's avatar
Peter Eastman committed
147
                raise Exception("Unexpected line in .gro file: "+line)
148
149
            ln += 1
            
Peter Eastman's avatar
Peter Eastman committed
150
151
152
153
154
155
156
157
158
159
160
161
        ## The atom positions read from the file.  If the file contains multiple frames, these are the positions in the first frame.
        self.positions = xyzs[0]
        ## A list containing the element of each atom stored in the file
        self.elements = elements
        ## A list containing the name of each atom stored in the file
        self.atomNames = atomname
        ## A list containing the ID of the residue that each atom belongs to
        self.residueIds = resid
        ## A list containing the name of the residue that each atom belongs to
        self.residueNames = resname
        self._positions = xyzs
        self._unitCellDimensions = boxes
162
        self._numpyPositions = None
Peter Eastman's avatar
Peter Eastman committed
163
164
165
166
167
168
    
    def getNumFrames(self):
        """Get the number of frames stored in the file."""
        return len(self._positions)
    
    def getPositions(self, asNumpy=False, frame=0):
169
170
171
172
        """Get the atomic positions.
        
        Parameters:
         - asNumpy (boolean=False) if true, the values are returned as a numpy array instead of a list of Vec3s
Peter Eastman's avatar
Peter Eastman committed
173
         - frame (int=0) the index of the frame for which to get positions
174
175
176
         """
        if asNumpy:
            if self._numpyPositions is None:
Peter Eastman's avatar
Peter Eastman committed
177
178
                self._numpyPositions = [None]*len(self._positions)
            if self._numpyPositions[frame] is None:
179
                self._numpyPositions[frame] = Quantity(numpy.array(self._positions[frame].value_in_unit(nanometers)), nanometers)
Peter Eastman's avatar
Peter Eastman committed
180
181
            return self._numpyPositions[frame]
        return self._positions[frame]
182
    
Peter Eastman's avatar
Peter Eastman committed
183
184
185
186
187
188
189
    def getUnitCellDimensions(self, frame=0):
        """Get the dimensions of the crystallographic unit cell.
        
        Parameters:
         - frame (int=0) the index of the frame for which to get the unit cell dimensions
        """
        return self._unitCellDimensions[frame]