phbuilder 1.2.5__tar.gz → 1.3__tar.gz

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.
Files changed (49) hide show
  1. {phbuilder-1.2.5 → phbuilder-1.3}/PKG-INFO +14 -6
  2. {phbuilder-1.2.5 → phbuilder-1.3}/README.md +13 -5
  3. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/__init__.py +8 -4
  4. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/parsecmdline.py +13 -7
  5. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/phbuilder.py +91 -77
  6. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/sanitize.py +48 -48
  7. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/structure.py +20 -19
  8. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/user.py +4 -5
  9. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/PKG-INFO +14 -6
  10. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/SOURCES.txt +10 -1
  11. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/top_level.txt +1 -0
  12. {phbuilder-1.2.5 → phbuilder-1.3}/setup.cfg +1 -1
  13. phbuilder-1.3/tests/__init__.py +0 -0
  14. phbuilder-1.3/tests/test_genparams.py +46 -0
  15. phbuilder-1.3/tests/test_gentopol.py +32 -0
  16. phbuilder-1.3/tests/test_neutralize.py +18 -0
  17. phbuilder-1.3/tests/testutils.py +47 -0
  18. {phbuilder-1.2.5 → phbuilder-1.3}/LICENSE +0 -0
  19. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/README.md +0 -0
  20. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/atomtypes.atp +0 -0
  21. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/cmap.itp +0 -0
  22. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffbonded.itp +0 -0
  23. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/ffnonbonded.itp +0 -0
  24. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.doc +0 -0
  25. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/forcefield.itp +0 -0
  26. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/gb.itp +0 -0
  27. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/ions.itp +0 -0
  28. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.arn +0 -0
  29. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.c.tdb +0 -0
  30. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.hdb +0 -0
  31. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.n.tdb +0 -0
  32. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.r2b +0 -0
  33. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.rtp +0 -0
  34. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/merged.vsd +0 -0
  35. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/nbfix.itp +0 -0
  36. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/old_c36_cmap.itp +0 -0
  37. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/popc.itp +0 -0
  38. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/spc.itp +0 -0
  39. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/spce.itp +0 -0
  40. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip3p.itp +0 -0
  41. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip4p.itp +0 -0
  42. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/charmm36-mar2019-cphmd.ff/watermodels.dat +0 -0
  43. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/lambdagrouptypes.dat +0 -0
  44. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/ffield/residuetypes.dat +0 -0
  45. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder/mdp.py +0 -0
  46. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/dependency_links.txt +0 -0
  47. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/entry_points.txt +0 -0
  48. {phbuilder-1.2.5 → phbuilder-1.3}/phbuilder.egg-info/requires.txt +0 -0
  49. {phbuilder-1.2.5 → phbuilder-1.3}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: phbuilder
3
- Version: 1.2.5
3
+ Version: 1.3
4
4
  Summary: System builder for constant-pH simulations in GROMACS.
5
5
  Home-page: https://gitlab.com/gromacs-constantph/phbuilder
6
6
  Author: Anton Jansen
@@ -136,6 +136,13 @@ If you don't want to manually set initial lambda values, you can use the `-ph <p
136
136
  phbuilder gentopol -f input.pdb -ph <ph>
137
137
  ```
138
138
 
139
+ Furthermore, if you only want certain residue types to be made titratable, you can use the `-groups` flag. For example:
140
+
141
+ ```
142
+ phbuilder gentopol -f input.pdb -groups "ASPT GLUT"
143
+ ```
144
+
145
+ only considers aspartate and glutamate residues for setting up the CpHMD simulation.
139
146
  ### 4. Add a periodic box and solvent (if not already present).
140
147
 
141
148
  Periodic box (see [gmx editconf](https://manual.gromacs.org/documentation/current/onlinehelp/gmx-editconf.html)):
@@ -399,15 +406,15 @@ will position restrain only atom 19. Position restraining during the parameteriz
399
406
 
400
407
  ### 5. Perform solvation and neutralization to obtain a net-neutral simulation system.
401
408
 
402
- * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 2 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 2.0` flags.
403
- * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of 5 nm cubed for the paramterization and replica simulations.
409
+ * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 1.5 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 1.5` flags.
410
+ * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of at least 5 nm cubed for the paramterization and replica simulations.
404
411
  * The effects of ionic strength on the parameterization should be limited, but we nonetheless recommend adding at least a few ions to the parameterization system and replicates, e.g. by setting `-conc 0.15` (physiological NaCl concentration).
405
412
  * For more information on the effects of box size and ionic strength on the parameterization, please refer to the [best practices paper](https://pubs.acs.org/doi/full/10.1021/acs.jctc.2c00517).
406
413
 
407
414
  ```
408
- gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 1.8
415
+ gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 2.0
409
416
  gmx solvate -cp box.pdb -p topol.top -o solvated.pdb
410
- phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 2.0 -conc 0.15
417
+ phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 1.5 -conc 0.15
411
418
  ```
412
419
 
413
420
  ### 6. Use `genparams` to generate the `.mdp` files in calibration mode.
@@ -557,11 +564,12 @@ Allows you to select which residues to make titratable and which initial lambda
557
564
 
558
565
  OPTIONS
559
566
 
560
- | Flag__ | Description |
567
+ | Flag____ | Description |
561
568
  |--------------|----------------|
562
569
  | `-f` | [\<.pdb/.gro>] (required) <br /> Specify input structure file. |
563
570
  | `-o` | [\<.pdb/.gro>] (phprocessed.pdb) <br /> Specify output structure file. |
564
571
  | `-ph` | [\<float>] <br /> Specify intended simulation pH. Will be used together with the reference pKas of the titratable sites to auto set the initial lambdas. |
572
+ | `-groups` | [\<str>] <br /> Specify which titratable residue types to consider. Example: "ASPT GLUT" will only consider Asp and Glu residues for CpHMD. |
565
573
  | `-v` | (no) <br /> Be more verbose. |
566
574
 
567
575
  # Synopsis `phbuilder neutralize`
@@ -113,6 +113,13 @@ If you don't want to manually set initial lambda values, you can use the `-ph <p
113
113
  phbuilder gentopol -f input.pdb -ph <ph>
114
114
  ```
115
115
 
116
+ Furthermore, if you only want certain residue types to be made titratable, you can use the `-groups` flag. For example:
117
+
118
+ ```
119
+ phbuilder gentopol -f input.pdb -groups "ASPT GLUT"
120
+ ```
121
+
122
+ only considers aspartate and glutamate residues for setting up the CpHMD simulation.
116
123
  ### 4. Add a periodic box and solvent (if not already present).
117
124
 
118
125
  Periodic box (see [gmx editconf](https://manual.gromacs.org/documentation/current/onlinehelp/gmx-editconf.html)):
@@ -376,15 +383,15 @@ will position restrain only atom 19. Position restraining during the parameteriz
376
383
 
377
384
  ### 5. Perform solvation and neutralization to obtain a net-neutral simulation system.
378
385
 
379
- * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 2 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 2.0` flags.
380
- * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of 5 nm cubed for the paramterization and replica simulations.
386
+ * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 1.5 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 1.5` flags.
387
+ * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of at least 5 nm cubed for the paramterization and replica simulations.
381
388
  * The effects of ionic strength on the parameterization should be limited, but we nonetheless recommend adding at least a few ions to the parameterization system and replicates, e.g. by setting `-conc 0.15` (physiological NaCl concentration).
382
389
  * For more information on the effects of box size and ionic strength on the parameterization, please refer to the [best practices paper](https://pubs.acs.org/doi/full/10.1021/acs.jctc.2c00517).
383
390
 
384
391
  ```
