gromacsgrofile.py 8.57 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

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.

9
Portions copyright (c) 2012-2015 Stanford University and the Authors.
Peter Eastman's avatar
Peter Eastman committed
10
Authors: Lee-Ping Wang, Peter Eastman
11
12
Contributors:

Justin MacCallum's avatar
Justin MacCallum committed
13
Permission is hereby granted, free of charge, to any person obtaining a
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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.
"""
31
from __future__ import absolute_import
32
33
34
35
36
37
38
__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
39
from simtk.unit import nanometers, angstroms, Quantity
40
from . import element as elem
41
42
43
44
45
try:
    import numpy
except:
    pass

Peter Eastman's avatar
Peter Eastman committed
46
def _isint(word):
47
48
49
50
    """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)
Justin MacCallum's avatar
Justin MacCallum committed
51

52
53
54
    """
    return match('^[-+]?[0-9]+$',word)

Peter Eastman's avatar
Peter Eastman committed
55
def _isfloat(word):
56
57
58
59
60
    """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
Justin MacCallum's avatar
Justin MacCallum committed
61

62
63
64
    """
    return match('^[-+]?[0-9]*\.?[0-9]*([eEdD][-+]?[0-9]+)?$',word)

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

    @param[in] line The line to be tested
Justin MacCallum's avatar
Justin MacCallum committed
69

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

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

    @param[in] line The line to be tested
Justin MacCallum's avatar
Justin MacCallum committed
83

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

93
94
95
96
97
98
99
100
101
102
103
104
def _construct_box_vectors(line):
    """Create the periodic box vectors based on the values stored in the file.

    @param[in] line The line containing the description
    """

    sline = line.split()
    values = [float(i) for i in sline]
    if len(sline) == 3:
        return (Vec3(values[0], 0, 0), Vec3(0, values[1], 0), Vec3(0, 0, values[2]))*nanometers
    return (Vec3(values[0], values[3], values[4]), Vec3(values[5], values[1], values[6]), Vec3(values[7], values[8], values[2]))*nanometers

Peter Eastman's avatar
Peter Eastman committed
105
106
class GromacsGroFile(object):
    """GromacsGroFile parses a Gromacs .gro file and constructs a set of atom positions from it.
Justin MacCallum's avatar
Justin MacCallum committed
107

Peter Eastman's avatar
Peter Eastman committed
108
109
110
    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."""
Justin MacCallum's avatar
Justin MacCallum committed
111

112
    def __init__(self, file):
Peter Eastman's avatar
Peter Eastman committed
113
        """Load a .gro file.
Justin MacCallum's avatar
Justin MacCallum committed
114

115
        The atom positions can be retrieved by calling getPositions().
Justin MacCallum's avatar
Justin MacCallum committed
116

