phbuilder 1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- phbuilder/__init__.py +16 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/atomtypes.atp +455 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/cmap.itp +1025 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffbonded.itp +19675 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffnonbonded.itp +40366 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.doc +252 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.itp +26 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/gb.itp +49 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/ions.itp +98 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.arn +6 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.c.tdb +76 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.hdb +414 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.n.tdb +93 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.r2b +16 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.rtp +123316 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.vsd +221 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/nbfix.itp +101 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/old_c36_cmap.itp +486 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/popc.itp +1279 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/spc.itp +30 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/spce.itp +30 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip3p.itp +49 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip4p.itp +53 -0
- phbuilder/ffield/charmm36-mar2019-cphmd.ff/watermodels.dat +6 -0
- phbuilder/ffield/lambdagrouptypes.dat +40 -0
- phbuilder/ffield/residuetypes.dat +211 -0
- phbuilder/mdp.py +133 -0
- phbuilder/parsecmdline.py +228 -0
- phbuilder/phbuilder.py +1408 -0
- phbuilder/sanitize.py +180 -0
- phbuilder/structure.py +333 -0
- phbuilder/user.py +142 -0
- phbuilder-1.1.dist-info/LICENSE +674 -0
- phbuilder-1.1.dist-info/METADATA +609 -0
- phbuilder-1.1.dist-info/RECORD +38 -0
- phbuilder-1.1.dist-info/WHEEL +5 -0
- phbuilder-1.1.dist-info/entry_points.txt +2 -0
- phbuilder-1.1.dist-info/top_level.txt +1 -0
phbuilder/phbuilder.py
ADDED
|
@@ -0,0 +1,1408 @@
|
|
|
1
|
+
import configparser
|
|
2
|
+
import subprocess
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from .user import User
|
|
6
|
+
from .sanitize import Sanitize
|
|
7
|
+
from .structure import Structure
|
|
8
|
+
from .mdp import gen_mdp
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LambdaType:
|
|
12
|
+
"""Data structure for storing a LambdaType.
|
|
13
|
+
"""
|
|
14
|
+
def __init__(self, groupname: str, incl: list, pKa: list, atoms: list, qqA: list, qqB: list, dvdl: list):
|
|
15
|
+
"""Initialize LambdaType object.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
groupname (str): name of the LambdaGroupType. E.g. ASPT.
|
|
19
|
+
incl (list): residue name variants to consider. E.g. ASP, ASPH.
|
|
20
|
+
pKa (list): pKa value(s).
|
|
21
|
+
atoms (list): titratable atom names.
|
|
22
|
+
qqA (list): titratable atom charges in state A.
|
|
23
|
+
qqB (list): titratable atom charges in state B.
|
|
24
|
+
dvdl (list): dV/dl coefficients.
|
|
25
|
+
"""
|
|
26
|
+
self.d_groupname = groupname
|
|
27
|
+
self.d_incl = incl
|
|
28
|
+
self.d_pKa = pKa
|
|
29
|
+
self.d_atoms = atoms
|
|
30
|
+
self.d_qqA = qqA
|
|
31
|
+
self.d_qqB = qqB
|
|
32
|
+
self.d_dvdl = dvdl
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class phbuilder(User):
|
|
36
|
+
"""Main phbuilder object."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, CLI):
|
|
39
|
+
"""Construct phbuilder object. Handles both input parsed from the command line
|
|
40
|
+
as well from the lambdagrouptypes.dat file.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
CLI (dict): parsed command line arguments.
|
|
44
|
+
"""
|
|
45
|
+
# Handle verbosity
|
|
46
|
+
if CLI.verbosity is not None: # If -v flag is set...
|
|
47
|
+
self.d_verbosity = 3
|
|
48
|
+
else:
|
|
49
|
+
self.d_verbosity = 2
|
|
50
|
+
|
|
51
|
+
# Inherit all methods from User class and initialize.
|
|
52
|
+
super().__init__(self.d_verbosity, logFileName='builder.log')
|
|
53
|
+
|
|
54
|
+
# Command line parameters that are always required (by all three subtools).
|
|
55
|
+
self.d_target = CLI.target
|
|
56
|
+
self.d_file = Sanitize(CLI.file, 'file').path(ext=['.pdb', '.gro'])
|
|
57
|
+
|
|
58
|
+
# If we run gentopol...
|
|
59
|
+
if (CLI.target == 'gentopol'):
|
|
60
|
+
self.d_output = Sanitize(CLI.output, 'output').path(ext=['.pdb', '.gro'], out=True)
|
|
61
|
+
self.ph_auto = CLI.ph # None if not set, else float
|
|
62
|
+
|
|
63
|
+
# If we run neutralize...
|
|
64
|
+
elif (CLI.target == 'neutralize'):
|
|
65
|
+
# Either required or has a default value.
|
|
66
|
+
self.d_output = Sanitize(CLI.output, 'output').path(ext=['.pdb', '.gro'], out=True)
|
|
67
|
+
self.d_topol = Sanitize(CLI.topol, 'topol').path(ext=['.top'])
|
|
68
|
+
self.d_solname = Sanitize(CLI.solname, 'solname').string(Range=[1, 4], upper=True, ws=False)
|
|
69
|
+
self.d_pname = Sanitize(CLI.pname, 'pname').string(Range=[1, 4], upper=True, ws=False)
|
|
70
|
+
self.d_nname = Sanitize(CLI.nname, 'nname').string(Range=[1, 4], upper=True, ws=False)
|
|
71
|
+
self.d_conc = Sanitize(CLI.conc, 'conc').num(signed=True)
|
|
72
|
+
self.d_rmin = Sanitize(CLI.rmin, 'rmin').num(signed=True)
|
|
73
|
+
|
|
74
|
+
# Optional
|
|
75
|
+
if CLI.nbufs is not None:
|
|
76
|
+
self.ph_nbufs = Sanitize(CLI.nbufs, 'nbufs').num(signed=True, Type=int)
|
|
77
|
+
|
|
78
|
+
if CLI.ignw is not None:
|
|
79
|
+
self.d_ignw = -1
|
|
80
|
+
else:
|
|
81
|
+
self.d_ignw = 0
|
|
82
|
+
|
|
83
|
+
# This needs to be defined because neutralize calls writeLambda_mdp.
|
|
84
|
+
self.ph_cal = False
|
|
85
|
+
|
|
86
|
+
# If we run genparams...
|
|
87
|
+
elif (CLI.target == 'genparams'):
|
|
88
|
+
|
|
89
|
+
if CLI.mdp is not None:
|
|
90
|
+
self.d_mdp = Sanitize(CLI.mdp, 'mdp').path(ext=['.mdp'])
|
|
91
|
+
else:
|
|
92
|
+
self.d_mdp = None
|
|
93
|
+
|
|
94
|
+
if CLI.ndx is not None:
|
|
95
|
+
self.d_ndx = Sanitize(CLI.ndx, 'ndx').path(ext=['.ndx'])
|
|
96
|
+
else:
|
|
97
|
+
self.d_ndx = None
|
|
98
|
+
|
|
99
|
+
self.ph_ph = Sanitize(CLI.ph, 'ph').num(Range=[0, 14])
|
|
100
|
+
self.ph_nstout = Sanitize(CLI.nstout, 'nstout').num(Type=int, signed=True)
|
|
101
|
+
self.ph_dwpE = Sanitize(CLI.dwpE, 'dwpE').num(signed=True)
|
|
102
|
+
|
|
103
|
+
# Process whether the -inter flag was or wasn't set.
|
|
104
|
+
if CLI.inter is not None:
|
|
105
|
+
self.ph_inter = True
|
|
106
|
+
else:
|
|
107
|
+
self.ph_inter = False
|
|
108
|
+
|
|
109
|
+
# Process whether the -cal flag was or wasn't set.
|
|
110
|
+
if CLI.cal is not None:
|
|
111
|
+
self.ph_cal = True
|
|
112
|
+
else:
|
|
113
|
+
self.ph_cal = False
|
|
114
|
+
|
|
115
|
+
# User information.
|
|
116
|
+
self.verbose("Parsed the following input from the command line:")
|
|
117
|
+
self.verbose(vars(CLI))
|
|
118
|
+
|
|
119
|
+
self.parseLambdaGroupTypesFile()
|
|
120
|
+
self.checkCorrectGromacsSettings()
|
|
121
|
+
|
|
122
|
+
def parseLambdaGroupTypesFile(self):
|
|
123
|
+
"""Parse lambdagrouptypes.dat file and load into internal data structure.
|
|
124
|
+
"""
|
|
125
|
+
# Initialize some entries
|
|
126
|
+
self.ph_lambdaTypes = []
|
|
127
|
+
self.ph_BUF_dvdl = None
|
|
128
|
+
|
|
129
|
+
def defineLambdaType(groupname: str, incl: list, pKa: list, atoms: list, qqA: list, qqB: list, dvdl: list):
|
|
130
|
+
"""Add lambdaType to ph_lambdaTypes (or skip if it is already there).
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
groupname (str): name of the LambdaGroupType. E.g. ASPT.
|
|
134
|
+
incl (list): residue name variants to consider. E.g. ASP, ASPH.
|
|
135
|
+
pKa (list): pKa value(s).
|
|
136
|
+
atoms (list): titratable atom names.
|
|
137
|
+
qqA (list): titratable atom charges in state A.
|
|
138
|
+
qqB (list): titratable atom charges in state B.
|
|
139
|
+
dvdl (list): dV/dl coefficients.
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
# Create a temporary LambdaType object.
|
|
143
|
+
NewLambdaType = LambdaType(groupname, incl, pKa, atoms, qqA, qqB, dvdl)
|
|
144
|
+
|
|
145
|
+
# Only add NewLambdaType to ph_lambdaTypes if it does not exist yet.
|
|
146
|
+
alreadyPresent = False
|
|
147
|
+
for entry in self.ph_lambdaTypes:
|
|
148
|
+
if entry.d_groupname == NewLambdaType.d_groupname:
|
|
149
|
+
self.warning(f"LambdaType with groupname {groupname} is already defined. Skipping...")
|
|
150
|
+
alreadyPresent = True
|
|
151
|
+
break
|
|
152
|
+
|
|
153
|
+
if not alreadyPresent:
|
|
154
|
+
self.ph_lambdaTypes.append(NewLambdaType)
|
|
155
|
+
|
|
156
|
+
def str2floatList(string: str):
|
|
157
|
+
"""Internal function to convert string to list of floats."""
|
|
158
|
+
return [float(val) for val in string.split(' ')]
|
|
159
|
+
|
|
160
|
+
def str2strList(string: str):
|
|
161
|
+
"""Internal function to convert string to list of strings."""
|
|
162
|
+
return string.split(' ')
|
|
163
|
+
|
|
164
|
+
# Get path to the packaging_data/ffield directory.
|
|
165
|
+
# packaging_data is in the same dir as phbuilder.py, so we can do this:
|
|
166
|
+
tail, _ = os.path.split(__file__)
|
|
167
|
+
self.p_ffield = os.path.normpath(tail + '/' + 'ffield')
|
|
168
|
+
|
|
169
|
+
# If there is a 'lambdagrouptypes.dat' in the working directory, this
|
|
170
|
+
# overrides the default one (located in the packaging_data/ffield).
|
|
171
|
+
if os.path.exists('lambdagrouptypes.dat'):
|
|
172
|
+
self.warning('Found \'lambdagrouptypes.dat\' in working dir, this overrides the default')
|
|
173
|
+
p_lambdagrouptypes = os.path.normpath(os.getcwd() + '/' + 'lambdagrouptypes.dat')
|
|
174
|
+
else:
|
|
175
|
+
p_lambdagrouptypes = os.path.normpath(self.p_ffield + '/' + 'lambdagrouptypes.dat')
|
|
176
|
+
# Error if lambdagrouptypes.dat is not present in directory.
|
|
177
|
+
if not os.path.isfile(p_lambdagrouptypes):
|
|
178
|
+
self.error('Did not find lambdagrouptypes.dat in {}. Please check your directory and/or update your PHFFIELD environment variable in your ~/.bashrc and reload terminal(s).'.format(self.p_ffield))
|
|
179
|
+
|
|
180
|
+
self.p_lambdagrouptypes = p_lambdagrouptypes
|
|
181
|
+
|
|
182
|
+
# User update
|
|
183
|
+
self.verbose('path to ffield dir = {}'.format(self.p_ffield))
|
|
184
|
+
self.verbose('path to lambdagrouptypes.dat = {}\n'.format(p_lambdagrouptypes))
|
|
185
|
+
|
|
186
|
+
# Do the actual parsing
|
|
187
|
+
parser = configparser.ConfigParser()
|
|
188
|
+
parser.read(p_lambdagrouptypes)
|
|
189
|
+
|
|
190
|
+
# Loop through the sections.
|
|
191
|
+
for sect in parser.sections():
|
|
192
|
+
|
|
193
|
+
# Parse GROMACS base path
|
|
194
|
+
if sect.strip() == "GROMACS":
|
|
195
|
+
self.d_gmxbasepath = parser.get(sect, 'path')
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
# Parse force field parameters
|
|
199
|
+
if sect.strip() == "FORCEFIELD":
|
|
200
|
+
self.d_modelFF = parser.get(sect, 'name')
|
|
201
|
+
self.d_modelwater = parser.get(sect, 'water')
|
|
202
|
+
continue
|
|
203
|
+
|
|
204
|
+
# Parse buffer parameters
|
|
205
|
+
if sect.strip() == "BUF":
|
|
206
|
+
self.ph_BUF_dvdl = str2floatList(parser.get(sect, 'dvdl'))
|
|
207
|
+
self.ph_BUF_range = str2floatList(parser.get(sect, 'range'))
|
|
208
|
+
continue
|
|
209
|
+
|
|
210
|
+
# Parse groupname
|
|
211
|
+
groupname = sect.strip()
|
|
212
|
+
|
|
213
|
+
# Parse incl
|
|
214
|
+
incl = str2strList(parser.get(sect, 'incl'))
|
|
215
|
+
|
|
216
|
+
# Parse atoms
|
|
217
|
+
atoms = str2strList(parser.get(sect, 'atoms'))
|
|
218
|
+
|
|
219
|
+
# Parse qqA
|
|
220
|
+
qqA = str2floatList(parser.get(sect, 'qqA'))
|
|
221
|
+
|
|
222
|
+
pKa = []
|
|
223
|
+
qqB = []
|
|
224
|
+
dvdl = []
|
|
225
|
+
for idx in range(1, 11): # Max 10 multisites
|
|
226
|
+
try:
|
|
227
|
+
# Parse pKa(s)
|
|
228
|
+
pKa.append(float(parser.get(sect, 'pKA_{}'.format(idx))))
|
|
229
|
+
|
|
230
|
+
# Parse qqB(s)
|
|
231
|
+
qqB.append(str2floatList(parser.get(sect, 'qqB_{}'.format(idx))))
|
|
232
|
+
|
|
233
|
+
# Parse dvdl(s)
|
|
234
|
+
dvdl.append(str2floatList(parser.get(sect, 'dvdl_{}'.format(idx))))
|
|
235
|
+
except configparser.NoOptionError:
|
|
236
|
+
break
|
|
237
|
+
|
|
238
|
+
# SANITIZE INPUT
|
|
239
|
+
|
|
240
|
+
groupname = Sanitize(groupname, "groupname in lambdagrouptypes.dat").string(Range=[2, 4], upper=True)
|
|
241
|
+
incl = [Sanitize(val, f"incl for {groupname} in lambdagrouptypes.dat").string(Range=[2, 4], upper=True) for val in incl]
|
|
242
|
+
atoms = [Sanitize(val, f"atoms for {groupname} in lambdagrouptypes.dat").string(Range=[1, 4], upper=True) for val in atoms]
|
|
243
|
+
qqA = [Sanitize(val, f"qqA for {groupname} in lambdagrouptypes.dat").num(Range=[-1.0, 1.0]) for val in qqA]
|
|
244
|
+
pKa = [Sanitize(val, f"pKa for {groupname} in lambdagrouptypes.dat").num(Range=[0, 14]) for val in pKa]
|
|
245
|
+
|
|
246
|
+
for array in qqB:
|
|
247
|
+
for val in array:
|
|
248
|
+
Sanitize(val, f"qqB for {groupname} in lambdagrouptypes.dat").num(Range=[-1, 1])
|
|
249
|
+
|
|
250
|
+
# Call function that constructs the LambdaType object.
|
|
251
|
+
defineLambdaType(groupname, incl, pKa, atoms, qqA, qqB, dvdl)
|
|
252
|
+
|
|
253
|
+
# USER UPDATE
|
|
254
|
+
self.verbose("gmxpath = {}".format(self.d_gmxbasepath))
|
|
255
|
+
self.verbose("ffname = {}".format(self.d_modelFF))
|
|
256
|
+
self.verbose("water = {}\n".format(self.d_modelwater))
|
|
257
|
+
|
|
258
|
+
for obj in self.ph_lambdaTypes:
|
|
259
|
+
self.verbose("groupname = {}".format(obj.d_groupname))
|
|
260
|
+
self.verbose("incl = {}".format(obj.d_incl))
|
|
261
|
+
self.verbose("pKa = {}".format(obj.d_pKa))
|
|
262
|
+
self.verbose("atoms = {}".format(obj.d_atoms))
|
|
263
|
+
self.verbose("qqA = {}".format(obj.d_qqA))
|
|
264
|
+
self.verbose("qqB = {}".format(obj.d_qqB))
|
|
265
|
+
self.verbose("dvdl = {}\n".format(obj.d_dvdl))
|
|
266
|
+
|
|
267
|
+
self.verbose("BUF_range = {}".format(self.ph_BUF_range))
|
|
268
|
+
self.verbose("BUF_dvdl = {}".format(self.ph_BUF_dvdl))
|
|
269
|
+
|
|
270
|
+
def checkCorrectGromacsSettings(self) -> None:
|
|
271
|
+
"""This function attempts to make sure that the GROMACS CpHMD install is correctly loaded in the environment from which phbuilder is called."""
|
|
272
|
+
|
|
273
|
+
# Part I is to make sure a valid path to the (supposed) GROMACS CpHMD
|
|
274
|
+
# installation is provided (either in lambdagrouptypes.dat or as the
|
|
275
|
+
# envvar GMXPH_BASEPATH).
|
|
276
|
+
if not os.path.isdir(self.d_gmxbasepath):
|
|
277
|
+
self.warning(f"GROMACS base path '{self.d_gmxbasepath}' specified in {self.p_lambdagrouptypes} does not seem to exist, will instead look for the GMXPH_BASEPATH environment variable...")
|
|
278
|
+
|
|
279
|
+
# Get the GROMACS base path from the environment variable.
|
|
280
|
+
fromEnvVar = os.getenv('GMXPH_BASEPATH')
|
|
281
|
+
|
|
282
|
+
if not isinstance(fromEnvVar, str): # If empty...
|
|
283
|
+
self.error("GMXPH_BASEPATH is not set. Please update your lambdagrouptypes.dat or GMXPH_BASEPATH.")
|
|
284
|
+
|
|
285
|
+
if not os.path.isdir(fromEnvVar): # If not empty but not existing...
|
|
286
|
+
self.error(f"GMXPH_BASEPATH was found, but the specified path '{fromEnvVar}' does not seem to exist. Please update your GMXPH_BASEPATH environment variable.")
|
|
287
|
+
|
|
288
|
+
self.d_gmxbasepath = fromEnvVar
|
|
289
|
+
|
|
290
|
+
# Now we do part II, we check if the GROMACS version loaded in the user
|
|
291
|
+
# environment matches the (supposed) path to th CpHMD version.
|
|
292
|
+
|
|
293
|
+
envDict = os.environ.copy() # Get a copy of the environment variables.
|
|
294
|
+
|
|
295
|
+
if 'GROMACS_DIR' not in envDict:
|
|
296
|
+
self.error(f"The GROMACS_DIR environment appears to not be set, indicating the GROMACS CpHMD installation was not or incorrectly loaded. The GROMACS CpHMD installation needs to be loaded for phbuilder to function correctly. Please try 'source {os.path.normpath(f'{self.d_gmxbasepath}/bin/GMXRC')}' or equivalent (e.g. module load) to load the correct version (printenv to check) before continuing.")
|
|
297
|
+
|
|
298
|
+
if envDict['GROMACS_DIR'] != self.d_gmxbasepath:
|
|
299
|
+
self.error(f"The detected GROMACS_DIR environment variable ({envDict['GROMACS_DIR']}) does not correspond to the correct GROMACS CpHMD installation ({self.d_gmxbasepath}). The GROMACS CpHMD installation needs to be loaded for phbuilder to function correctly. Please try 'source {os.path.normpath(f'{self.d_gmxbasepath}/bin/GMXRC')}' or equivalent (e.g. module load) to load the correct version (printenv to check) before continuing.")
|
|
300
|
+
|
|
301
|
+
else:
|
|
302
|
+
p1 = os.path.normpath(f"{self.d_gmxbasepath}/lib")
|
|
303
|
+
if 'LD_LIBRARY_PATH' in envDict and p1 not in envDict["LD_LIBRARY_PATH"]:
|
|
304
|
+
self.error(f"Although GROMACS_DIR appears to be set correctly, the LD_LIBRARY_PATH environment variable does not appear to include '{p1}', indicating the GROMACS CpHMD installation was loaded incorrectly. The GROMACS CpHMD installation needs to be loaded for phbuilder to function correctly. Please try 'source {os.path.normpath(f'{self.d_gmxbasepath}/bin/GMXRC')}' or equivalent (e.g. module load) to load the correct version (printenv to check) before continuing.")
|
|
305
|
+
|
|
306
|
+
p2 = os.path.normpath(f"{self.d_gmxbasepath}/bin")
|
|
307
|
+
if 'PATH' in envDict and p2 not in envDict["PATH"]:
|
|
308
|
+
self.error(f"Although GROMACS_DIR and LD_LIBRARY_PATH appear to be set correctly, the PATH environment variable does not appear to include '{p2}', indicating the GROMACS CpHMD installation was loaded incorrectly. The GROMACS CpHMD installation needs to be loaded for phbuilder to function correctly. Please try 'source {os.path.normpath(f'{self.d_gmxbasepath}/bin/GMXRC')}' or equivalent (e.g. module load) to load the correct version (printenv to check) before continuing.")
|
|
309
|
+
|
|
310
|
+
def gromacs(self, command: str, stdin: list = [], terminal: bool = False, logFile: str = 'builder.log') -> int:
|
|
311
|
+
"""Handles calls to GROMACS. Assumes the correct environment was set by checkCorrectGromacsSettings.
|
|
312
|
+
|
|
313
|
+
Args:
|
|
314
|
+
command (str): GROMACS command, e.g. 'make_ndx -f protein.pdb'.
|
|
315
|
+
stdin (list, optional): list of input arguments. Defaults to [].
|
|
316
|
+
terminal (bool, optional): print output to terminal. Defaults to False.
|
|
317
|
+
logFile (str, optional): log file to use when terminal=False. Defaults to 'gromacs.log'.
|
|
318
|
+
|
|
319
|
+
Returns:
|
|
320
|
+
int: return code (0 if things were successful).
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
if stdin:
|
|
324
|
+
xstr = ' << EOF\n'
|
|
325
|
+
for val in stdin:
|
|
326
|
+
xstr += '{}\n'.format(val)
|
|
327
|
+
command += xstr + 'EOF'
|
|
328
|
+
|
|
329
|
+
self.verbose("Running {} ...".format(command))
|
|
330
|
+
|
|
331
|
+
envDict = os.environ.copy()
|
|
332
|
+
|
|
333
|
+
if terminal:
|
|
334
|
+
process = subprocess.run("gmx " + command, shell=True, env=envDict)
|
|
335
|
+
else:
|
|
336
|
+
with open(logFile, 'a+') as file:
|
|
337
|
+
process = subprocess.run("gmx " + command, shell=True, stdout=file, stderr=file, env=envDict)
|
|
338
|
+
|
|
339
|
+
if process.returncode != 0:
|
|
340
|
+
if terminal:
|
|
341
|
+
self.error("Failed to run \"{}\" (exitcode {}).".format(command, process.returncode))
|
|
342
|
+
else:
|
|
343
|
+
self.error("Failed to run \"{}\" (exitcode {}). Check your logfile ({})".format(command, process.returncode, logFile))
|
|
344
|
+
|
|
345
|
+
return process.returncode
|
|
346
|
+
|
|
347
|
+
def runner(self):
|
|
348
|
+
"""Call correct sub-function depending on specified target on cmdline.
|
|
349
|
+
"""
|
|
350
|
+
if self.d_target == 'gentopol':
|
|
351
|
+
self.update('Running gentopol...')
|
|
352
|
+
self.gentopol()
|
|
353
|
+
|
|
354
|
+
elif self.d_target == 'neutralize':
|
|
355
|
+
self.update('Running neutralize...')
|
|
356
|
+
self.neutralize()
|
|
357
|
+
|
|
358
|
+
elif self.d_target == 'genparams':
|
|
359
|
+
self.update('Running genparams...')
|
|
360
|
+
self.genparams()
|
|
361
|
+
self.pleaseCite()
|
|
362
|
+
|
|
363
|
+
def gentopol(self):
|
|
364
|
+
"""gentopol prepares the topology.
|
|
365
|
+
"""
|
|
366
|
+
# Part I - COPY FORCE FIELD AND RESIDUETYPES.DAT TO WORKING DIR.
|
|
367
|
+
|
|
368
|
+
# /path/to/ffield/charmm36-mar2019-cphmd.ff
|
|
369
|
+
p_modelFF = os.path.normpath(self.p_ffield + '/' + self.d_modelFF)
|
|
370
|
+
|
|
371
|
+
# /path/to/ffield/residuetypes.dat
|
|
372
|
+
p_residuetypes = os.path.normpath(self.p_ffield + '/' + 'residuetypes.dat')
|
|
373
|
+
|
|
374
|
+
# User update
|
|
375
|
+
self.verbose('Force field path stuff:')
|
|
376
|
+
self.verbose('path to ffield dir = {}'.format(self.p_ffield))
|
|
377
|
+
self.verbose('default ffield = {}'.format(p_modelFF))
|
|
378
|
+
self.verbose('default residuetypes = {}'.format(p_residuetypes))
|
|
379
|
+
|
|
380
|
+
# Copy force field and residuetypes.dat from packaging_data/ffield to
|
|
381
|
+
# working dir IF they are not present. Else, use those in working dir.
|
|
382
|
+
if os.path.exists(self.d_modelFF):
|
|
383
|
+
self.update(f'Found \'{self.d_modelFF}\' in working dir, will not (again) copy from default')
|
|
384
|
+
elif os.path.exists(p_modelFF):
|
|
385
|
+
os.system("cp -r {} .".format(p_modelFF))
|
|
386
|
+
else:
|
|
387
|
+
self.error(f"Did not find {self.d_modelFF} in {self.p_ffield}. Please check your directory and/or update your PHFFIELD environment variable.")
|
|
388
|
+
|
|
389
|
+
if os.path.exists('residuetypes.dat'):
|
|
390
|
+
self.update('Found \'residuetypes.dat\' in working dir, will not (again) copy from default')
|
|
391
|
+
elif os.path.exists(p_residuetypes):
|
|
392
|
+
os.system("cp {} .".format(p_residuetypes))
|
|
393
|
+
else:
|
|
394
|
+
self.error(f"Did not find residuetypes.dat in {self.p_ffield}. Please check your directory and/or update your PHFFIELD environment variable.")
|
|
395
|
+
|
|
396
|
+
# Remove .ff extension from force field (we need d_modelFF for pdb2gmx).
|
|
397
|
+
tail, head = os.path.split(p_modelFF)
|
|
398
|
+
self.d_modelFF = os.path.splitext(head)[0]
|
|
399
|
+
|
|
400
|
+
# PART II - LOAD DATA.
|
|
401
|
+
|
|
402
|
+
# Load the .pdb/.gro structure (and implicitly phrecord.dat, if it exists).
|
|
403
|
+
pdb = Structure(self.d_file, self.d_verbosity)
|
|
404
|
+
|
|
405
|
+
# Load user-specified list of residues (if any).
|
|
406
|
+
if hasattr(self, 'ph_list_resid'):
|
|
407
|
+
list_resid = self.ph_list_resid
|
|
408
|
+
|
|
409
|
+
self.update('Found user-defined list containing residues to consider...')
|
|
410
|
+
self.verbose(list_resid)
|
|
411
|
+
|
|
412
|
+
# PART III - LOOP THROUGH THE RESIDUES AND MODIFY.
|
|
413
|
+
|
|
414
|
+
self.update("Modifying structure file...")
|
|
415
|
+
|
|
416
|
+
# Loop through all the residue objects.
|
|
417
|
+
for residue in pdb.d_residues:
|
|
418
|
+
|
|
419
|
+
# Get the lambdaType object for which d_incl contains residue.d_resname (if any).
|
|
420
|
+
associatedLambdaType = [lambdaType for lambdaType in self.ph_lambdaTypes if residue.d_resname in lambdaType.d_incl]
|
|
421
|
+
|
|
422
|
+
# If this list is not empty, i.e. an associated LambdaType was found...
|
|
423
|
+
if associatedLambdaType:
|
|
424
|
+
|
|
425
|
+
# Turn this list, containing one object, into the object.
|
|
426
|
+
associatedLambdaType = associatedLambdaType[0]
|
|
427
|
+
|
|
428
|
+
# If -list was set AND the current residue is not in the list, continue to the next residue.
|
|
429
|
+
if hasattr(self, 'ph_list_resid') and (residue.d_resid not in list_resid):
|
|
430
|
+
continue
|
|
431
|
+
|
|
432
|
+
# Store original name here as we'll need it later for a user update.
|
|
433
|
+
origName = residue.d_resname
|
|
434
|
+
|
|
435
|
+
# If -ph was set (contains a float), do not ask for every residue individually:
|
|
436
|
+
if not type(self.ph_auto) == float:
|
|
437
|
+
# List to hold the various options for the user.
|
|
438
|
+
options = ["Keep current (static) protonation state"]
|
|
439
|
+
|
|
440
|
+
# Is this multistate yes/no? Multistate and 2state need to be treated differently.
|
|
441
|
+
multistate = len(associatedLambdaType.d_pKa) > 1
|
|
442
|
+
|
|
443
|
+
if multistate:
|
|
444
|
+
chargeLists = associatedLambdaType.d_qqB
|
|
445
|
+
for idx in range(0, len(chargeLists)):
|
|
446
|
+
options.append("Make titratable (rename to {}), start in state {} (q = {:+.2f})".format(associatedLambdaType.d_groupname, idx + 1, sum(chargeLists[idx])))
|
|
447
|
+
|
|
448
|
+
val = self.inputOptionHandler("Choose what to do with residue {}-{} in chain {}".format(residue.d_resname, residue.d_resid, residue.d_chain), options)
|
|
449
|
+
|
|
450
|
+
if val != 0:
|
|
451
|
+
residue.d_resname = associatedLambdaType.d_groupname
|
|
452
|
+
residue.d_init = str(val)
|
|
453
|
+
|
|
454
|
+
if not multistate:
|
|
455
|
+
chargeLists = [associatedLambdaType.d_qqA, associatedLambdaType.d_qqB[0]]
|
|
456
|
+
for idx in range(0, len(chargeLists)):
|
|
457
|
+
options.append("Make titratable (rename to {}), start in state {} (q = {:+.2f})".format(associatedLambdaType.d_groupname, idx, sum(chargeLists[idx])))
|
|
458
|
+
|
|
459
|
+
val = self.inputOptionHandler("Choose what to do with residue {}-{} in chain {}".format(residue.d_resname, residue.d_resid, residue.d_chain), options)
|
|
460
|
+
|
|
461
|
+
if val != 0:
|
|
462
|
+
residue.d_resname = associatedLambdaType.d_groupname
|
|
463
|
+
residue.d_init = str(val - 1)
|
|
464
|
+
|
|
465
|
+
else: # If -ph was set, just protonate everything automatically.
|
|
466
|
+
residue.d_resname = associatedLambdaType.d_groupname
|
|
467
|
+
|
|
468
|
+
# Additionally, use automaticLambdaInits to set the initial lambda values.
|
|
469
|
+
init = self.automaticLambdaInits(associatedLambdaType.d_pKa, self.ph_auto)
|
|
470
|
+
residue.d_init = str(init)
|
|
471
|
+
|
|
472
|
+
self.update("Made residue {:>4s}-{:<4d} in chain {:1s} titratable (changed name to {}, initlambda = {})".format(origName, residue.d_resid, residue.d_chain, residue.d_resname, init))
|
|
473
|
+
|
|
474
|
+
continue # Otherwise code below is executed for the same residue we just changed.
|
|
475
|
+
|
|
476
|
+
# Get the lambdaType object for which d_groupname = residue.d_resname (if any).
|
|
477
|
+
associatedLambdaType = [lambdaType for lambdaType in self.ph_lambdaTypes if residue.d_resname == lambdaType.d_groupname]
|
|
478
|
+
|
|
479
|
+
# If this list is not empty, i.e. an associated LambdaType was found,
|
|
480
|
+
if associatedLambdaType:
|
|
481
|
+
|
|
482
|
+
# Turn this list, containing one object, into the object.
|
|
483
|
+
associatedLambdaType = associatedLambdaType[0]
|
|
484
|
+
|
|
485
|
+
# If -list was set AND the current residue is not in the list, continue to the next residue.
|
|
486
|
+
if hasattr(self, 'ph_list_resid') and (residue.d_resid not in list_resid):
|
|
487
|
+
continue
|
|
488
|
+
|
|
489
|
+
# If -ph was set (contains a float), do not ask for every residue individually:
|
|
490
|
+
if not type(self.ph_auto) == float:
|
|
491
|
+
|
|
492
|
+
# List to hold the various options for the user.
|
|
493
|
+
options = []
|
|
494
|
+
|
|
495
|
+
# Is this multistate yes/no? Multistate and 2state need to be treated differently.
|
|
496
|
+
multistate = len(associatedLambdaType.d_pKa) > 1
|
|
497
|
+
|
|
498
|
+
if multistate:
|
|
499
|
+
chargeLists = associatedLambdaType.d_qqB
|
|
500
|
+
for idx in range(0, len(chargeLists)):
|
|
501
|
+
options.append("Keep titratable, start in state {} (q = {:+.2f})".format(idx + 1, sum(chargeLists[idx])))
|
|
502
|
+
|
|
503
|
+
if not multistate:
|
|
504
|
+
chargeLists = [associatedLambdaType.d_qqA, associatedLambdaType.d_qqB[0]]
|
|
505
|
+
for idx in range(0, len(chargeLists)):
|
|
506
|
+
options.append("Keep titratable, start in state {} (q = {:+.2f})".format(idx, sum(chargeLists[idx])))
|
|
507
|
+
|
|
508
|
+
for name in associatedLambdaType.d_incl:
|
|
509
|
+
options.append("Change name to {}".format(name))
|
|
510
|
+
|
|
511
|
+
val = self.inputOptionHandler("Choose what to do with residue {}-{} in chain {} in initial state {}".format(residue.d_resname, residue.d_resid, residue.d_chain, residue.d_init), options)
|
|
512
|
+
|
|
513
|
+
# If user picks one of the "still titratable" options:
|
|
514
|
+
if val in range(0, len(chargeLists)):
|
|
515
|
+
residue.d_init = str(val)
|
|
516
|
+
|
|
517
|
+
else: # Else the user picked one of the non-titratable options
|
|
518
|
+
residue.d_resname = associatedLambdaType.d_incl[val - len(chargeLists)]
|
|
519
|
+
residue.d_init = ' '
|
|
520
|
+
|
|
521
|
+
# Normally, we would not have to do anything. However, if we are
|
|
522
|
+
else: # missing initial lambda values in the record, we need to add them.
|
|
523
|
+
init = self.automaticLambdaInits(associatedLambdaType.d_pKa, self.ph_auto)
|
|
524
|
+
residue.d_init = str(init)
|
|
525
|
+
|
|
526
|
+
self.update("Residue {}-{} in chain {} is already titratable (initlambda = {})".format(residue.d_resname, residue.d_resid, residue.d_chain, init))
|
|
527
|
+
|
|
528
|
+
# If the residue in question is neither an ASP nor an ASPT, as an extra
|
|
529
|
+
else: # measure we make sure that nothing is present in the init field.
|
|
530
|
+
residue.d_init = ' '
|
|
531
|
+
|
|
532
|
+
# Write the modified structure file (input for pdb2gmx).
|
|
533
|
+
pdb.write('phset.pdb')
|
|
534
|
+
self.d_file = 'phset.pdb'
|
|
535
|
+
|
|
536
|
+
# PART 3.5 - PRINT A REFERENCE LIST OF LAMBDA COORDINATES.
|
|
537
|
+
|
|
538
|
+
self.update('writing lambda coordinates reference list (lambdareference.dat)...')
|
|
539
|
+
LambdaTypeDict = {} # Make dict of names and associated number of coordinate files.
|
|
540
|
+
|
|
541
|
+
for obj in self.ph_lambdaTypes:
|
|
542
|
+
if len(obj.d_pKa) > 1: # if this is a multistate...
|
|
543
|
+
# We have #coordinate (files) = number of qqB lists.
|
|
544
|
+
LambdaTypeDict[obj.d_groupname] = len(obj.d_qqB)
|
|
545
|
+
else:
|
|
546
|
+
# If this is not multisite we only have one coordinate (file).
|
|
547
|
+
LambdaTypeDict[obj.d_groupname] = 1
|
|
548
|
+
|
|
549
|
+
with open('lambdareference.dat', 'w+') as file:
|
|
550
|
+
file.write('resname coord# resid chain coordinateFile\n')
|
|
551
|
+
|
|
552
|
+
coordCount = 1
|
|
553
|
+
for residue in pdb.d_residues:
|
|
554
|
+
if residue.d_resname in LambdaTypeDict.keys():
|
|
555
|
+
multiCount = 1
|
|
556
|
+
for _ in range(0, LambdaTypeDict[residue.d_resname]):
|
|
557
|
+
file.write(f"{residue.d_resname} {multiCount} {residue.d_resid:4d} {residue.d_chain:1s} cphmd-coord-{coordCount}.xvg\n")
|
|
558
|
+
coordCount += 1
|
|
559
|
+
multiCount += 1
|
|
560
|
+
|
|
561
|
+
# PART IV - HANDLE UNKNOWN RESIDUE TYPES.
|
|
562
|
+
|
|
563
|
+
self.update("Checking if every residue type is present in residuetypes.dat...")
|
|
564
|
+
|
|
565
|
+
# Load residuetypes.dat into a dictionary
|
|
566
|
+
residueTypes = {}
|
|
567
|
+
for val in open('residuetypes.dat').readlines():
|
|
568
|
+
residueTypes[val.split()[0]] = val.split()[1]
|
|
569
|
+
|
|
570
|
+
# Compile lists of the unknown residue(s)(types)
|
|
571
|
+
unknownResidues = []
|
|
572
|
+
unknownResTypeNames = []
|
|
573
|
+
for residue in pdb.d_residues:
|
|
574
|
+
# If it's either not in residuetypes at all, or it is but it is an
|
|
575
|
+
# we add it to the list of unknown residues.
|
|
576
|
+
if residue.d_resname not in residueTypes or residueTypes[residue.d_resname] in ['Ion']:
|
|
577
|
+
unknownResidues.append(residue)
|
|
578
|
+
|
|
579
|
+
if residue.d_resname not in unknownResTypeNames:
|
|
580
|
+
unknownResTypeNames.append(residue.d_resname)
|
|
581
|
+
|
|
582
|
+
pathList = [] # Loop through the unknown residue types and add them to
|
|
583
|
+
skipList = [] # skipList and (the manually specified path to) pathList.
|
|
584
|
+
good = True
|
|
585
|
+
for val in unknownResTypeNames:
|
|
586
|
+
self.warning(f"residue type '{val}' in '{self.d_file}' was not found in residuetypes.dat associated with '{self.d_modelFF}'. phbuilder cannot provide topology information for non-standard residue types. Therefore, we expect the user to provide a separate topology (.itp) file. Additionally, be aware that pdb2gmx cannot add hydrogens to non-standard residues, so you either have to add an entry to the force field .hdb file, or make sure that hydrogens are already present in the structure for this residue type. See also https://manual.gromacs.org/current/how-to/topology.html.")
|
|
587
|
+
|
|
588
|
+
while True:
|
|
589
|
+
path = input("phbuilder : Specify /path/to/some.itp (or enter to ignore) (ions can be ignored): ")
|
|
590
|
+
if path == "":
|
|
591
|
+
break
|
|
592
|
+
path = Sanitize(path, "path to .itp file", exit=False).path(ext=['.itp'])
|
|
593
|
+
if path is not None:
|
|
594
|
+
break
|
|
595
|
+
|
|
596
|
+
skipList.append(val)
|
|
597
|
+
pathList.append(path)
|
|
598
|
+
good = False
|
|
599
|
+
|
|
600
|
+
self.update("Set path for residue type {} to {}...".format(val, path))
|
|
601
|
+
|
|
602
|
+
if good:
|
|
603
|
+
self.update("everything seems OK.")
|
|
604
|
+
|
|
605
|
+
else:
|
|
606
|
+
# Create a list knownResidues containing only the known residues.
|
|
607
|
+
knownResidues = []
|
|
608
|
+
for residue in pdb.d_residues:
|
|
609
|
+
if residue.d_resname not in skipList:
|
|
610
|
+
knownResidues.append(residue)
|
|
611
|
+
|
|
612
|
+
# Update d_residues in universe with knownResidues.
|
|
613
|
+
pdb.d_residues = knownResidues
|
|
614
|
+
|
|
615
|
+
# Write temporary .pdb containing only the known residues.
|
|
616
|
+
someTempName = 'pdb2gmxtemp.pdb'
|
|
617
|
+
pdb.write(someTempName)
|
|
618
|
+
self.d_file = someTempName
|
|
619
|
+
|
|
620
|
+
# Update value of d_output (so that pdb2gmx is called on the temporary
|
|
621
|
+
# structure), and backup the final output name as specified by user.
|
|
622
|
+
self.d_output_orig = self.d_output
|
|
623
|
+
self.d_output = someTempName
|
|
624
|
+
|
|
625
|
+
# PART IV - RUN PDB2GMX AND ASK USER FOR INPUT ABOUT IT.
|
|
626
|
+
|
|
627
|
+
# FIX: If 'pdb2gmxtemp.pdb' is empty (e.g. because ALL residuetypes are
|
|
628
|
+
# unrecognized) pdb2gmx will crash. We therefore skip this part entirely.
|
|
629
|
+
if len(pdb.d_residues) == 0:
|
|
630
|
+
|
|
631
|
+
self.update('skipping pdb2gmx step entirely as there are no recognized residues.')
|
|
632
|
+
with open('topol.top', 'w+') as file:
|
|
633
|
+
file.write('; Include forcefield parameters\n')
|
|
634
|
+
file.write('#include \"{}.ff/forcefield.itp\"\n\n'.format(self.d_modelFF))
|
|
635
|
+
file.write('; Include water topology\n')
|
|
636
|
+
file.write('#include \"{}.ff/{}.itp\"\n\n'.format(self.d_modelFF, self.d_modelwater))
|
|
637
|
+
file.write('; Include topology for ions\n')
|
|
638
|
+
file.write('#include \"{}.ff/ions.itp\"\n\n'.format(self.d_modelFF))
|
|
639
|
+
file.write('[ system ]\n; Name\n{}\n\n'.format(pdb.d_title))
|
|
640
|
+
file.write('[ molecules ]\n; Compounds #mols\n')
|
|
641
|
+
|
|
642
|
+
else:
|
|
643
|
+
self.update("\nRecommended pdb2gmx command:")
|
|
644
|
+
self.update("gmx pdb2gmx -f {} -o {} -ff {} -water {} -ignh".format(self.d_file, self.d_output, self.d_modelFF, self.d_modelwater))
|
|
645
|
+
|
|
646
|
+
# Ask for input for what to do regarding pdb2gmx:
|
|
647
|
+
val = self.inputOptionHandler(
|
|
648
|
+
"Choose whether to",
|
|
649
|
+
["Do nothing", "Run", "Add additional flags (https://manual.gromacs.org/documentation/current/onlinehelp/gmx-pdb2gmx.html)"])
|
|
650
|
+
|
|
651
|
+
flags = ""
|
|
652
|
+
if val == 2:
|
|
653
|
+
flags += input("phbuilder : Enter flags: ")
|
|
654
|
+
|
|
655
|
+
# Run pdb2gmx:
|
|
656
|
+
if val in [1, 2]:
|
|
657
|
+
self.gromacs("pdb2gmx -f {} -o {} -ff {} -water {} -ignh {}".format(self.d_file, self.d_output, self.d_modelFF, self.d_modelwater, flags), terminal=True)
|
|
658
|
+
|
|
659
|
+
# If we do nothing, then return because we do not want to do PART V?
|
|
660
|
+
if val == 0:
|
|
661
|
+
return
|
|
662
|
+
|
|
663
|
+
# PART V - MERGE THE .PDB FILES.
|
|
664
|
+
|
|
665
|
+
# If pathList is not empty, i.e. if we had at least one unknown residue:
|
|
666
|
+
if pathList:
|
|
667
|
+
# Load the structure output of pdb2gmx (update d_residues in universe)
|
|
668
|
+
pdb.read(someTempName)
|
|
669
|
+
|
|
670
|
+
# Merge the processed structure of good residues with unknown residues
|
|
671
|
+
mergedResidues = pdb.d_residues + unknownResidues
|
|
672
|
+
|
|
673
|
+
# Update d_residues in universe
|
|
674
|
+
pdb.d_residues = mergedResidues
|
|
675
|
+
|
|
676
|
+
# Write the final structure
|
|
677
|
+
pdb.write(self.d_output_orig)
|
|
678
|
+
|
|
679
|
+
# PART VI - MERGE THE TOPOLOGIES.
|
|
680
|
+
|
|
681
|
+
def add_mol(itpfname: str, comment: str, molname=None, molcount=None):
|
|
682
|
+
"""Write manually specified files to the topology file.
|
|
683
|
+
|
|
684
|
+
Args:
|
|
685
|
+
itpfname (str): name of the .itp file.
|
|
686
|
+
comment (_type_): additional comment.
|
|
687
|
+
molname (str, optional): molecule name. Defaults to None.
|
|
688
|
+
molcount (str, optional): number of molecules. Defaults to None.
|
|
689
|
+
"""
|
|
690
|
+
# Get the contents of current topol.top.
|
|
691
|
+
topList = []
|
|
692
|
+
with open("topol.top") as file:
|
|
693
|
+
for line in file.readlines():
|
|
694
|
+
topList.append(line)
|
|
695
|
+
|
|
696
|
+
# Add the .itp file (line saying: #include "blabla.itp").
|
|
697
|
+
with open("topol.top", 'w') as file:
|
|
698
|
+
try:
|
|
699
|
+
for line in range(0, len(topList)):
|
|
700
|
+
file.write(topList[line])
|
|
701
|
+
|
|
702
|
+
if "[ system ]\n" == topList[line + 1] and itpfname != '':
|
|
703
|
+
file.write("; {0}\n".format(comment))
|
|
704
|
+
file.write("#include \"{0}\"\n\n".format(itpfname))
|
|
705
|
+
|
|
706
|
+
except IndexError:
|
|
707
|
+
pass
|
|
708
|
+
|
|
709
|
+
# if molcount not present, add it, otherwise do nothing.
|
|
710
|
+
if molname is not None and molcount is not None and molname not in topList[-1]:
|
|
711
|
+
file.write("{0}\t\t\t{1}\n".format(molname, molcount))
|
|
712
|
+
|
|
713
|
+
# If pathList is not empty, i.e. if we had at least one unknown residue:
|
|
714
|
+
if pathList:
|
|
715
|
+
# Remove temporary .pdb file.
|
|
716
|
+
os.remove(someTempName)
|
|
717
|
+
|
|
718
|
+
# Loop through the unknown residue types.
|
|
719
|
+
for idx in range(0, len(skipList)):
|
|
720
|
+
|
|
721
|
+
# For each one, count how many there are.
|
|
722
|
+
count = 0
|
|
723
|
+
for residue in pdb.d_residues:
|
|
724
|
+
if residue.d_resname == skipList[idx]:
|
|
725
|
+
count += 1
|
|
726
|
+
|
|
727
|
+
# Add manually to topol.top.
|
|
728
|
+
add_mol(pathList[idx], "Include topology for {}".format(skipList[idx]), skipList[idx], count)
|
|
729
|
+
|
|
730
|
+
self.update("Finished generating topology for constant-pH.")
|
|
731
|
+
|
|
732
|
+
def countRes(self, Structure: Structure, resname: str):
|
|
733
|
+
"""Count the number of residues with resname in Structure.
|
|
734
|
+
"""
|
|
735
|
+
count = 0
|
|
736
|
+
for residue in Structure.d_residues:
|
|
737
|
+
if residue.d_resname == resname:
|
|
738
|
+
count += 1
|
|
739
|
+
return count
|
|
740
|
+
|
|
741
|
+
# Add appropriate number ions and buffers to make the system neutral.
|
|
742
|
+
def neutralize(self):
|
|
743
|
+
"""Add ions and buffers to ensure a net-neutral system."""
|
|
744
|
+
# I - LOAD DATA, PERFORM SOME CHECKS
|
|
745
|
+
|
|
746
|
+
# Load the input structure into d_residues.
|
|
747
|
+
pdb = Structure(self.d_file, self.d_verbosity)
|
|
748
|
+
|
|
749
|
+
# Perform some basic checks for PBC box, solvent, and titratable groups.
|
|
750
|
+
foundPBC = hasattr(pdb, 'd_box')
|
|
751
|
+
foundSolvent = False
|
|
752
|
+
foundTitratables = False
|
|
753
|
+
|
|
754
|
+
LambdaTypeNames = []
|
|
755
|
+
for LambdaType in self.ph_lambdaTypes:
|
|
756
|
+
LambdaTypeNames.append(LambdaType.d_groupname)
|
|
757
|
+
|
|
758
|
+
for residue in pdb.d_residues:
|
|
759
|
+
|
|
760
|
+
if residue.d_resname == self.d_solname:
|
|
761
|
+
foundSolvent = True
|
|
762
|
+
|
|
763
|
+
elif residue.d_resname in LambdaTypeNames:
|
|
764
|
+
foundTitratables = True
|
|
765
|
+
|
|
766
|
+
if foundSolvent and foundTitratables:
|
|
767
|
+
break
|
|
768
|
+
|
|
769
|
+
# Error if no periodic box was found.
|
|
770
|
+
if not foundPBC:
|
|
771
|
+
self.error("{} does not have a periodic box! Did you forget to add one?".format(self.d_file))
|
|
772
|
+
|
|
773
|
+
# Error if no solvent was found.
|
|
774
|
+
if not foundSolvent:
|
|
775
|
+
self.error("{} does not seem to have any solvent with molname {}! Did you forget to add solvent? Alternatively you can change the solvent name by setting -solname.".format(self.d_file, self.d_solname))
|
|
776
|
+
|
|
777
|
+
# Error if no titratable residues were found.
|
|
778
|
+
# We need to throw an error here and not a warning because grompp in getcpHMDcharge will not compile without at least one lambda group being present.
|
|
779
|
+
if not foundTitratables:
|
|
780
|
+
self.error("{} does not seem to have any titratable groups! Did you forget to run gentopol?".format(self.d_file))
|
|
781
|
+
|
|
782
|
+
# II - DO THE IONS PART
|
|
783
|
+
|
|
784
|
+
def getcpHMDcharge(name: str, file: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
|
|
785
|
+
"""Create a dummy .mdp file (including CpHMD parameters), calls gmx grompp,
|
|
786
|
+
and from the output extracts the system net-charge (in the actual CpHMD simulation).
|
|
787
|
+
|
|
788
|
+
Args:
|
|
789
|
+
name (str): name of the .mdp file to be generated.
|
|
790
|
+
file (str): structure file (only required for gmx grompp).
|
|
791
|
+
Structure (Structure): Structure object.
|
|
792
|
+
LambdaTypeNames (list): list of LambdaType names.
|
|
793
|
+
constrainCharge (bool): do we have charge constraining?
|
|
794
|
+
|
|
795
|
+
Returns:
|
|
796
|
+
int: total charge at CpHMD in the system.
|
|
797
|
+
"""
|
|
798
|
+
# Create empty name.mdp to append the lambda dynamics parameters to.
|
|
799
|
+
open('{}.mdp'.format(name), 'w').close()
|
|
800
|
+
|
|
801
|
+
# Set dummy parameters
|
|
802
|
+
self.ph_ph = 7.0
|
|
803
|
+
self.ph_nstout = 500
|
|
804
|
+
self.ph_inter = False
|
|
805
|
+
self.ph_dwpE = 7.5
|
|
806
|
+
|
|
807
|
+
# Write the lambda dynamics parameters to name.mdp
|
|
808
|
+
self.writeLambda_mdp(name, Structure, LambdaTypeNames, constrainCharge)
|
|
809
|
+
|
|
810
|
+
# Write index groups to name.ndx
|
|
811
|
+
self.writeLambda_ndx('{}.ndx'.format(name), Structure, LambdaTypeNames, constrainCharge)
|
|
812
|
+
|
|
813
|
+
# Execute grompp on this using cpHMD GROMACS version and direct output to charge.log.
|
|
814
|
+
self.update("Getting the net-charge of the system (running grompp, this can take some time for larger systems)...")
|
|
815
|
+
self.gromacs("grompp -f {0}.mdp -c {1} -p {2} -n {0}.ndx -o {0}.tpr -maxwarn {3}".format(name, file, self.d_topol, self.d_ignw), logFile='{}.log'.format(name))
|
|
816
|
+
|
|
817
|
+
# Grep total charge from grompp output message
|
|
818
|
+
QQtotalcpHMD = 0
|
|
819
|
+
for line in open('{}.log'.format(name)).read().splitlines():
|
|
820
|
+
if "non-zero total charge" in line:
|
|
821
|
+
QQtotalcpHMD = float(line.split()[-1])
|
|
822
|
+
break
|
|
823
|
+
|
|
824
|
+
# Cleanup
|
|
825
|
+
os.remove('{}.mdp'.format(name))
|
|
826
|
+
os.remove('{}.ndx'.format(name))
|
|
827
|
+
os.remove('{}.log'.format(name))
|
|
828
|
+
|
|
829
|
+
return QQtotalcpHMD
|
|
830
|
+
|
|
831
|
+
# boolean to prevent execution for when the system is already neutral.
|
|
832
|
+
isNeutral = False
|
|
833
|
+
|
|
834
|
+
# If we already have ions in the input file, give the user an extra update.
|
|
835
|
+
|
|
836
|
+
def getIonConcentration(Structure: Structure, Nwater: int):
|
|
837
|
+
"""Get current ion concentration in system (from) solvent volume."""
|
|
838
|
+
totalIons = self.countRes(Structure, self.d_pname) + self.countRes(Structure, self.d_nname)
|
|
839
|
+
return totalIons / (0.01808 * Nwater)
|
|
840
|
+
|
|
841
|
+
Nwater = self.countRes(pdb, self.d_solname)
|
|
842
|
+
ionConcInInput = getIonConcentration(pdb, Nwater)
|
|
843
|
+
|
|
844
|
+
if ionConcInInput:
|
|
845
|
+
self.update("Detected {} {} and {} {} in {}, corresponding to a concentration of {:.3f} mol/L for given solvent volume.".format(
|
|
846
|
+
self.countRes(pdb, self.d_pname),
|
|
847
|
+
self.d_pname,
|
|
848
|
+
self.countRes(pdb, self.d_nname),
|
|
849
|
+
self.d_nname,
|
|
850
|
+
self.d_file,
|
|
851
|
+
ionConcInInput))
|
|
852
|
+
|
|
853
|
+
# If we already have ions in the input file, d_conc can never be smaller than what we ALREADY HAVE.
|
|
854
|
+
if self.d_conc and ionConcInInput > self.d_conc:
|
|
855
|
+
self.error('Target ion concentration of {} mol/L is smaller than the current ion concentration in {}. Either remove -conc or increase it.'.format(self.d_conc, self.d_file))
|
|
856
|
+
|
|
857
|
+
# Get the cpHMD charge (we set constrainCharge to False because we have no buffers at this point).
|
|
858
|
+
QQtotalcpHMD = getcpHMDcharge('ions', self.d_file, pdb, LambdaTypeNames, constrainCharge=False)
|
|
859
|
+
|
|
860
|
+
self.update('Net-charge of system = {:+.2f}'.format(QQtotalcpHMD))
|
|
861
|
+
|
|
862
|
+
np = 0
|
|
863
|
+
nn = 0
|
|
864
|
+
if QQtotalcpHMD > 0:
|
|
865
|
+
nn = round(QQtotalcpHMD)
|
|
866
|
+
elif QQtotalcpHMD < 0:
|
|
867
|
+
np = round(-QQtotalcpHMD)
|
|
868
|
+
else:
|
|
869
|
+
self.update('System seems to be neutral already.')
|
|
870
|
+
isNeutral = True
|
|
871
|
+
|
|
872
|
+
def fromBoxVol():
|
|
873
|
+
"""Return number of ions required for a specific concentration, based on volume of the box."""
|
|
874
|
+
Avo = 6.02214076 * 10 ** 23
|
|
875
|
+
boxVol = pdb.d_box.d_a * pdb.d_box.d_b * pdb.d_box.d_c
|
|
876
|
+
return int(round(self.d_conc * Avo * boxVol * 10 ** -27))
|
|
877
|
+
|
|
878
|
+
def fromSolVol(Structure, concentration):
|
|
879
|
+
"""Return the number of ions required for a specific concentration, based on volume of the solvent."""
|
|
880
|
+
Nwater = self.countRes(Structure, self.d_solname)
|
|
881
|
+
return int(round(0.01808 * Nwater * concentration))
|
|
882
|
+
|
|
883
|
+
if not (isNeutral and self.d_conc == 0):
|
|
884
|
+
|
|
885
|
+
if self.d_conc != 0:
|
|
886
|
+
Nions = fromSolVol(pdb, self.d_conc - ionConcInInput)
|
|
887
|
+
ionsMinRequired = np + nn
|
|
888
|
+
|
|
889
|
+
if Nions < ionsMinRequired:
|
|
890
|
+
self.error('Target ion concentration of {} mol/L is smaller than the minimum (additional) concentration required to neutralize the system. Either remove -conc or increase it.'.format(self.d_conc))
|
|
891
|
+
|
|
892
|
+
# We only want integers so we want to divide an even number.
|
|
893
|
+
if (Nions - np - nn) % 2 != 0:
|
|
894
|
+
Nions += 1
|
|
895
|
+
|
|
896
|
+
factor = int((Nions - np - nn) / 2.0)
|
|
897
|
+
|
|
898
|
+
np += factor
|
|
899
|
+
nn += factor
|
|
900
|
+
|
|
901
|
+
self.update('Specified ion concentration of {} mol/L corresponds to {} (additional) ions for given solvent volume'.format(self.d_conc, Nions))
|
|
902
|
+
|
|
903
|
+
self.update('Will add {} positive ({}) and {} negative ({}) ions...'.format(np, self.d_pname, nn, self.d_nname))
|
|
904
|
+
self.update('Total charge to be added = {:+.2f}'.format(np - nn))
|
|
905
|
+
|
|
906
|
+
# Run genion to add the appropriate number of ions.
|
|
907
|
+
self.gromacs("genion -s ions.tpr -o phions.pdb -p {} -pname {} -nname {} -np {} -nn {} -rmin {}".format(
|
|
908
|
+
self.d_topol, self.d_pname, self.d_nname, np, nn, self.d_rmin), stdin=['SOL']) # this is always SOL, even if the molname is e.g. HOH...
|
|
909
|
+
|
|
910
|
+
self.update('Finished adding ions')
|
|
911
|
+
|
|
912
|
+
else:
|
|
913
|
+
# Get the number of ions (that are already making the system neutral from input file).
|
|
914
|
+
# We will need these later for the checking part.
|
|
915
|
+
np = self.countRes(pdb, self.d_pname)
|
|
916
|
+
nn = self.countRes(pdb, self.d_nname)
|
|
917
|
+
|
|
918
|
+
# User update and write internal structure to phions.pdb.
|
|
919
|
+
self.update("System is already neutral and -conc was not set. Will not add any ions...")
|
|
920
|
+
pdb.write('phions.pdb')
|
|
921
|
+
|
|
922
|
+
# III - DO THE BUFFER PART
|
|
923
|
+
|
|
924
|
+
# Load the structure that now contains the ions.
|
|
925
|
+
pdb.read('phions.pdb')
|
|
926
|
+
|
|
927
|
+
# Boolean to prevent execution for when the system already has enough buffers.
|
|
928
|
+
hasEnoughBUFs = False
|
|
929
|
+
|
|
930
|
+
# Obtain the number of buffers that should be added.
|
|
931
|
+
if not hasattr(self, 'ph_nbufs'):
|
|
932
|
+
# Count number of titratable residues.
|
|
933
|
+
titratables = 0
|
|
934
|
+
for residue in pdb.d_residues:
|
|
935
|
+
if residue.d_resname in LambdaTypeNames:
|
|
936
|
+
titratables += 1
|
|
937
|
+
|
|
938
|
+
# This is the equation we use to estimate the required number of buffers (hardcoded).
|
|
939
|
+
# q_max = abs(self.ph_BUF_range[0])
|
|
940
|
+
# nbufs = int(titratables / (2 * q_max))
|
|
941
|
+
nbufs = 2 * titratables + 1
|
|
942
|
+
|
|
943
|
+
self.update(f"Will add 2N_sites + 1 = {nbufs} buffer(s)...")
|
|
944
|
+
|
|
945
|
+
else:
|
|
946
|
+
nbufs = self.ph_nbufs
|
|
947
|
+
self.update(f"Will add {nbufs} buffer(s) (user), allowing a max charge fluctuation of ±{nbufs/2.0:.1f}...")
|
|
948
|
+
|
|
949
|
+
nbufspresent = self.countRes(pdb, 'BUF')
|
|
950
|
+
|
|
951
|
+
if nbufspresent == nbufs:
|
|
952
|
+
self.warning("The number of buffers in {} is already equal to the request number of buffers. Will not add any buffers...".format(self.d_file))
|
|
953
|
+
hasEnoughBUFs = True
|
|
954
|
+
|
|
955
|
+
elif nbufspresent > nbufs:
|
|
956
|
+
self.warning("The number of buffers in {} exceeds the requested number of buffers. Will not add any buffers...".format(self.d_file))
|
|
957
|
+
hasEnoughBUFs = True
|
|
958
|
+
|
|
959
|
+
if not hasEnoughBUFs:
|
|
960
|
+
|
|
961
|
+
# We don't need the cpHMD parameters for adding the buffers, therefore
|
|
962
|
+
# we create a dummy buffers.mdp file (containing nothing).
|
|
963
|
+
open('buffers.mdp', 'w+').close()
|
|
964
|
+
self.gromacs("grompp -f buffers.mdp -c phions.pdb -p {} -o buffers.tpr -maxwarn {}".format(self.d_topol, self.d_ignw))
|
|
965
|
+
|
|
966
|
+
# Run genion to add the appropriate number of buffers.
|
|
967
|
+
self.gromacs("genion -s buffers.tpr -o {} -p {} -pname BUF -np {} -rmin {}".format(self.d_output, self.d_topol, nbufs, self.d_rmin), stdin=['SOL']) # this is always SOL, even if the molname is e.g. HOH...
|
|
968
|
+
|
|
969
|
+
self.update('Finished adding buffers')
|
|
970
|
+
|
|
971
|
+
os.remove('buffers.mdp')
|
|
972
|
+
os.remove('buffers.tpr')
|
|
973
|
+
|
|
974
|
+
# We need the else-statement here because if there are already enough bufs
|
|
975
|
+
# (e.g. -nbufs = 0) we will still need to obtain phneutral.pdb.
|
|
976
|
+
else:
|
|
977
|
+
os.system(f"cp phions.pdb {self.d_output}")
|
|
978
|
+
|
|
979
|
+
# IV - WRAPUP : CHECK IF EVERYTHING IS NOW CORRECT
|
|
980
|
+
|
|
981
|
+
os.remove('ions.tpr')
|
|
982
|
+
|
|
983
|
+
# Check if the correct number of ions and buffers are present in the output file.
|
|
984
|
+
|
|
985
|
+
self.update('\nChecking whether everything was successful:\n')
|
|
986
|
+
|
|
987
|
+
# Update internal pdb record to phneutral.pdb.
|
|
988
|
+
pdb.read(self.d_output)
|
|
989
|
+
|
|
990
|
+
countPions = self.countRes(pdb, self.d_pname)
|
|
991
|
+
if countPions != np:
|
|
992
|
+
self.warning('Detected {}/{} required positive ions (ignore this if your input already contained ions).'.format(countPions, np))
|
|
993
|
+
else:
|
|
994
|
+
self.update('Detected correct number of positive ions ({}) - check'.format(np))
|
|
995
|
+
|
|
996
|
+
countNions = self.countRes(pdb, self.d_nname)
|
|
997
|
+
if countNions != nn:
|
|
998
|
+
self.warning('Detected {}/{} required negative ions (ignore this if your input already contained ions).'.format(countNions, nn))
|
|
999
|
+
else:
|
|
1000
|
+
self.update('Detected correct number of negative ions ({}) - check'.format(nn))
|
|
1001
|
+
|
|
1002
|
+
countBUFs = self.countRes(pdb, 'BUF')
|
|
1003
|
+
if countBUFs != nbufs:
|
|
1004
|
+
self.warning('Detected {}/{} required buffers'.format(countBUFs, nbufs))
|
|
1005
|
+
else:
|
|
1006
|
+
self.update('Detected correct number of buffers ({}) - check'.format(nbufs))
|
|
1007
|
+
|
|
1008
|
+
# Give a user update about the ion concentration in the output file.
|
|
1009
|
+
self.update("{} {} and {} {} in {} corresponds to a concentration of {:.3f} mol/L for given solvent volume...".format(
|
|
1010
|
+
self.countRes(pdb, self.d_pname),
|
|
1011
|
+
self.d_pname,
|
|
1012
|
+
self.countRes(pdb, self.d_nname),
|
|
1013
|
+
self.d_nname,
|
|
1014
|
+
self.d_output,
|
|
1015
|
+
getIonConcentration(pdb, self.countRes(pdb, 'SOL')))) # For some reason, genion renames whatever solname we had in the input file to 'SOL'...
|
|
1016
|
+
|
|
1017
|
+
# Check if the charge is now neutral.
|
|
1018
|
+
|
|
1019
|
+
QQFinal = getcpHMDcharge('check', self.d_output, pdb, LambdaTypeNames, constrainCharge=True)
|
|
1020
|
+
if QQFinal != 0:
|
|
1021
|
+
self.warning('Output system ({}) is not neutral at cpHMD (net-charge = {:+.2f})! Something went wrong! Check your log files...'.format(self.d_output, QQFinal))
|
|
1022
|
+
else:
|
|
1023
|
+
self.update('Output system ({}) is neutral at cpHMD (net-charge = {:+.2f}) - check'.format(self.d_output, QQFinal))
|
|
1024
|
+
|
|
1025
|
+
os.remove('check.tpr')
|
|
1026
|
+
self.update("Finished phbuilder neutralize.")
|
|
1027
|
+
|
|
1028
|
+
def writeLambda_mdp(self, Type: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
|
|
1029
|
+
"""Generate the actual lambda dynamics parameters for .mdp file.
|
|
1030
|
+
|
|
1031
|
+
Args:
|
|
1032
|
+
Type (str): type of .mdp file (choose EM, NVT, NPT, MD).
|
|
1033
|
+
Structure (Structure): Structure object.
|
|
1034
|
+
LambdaTypeNames (list): list of LambdaType names.
|
|
1035
|
+
constrainCharge (bool): do we have charge constraining?
|
|
1036
|
+
"""
|
|
1037
|
+
file = open("{}.mdp".format(Type), 'a')
|
|
1038
|
+
|
|
1039
|
+
def addParam(name: str, value: any):
|
|
1040
|
+
"""Formatting function for adding parameters."""
|
|
1041
|
+
file.write("{:54s} = {:13s}\n".format(name, str(value)))
|
|
1042
|
+
|
|
1043
|
+
# PART 1 - WRITE GENERAL PARAMETERS
|
|
1044
|
+
|
|
1045
|
+
file.write("\n; CONSTANT PH\n")
|
|
1046
|
+
|
|
1047
|
+
addParam('lambda-dynamics', 'yes')
|
|
1048
|
+
addParam('lambda-dynamics-simulation-ph', "{:.1f}".format(self.ph_ph))
|
|
1049
|
+
addParam('lambda-dynamics-lambda-particle-mass', "{:.1f}".format(5.0)) # lmass is hardcoded to 5.0 (amu).
|
|
1050
|
+
addParam('lambda-dynamics-tau', "{:.1f}".format(2.0)) # ltau is hardcoded to 2.0 (ps).
|
|
1051
|
+
addParam('lambda-dynamics-update-nst', self.ph_nstout)
|
|
1052
|
+
|
|
1053
|
+
# If we use charge constraining...
|
|
1054
|
+
if constrainCharge:
|
|
1055
|
+
addParam('lambda-dynamics-charge-constraints', 'yes')
|
|
1056
|
+
|
|
1057
|
+
# If we are doing EM/NVT/NPT, we do not want the lambdas to move:
|
|
1058
|
+
if Type in ['EM', 'NVT', 'NPT'] or self.ph_cal:
|
|
1059
|
+
addParam('lambda-dynamics-calibration', 'yes')
|
|
1060
|
+
|
|
1061
|
+
# We need to count how many titratable residues in total we have in the
|
|
1062
|
+
# protein. For this we compile a list LambdasFoundinProtein.
|
|
1063
|
+
LambdasFoundinProtein = [] # (e.g ASPT ASPT GLUT ASPT GLUT ASPT...)
|
|
1064
|
+
|
|
1065
|
+
# Stores the number of buffer atoms/ions.
|
|
1066
|
+
buffersFoundinProtein = 0
|
|
1067
|
+
|
|
1068
|
+
for residue in Structure.d_residues:
|
|
1069
|
+
if residue.d_resname in LambdaTypeNames:
|
|
1070
|
+
LambdasFoundinProtein.append(residue.d_resname)
|
|
1071
|
+
|
|
1072
|
+
# Also in this loop we count how many buffer ions we have.
|
|
1073
|
+
elif constrainCharge and residue.d_resname == 'BUF':
|
|
1074
|
+
buffersFoundinProtein += 1
|
|
1075
|
+
|
|
1076
|
+
# The fact that we have a LambdaType in lambdagrouptypes.dat does not mean
|
|
1077
|
+
# one of those is also present in the protein. In that case, we want to
|
|
1078
|
+
# prevent counting it, so we compile a subgroup of LambdaType groupnames
|
|
1079
|
+
# that are not only in lambdagrouptypes.dat, but ALSO found at least once
|
|
1080
|
+
# in the actual protein.
|
|
1081
|
+
LambdaTypeNamesFoundinProtein = list(set(LambdasFoundinProtein)) # (e.g ASPT GLUT)
|
|
1082
|
+
|
|
1083
|
+
# If we not only have multistate LambdaResidueTypes defined in the .dat file,
|
|
1084
|
+
# but we also have detected such a LambdaResidueType in the actual protein,
|
|
1085
|
+
# we'll need to turn on multistate:
|
|
1086
|
+
for LambdaType in self.ph_lambdaTypes:
|
|
1087
|
+
if len(LambdaType.d_pKa) > 1 and LambdaType.d_groupname in LambdaTypeNamesFoundinProtein:
|
|
1088
|
+
addParam('lambda-dynamics-multistate-constraints', 'yes')
|
|
1089
|
+
|
|
1090
|
+
# If we use charge constraining we also have he BUF residue-type, as well as
|
|
1091
|
+
# one extra lambda group containing all the BUFs.
|
|
1092
|
+
if constrainCharge:
|
|
1093
|
+
addParam('lambda-dynamics-number-lambda-group-types', len(LambdaTypeNamesFoundinProtein) + 1)
|
|
1094
|
+
addParam('lambda-dynamics-number-atom-collections', len(LambdasFoundinProtein) + 1)
|
|
1095
|
+
else:
|
|
1096
|
+
addParam('lambda-dynamics-number-lambda-group-types', len(LambdaTypeNamesFoundinProtein))
|
|
1097
|
+
addParam('lambda-dynamics-number-atom-collections', len(LambdasFoundinProtein))
|
|
1098
|
+
|
|
1099
|
+
file.write('\n')
|
|
1100
|
+
|
|
1101
|
+
# PART 2 - WRITE LAMBDA GROUP TYPES
|
|
1102
|
+
|
|
1103
|
+
def to_string(Input, round):
|
|
1104
|
+
"""Convert a list to a string."""
|
|
1105
|
+
string = ""
|
|
1106
|
+
for element in Input:
|
|
1107
|
+
string += "{0:.{arg}f} ".format(element, arg=round)
|
|
1108
|
+
return string
|
|
1109
|
+
|
|
1110
|
+
def writeLambdaGroupTypeBlock(number, name, multistates, qqA, qqB, pKa, dvdl):
|
|
1111
|
+
"""Writes the lambda group type block."""
|
|
1112
|
+
addParam('lambda-dynamics-group-type{}-name'.format(number), name)
|
|
1113
|
+
addParam('lambda-dynamics-group-type{}-n-states'.format(number), multistates)
|
|
1114
|
+
addParam('lambda-dynamics-group-type{}-state-0-charges'.format(number), to_string(qqA, 3))
|
|
1115
|
+
|
|
1116
|
+
for idx in range(1, multistates + 1):
|
|
1117
|
+
# When we have a multistate lambdagrouptype, one of the pKas should
|
|
1118
|
+
# be equal to the simulation-pH. This is done by setting this pKa
|
|
1119
|
+
# to zero in the lambdagrouptypes.dat file.
|
|
1120
|
+
pKaNew = pKa[idx - 1]
|
|
1121
|
+
if multistates > 1 and float(pKaNew) == 0.0:
|
|
1122
|
+
pKaNew = self.ph_ph
|
|
1123
|
+
|
|
1124
|
+
addParam('lambda-dynamics-group-type{}-state-{}-charges'.format(number, idx), to_string(qqB[idx - 1], 3))
|
|
1125
|
+
addParam('lambda-dynamics-group-type{}-state-{}-reference-pka'.format(number, idx), pKaNew)
|
|
1126
|
+
addParam('lambda-dynamics-group-type{}-state-{}-dvdl-coefficients'.format(number, idx), to_string(dvdl[idx - 1], 3))
|
|
1127
|
+
|
|
1128
|
+
file.write('\n')
|
|
1129
|
+
|
|
1130
|
+
number = 1
|
|
1131
|
+
# We loop over the object itself instead of the d_groupname as we need all
|
|
1132
|
+
# the information in the object.
|
|
1133
|
+
for LambdaType in self.ph_lambdaTypes:
|
|
1134
|
+
# This if-statement prevents writing a block when there are no residues
|
|
1135
|
+
# of this type in the protein.
|
|
1136
|
+
if (LambdaType.d_groupname in LambdaTypeNamesFoundinProtein):
|
|
1137
|
+
|
|
1138
|
+
writeLambdaGroupTypeBlock(
|
|
1139
|
+
number,
|
|
1140
|
+
LambdaType.d_groupname,
|
|
1141
|
+
len(LambdaType.d_pKa),
|
|
1142
|
+
LambdaType.d_qqA,
|
|
1143
|
+
LambdaType.d_qqB,
|
|
1144
|
+
LambdaType.d_pKa,
|
|
1145
|
+
LambdaType.d_dvdl
|
|
1146
|
+
)
|
|
1147
|
+
|
|
1148
|
+
number += 1
|
|
1149
|
+
|
|
1150
|
+
# If we do charge constraining, we additionally need the block for the buffer.
|
|
1151
|
+
if constrainCharge:
|
|
1152
|
+
qqA = self.ph_BUF_range[0]
|
|
1153
|
+
qqB = self.ph_BUF_range[1]
|
|
1154
|
+
|
|
1155
|
+
writeLambdaGroupTypeBlock(
|
|
1156
|
+
number,
|
|
1157
|
+
'BUF',
|
|
1158
|
+
1,
|
|
1159
|
+
[qqA],
|
|
1160
|
+
[[qqB]],
|
|
1161
|
+
[0],
|
|
1162
|
+
[self.ph_BUF_dvdl]
|
|
1163
|
+
)
|
|
1164
|
+
|
|
1165
|
+
# PART 3 - WRITE LAMBDA GROUPS
|
|
1166
|
+
|
|
1167
|
+
def writeResBlock(number: int, name: str, initList: list, Edwp: float):
|
|
1168
|
+
"""Writes the block for a specific residue."""
|
|
1169
|
+
addParam('lambda-dynamics-atom-set{}-name'.format(number), name)
|
|
1170
|
+
addParam('lambda-dynamics-atom-set{}-index-group-name'.format(number), 'LAMBDA{}'.format(number))
|
|
1171
|
+
addParam('lambda-dynamics-atom-set{}-initial-lambda'.format(number), to_string(initList, 1))
|
|
1172
|
+
addParam('lambda-dynamics-atom-set{}-barrier'.format(number), Edwp)
|
|
1173
|
+
|
|
1174
|
+
if constrainCharge:
|
|
1175
|
+
addParam('lambda-dynamics-atom-set{}-charge-restraint-group-index'.format(number), 1)
|
|
1176
|
+
|
|
1177
|
+
if (name == 'BUF'):
|
|
1178
|
+
addParam('lambda-dynamics-atom-set{}-buffer-residue'.format(number), 'yes')
|
|
1179
|
+
addParam('lambda-dynamics-atom-set{}-buffer-residue-multiplier'.format(number), buffersFoundinProtein)
|
|
1180
|
+
|
|
1181
|
+
file.write('\n')
|
|
1182
|
+
|
|
1183
|
+
number = 1
|
|
1184
|
+
|
|
1185
|
+
for residue in Structure.d_residues:
|
|
1186
|
+
|
|
1187
|
+
if residue.d_resname in LambdaTypeNamesFoundinProtein:
|
|
1188
|
+
|
|
1189
|
+
LambdaType = [obj for obj in self.ph_lambdaTypes if obj.d_groupname == residue.d_resname][0]
|
|
1190
|
+
multistate = len(LambdaType.d_pKa) > 1
|
|
1191
|
+
|
|
1192
|
+
# HANDLE INTERACTIVE EDWP
|
|
1193
|
+
|
|
1194
|
+
# Only do this if -inter was set AND we're writing params for production run (no point for EM/NVT/NPT).
|
|
1195
|
+
if self.ph_inter and Type == 'MD':
|
|
1196
|
+
Edwp = input("phbuilder : set bias barrier (kJ/mol) for {}-{} in chain {} (or hit enter for default = {}): ".format(residue.d_resname, residue.d_resid, residue.d_chain, self.ph_dwpE))
|
|
1197
|
+
if Edwp == '':
|
|
1198
|
+
Edwp = self.ph_dwpE
|
|
1199
|
+
else:
|
|
1200
|
+
Edwp = float(Edwp)
|
|
1201
|
+
self.verbose("Setting custom Edwp ({}) for residue {}-{} in chain {} (LAMBDA{})".format(Edwp, residue.d_resname, residue.d_resid, residue.d_chain, number))
|
|
1202
|
+
else:
|
|
1203
|
+
Edwp = self.ph_dwpE
|
|
1204
|
+
|
|
1205
|
+
# HANDLE INITIAL LAMBDA FROM PHRECORD.DAT
|
|
1206
|
+
|
|
1207
|
+
init = residue.d_init
|
|
1208
|
+
if init == '':
|
|
1209
|
+
init = self.automaticLambdaInits(LambdaType.d_pKa, self.ph_ph)
|
|
1210
|
+
self.warning('Initial lambda value for residue {}-{} in chain {} not found! Check your phrecord.dat file. Will revert to automatic (state {}), but your system might no-longer be neutral.'.format(residue.d_resname, residue.d_resid, residue.d_chain, init))
|
|
1211
|
+
|
|
1212
|
+
if multistate:
|
|
1213
|
+
initList = []
|
|
1214
|
+
for idx in range(0, len(LambdaType.d_pKa)):
|
|
1215
|
+
initList.append(idx == int(init) - 1)
|
|
1216
|
+
|
|
1217
|
+
if not multistate:
|
|
1218
|
+
initList = [int(init)]
|
|
1219
|
+
|
|
1220
|
+
# DO THE WRITING
|
|
1221
|
+
|
|
1222
|
+
writeResBlock(number, residue.d_resname, initList, Edwp)
|
|
1223
|
+
|
|
1224
|
+
number += 1
|
|
1225
|
+
|
|
1226
|
+
if constrainCharge:
|
|
1227
|
+
# Write block for the buffer.
|
|
1228
|
+
if self.ph_cal:
|
|
1229
|
+
writeResBlock(number, 'BUF', initList=[1], Edwp=0.0)
|
|
1230
|
+
else:
|
|
1231
|
+
writeResBlock(number, 'BUF', initList=[0.5], Edwp=0.0)
|
|
1232
|
+
|
|
1233
|
+
file.close() # MD.mdp
|
|
1234
|
+
|
|
1235
|
+
def writeLambda_ndx(self, fileName: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
|
|
1236
|
+
"""Write the LAMBDA groups to the (a generic) index file.
|
|
1237
|
+
|
|
1238
|
+
Args:
|
|
1239
|
+
fileName (str): name of index.ndx file.
|
|
1240
|
+
Structure (Structure): Structure object.
|
|
1241
|
+
LambdaTypeNames (list): lambdaType names.
|
|
1242
|
+
constrainCharge (bool): do we have charge restraining?
|
|
1243
|
+
"""
|
|
1244
|
+
|
|
1245
|
+
# Create list of Lambda group types found in protein.
|
|
1246
|
+
LambdasFoundinProtein = []
|
|
1247
|
+
for residue in Structure.d_residues:
|
|
1248
|
+
if residue.d_resname in LambdaTypeNames:
|
|
1249
|
+
LambdasFoundinProtein.append(residue.d_resname)
|
|
1250
|
+
|
|
1251
|
+
file = open(fileName, 'a')
|
|
1252
|
+
|
|
1253
|
+
def writeTheGroup(number, atomIndexList):
|
|
1254
|
+
"""Formatting function for writing the index block."""
|
|
1255
|
+
file.write('\n[ LAMBDA{} ]\n'.format(number))
|
|
1256
|
+
for index in atomIndexList:
|
|
1257
|
+
file.write('{} '.format(index))
|
|
1258
|
+
file.write('\n')
|
|
1259
|
+
|
|
1260
|
+
atomCount = 1
|
|
1261
|
+
groupNumber = 1
|
|
1262
|
+
bufferIndexList = []
|
|
1263
|
+
|
|
1264
|
+
# Write the lambda index groups for the titratable residues.
|
|
1265
|
+
for residue in Structure.d_residues:
|
|
1266
|
+
# If the residue is titratable
|
|
1267
|
+
if residue.d_resname in list(set(LambdasFoundinProtein)):
|
|
1268
|
+
# To hold the atom indices corresponding to the titratable atoms.
|
|
1269
|
+
atomIndexList = []
|
|
1270
|
+
# Corresponding LambdaType object
|
|
1271
|
+
LambdaType = [obj for obj in self.ph_lambdaTypes if obj.d_groupname == residue.d_resname][0]
|
|
1272
|
+
|
|
1273
|
+
# Loop through atoms - note that the atoms need to be descending order.
|
|
1274
|
+
for atom in residue.d_atoms:
|
|
1275
|
+
if atom in LambdaType.d_atoms:
|
|
1276
|
+
atomIndexList.append(atomCount)
|
|
1277
|
+
|
|
1278
|
+
atomCount += 1
|
|
1279
|
+
|
|
1280
|
+
# Write the lambda index group and increment groupnumber.
|
|
1281
|
+
writeTheGroup(groupNumber, atomIndexList)
|
|
1282
|
+
groupNumber += 1
|
|
1283
|
+
|
|
1284
|
+
elif constrainCharge and residue.d_resname == 'BUF':
|
|
1285
|
+
bufferIndexList.append(atomCount)
|
|
1286
|
+
atomCount += 1
|
|
1287
|
+
|
|
1288
|
+
else: # Increment atomCount.
|
|
1289
|
+
for atom in residue.d_atoms:
|
|
1290
|
+
atomCount += 1
|
|
1291
|
+
|
|
1292
|
+
# If we do charge constraining write the lambda index group for the buffer(s).
|
|
1293
|
+
if constrainCharge:
|
|
1294
|
+
writeTheGroup(groupNumber, bufferIndexList)
|
|
1295
|
+
|
|
1296
|
+
file.close()
|
|
1297
|
+
|
|
1298
|
+
def genparams(self):
|
|
1299
|
+
"""Generate parameters for MD.mdp."""
|
|
1300
|
+
# PART I - PREP
|
|
1301
|
+
|
|
1302
|
+
# Load the input structure into d_residues.
|
|
1303
|
+
pdb = Structure(self.d_file, self.d_verbosity)
|
|
1304
|
+
|
|
1305
|
+
# List of groupnames of the LambdaTypes specified in lambdagrouptypes.dat.
|
|
1306
|
+
LambdaTypeNames = []
|
|
1307
|
+
for LambdaType in self.ph_lambdaTypes:
|
|
1308
|
+
LambdaTypeNames.append(LambdaType.d_groupname)
|
|
1309
|
+
|
|
1310
|
+
# Check whether we have any titratable residues in the structure,
|
|
1311
|
+
# and also check whether we have any buffers.
|
|
1312
|
+
anyTitratables = False
|
|
1313
|
+
constrainCharge = False
|
|
1314
|
+
|
|
1315
|
+
for residue in pdb.d_residues:
|
|
1316
|
+
if residue.d_resname in LambdaTypeNames:
|
|
1317
|
+
anyTitratables = True
|
|
1318
|
+
|
|
1319
|
+
elif residue.d_resname == 'BUF':
|
|
1320
|
+
constrainCharge = True
|
|
1321
|
+
|
|
1322
|
+
if anyTitratables and constrainCharge:
|
|
1323
|
+
break
|
|
1324
|
+
|
|
1325
|
+
if not constrainCharge:
|
|
1326
|
+
self.warning("No BUF(s) found. Will not use charge constraining...")
|
|
1327
|
+
|
|
1328
|
+
# If we are doing a calibration, set the BUF charges from 0 to 1 as this is
|
|
1329
|
+
# more straightforward for keeping net neutral charge.
|
|
1330
|
+
if self.ph_cal:
|
|
1331
|
+
self.ph_BUF_range = [1, 0]
|
|
1332
|
+
|
|
1333
|
+
gen_mdp(Type='EM', nsteps=5000, nstxout=0, posRes=self.ph_cal)
|
|
1334
|
+
self.update('Wrote a generic EM.mdp file (for energy minimization)...')
|
|
1335
|
+
|
|
1336
|
+
gen_mdp(Type='NVT', nsteps=5000, nstxout=0, posRes=self.ph_cal)
|
|
1337
|
+
self.update('Wrote a generic NPT.mdp file (for temperature coupling)...')
|
|
1338
|
+
|
|
1339
|
+
gen_mdp(Type='NPT', nsteps=5000, nstxout=0, posRes=self.ph_cal)
|
|
1340
|
+
self.update('Wrote a generic NVT.mdp file (for pressure coupling)...')
|
|
1341
|
+
|
|
1342
|
+
# If no existing .mdp file is specified using the -mdp flag, write a generic one.
|
|
1343
|
+
if self.d_mdp is None:
|
|
1344
|
+
if self.ph_cal:
|
|
1345
|
+
gen_mdp('MD', 500000, 25000, posRes=self.ph_cal)
|
|
1346
|
+
else:
|
|
1347
|
+
gen_mdp('MD', 50000000, 25000, posRes=self.ph_cal)
|
|
1348
|
+
|
|
1349
|
+
self.update('Wrote a generic MD.mdp file (for production)...')
|
|
1350
|
+
self.warning("Although the generated .mdp files should mostly be fine, it is up to the user to verify that the (non-CpHMD part of the) generated .mdp file(s) is suitable for their particular system (e.g. you might want to use semi-isotropic pressure coupling when simulating a membrane protein etc).")
|
|
1351
|
+
|
|
1352
|
+
# Move this warning here so that we can also build normal MD sims with phbuilder.
|
|
1353
|
+
if not anyTitratables:
|
|
1354
|
+
self.error("No titratable residues detected! Will not perform any cpHMD related stuff...")
|
|
1355
|
+
|
|
1356
|
+
# PARTS II - WRITE LAMBDA DYNAMICS PARAMETERS IN MDP FILE
|
|
1357
|
+
|
|
1358
|
+
# We do not only MD, but also EM, NVT, and NPT at constant-pH.
|
|
1359
|
+
# Therefore loop over these files for PARTS I, II, and III (but not IV):
|
|
1360
|
+
for Type in ['EM', 'NVT', 'NPT', 'MD']:
|
|
1361
|
+
self.writeLambda_mdp(Type, pdb, LambdaTypeNames, constrainCharge)
|
|
1362
|
+
|
|
1363
|
+
# PART III - WRITE LAMBDA INDEX GROUPS
|
|
1364
|
+
|
|
1365
|
+
# If no .ndx file was specified on the command line, generate our generic one:
|
|
1366
|
+
if self.d_ndx is None:
|
|
1367
|
+
self.update('No .ndx file was specified. Creating a generic index.ndx file...')
|
|
1368
|
+
self.gromacs("make_ndx -f {}".format(self.d_file), stdin=['q'])
|
|
1369
|
+
self.d_ndx = 'index.ndx'
|
|
1370
|
+
|
|
1371
|
+
self.writeLambda_ndx(self.d_ndx, pdb, LambdaTypeNames, constrainCharge)
|
|
1372
|
+
|
|
1373
|
+
self.update('Finished phbuilder genparams. Please check the parameters in the generated .mdp files.')
|
|
1374
|
+
|
|
1375
|
+
def automaticLambdaInits(self, pKaList: list, systempH: float) -> int:
|
|
1376
|
+
"""If the user does not specify the -inter flag, all the residues associated
|
|
1377
|
+
with a lambdagrouptype will by default made titratable. The charge states
|
|
1378
|
+
of these residues will be guessed based on an optional pH parameter
|
|
1379
|
+
(default = 7.0) that can be specified for gentopol.
|
|
1380
|
+
|
|
1381
|
+
Args:
|
|
1382
|
+
pKaList (list): list of pKas for the LambdaGroupTypes.
|
|
1383
|
+
systempH (float): specified system pH.
|
|
1384
|
+
|
|
1385
|
+
Returns:
|
|
1386
|
+
int: initial lambda value.
|
|
1387
|
+
"""
|
|
1388
|
+
# multistate case
|
|
1389
|
+
if len(pKaList) > 1:
|
|
1390
|
+
|
|
1391
|
+
highest = 0
|
|
1392
|
+
for pKa in pKaList:
|
|
1393
|
+
if pKa <= systempH and pKa > highest:
|
|
1394
|
+
highest = pKa
|
|
1395
|
+
|
|
1396
|
+
return pKaList.index(highest) + 1
|
|
1397
|
+
|
|
1398
|
+
#2state case
|
|
1399
|
+
else:
|
|
1400
|
+
if systempH >= pKaList[0]:
|
|
1401
|
+
return 1 # if pH >= pKa, we are in deproto = 1 state.
|
|
1402
|
+
|
|
1403
|
+
return 0 # if pH < pKa, we are in the proto = 0 state.
|
|
1404
|
+
|
|
1405
|
+
def pleaseCite(self):
|
|
1406
|
+
"""Print citation request.
|
|
1407
|
+
"""
|
|
1408
|
+
self.update('If this software contributed to your research, please cite https://chemrxiv.org/engage/chemrxiv/article-details/64d4d5af69bfb8925ab380a4.')
|