385
- gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 1.8
392
+ gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 2.0
386
393
  gmx solvate -cp box.pdb -p topol.top -o solvated.pdb
387
- phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 2.0 -conc 0.15
394
+ phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 1.5 -conc 0.15
388
395
  ```
389
396
 
390
397
  ### 6. Use `genparams` to generate the `.mdp` files in calibration mode.
@@ -534,11 +541,12 @@ Allows you to select which residues to make titratable and which initial lambda
534
541
 
535
542
  OPTIONS
536
543
 
537
- | Flag__ | Description |
544
+ | Flag____ | Description |
538
545
  |--------------|----------------|
539
546
  | `-f` | [\<.pdb/.gro>] (required) <br /> Specify input structure file. |
540
547
  | `-o` | [\<.pdb/.gro>] (phprocessed.pdb) <br /> Specify output structure file. |
541
548
  | `-ph` | [\<float>] <br /> Specify intended simulation pH. Will be used together with the reference pKas of the titratable sites to auto set the initial lambdas. |
549
+ | `-groups` | [\<str>] <br /> Specify which titratable residue types to consider. Example: "ASPT GLUT" will only consider Asp and Glu residues for CpHMD. |
542
550
  | `-v` | (no) <br /> Be more verbose. |
543
551
 
544
552
  # Synopsis `phbuilder neutralize`
@@ -1,16 +1,20 @@
1
1
  # PYTHON_ARGCOMPLETE_OK
2
2
 
3
3
  def entryFunction():
4
+ """Entry point for phbuilder. When phbuilder is run, this function is
5
+ called first.
6
+ """
7
+
4
8
  # PYTHON_ARGCOMPLETE_OK
5
9
 
6
10
  # Execute this as soon as possible because of the TAB autocomplete thing.
7
- from . import parsecmdline
11
+ from .parsecmdline import parsecmdline
8
12
 
9
13
  # Parse command line input.
10
- CLI = parsecmdline.parsecmdline()
14
+ CLI = parsecmdline()
11
15
 
12
16
  # Import everything else.
13
- from . import phbuilder
17
+ from .phbuilder import phbuilder
14
18
 
15
19
  # Run main program.
16
- phbuilder.phbuilder(CLI).runner()
20
+ return phbuilder(CLI).runner()
@@ -1,8 +1,7 @@
1
1
  # PYTHON_ARGCOMPLETE_OK
2
2
 
3
- import argparse
4
- import argcomplete
5
- import sys
3
+ from argparse import ArgumentParser
4
+ from argcomplete import autocomplete
6
5
 
7
6
 
8
7
  def parsecmdline():
@@ -16,7 +15,7 @@ def parsecmdline():
16
15
  desc_1 = "System builder for constant-pH simulations in GROMACS. phbuilder consists of three tools: gentopol, neutralize, and genparams. Each tool performs a specific task for preparing a constant-pH simulation. Functionality for setting up titrations and parameterizations is provided with the help of stand-alone Python scripts, provided on the gitlab. Out of the box, phbuilder comes with the force field and CpHMD topology parameters required for setting up titratable Arg, Lys, Asp, Glu, and His residues in CHARMM36m."
17
16
 
18
17
  # Epilogue. Also used by subcommands.
19
- desc_2 = "phbuilder VERSION 1.2.5. For the user manual visit https://gitlab.com/gromacs-constantph/phbuilder."
18
+ desc_2 = "phbuilder VERSION 1.3. For the user manual visit https://gitlab.com/gromacs-constantph/phbuilder."
20
19
 
21
20
  # gentopol main description.
22
21
  desc_3 = "Allows you to select which residues to make titratable and which initial lambda (protonation) state they should have. Also (re)generates the system topology using the modified CHARMM36m force field. If you don't want to manually set initial lambda values, you can use the -ph flag to have gentopol automatically choose the appropriate initial lambda values, based on the criterion: pH > pKa means start deprotonated, else start protonated."
@@ -27,7 +26,7 @@ def parsecmdline():
27
26
  # genparams main description.
28
27
  desc_5 = "Generates the CpHMD-specific .mdp and .ndx files. Will write generic EM.mdp EQ.mdp, and MD.mdp files for CHARMM36m and append the CpHMD parameters at the bottom. genparams requires the existence of a phrecord.dat file, which contains the initial lambda values and is created during the gentopol step. Note: if you previously used the auto feature (-ph flag) for gentopol, the pH you specify for genparams should reflect this."
29
28
 
30
- parser = argparse.ArgumentParser(prog='phbuilder', description=desc_1, epilog=desc_2)
29
+ parser = ArgumentParser(prog='phbuilder', description=desc_1, epilog=desc_2)
31
30
 
32
31
  subparsers = parser.add_subparsers(required=False)
33
32
 
@@ -54,6 +53,12 @@ def parsecmdline():
54
53
  help='[<float>] Specify intended simulation pH. Will be used together with the reference pKas of the titratable sites to auto set the initial lambdas.',
55
54
  type=float)
56
55
 
56
+ parser_1.add_argument('-groups',
57
+ required=False,
58
+ dest='groups',
59
+ action='store',
60
+ help='[<str>] Specify which titratable residue types to consider. Example: \"ASPT GLUT\" will only consider Asp and Glu residues for CpHMD. Also residue alternative name (e.g. \"ASP GLU\") can be provided.')
61
+
57
62
  parser_1.add_argument('-v',
58
63
  required=False,
59
64
  dest='verbosity',
@@ -221,7 +226,7 @@ def parsecmdline():
221
226
  parser_3.set_defaults(target='genparams')
222
227
 
223
228
  # Required for auto-completing using argcomplete.
224
- argcomplete.autocomplete(parser)
229
+ autocomplete(parser)
225
230
 
226
231
  # Do the actual parsing.
227
232
  CLI = parser.parse_args()
@@ -229,7 +234,8 @@ def parsecmdline():
229
234
  # Prevent Python errors when no subcommand is specified.
230
235
  if vars(CLI) == {}:
231
236
  parser.print_help()
232
- sys.exit(0)
237
+ from sys import exit # Lazy/deffered import.
238
+ exit(0)
233
239
 
234
240
  # Object containing all the parsed key-value pairs.
235
241
  return CLI
@@ -1,20 +1,21 @@
1
- import configparser
2
- import subprocess
3
1
  import os
2
+ from configparser import ConfigParser, NoOptionError
3
+ from subprocess import run
4
+ from typing import List
4
5
 
5
6
  from sympy.parsing.sympy_parser import parse_expr
6
7
  from sympy import symbols
7
8
 
8
- from .user import User
9
+ from .mdp import gen_mdp
9
10
  from .sanitize import Sanitize
10
11
  from .structure import Structure
11
- from .mdp import gen_mdp
12
+ from .user import User
12
13
 
13
14
 
14
15
  class LambdaType:
15
16
  """Data structure for storing a LambdaType.
16
17
  """
17
- def __init__(self, groupname: str, incl: list, pKa: list, atoms: list, qqA: list, qqB: list, dvdl: list):
18
+ def __init__(self, groupname: str, incl: List[str], pKa: List[float], atoms: List[str], qqA: List[float], qqB: List[float], dvdl: List[float]):
18
19
  """Initialize LambdaType object.
19
20
 
20
21
  Args:
@@ -62,6 +63,7 @@ class phbuilder(User):
62
63
  if (CLI.target == 'gentopol'):
63
64
  self.d_output = Sanitize(CLI.output, 'output').path(ext=['.pdb', '.gro'], out=True)
64
65
  self.ph_auto = CLI.ph # None if not set, else float
66
+ self.ph_groups = CLI.groups.split() if CLI.groups else None
65
67
 
66
68
  # If we run neutralize...
67
69
  elif (CLI.target == 'neutralize'):
@@ -126,7 +128,7 @@ class phbuilder(User):
126
128
  self.verbose(vars(CLI))
127
129
 
128
130
  self.parseLambdaGroupTypesFile()
129
- self.checkGROMACSLoaded()
131
+ self.checkCPHMDGROMACSLoaded()
130
132
  # self.checkCorrectGromacsSettings()
131
133
 
132
134
  def parseLambdaGroupTypesFile(self):
@@ -136,7 +138,7 @@ class phbuilder(User):
136
138
  self.ph_lambdaTypes = []
137
139
  self.ph_BUF_dvdl = None
138
140
 
139
- def defineLambdaType(groupname: str, incl: list, pKa: list, atoms: list, qqA: list, qqB: list, dvdl: list):
141
+ def defineLambdaType(groupname: str, incl: List[str], pKa: List[float], atoms: List[str], qqA: List[float], qqB: List[float], dvdl: List[float]):
140
142
  """Add lambdaType to ph_lambdaTypes (or skip if it is already there).
141
143
 
142
144
  Args:
@@ -153,14 +155,28 @@ class phbuilder(User):
153
155
  NewLambdaType = LambdaType(groupname, incl, pKa, atoms, qqA, qqB, dvdl)
154
156
 
155
157
  # Only add NewLambdaType to ph_lambdaTypes if it does not exist yet.
156
- alreadyPresent = False
158
+ already_present = False
157
159
  for entry in self.ph_lambdaTypes:
158
160
  if entry.d_groupname == NewLambdaType.d_groupname:
159
161
  self.warning(f"LambdaType with groupname {groupname} is already defined. Skipping...")
160
- alreadyPresent = True
162
+ already_present = True
161
163
  break
162
164
 
163
- if not alreadyPresent:
165
+ # The lines below were added to enable the -groups functionality of
166
+ # gentopol. Effectively, we check if lambda group name is specified on
167
+ # cmdline for -groups (is in the ph_groups list). The check has two stages
168
+ # 1. We check the name directly
169
+ # 2. We check all the alternative names (provided under incl keyword)
170
+
171
+ residue_in_groups_flag = True
172
+ # defaults to True, since we consider all titratable residues by default.
173
+
174
+ if hasattr(self, 'ph_groups') and self.ph_groups is not None:
175
+ residue_in_groups_flag = False
176
+ if (groupname in self.ph_groups) or (any([x in self.ph_groups for x in incl])):
177
+ residue_in_groups_flag = True
178
+
179
+ if not already_present and residue_in_groups_flag:
164
180
  self.ph_lambdaTypes.append(NewLambdaType)
165
181
 
166
182
  def str2floatList(string: str):
@@ -194,7 +210,7 @@ class phbuilder(User):
194
210
  self.verbose('path to lambdagrouptypes.dat = {}\n'.format(p_lambdagrouptypes))
195
211
 
196
212
  # Do the actual parsing
197
- parser = configparser.ConfigParser()
213
+ parser = ConfigParser()
198
214
  parser.read(p_lambdagrouptypes)
199
215
 
200
216
  # Loop through the sections.
@@ -245,7 +261,7 @@ class phbuilder(User):
245
261
 
246
262
  # Parse dvdl(s)
247
263
  dvdl.append(str2floatList(parser.get(sect, 'dvdl_{}'.format(idx))))
248
- except configparser.NoOptionError:
264
+ except NoOptionError:
249
265
  break
250
266
 
251
267
  # SANITIZE INPUT
@@ -280,11 +296,11 @@ class phbuilder(User):
280
296
  self.verbose("BUF_range = {}".format(self.ph_BUF_range))
281
297
  self.verbose("BUF_dvdl = {}".format(self.ph_BUF_dvdl))
282
298
 
283
- def checkGROMACSLoaded(self) -> None:
284
- """This function checks whether GROMACS (any version) was set in the environment."""
299
+ def checkCPHMDGROMACSLoaded(self) -> None:
300
+ """Check whether the constant-pH beta is active by attempting to run 'gmx cphmd -h'."""
285
301
 
286
- if not isinstance(os.getenv('GROMACS_DIR'), str):
287
- self.error("The GROMACS_DIR environment variable is not set, suggesting GROMACS wasn't properly sourced or loaded. Please make sure to source or module load the GROMACS constant-pH beta.")
302
+ if run("gmx cphmd -h", shell=True, stdout=-1, stderr=-1).returncode:
303
+ self.warning("The GROMACS constant-pH beta does not appear to be loaded. While this might be fine for gentopol and genparams, it MUST be loaded when using neutralize. Please source or module load the GROMACS constant-pH beta.")
288
304
 
289
305
  def checkCorrectGromacsSettings(self) -> None:
290
306
  """This function attempts to make sure that the GROMACS CpHMD install is correctly loaded in the environment from which phbuilder is called."""
@@ -350,10 +366,10 @@ class phbuilder(User):
350
366
  envDict = os.environ.copy()
351
367
 
352
368
  if terminal:
353
- process = subprocess.run("gmx " + command, shell=True, env=envDict)
369
+ process = run("gmx " + command, shell=True, env=envDict)
354
370
  else:
355
371
  with open(logFile, 'a+') as file:
356
- process = subprocess.run("gmx " + command, shell=True, stdout=file, stderr=file, env=envDict)
372
+ process = run("gmx " + command, shell=True, stdout=file, stderr=file, env=envDict)
357
373
 
358
374
  if process.returncode != 0:
359
375
  if terminal:
@@ -363,9 +379,13 @@ class phbuilder(User):
363
379
 
364
380
  return process.returncode
365
381
 
366
- def runner(self):
382
+ def runner(self) -> int:
367
383
  """Call correct sub-function depending on specified target on cmdline.
384
+
385
+ Returns:
386
+ int: exitcode.
368
387
  """
388
+
369
389
  if self.d_target == 'gentopol':
370
390
  self.update('Running gentopol...')
371
391
  self.gentopol()
@@ -379,6 +399,8 @@ class phbuilder(User):
379
399
  self.genparams()
380
400
  self.pleaseCite()
381
401
 
402
+ return 0 # phbuilder ran succesfully if we end up here.
403
+
382
404
  def gentopol(self):
383
405
  """gentopol prepares the topology.
384
406
  """
@@ -566,7 +588,7 @@ class phbuilder(User):
566
588
  LambdaTypeDict[obj.d_groupname] = 1
567
589
 
568
590
  with open('lambdareference.dat', 'w+') as file:
569
- file.write('resname coord# resid chain coordinateFile\n')
591
+ file.write('resname state# resid chain coordinateFile\n')
570
592
 
571
593
  coordCount = 1
572
594
  for residue in pdb.d_residues:
@@ -803,7 +825,7 @@ class phbuilder(User):
803
825
 
804
826
  # II - DO THE IONS PART
805
827
 
806
- def getcpHMDcharge(name: str, file: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
828
+ def getcpHMDcharge(name: str, file: str, Structure: Structure, LambdaTypeNames: List[str], constrainCharge: bool):
807
829
  """Create a dummy .mdp file (including CpHMD parameters), calls gmx grompp,
808
830
  and from the output extracts the system net-charge (in the actual CpHMD simulation).
809
831
 
@@ -853,28 +875,42 @@ class phbuilder(User):
853
875
  # boolean to prevent execution for when the system is already neutral.
854
876
  isNeutral = False
855
877
 
856
- # If we already have ions in the input file, give the user an extra update.
878
+ # Molecular weight of water as a global-scope constant.
879
+ # Used to calculate ion concentrations based on solvent volume.
880
+ WATER_MOL_WEIGHT = 0.01808
857
881
 
858
- def getIonConcentration(Structure: Structure, Nwater: int):
859
- """Get current ion concentration in system (from) solvent volume."""
860
- totalIons = self.countRes(Structure, self.d_pname) + self.countRes(Structure, self.d_nname)
861
- return totalIons / (0.01808 * Nwater)
882
+ def getIonData(Structure: Structure):
883
+ """Retrieve positive ion, negative ion, and salt concentrations from
884
+ the input structure file. Calculation performed by solvent volume."""
862
885
 
863
- Nwater = self.countRes(pdb, self.d_solname)
864
- ionConcInInput = getIonConcentration(pdb, Nwater)
886
+ N_pos = self.countRes(Structure, self.d_pname)
887
+ N_neg = self.countRes(Structure, self.d_nname)
888
+ N_salt = min(N_pos, N_neg)
889
+ N_water = self.countRes(Structure, self.d_solname)
865
890
 
866
- if ionConcInInput:
867
- self.update("Detected {} {} and {} {} in {}, corresponding to a concentration of {:.3f} mol/L for given solvent volume.".format(
868
- self.countRes(pdb, self.d_pname),
869
- self.d_pname,
870
- self.countRes(pdb, self.d_nname),
871
- self.d_nname,
872
- self.d_file,
873
- ionConcInInput))
891
+ C_pos = N_pos / (WATER_MOL_WEIGHT * N_water)
892
+ C_neg = N_neg / (WATER_MOL_WEIGHT * N_water)
893
+ C_salt = N_salt / (WATER_MOL_WEIGHT * N_water)
874
894
 
875
- # If we already have ions in the input file, d_conc can never be smaller than what we ALREADY HAVE.
876
- if self.d_conc and ionConcInInput > self.d_conc:
877
- 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))
895
+ return N_pos, N_neg, N_salt, C_pos, C_neg, C_salt
896
+
897
+ def fromSolVol(Structure, concentration: float):
898
+ """Return the number of ions required for a specific concentration, based on volume of the solvent."""
899
+ Nwater = self.countRes(Structure, self.d_solname)
900
+ return int(round(WATER_MOL_WEIGHT * Nwater * concentration))
901
+
902
+ N_pos, N_neg, N_salt, C_pos, C_neg, C_salt = getIonData(pdb)
903
+
904
+ if (C_pos or C_neg): # if we already have some ions...
905
+ self.update(f"Detected {N_pos} {self.d_pname} and {N_neg} {self.d_nname} in {self.d_file}, corresponding to [{self.d_pname}{self.d_nname}] = {C_salt:.3f} mol/L for given solvent volume.")
906
+ self.verbose(f"Individual ion concentrations are [{self.d_pname}] = {C_pos:.3f} mol/L and [{self.d_nname}] = {C_neg:.3f} mol/L.")
907
+ else:
908
+ self.update(f"No previous ions detected in {self.d_file}.")
909
+
910
+ # If #salt ions that are already present corresponds to a larger concentration
911
+ # than #salt ions corresponding to the requested concentration, we throw an error.
912
+ if N_salt > fromSolVol(pdb, self.d_conc):
913
+ self.error('Target concentration of {} mol/L is smaller than the current concentration in {} ({:.2f}). Either remove -conc or increase it.'.format(self.d_conc, self.d_file, C_salt))
878
914
 
879
915
  # Get the cpHMD charge (we set constrainCharge to False because we have no buffers at this point).
880
916
  QQtotalcpHMD = getcpHMDcharge('ions', self.d_file, pdb, LambdaTypeNames, constrainCharge=False)
@@ -891,36 +927,15 @@ class phbuilder(User):
891
927
  self.update('System seems to be neutral already.')
892
928
  isNeutral = True
893
929
 
894
- def fromBoxVol():
895
- """Return number of ions required for a specific concentration, based on volume of the box."""
896
- Avo = 6.02214076 * 10 ** 23
897
- boxVol = pdb.d_box.d_a * pdb.d_box.d_b * pdb.d_box.d_c
898
- return int(round(self.d_conc * Avo * boxVol * 10 ** -27))
899
-
900
- def fromSolVol(Structure, concentration):
901
- """Return the number of ions required for a specific concentration, based on volume of the solvent."""
902
- Nwater = self.countRes(Structure, self.d_solname)
903
- return int(round(0.01808 * Nwater * concentration))
904
-
905
930
  if not (isNeutral and self.d_conc == 0):
906
931
 
907
932
  if self.d_conc != 0:
908
- Nions = fromSolVol(pdb, self.d_conc - ionConcInInput)
909
- ionsMinRequired = np + nn
910
-
911
- if Nions < ionsMinRequired:
912
- 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))
913
-
914
- # We only want integers so we want to divide an even number.
915
- if (Nions - np - nn) % 2 != 0:
916
- Nions += 1
917
-
918
- factor = int((Nions - np - nn) / 2.0)
933
+ factor = fromSolVol(pdb, self.d_conc - C_salt)
919
934
 
920
935
  np += factor
921
936
  nn += factor
922
937
 
923
- self.update('Specified ion concentration of {} mol/L corresponds to {} (additional) ions for given solvent volume'.format(self.d_conc, Nions))
938
+ self.update(f"Requested salt concentration of {self.d_conc} mol/L requires {factor} {self.d_pname}{self.d_nname} for given solvent volume")
924
939
 
925
940
  self.update('Will add {} positive ({}) and {} negative ({}) ions...'.format(np, self.d_pname, nn, self.d_nname))
926
941
  self.update('Total charge to be added = {:+.2f}'.format(np - nn))
@@ -1004,7 +1019,8 @@ class phbuilder(User):
1004
1019
 
1005
1020
  # Check if the correct number of ions and buffers are present in the output file.
1006
1021
 
1007
- self.update('\nChecking whether everything was successful:\n')
1022
+ self.update('\nChecking whether everything was successful:')
1023
+ self.update('\n')
1008
1024
 
1009
1025
  # Update internal pdb record to phneutral.pdb.
1010
1026
  pdb.read(self.d_output)
@@ -1028,13 +1044,11 @@ class phbuilder(User):
1028
1044
  self.update('Detected correct number of buffers ({}) - check'.format(nbufs))
1029
1045
 
1030
1046
  # Give a user update about the ion concentration in the output file.
1031
- self.update("{} {} and {} {} in {} corresponds to a concentration of {:.3f} mol/L for given solvent volume...".format(
1032
- self.countRes(pdb, self.d_pname),
1033
- self.d_pname,
1034
- self.countRes(pdb, self.d_nname),
1035
- self.d_nname,
1036
- self.d_output,
1037
- getIonConcentration(pdb, self.countRes(pdb, 'SOL')))) # For some reason, genion renames whatever solname we had in the input file to 'SOL'...
1047
+ N_pos, N_neg, N_salt, C_pos, C_neg, C_salt = getIonData(pdb)
1048
+ self.update(f"{N_pos} {self.d_pname} and {N_neg} {self.d_nname} for solvent volume in {self.d_output} corresponds to:")
1049
+ self.update(f"[{self.d_pname}{self.d_nname}] = {C_salt:.3f} mol/L")
1050
+ self.update(f"[{self.d_pname}] = {C_pos:.3f} mol/L")
1051
+ self.update(f"[{self.d_nname}] = {C_neg:.3f} mol/L")
1038
1052
 
1039
1053
  # Check if the charge is now neutral.
1040
1054
 
@@ -1047,7 +1061,7 @@ class phbuilder(User):
1047
1061
  os.remove('check.tpr')
1048
1062
  self.update("Finished phbuilder neutralize.")
1049
1063
 
1050
- def writeLambda_mdp(self, Type: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
1064
+ def writeLambda_mdp(self, Type: str, Structure: Structure, LambdaTypeNames: List[str], constrainCharge: bool):
1051
1065
  """Generate the actual lambda dynamics parameters for .mdp file.
1052
1066
 
1053
1067
  Args:
@@ -1126,10 +1140,10 @@ class phbuilder(User):
1126
1140
  # PART 2 - WRITE LAMBDA GROUP TYPES
1127
1141
 
1128
1142
  def to_string(Input: list):
1129
- """Convert a list to a string."""
1143
+ """Internal function to convert a list to a string."""
1130
1144
  return ' '.join([str(float(val)) for val in Input])
1131
1145
 
1132
- def writeLambdaGroupTypeBlock(number, name, multistates, qqA, qqB, pKa, dvdl):
1146
+ def writeLambdaGroupTypeBlock(number: int, name: str, multistates: int, qqA: List[float], qqB: List[float], pKa: List[float], dvdl: List[float]):
1133
1147
  """Writes the lambda group type block."""
1134
1148
  addParam('lambda-dynamics-group-type{}-name'.format(number), name)
1135
1149
  addParam('lambda-dynamics-group-type{}-n-states'.format(number), multistates)
@@ -1190,7 +1204,7 @@ class phbuilder(User):
1190
1204
 
1191
1205
  # PART 3 - WRITE LAMBDA GROUPS
1192
1206
 
1193
- def writeResBlock(number: int, name: str, initList: list, Edwp: float):
1207
+ def writeResBlock(number: int, name: str, initList: List[float], Edwp: float):
1194
1208
  """Writes the block for a specific residue."""
1195
1209
  addParam('lambda-dynamics-atom-set{}-name'.format(number), name)
1196
1210
  addParam('lambda-dynamics-atom-set{}-index-group-name'.format(number), 'LAMBDA{}'.format(number))
@@ -1258,7 +1272,7 @@ class phbuilder(User):
1258
1272
 
1259
1273
  file.close() # MD.mdp
1260
1274
 
1261
- def writeLambda_ndx(self, fileName: str, Structure: Structure, LambdaTypeNames: list, constrainCharge: bool):
1275
+ def writeLambda_ndx(self, fileName: str, Structure: Structure, LambdaTypeNames: List[str], constrainCharge: bool):
1262
1276
  """Write the LAMBDA groups to the (a generic) index file.
1263
1277
 
1264
1278
  Args:
@@ -1276,7 +1290,7 @@ class phbuilder(User):
1276
1290
 
1277
1291
  file = open(fileName, 'a')
1278
1292
 
1279
- def writeTheGroup(number, atomIndexList):
1293
+ def writeTheGroup(number, atomIndexList: List[float]):
1280
1294
  """Formatting function for writing the index block."""
1281
1295
 
1282
1296
  file.write('\n[ LAMBDA{} ]\n'.format(number))
@@ -1408,7 +1422,7 @@ class phbuilder(User):
1408
1422
 
1409
1423
  self.update('Finished phbuilder genparams. Please check the parameters in the generated .mdp files.')
1410
1424
 
1411
- def automaticLambdaInits(self, pKaList: list, systempH: float) -> int:
1425
+ def automaticLambdaInits(self, pKaList: List[float], systempH: float) -> int:
1412
1426
  """If the user does not specify the -inter flag, all the residues associated
1413
1427
  with a lambdagrouptype will by default made titratable. The charge states
1414
1428
  of these residues will be guessed based on an optional pH parameter
@@ -1,5 +1,4 @@
1
- import sys
2
- import os
1
+ from os import path
3
2
 
4
3
  class Sanitize:
5
4
  """Class for sanitizing user input of various types."""
@@ -15,12 +14,12 @@ class Sanitize:
15
14
  """
16
15
 
17
16
  self.var = var
18
- self.__name = name
19
- self.__verbose = v
20
- self.__exit = exit
21
- self.__good = True
17
+ self._name = name
18
+ self._verbose = v
19
+ self._exit = exit
20
+ self._good = True
22
21
 
23
- def __error(self, msg: str) -> None:
22
+ def _error(self, msg: str) -> None:
24
23
  """Handles the error message program logic. Sets exitcode to 1 when executed.
25
24
 
26
25
  Args:
@@ -29,13 +28,13 @@ class Sanitize:
29
28
 
30
29
  pre = 'phbuilder : SANITIZE - ' # Pre-string for error messages.
31
30
 
32
- if self.__verbose:
31
+ if self._verbose:
33
32
 
34
- if self.__name:
33
+ if self._name:
35
34
  if type(self.var) == str:
36
- print(f'{pre}[\'{self.var}\'] specified for [{self.__name}] {msg}.')
35
+ print(f'{pre}[\'{self.var}\'] specified for [{self._name}] {msg}.')
37
36
  else:
38
- print(f'{pre}[{self.var}] specified for [{self.__name}] {msg}.')
37
+ print(f'{pre}[{self.var}] specified for [{self._name}] {msg}.')
39
38
 
40
39
  else:
41
40
  if type(self.var) == str:
@@ -43,14 +42,15 @@ class Sanitize:
43
42
  else:
44
43
  print(f'{pre}[{self.var}] {msg}.')
45
44
 
46
- self.__good = False
45
+ self._good = False
47
46
 
48
- def __endbehavior(self):
47
+ def _endbehavior(self):
49
48
  # if exit=True and we've had an error, exit python.
50
- if self.__exit and not self.__good:
51
- sys.exit(1)
49
+ if self._exit and not self._good:
50
+ from sys import exit # Lazy/deferred import.
51
+ exit(1)
52
52
  # if exit=False and we've had an error, return None.
53
- elif not self.__good:
53
+ elif not self._good:
54
54
  return None
55
55
  # If exit=False and we haven't had an error we're good.
56
56
  else:
@@ -74,22 +74,22 @@ class Sanitize:
74
74
 
75
75
  # First of all, if you use this function var should be an int, float, bool.
76
76
  if type(self.var) not in [int, float, bool]:
77
- self.__error(f'not a number (should be in {[int, float, bool]})')
77
+ self._error(f'not a number (should be in {[int, float, bool]})')
78
78
 
79
79
  else:
80
80
  # Second, if Type was user-specified in any way, check for match.
81
81
  if Type is not None and type(self.var) not in Type:
82
- self.__error(f'should be of type {Type} (found {type(self.var)})')
82
+ self._error(f'should be of type {Type} (found {type(self.var)})')
83
83
 
84
84
  # Check range.
85
85
  if len(Range) and (self.var < Range[0] or self.var > Range[1]):
86
- self.__error(f'outside of acceptable interval {Range}')
86
+ self._error(f'outside of acceptable interval {Range}')
87
87
 
88
88
  # Check signed versus unsigned.
89
89
  if signed and self.var < 0:
90
- self.__error('cannot be negative')
90
+ self._error('cannot be negative')
91
91
 
92
- return self.__endbehavior()
92
+ return self._endbehavior()
93
93
 
94
94
  def pka_string(self, Range: list = []):
95
95
  """Sanitize strings that describe pka values for lambda coordinate.
@@ -106,24 +106,24 @@ class Sanitize:
106
106
 
107
107
  # Confirm whether var is a string.
108
108
  if not isinstance(self.var, str):
109
- self.__error(f'should be of type {str}')
109
+ self._error(f'should be of type {str}')
110
110
 
111
111
  # Check if ph in var
112
112
  if 'ph' in self.var:
113
113
  # Do nothing
114
- return self.__endbehavior()
114
+ return self._endbehavior()
115
115
 
116
116
  # Try converting to string
117
117
  try:
118
118
  float(self.var)
119
119
  except ValueError:
120
- self.__error('should be convertible to float or have "ph"')
120
+ self._error('should be convertible to float or have "ph"')
121
121
 
122
122
  # Check range.
123
123
  if Range and (float(self.var) < Range[0] or float(self.var) > Range[1]):
124
- self.__error(f'outside of acceptable interval {Range}')
124
+ self._error(f'outside of acceptable interval {Range}')
125
125
 
126
- return self.__endbehavior()
126
+ return self._endbehavior()
127
127
 
128
128
  def string(self, Range: list = [], upper: bool = False, lower: bool = False, ws: bool = True):
129
129
  """sanitize strings (str).
@@ -139,22 +139,22 @@ class Sanitize:
139
139
  """
140
140
  # Confirm whether var is a string.
141
141
  if type(self.var) != str:
142
- self.__error(f'should be of type {str}')
142
+ self._error(f'should be of type {str}')
143
143
 
144
144
  # Check range.
145
145
  if len(Range) and (len(self.var) < Range[0] or len(self.var) > Range[1]):
146
- self.__error(f'outside of acceptable length {Range}')
146
+ self._error(f'outside of acceptable length {Range}')
147
147
 
148
148
  if upper and not self.var.isupper():
149
- self.__error('should be all uppercase')
149
+ self._error('should be all uppercase')
150
150
 
151
151
  if lower and not self.var.islower():
152
- self.__error('should be all lowercase')
152
+ self._error('should be all lowercase')
153
153
 
154
154
  if (not ws) and (self.var.count(' ') > 0):
155
- self.__error('cannot contain whitespace')
155
+ self._error('cannot contain whitespace')
156
156
 
157
- return self.__endbehavior()
157
+ return self._endbehavior()
158
158
 
159
159
  def path(self, ext: str = '', out: bool = False, abs: bool = False):
160
160
  """Sanitize file paths (str).
@@ -169,28 +169,28 @@ class Sanitize:
169
169
  """
170
170
  # Only strings can represent file paths.
171
171
  if type(self.var) != str:
172
- self.__error(f'should be of type {str}')
173
- return int(not self.__good)
172
+ self._error(f'should be of type {str}')
173
+ return int(not self._good)
174
174
 
175
175
  # File paths cannot be empty strings.
176
176
  if self.var == '':
177
- self.__error('cannot be empty')
177
+ self._error('cannot be empty')
178
178
 
179
179
  # File paths cannot be directories.
180
- elif os.path.isdir(self.var):
181
- self.__error('is a directory')
180
+ elif path.isdir(self.var):
181
+ self._error('is a directory')
182
182
 
183
183
  # (input) file path should correspond to an existing file.
184
- elif not os.path.exists(self.var) and not out:
185
- self.__error('corresponding file does not exist')
184
+ elif not path.exists(self.var) and not out:
185
+ self._error('corresponding file does not exist')
186
186
 
187
187
  # (output) file DIRECTORY should already exist:
188
- if out and not os.path.isdir(os.path.split(os.path.abspath(self.var))[0]):
189
- self.__error('directory for output does not exist')
188
+ if out and not path.isdir(path.split(path.abspath(self.var))[0]):
189
+ self._error('directory for output does not exist')
190
190
 
191
191
  # Check extension.
192
192
  if ext:
193
- tail = os.path.split(self.var)[1]
193
+ tail = path.split(self.var)[1]
194
194
 
195
195
  if type(ext) != list:
196
196
  ext = [ext]
@@ -202,16 +202,16 @@ class Sanitize:
202
202
 
203
203
  # Comment this because file names can contain whitespace in linux.
204
204
  # if tail.count(" ") != 0:
205
- # self.__error("cannot contain whitespace")
205
+ # self._error("cannot contain whitespace")
206
206
 
207
207
  if "." not in tail or (tail.index(".") == 0 and tail.count(".") == 1):
208
- self.__error(f"does not have a file extension (should be {ext})")
208
+ self._error(f"does not have a file extension (should be {ext})")
209
209
 
210
210
  elif "." + tail.split(".")[-1] not in ext:
211
- self.__error(f"should have extension {ext}")
211
+ self._error(f"should have extension {ext}")
212
212
 
213
213
  # Check absolute file path.
214
- if abs and not os.path.isabs(self.var):
215
- self.__error('should be an absolute file path')
214
+ if abs and not path.isabs(self.var):
215
+ self._error('should be an absolute file path')
216
216
 
217
- return self.__endbehavior()
217
+ return self._endbehavior()
@@ -1,11 +1,12 @@
1
- import os
1
+ from os import path
2
+ from typing import List
2
3
  from .user import User
3
4
 
4
5
 
5
6
  class Residue:
6
7
  """Stores the structural (pdb, gro) information for one residue."""
7
8
 
8
- def __init__(self, atoms: list, resname: str, chain: str, resid: int, x: list, y: list, z: list):
9
+ def __init__(self, atoms: List[str], resname: str, chain: str, resid: int, x: List[float], y: List[float], z: List[float]):
9
10
  """Initialize Residue object.
10
11
 
11
12
  Args:
@@ -74,15 +75,15 @@ class Structure:
74
75
  Args:
75
76
  name (str): input structure file name.
76
77
  """
77
- extension = os.path.splitext(name)[1]
78
+ extension = path.splitext(name)[1]
78
79
 
79
80
  if extension == ".pdb":
80
- self.__read_pdb(name)
81
- self.__read_record()
81
+ self._read_pdb(name)
82
+ self._read_record()
82
83
 
83
84
  if extension == ".gro":
84
- self.__read_gro(name)
85
- self.__read_record()
85
+ self._read_gro(name)
86
+ self._read_record()
86
87
 
87
88
  def write(self, name: str):
88
89
  """Write internal data to a structure (.pdb/.gro) file.
@@ -90,17 +91,17 @@ class Structure:
90
91
  Args:
91
92
  name (str): output structure file name.
92
93
  """
93
- extension = os.path.splitext(name)[1]
94
+ extension = path.splitext(name)[1]
94
95
 
95
96
  if extension == ".pdb":
96
- self.__write_pdb(name)
97
- self.__write_record()
97
+ self._write_pdb(name)
98
+ self._write_record()
98
99
 
99
100
  if extension == ".gro":
100
- self.__write_gro(name)
101
- self.__write_record()
101
+ self._write_gro(name)
102
+ self._write_record()
102
103
 
103
- def __read_pdb(self, name: str):
104
+ def _read_pdb(self, name: str):
104
105
  """Load a .pdb file into d_residues.
105
106
 
106
107
  Args:
@@ -169,7 +170,7 @@ class Structure:
169
170
  # Add the list of Residues to universe.
170
171
  self.d_residues = residues
171
172
 
172
- def __write_pdb(self, name: str):
173
+ def _write_pdb(self, name: str):
173
174
  """Write a .pdb file from d_residues.
174
175
 
175
176
  Args:
@@ -200,7 +201,7 @@ class Structure:
200
201
 
201
202
  file.write("TER\nENDMDL\n")
202
203
 
203
- def __read_gro(self, name: str):
204
+ def _read_gro(self, name: str):
204
205
  """Load a .gro file into d_residues.
205
206
 
206
207
  Args:
@@ -258,7 +259,7 @@ class Structure:
258
259
  # Add the list of Residues to universe.
259
260
  self.d_residues = residues
260
261
 
261
- def __write_gro(self, name: str):
262
+ def _write_gro(self, name: str):
262
263
  """Write a .gro file from d_residues.
263
264
 
264
265
  Args:
@@ -296,12 +297,12 @@ class Structure:
296
297
  else:
297
298
  file.write(f"{0.0:>10.5f}{0.0:>10.5f}{0.0:>10.5f}\n")
298
299
 
299
- def __read_record(self):
300
+ def _read_record(self):
300
301
  """Reads the record of initial lambda values (phrecord.dat) if it exists.
301
302
  Will set any inits found in phrecord.dat to the corresponding residue in d_residues.
302
303
  """
303
304
 
304
- if os.path.isfile('phrecord.dat'):
305
+ if path.isfile('phrecord.dat'):
305
306
  self.__user.verbose('Found existing record of initial lambda values (phrecord.dat)...')
306
307
  # Split file by lines.
307
308
  idx = 0
@@ -323,7 +324,7 @@ class Structure:
323
324
  else:
324
325
  self.__user.update("Did not find existing record of initial lambda values (phrecord.dat)...")
325
326
 
326
- def __write_record(self):
327
+ def _write_record(self):
327
328
  """Write a record of initial lambda values to phrecord.dat
328
329
  """
329
330
  self.__user.verbose('Writing initial lambda record to phrecord.dat...')
@@ -1,10 +1,8 @@
1
- import sys
2
-
3
1
  class User:
4
2
  """Provides and formats user updates, warnings, and errors.
5
3
  """
6
4
 
7
- def __init__(self, verbosity: int, logFileName='', maxLineLength=90):
5
+ def __init__(self, verbosity: int, logFileName: str = "", maxLineLength: int = 90):
8
6
  """Initialize User object.
9
7
 
10
8
  Args:
@@ -29,7 +27,7 @@ class User:
29
27
 
30
28
  print(message)
31
29
 
32
- def base(self, message: str, preMessage: str = ''):
30
+ def base(self, message: str, preMessage: str = ""):
33
31
  """Base method for handeling user messages.
34
32
 
35
33
  Args:
@@ -109,7 +107,8 @@ class User:
109
107
  self.base(message, preMessage='ERROR - ')
110
108
  self.doPrint('phbuilder : ')
111
109
 
112
- sys.exit()
110
+ from sys import exit # Lazy/deferred import.
111
+ exit(1)
113
112
 
114
113
  def inputOptionHandler(self, message: str, options: list) -> int:
115
114
  """Handles user input.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: phbuilder
3
- Version: 1.2.5
3
+ Version: 1.3
4
4
  Summary: System builder for constant-pH simulations in GROMACS.
5
5
  Home-page: https://gitlab.com/gromacs-constantph/phbuilder
6
6
  Author: Anton Jansen
@@ -136,6 +136,13 @@ If you don't want to manually set initial lambda values, you can use the `-ph <p
136
136
  phbuilder gentopol -f input.pdb -ph <ph>