117
118
119
120
121
        Parameters:
         - file (string) the name of the file to load
        """

        xyzs     = []
Peter Eastman's avatar
Peter Eastman committed
122
        elements = [] # The element, most useful for quantum chemistry calculations
123
124
125
126
127
128
129
130
131
132
133
134
135
        atomname = [] # The atom name, for instance 'HW1'
        comms    = []
        resid    = []
        resname  = []
        boxes    = []
        xyz      = []
        ln       = 0
        frame    = 0
        for line in open(file):
            if ln == 0:
                comms.append(line.strip())
            elif ln == 1:
                na = int(line.strip())
Peter Eastman's avatar
Peter Eastman committed
136
            elif _is_gro_coord(line):
137
                if frame == 0: # Create the list of residues, atom names etc. only if it's the first frame.
138
                    (thisresnum, thisresname, thisatomname) = [line[i*5:i*5+5].strip() for i in range(3)]
139
                    resname.append(thisresname)
140
141
142
                    resid.append(int(thisresnum))
                    atomname.append(thisatomname)
                    thiselem = thisatomname
143
144
                    if len(thiselem) > 1:
                        thiselem = thiselem[0] + sub('[A-Z0-9]','',thiselem[1:])
Peter Eastman's avatar
Peter Eastman committed
145
146
147
148
                        try:
                            elements.append(elem.get_by_symbol(thiselem))
                        except KeyError:
                            elements.append(None)
149
150
151
152
                firstDecimalPos = line.index('.', 20)
                secondDecimalPos = line.index('.', firstDecimalPos+1)
                digits = secondDecimalPos-firstDecimalPos
                pos = [float(line[20+i*digits:20+(i+1)*digits]) for i in range(3)]
153
                xyz.append(Vec3(pos[0], pos[1], pos[2]))
Peter Eastman's avatar
Peter Eastman committed
154
            elif _is_gro_box(line) and ln == na + 2:
155
                sline = line.split()
156
                boxes.append(_construct_box_vectors(line))
157
158
159
160
161
                xyzs.append(xyz*nanometers)
                xyz = []
                ln = -1
                frame += 1
            else:
Peter Eastman's avatar
Peter Eastman committed
162
                raise Exception("Unexpected line in .gro file: "+line)
163
            ln += 1
Justin MacCallum's avatar
Justin MacCallum committed
164

Peter Eastman's avatar
Peter Eastman committed
165
166
167
168
169
170
171
172
173
174
175
        ## 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
176
        self._periodicBoxVectors = boxes
177
        self._numpyPositions = None
Justin MacCallum's avatar
Justin MacCallum committed
178

Peter Eastman's avatar
Peter Eastman committed
179
180
181
    def getNumFrames(self):
        """Get the number of frames stored in the file."""
        return len(self._positions)
Justin MacCallum's avatar
Justin MacCallum committed
182

Peter Eastman's avatar
Peter Eastman committed
183
    def getPositions(self, asNumpy=False, frame=0):
184
        """Get the atomic positions.
Justin MacCallum's avatar
Justin MacCallum committed
185

Robert McGibbon's avatar
Robert McGibbon committed
186
187
188
189
190
191
192
193
        Parameters
        ----------
        asNumpy : boolean=False
            if true, the values are returned as a numpy array instead of a list
            of Vec3s
        frame : int=0
            the index of the frame for which to get positions
        """
194
195
        if asNumpy:
            if self._numpyPositions is None:
Peter Eastman's avatar
Peter Eastman committed
196
197
                self._numpyPositions = [None]*len(self._positions)
            if self._numpyPositions[frame] is None:
198
                self._numpyPositions[frame] = Quantity(numpy.array(self._positions[frame].value_in_unit(nanometers)), nanometers)
Peter Eastman's avatar
Peter Eastman committed
199
200
            return self._numpyPositions[frame]
        return self._positions[frame]
Justin MacCallum's avatar
Justin MacCallum committed
201

202
203
204
    def getPeriodicBoxVectors(self, frame=0):
        """Get the vectors defining the periodic box.

Robert McGibbon's avatar
Robert McGibbon committed
205
206
207
208
        Parameters
        ----------
        frame : int=0
            the index of the frame for which to get the box vectors
209
210
211
        """
        return self._periodicBoxVectors[frame]

Peter Eastman's avatar
Peter Eastman committed
212
213
    def getUnitCellDimensions(self, frame=0):
        """Get the dimensions of the crystallographic unit cell.
Justin MacCallum's avatar
Justin MacCallum committed
214

Robert McGibbon's avatar
Robert McGibbon committed
215
216
217
218
        Parameters
        ----------
        frame : int=0
            the index of the frame for which to get the unit cell dimensions
Peter Eastman's avatar
Peter Eastman committed
219
        """
220
221
222
223
        xsize = self._periodicBoxVectors[frame][0][0].value_in_unit(nanometers)
        ysize = self._periodicBoxVectors[frame][1][1].value_in_unit(nanometers)
        zsize = self._periodicBoxVectors[frame][2][2].value_in_unit(nanometers)
        return Vec3(xsize, ysize, zsize)*nanometers