137
137
  ```
138
138
 
139
+ Furthermore, if you only want certain residue types to be made titratable, you can use the `-groups` flag. For example:
140
+
141
+ ```
142
+ phbuilder gentopol -f input.pdb -groups "ASPT GLUT"
143
+ ```
144
+
145
+ only considers aspartate and glutamate residues for setting up the CpHMD simulation.
139
146
  ### 4. Add a periodic box and solvent (if not already present).
140
147
 
141
148
  Periodic box (see [gmx editconf](https://manual.gromacs.org/documentation/current/onlinehelp/gmx-editconf.html)):
@@ -399,15 +406,15 @@ will position restrain only atom 19. Position restraining during the parameteriz
399
406
 
400
407
  ### 5. Perform solvation and neutralization to obtain a net-neutral simulation system.
401
408
 
402
- * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 2 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 2.0` flags.
403
- * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of 5 nm cubed for the paramterization and replica simulations.
409
+ * When performing the neutralization step, we want to add only one buffer particle, and we want the buffer to be at least 1.5 nm away from the tripeptide. We therefore set the `-nbufs 1` and `-rmin 1.5` flags.
410
+ * To prevent finite-size effects for small simulation boxes, we recommend using a simulation box of at least 5 nm cubed for the paramterization and replica simulations.
404
411
  * The effects of ionic strength on the parameterization should be limited, but we nonetheless recommend adding at least a few ions to the parameterization system and replicates, e.g. by setting `-conc 0.15` (physiological NaCl concentration).
405
412
  * For more information on the effects of box size and ionic strength on the parameterization, please refer to the [best practices paper](https://pubs.acs.org/doi/full/10.1021/acs.jctc.2c00517).
406
413
 
407
414
  ```
408
- gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 1.8
415
+ gmx editconf -f phprocessed.pdb -o box.pdb -bt cubic -d 2.0
409
416
  gmx solvate -cp box.pdb -p topol.top -o solvated.pdb
410
- phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 2.0 -conc 0.15
417
+ phbuilder neutralize -f solvated.pdb -nbufs 1 -rmin 1.5 -conc 0.15
411
418
  ```
412
419
 
413
420
  ### 6. Use `genparams` to generate the `.mdp` files in calibration mode.
@@ -557,11 +564,12 @@ Allows you to select which residues to make titratable and which initial lambda
557
564
 
558
565
  OPTIONS
559
566
 
560
- | Flag__ | Description |
567
+ | Flag____ | Description |
561
568
  |--------------|----------------|
562
569
  | `-f` | [\<.pdb/.gro>] (required) <br /> Specify input structure file. |
563
570
  | `-o` | [\<.pdb/.gro>] (phprocessed.pdb) <br /> Specify output structure file. |
564
571
  | `-ph` | [\<float>] <br /> Specify intended simulation pH. Will be used together with the reference pKas of the titratable sites to auto set the initial lambdas. |
572
+ | `-groups` | [\<str>] <br /> Specify which titratable residue types to consider. Example: "ASPT GLUT" will only consider Asp and Glu residues for CpHMD. |
565
573
  | `-v` | (no) <br /> Be more verbose. |
566
574
 
567
575
  # Synopsis `phbuilder neutralize`
@@ -35,9 +35,18 @@ setup.cfg
35
35
  ./phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip3p.itp
36
36
  ./phbuilder/ffield/charmm36-mar2019-cphmd.ff/tip4p.itp
37
37
  ./phbuilder/ffield/charmm36-mar2019-cphmd.ff/watermodels.dat
38
+ ./tests/__init__.py
39
+ ./tests/test_genparams.py
40
+ ./tests/test_gentopol.py
41
+ ./tests/test_neutralize.py
42
+ ./tests/testutils.py
38
43
  phbuilder.egg-info/PKG-INFO
39
44
  phbuilder.egg-info/SOURCES.txt
40
45
  phbuilder.egg-info/dependency_links.txt
41
46
  phbuilder.egg-info/entry_points.txt
42
47
  phbuilder.egg-info/requires.txt
43
- phbuilder.egg-info/top_level.txt
48
+ phbuilder.egg-info/top_level.txt
49
+ tests/test_genparams.py
50
+ tests/test_gentopol.py
51
+ tests/test_neutralize.py
52
+ tests/testutils.py
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = phbuilder
3
- version = 1.2.5
3
+ version = 1.3
4
4
  author = Anton Jansen
5
5
  author_email = anton.jansen@scilifelab.se
6
6
  description = System builder for constant-pH simulations in GROMACS.
File without changes
@@ -0,0 +1,46 @@
1
+ from os import mkdir
2
+ from shutil import rmtree
3
+ from subprocess import run
4
+ from .testutils import cmd, reqTestFiles
5
+
6
+
7
+ def test_gentopol():
8
+ mkdir("_tmp")
9
+ reqTestFiles("phneutral.pdb phrecord.dat")
10
+
11
+ result = run(
12
+ cmd("phbuilder genparams -f phneutral.pdb -ph 4.0"), shell=True, cwd="_tmp"
13
+ )
14
+
15
+ if result.returncode == 0: # Cleanup if everything was fine.
16
+ rmtree("_tmp")
17
+
18
+ assert result.returncode == 0
19
+
20
+
21
+ def test_gentopol_verbose():
22
+ mkdir("_tmp")
23
+ reqTestFiles("phneutral.pdb phrecord.dat")
24
+
25
+ result = run(
26
+ cmd("phbuilder genparams -f phneutral.pdb -ph 4.0 -v"), shell=True, cwd="_tmp"
27
+ )
28
+
29
+ if result.returncode == 0: # Cleanup if everything was fine.
30
+ rmtree("_tmp")
31
+
32
+ assert result.returncode == 0
33
+
34
+
35
+ def test_gentopol_cal():
36
+ mkdir("_tmp")
37
+ reqTestFiles("phneutral.pdb phrecord.dat")
38
+
39
+ result = run(
40
+ cmd("phbuilder genparams -f phneutral.pdb -ph 4.0 -cal"), shell=True, cwd="_tmp"
41
+ )
42
+
43
+ if result.returncode == 0: # Cleanup if everything was fine.
44
+ rmtree("_tmp")
45
+
46
+ assert result.returncode == 0
@@ -0,0 +1,32 @@
1
+ from os import mkdir
2
+ from shutil import rmtree
3
+ from subprocess import run
4
+ from .testutils import cmd, reqTestFiles
5
+
6
+
7
+ def test_gentopol_pdb():
8
+ mkdir("_tmp")
9
+ reqTestFiles("1cvo.pdb")
10
+
11
+ result = run(
12
+ cmd("phbuilder gentopol -f 1cvo.pdb -ph 4.0", input=[1]), shell=True, cwd="_tmp"
13
+ )
14
+
15
+ if result.returncode == 0: # Cleanup if everything was fine.
16
+ rmtree("_tmp")
17
+
18
+ assert result.returncode == 0
19
+
20
+
21
+ def test_gentopol_gro():
22
+ mkdir("_tmp")
23
+ reqTestFiles("1cvo.gro")
24
+
25
+ result = run(
26
+ cmd("phbuilder gentopol -f 1cvo.gro -ph 4.0", input=[1]), shell=True, cwd="_tmp"
27
+ )
28
+
29
+ if result.returncode == 0: # Cleanup if everything was fine.
30
+ rmtree("_tmp")
31
+
32
+ assert result.returncode == 0
@@ -0,0 +1,18 @@
1
+ from os import mkdir
2
+ from shutil import rmtree
3
+ from subprocess import run
4
+ from .testutils import cmd, reqTestFiles
5
+
6
+
7
+ def test_neutralize():
8
+ mkdir("_tmp")
9
+ reqTestFiles("1cvo.pdb phrecord.dat solvated.pdb topol.top", ff=True)
10
+
11
+ result = run(
12
+ cmd("phbuilder neutralize -f solvated.pdb -conc 0.15"), shell=True, cwd="_tmp"
13
+ )
14
+
15
+ if result.returncode == 0: # Cleanup if everything was fine.
16
+ rmtree("_tmp")
17
+
18
+ assert result.returncode == 0
@@ -0,0 +1,47 @@
1
+ from typing import List
2
+ from shutil import copy, copytree
3
+
4
+
5
+ def cmd(command: str, input: List[str] = []) -> List[str]:
6
+ """Pre-process command line input for subprocess.run().
7
+
8
+ Args:
9
+ command (str): command line input.
10
+ input (List[str], optional): values to use when prompted for input. Defaults to [].
11
+
12
+ Returns:
13
+ List[str]: List of arguments for subprocess.
14
+ """
15
+
16
+ if input:
17
+ xstr = " << EOF\n"
18
+ for val in input:
19
+ xstr += "{}\n".format(val)
20
+ command += xstr + "EOF"
21
+
22
+ return command
23
+
24
+
25
+ def reqTestFiles(
26
+ fileNames: str, ff: bool = False, source: str = "test_files", target: str = "_tmp"
27
+ ) -> None:
28
+ """Copy test files from source to target directory.
29
+
30
+ Args:
31
+ fileNames (str): names of the files to copy.
32
+ ff (bool, optional): get the force field (from phbuilder/ffield). Defaults to False.
33
+ source (str, optional): source directory. Defaults to "test_files".
34
+ target (str, optional): target directory. Defaults to "_tmp".
35
+ """
36
+
37
+ for fileName in fileNames.split():
38
+ try:
39
+ copy(f"{source}/{fileName}", target)
40
+ except IsADirectoryError:
41
+ copytree(f"{source}/{fileName}", f"{target}/{fileName}")
42
+
43
+ # If required we copy the force field from phbuilder/ffield, as this is the
44
+ # version that is actually shipped with phbuilder. We want to avoid having a
45
+ # separate copy of the ffield in test_files.
46
+ if ff:
47
+ copytree("../phbuilder/ffield/charmm36-mar2019-cphmd.ff", f"{target}/charmm36-mar2019-cphmd.ff")
File without changes
File without changes
File without changes