-
Notifications
You must be signed in to change notification settings - Fork 19
/
_gromacs.py
2568 lines (1946 loc) · 96.8 KB
/
_gromacs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
######################################################################
# BioSimSpace: Making biomolecular simulation a breeze!
#
# Copyright: 2017-2022
#
# Authors: Lester Hedges <lester.hedges@gmail.com>
#
# BioSimSpace is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BioSimSpace. If not, see <http://www.gnu.org/licenses/>.
#####################################################################
"""
Functionality for running simulations with GROMACS.
"""
__author__ = "Lester Hedges"
__email__ = "lester.hedges@gmail.com"
__all__ = ["Gromacs"]
from .._Utils import _try_import
import math as _math
import os as _os
_pygtail = _try_import("pygtail")
import shutil as _shutil
import shlex as _shlex
import subprocess as _subprocess
import timeit as _timeit
import warnings as _warnings
from sire.legacy import Base as _SireBase
from sire.legacy import IO as _SireIO
from sire.legacy import Maths as _SireMaths
from sire.legacy import Vol as _SireVol
from sire import units as _SireUnits
from .. import _gmx_exe
from .. import _isVerbose
from .._Exceptions import MissingSoftwareError as _MissingSoftwareError
from .._SireWrappers import System as _System
from ..Types._type import Type as _Type
from .. import IO as _IO
from .. import Protocol as _Protocol
from .. import Trajectory as _Trajectory
from .. import Types as _Types
from .. import Units as _Units
from .. import _Utils
from . import _process
from ._plumed import Plumed as _Plumed
class Gromacs(_process.Process):
"""A class for running simulations using GROMACS."""
def __init__(self, system, protocol, exe=None, name="gromacs",
work_dir=None, seed=None, extra_options=None,
extra_lines=None, property_map={}, ignore_warnings=False,
show_errors=True, checkpoint_file=None):
"""Constructor.
Parameters
----------
system : :class:`System <BioSimSpace._SireWrappers.System>`
The molecular system.
protocol : :class:`Protocol <BioSimSpace.Protocol>`
The protocol for the GROMACS process.
exe : str
The full path to the GROMACS executable.
name : str
The name of the process.
work_dir :
The working directory for the process.
seed : int
A random number seed.
extra_options : dict
A dictionary containing extra options. Overrides the ones generated from the protocol.
extra_lines : list
A list of extra lines to be put at the end of the script.
property_map : dict
A dictionary that maps system "properties" to their user defined
values. This allows the user to refer to properties with their
own naming scheme, e.g. { "charge" : "my-charge" }
ignore_warnings : bool
Whether to ignore warnings when generating the binary run file
with 'gmx grompp'. By default, these warnings are elevated to
errors and will halt the program.
show_errors : bool
Whether to show warning/error messages when generating the binary
run file.
checkpoint_file : str
The path to a checkpoint file from a previous run. This can be used
to continue an existing simulation. Currently we only support the
use of checkpoint files for Equilibration protocols.
"""
# Call the base class constructor.
super().__init__(system, protocol, name, work_dir, seed, extra_options, extra_lines, property_map)
# Set the package name.
self._package_name = "GROMACS"
# This process can generate trajectory data.
self._has_trajectory = True
# Use GROMACS executable from environment.
if exe is None:
if _gmx_exe is not None:
self._exe = _gmx_exe
else:
raise _MissingSoftwareError("'BioSimSpace.Process.Gromacs' is not supported. "
"Please install GROMACS (http://www.gromacs.org).")
# Use user-specified executable.
else:
# Make sure executable exists.
if _os.path.isfile(exe):
self._exe = exe
else:
raise IOError("GROMACS executable doesn't exist: '%s'" % exe)
if not isinstance(ignore_warnings, bool):
raise ValueError("'ignore_warnings' must be of type 'bool'.")
self._ignore_warnings = ignore_warnings
if not isinstance(show_errors, bool):
raise ValueError("'show_errors' must be of type 'bool'.")
self._show_errors = show_errors
# Initialise the stdout dictionary and title header.
self._stdout_dict = _process._MultiDict()
# Store the name of the GROMACS log file.
self._log_file = "%s/%s.log" % (self._work_dir, name)
# The names of the input files.
self._gro_file = "%s/%s.gro" % (self._work_dir, name)
self._top_file = "%s/%s.top" % (self._work_dir, name)
# The name of the trajectory file.
self._traj_file = "%s/%s.trr" % (self._work_dir, name)
# Set the path for the GROMACS configuration file.
self._config_file = "%s/%s.mdp" % (self._work_dir, name)
# Create the list of input files.
self._input_files = [self._config_file, self._gro_file, self._top_file]
# Initialise the PLUMED interface object.
self._plumed = None
# Set the path of Gromacs checkpoint file.
self._checkpoint_file = None
if checkpoint_file is not None:
if not isinstance(checkpoint_file, str):
raise ValueError("'checkpoint_file' must be of type 'str'.")
else:
if _os.path.isfile(checkpoint_file):
self._checkpoint_file = checkpoint_file
else:
raise IOError("GROMACS checkpoint file doesn't exist: '%s'" % checkpoint_file)
# Now set up the working directory for the process.
self._setup()
def _setup(self):
"""Setup the input files and working directory ready for simulation."""
# Create the input files...
# Create a copy of the system.
system = self._system.copy()
if isinstance(self._protocol, _Protocol._FreeEnergyMixin):
# Check that the system contains a perturbable molecule.
if self._system.nPerturbableMolecules() == 0:
raise ValueError("'BioSimSpace.Protocol.FreeEnergy' requires a "
"perturbable molecule!")
# Check that the perturbation type is supported..
if self._protocol.getPerturbationType() != "full":
msg = ("'BioSimSpace.Process.Gromacs' currently only supports the 'full' "
"perturbation type. Please use 'BioSimSpace.Process.Somd' "
"for multistep perturbation types.")
raise NotImplementedError(msg)
else:
# Check for perturbable molecules and convert to the chosen end state.
system = self._checkPerturbable(system)
# Convert the water model topology so that it matches the GROMACS naming convention.
system._set_water_topology("GROMACS")
# GRO87 file.
gro = _SireIO.Gro87(system._sire_object, self._property_map)
gro.writeToFile(self._gro_file)
# TOP file.
top = _SireIO.GroTop(system._sire_object, self._property_map)
top.writeToFile(self._top_file)
# Create the binary input file name.
self._tpr_file = "%s/%s.tpr" % (self._work_dir, self._name)
self._input_files.append(self._tpr_file)
# Generate the GROMACS configuration file.
# Skip if the user has passed a custom config.
if isinstance(self._protocol, _Protocol.Custom):
self.setConfig(self._protocol.getConfig())
else:
self._generate_config()
self.writeConfig(self._config_file)
# Generate the dictionary of command-line arguments.
self._generate_args()
# Return the list of input files.
return self._input_files
def _generate_config(self):
"""Generate GROMACS configuration file strings."""
# Clear the existing configuration list.
self._config = []
# Check whether the system contains periodic box information.
# For now, well not attempt to generate a box if the system property
# is missing. If no box is present, we'll assume a non-periodic simulation.
if "space" in self._system._sire_object.propertyKeys():
has_box = True
else:
_warnings.warn("No simulation box found. Assuming gas phase simulation.")
has_box = False
# The list of configuration strings.
# We don't repeatedly call addToConfig since this will run grommp
# to re-compile the binary run input file each time.
config = []
# Deal with PBC.
if not has_box or not self._has_water:
# Create a copy of the system.
system = self._system.copy()
# Create a 999.9 nm periodic box and apply to the system.
space = _SireVol.PeriodicBox(_SireMaths.Vector(9999, 9999, 9999))
system._sire_object.setProperty(self._property_map.get("space", "space"), space)
# Re-write the GRO file.
gro = _SireIO.Gro87(system._sire_object, self._property_map)
gro.writeToFile(self._gro_file)
config_options = {}
if not isinstance(self._protocol, _Protocol.Minimisation):
# Set the random number seed.
if self._is_seeded:
seed = self._seed
else:
seed = -1
config_options["ld-seed"] = seed
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
if not (has_box and self._has_water):
# Create a copy of the system.
system = self._system.copy()
# Convert the water model topology so that it matches the GROMACS naming convention.
system._set_water_topology("GROMACS")
# Create a 999.9 nm periodic box and apply to the system.
space = _SireVol.PeriodicBox(_SireMaths.Vector(9999, 9999, 9999))
system._sire_object.setProperty(self._property_map.get("space", "space"), space)
# Re-write the GRO file.
gro = _SireIO.Gro87(system._sire_object, self._property_map)
gro.writeToFile(self._gro_file)
if isinstance(self._protocol, _Protocol.Equilibration):
# Add any position restraints.
self._add_position_restraints(config)
# Add configuration variables for a metadynamics simulation.
if isinstance(self._protocol, _Protocol.Metadynamics):
# Convert the timestep to picoseconds.
timestep = self._protocol.getTimeStep().picoseconds().value()
config.append("integrator = sd") # Leap-frog stochastic dynamics.
config.append("ld-seed = %d" % seed) # Random number seed.
config.append("dt = %.3f" % timestep) # Integration time step.
config.append("nsteps = %d" % steps) # Number of integration steps.
config.append("nstlog = %d" % report_interval) # Interval between writing to the log file.
config.append("nstenergy = %d" % report_interval) # Interval between writing to the energy file.
config.append("nstxout = %d" % restart_interval) # Interval between writing to the trajectory file.
if self._checkpoint_file is not None:
config.append("continuation=yes")
if has_box and self._has_water:
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("ns-type = grid") # Use a grid to search for neighbours.
config.append("rlist = 1.2") # Set short-range cutoff.
config.append("rvdw = 1.2") # Set van der Waals cutoff.
config.append("rcoulomb = 1.2") # Set Coulomb cutoff.
config.append("coulombtype = PME") # Fast smooth Particle-Mesh Ewald.
config.append("DispCorr = EnerPres") # Dispersion corrections for energy and pressure.
else:
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("nstlist = 1") # Single neighbour list (all particles interact).
config.append("rlist = 333.3") # "Infinite" short-range cutoff.
config.append("rvdw = 333.3") # "Infinite" van der Waals cutoff.
config.append("rcoulomb = 333.3") # "Infinite" Coulomb cutoff.
config.append("coulombtype = Cut-off") # Plain cut-off.
config.append("vdwtype = Cut-off") # Twin-range van der Waals cut-off.
config.append("constraints = h-bonds") # Rigid water molecules.
config.append("constraint-algorithm = LINCS") # Linear constraint solver.
# Temperature control.
# No need for "berendsen" with integrator "sd".
config.append("tc-grps = system") # A single temperature group for the entire system.
config.append("tau-t = 2.0") # 2ps time constant for temperature coupling.
# Set the reference temperature.
config.append("ref-t = %.2f" % self._protocol.getEndTemperature().kelvin().value())
# Heating/cooling protocol.
if not self._protocol.isConstantTemp():
# Work out the final time of the simulation.
end_time = _math.floor(timestep*steps)
config.append("annealing = single") # Single sequence of annealing points.
config.append("annealing-npoints = 2") # Two annealing points for "system" temperature group.
# Linearly change temperature between start and end times.
config.append("annealing-time = 0 %d" % end_time)
config.append("annealing-temp = %.2f %.2f"
% (self._protocol.getStartTemperature().kelvin().value(),
self._protocol.getEndTemperature().kelvin().value()))
# Pressure control.
if self._protocol.getPressure() is not None and has_box and self._has_water:
config.append("pcoupl = berendsen") # Berendsen barostat.
config.append("tau-p = 1.0") # 1ps time constant for pressure coupling.
config.append("ref-p = %.5f" # Pressure in bar.
% self._protocol.getPressure().bar().value())
config.append("compressibility = 4.5e-5") # Compressibility of water.
# Add any position restraints.
self._add_position_restraints(config)
# Add configuration variables for a production simulation.
elif isinstance(self._protocol, _Protocol.Production):
# Work out the number of integration steps.
steps = _math.ceil(self._protocol.getRunTime() / self._protocol.getTimeStep())
# Get the report and restart intervals.
report_interval = self._protocol.getReportInterval()
restart_interval = self._protocol.getRestartInterval()
# Cap the intervals at the total number of steps.
if report_interval > steps:
report_interval = steps
if restart_interval > steps:
restart_interval = steps
# Set the random number seed.
if self._is_seeded:
seed = self._seed
else:
seed = -1
# Convert the timestep to picoseconds.
timestep = self._protocol.getTimeStep().picoseconds().value()
config.append("integrator = sd") # Leap-frog stochastic dynamics.
config.append("ld-seed = %d" % seed) # Random number seed.
config.append("dt = %.3f" % timestep) # Integration time step.
config.append("nsteps = %d" % steps) # Number of integration steps.
config.append("init-step = %d"
% self._protocol.getFirstStep()) # First time step.
config.append("nstlog = %d" % report_interval) # Interval between writing to the log file.
config.append("nstenergy = %d" % report_interval) # Interval between writing to the energy file.
config.append("nstxout = %d" % restart_interval) # Interval between writing to the trajectory file.
if has_box and self._has_water:
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("ns-type = grid") # Use a grid to search for neighbours.
config.append("nstlist = 10") # Rebuild neighbour list every 10 steps.
config.append("rlist = 1.2") # Set short-range cutoff.
config.append("rvdw = 1.2") # Set van der Waals cutoff.
config.append("rcoulomb = 1.2") # Set Coulomb cutoff.
config.append("coulombtype = PME") # Fast smooth Particle-Mesh Ewald.
config.append("DispCorr = EnerPres") # Dispersion corrections for energy and pressure.
else:
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("nstlist = 1") # Single neighbour list (all particles interact).
config.append("rlist = 333.3") # "Infinite" short-range cutoff.
config.append("rvdw = 333.3") # "Infinite" van der Waals cutoff.
config.append("rcoulomb = 333.3") # "Infinite" Coulomb cutoff.
config.append("coulombtype = Cut-off") # Plain cut-off.
config.append("vdwtype = Cut-off") # Twin-range van der Waals cut-off.
config.append("constraints = h-bonds") # Rigid water molecules.
config.append("constraint-algorithm = LINCS") # Linear constraint solver.
# Temperature control.
# No need for "berendsen" with integrator "sd".
config.append("tc-grps = system") # A single temperature group for the entire system.
config.append("tau-t = 2.0") # 2ps time constant for temperature coupling.
# Set the reference temperature.
config.append("ref-t = %.2f" % self._protocol.getTemperature().kelvin().value())
# Pressure control.
if self._protocol.getPressure() is not None and has_box and self._has_water:
config.append("pcoupl = berendsen") # Berendsen barostat.
config.append("tau-p = 1.0") # 1ps time constant for pressure coupling.
config.append("ref-p = %.5f" # Pressure in bar.
% self._protocol.getPressure().bar().value())
config.append("compressibility = 4.5e-5") # Compressibility of water.
elif isinstance(self._protocol, _Protocol.FreeEnergy):
# Work out the number of integration steps.
steps = _math.ceil(self._protocol.getRunTime() / self._protocol.getTimeStep())
# Get the report and restart intervals.
report_interval = self._protocol.getReportInterval()
restart_interval = self._protocol.getRestartInterval()
# Cap the intervals at the total number of steps.
if report_interval > steps:
report_interval = steps
if restart_interval > steps:
restart_interval = steps
# Set the random number seed.
if self._is_seeded:
seed = self._seed
else:
seed = -1
# Convert the timestep to picoseconds.
timestep = self._protocol.getTimeStep().picoseconds().value()
config.append("integrator = sd") # Leap-frog stochastic dynamics.
config.append("ld-seed = %d" % seed) # Random number seed.
config.append("dt = %.3f" % timestep) # Integration time step.
config.append("nsteps = %d" % steps) # Number of integration steps.
config.append("nstlog = %d" % report_interval) # Interval between writing to the log file.
config.append("nstenergy = %d" % report_interval) # Interval between writing to the energy file.
config.append("nstxout = %d" % restart_interval) # Interval between writing to the trajectory file.
if has_box and self._has_water:
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("ns-type = grid") # Use a grid to search for neighbours.
config.append("nstlist = 10") # Rebuild neighbour list every 10 steps.
config.append("rlist = 1.2") # Set short-range cutoff.
config.append("rvdw = 1.2") # Set van der Waals cutoff.
config.append("rcoulomb = 1.2") # Set Coulomb cutoff.
config.append("coulombtype = PME") # Fast smooth Particle-Mesh Ewald.
config.append("DispCorr = EnerPres") # Dispersion corrections for energy and pressure.
else:
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("nstlist = 1") # Single neighbour list (all particles interact).
config.append("rlist = 333.3") # "Infinite" short-range cutoff.
config.append("rvdw = 333.3") # "Infinite" van der Waals cutoff.
config.append("rcoulomb = 333.3") # "Infinite" Coulomb cutoff.
config.append("coulombtype = Cut-off") # Plain cut-off.
config.append("vdwtype = Cut-off") # Twin-range van der Waals cut-off.
config.append("constraints = h-bonds") # Rigid water molecules.
config.append("constraint-algorithm = LINCS") # Linear constraint solver.
# Temperature control.
# No need for "berendsen" with integrator "sd".
config.append("tc-grps = system") # A single temperature group for the entire system.
config.append("tau-t = 2.0") # 2ps time constant for temperature coupling.
# Set the reference temperature.
config.append("ref-t = %.2f" % self._protocol.getTemperature().kelvin().value())
# Pressure control.
if self._protocol.getPressure() is not None and has_box and self._has_water:
config.append("pcoupl = berendsen") # Berendsen barostat.
config.append("tau-p = 1.0") # 1ps time constant for pressure coupling.
config.append("ref-p = %.5f" # Pressure in bar.
% self._protocol.getPressure().bar().value())
config.append("compressibility = 4.5e-5") # Compressibility of water.
# Extract the lambda array.
lam_vals = self._protocol.getLambdaValues()
# Determine the index of the lambda value.
idx = self._protocol.getLambdaIndex()
# Free energy parameters.
config.append("free-energy = yes") # Free energy simulation.
config.append("init-lambda-state = %d" % idx) # Index of the lambda value.
config.append("fep-lambdas = %s" \
% " ".join([str(x) for x in lam_vals]))
config.append("couple-lambda0 = vdw-q") # All interactions on at lambda = 0
config.append("couple-lambda1 = vdw-q") # All interactions on at lambda = 1
config.append("calc-lambda-neighbors = -1") # Write all lambda values.
config.append("nstcalcenergy = 250") # Calculate energies every 250 steps.
config.append("nstdhdl = 250") # Write gradients every 250 steps.
# Add configuration variables for a metadynamics simulation.
elif isinstance(self._protocol, _Protocol.Metadynamics):
# Work out the number of integration steps.
steps = _math.ceil(self._protocol.getRunTime() / self._protocol.getTimeStep())
# Get the report and restart intervals.
report_interval = self._protocol.getReportInterval()
restart_interval = self._protocol.getRestartInterval()
# Cap the intervals at the total number of steps.
if report_interval > steps:
report_interval = steps
if restart_interval > steps:
restart_interval = steps
# Set the random number seed.
if self._is_seeded:
seed = self._seed
else:
seed = -1
# Convert the timestep to picoseconds.
timestep = self._protocol.getTimeStep().picoseconds().value()
config.append("integrator = sd") # Leap-frog stochastic dynamics.
config.append("ld-seed = %d" % seed) # Random number seed.
config.append("dt = %.3f" % timestep) # Integration time step.
config.append("nsteps = %d" % steps) # Number of integration steps.
config.append("nstlog = %d" % report_interval) # Interval between writing to the log file.
config.append("nstenergy = %d" % report_interval) # Interval between writing to the energy file.
config.append("nstxout = %d" % restart_interval) # Interval between writing to the trajectory file.
if has_box and self._has_water:
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("ns-type = grid") # Use a grid to search for neighbours.
config.append("nstlist = 10") # Rebuild neighbour list every 10 steps.
config.append("rlist = 1.2") # Set short-range cutoff.
config.append("rvdw = 1.2") # Set van der Waals cutoff.
config.append("rcoulomb = 1.2") # Set Coulomb cutoff.
config.append("coulombtype = PME") # Fast smooth Particle-Mesh Ewald.
config.append("DispCorr = EnerPres") # Dispersion corrections for energy and pressure.
else:
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("nstlist = 1") # Single neighbour list (all particles interact).
config.append("rlist = 333.3") # "Infinite" short-range cutoff.
config.append("rvdw = 333.3") # "Infinite" van der Waals cutoff.
config.append("rcoulomb = 333.3") # "Infinite" Coulomb cutoff.
config.append("coulombtype = Cut-off") # Plain cut-off.
config.append("vdwtype = Cut-off") # Twin-range van der Waals cut-off.
config.append("constraints = h-bonds") # Rigid water molecules.
config.append("constraint-algorithm = LINCS") # Linear constraint solver.
# Temperature control.
# No need for "berendsen" with integrator "sd".
config.append("tc-grps = system") # A single temperature group for the entire system.
config.append("tau-t = 2.0") # 2ps time constant for temperature coupling.
# Set the reference temperature.
config.append("ref-t = %.2f" % self._protocol.getTemperature().kelvin().value())
# Pressure control.
if self._protocol.getPressure() is not None and has_box and self._has_water:
config.append("pcoupl = berendsen") # Berendsen barostat.
config.append("tau-p = 1.0") # 1ps time constant for pressure coupling.
config.append("ref-p = %.5f" # Pressure in bar.
% self._protocol.getPressure().bar().value())
config.append("compressibility = 4.5e-5") # Compressibility of water.
# Create the PLUMED input file and copy auxiliary files to the working directory.
self._plumed = _Plumed(self._work_dir)
plumed_config, auxiliary_files = self._plumed.createConfig(self._system,
self._protocol,
self._property_map)
self._setPlumedConfig(plumed_config)
if auxiliary_files is not None:
for file in auxiliary_files:
file_name = _os.path.basename(file)
_shutil.copyfile(file, self._work_dir + f"/{file_name}")
self._input_files.append(self._plumed_config_file)
# Expose the PLUMED specific member functions.
setattr(self, "getPlumedConfig", self._getPlumedConfig)
setattr(self, "getPlumedConfigFile", self._getPlumedConfigFile)
setattr(self, "setPlumedConfig", self._setPlumedConfig)
setattr(self, "getFreeEnergy", self._getFreeEnergy)
setattr(self, "getCollectiveVariable", self._getCollectiveVariable)
setattr(self, "sampleConfigurations", self._sampleConfigurations)
setattr(self, "getTime", self._getTime)
# Add configuration variables for a steered molecular dynamics protocol.
elif isinstance(self._protocol, _Protocol.Steering):
# Work out the number of integration steps.
steps = _math.ceil(self._protocol.getRunTime() / self._protocol.getTimeStep())
# Get the report and restart intervals.
report_interval = self._protocol.getReportInterval()
restart_interval = self._protocol.getRestartInterval()
# Cap the intervals at the total number of steps.
if report_interval > steps:
report_interval = steps
if restart_interval > steps:
restart_interval = steps
# Set the random number seed.
if self._is_seeded:
seed = self._seed
else:
seed = -1
# Convert the timestep to picoseconds.
timestep = self._protocol.getTimeStep().picoseconds().value()
config.append("integrator = sd") # Leap-frog stochastic dynamics.
config.append("ld-seed = %d" % seed) # Random number seed.
config.append("dt = %.3f" % timestep) # Integration time step.
config.append("nsteps = %d" % steps) # Number of integration steps.
config.append("nstlog = %d" % report_interval) # Interval between writing to the log file.
config.append("nstenergy = %d" % report_interval) # Interval between writing to the energy file.
config.append("nstxout = %d" % restart_interval) # Interval between writing to the trajectory file.
if has_box and self._has_water:
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("ns-type = grid") # Use a grid to search for neighbours.
config.append("nstlist = 10") # Rebuild neighbour list every 10 steps.
config.append("rlist = 1.2") # Set short-range cutoff.
config.append("rvdw = 1.2") # Set van der Waals cutoff.
config.append("rcoulomb = 1.2") # Set Coulomb cutoff.
config.append("coulombtype = PME") # Fast smooth Particle-Mesh Ewald.
config.append("DispCorr = EnerPres") # Dispersion corrections for energy and pressure.
else:
# Perform vacuum simulations by implementing pseudo-PBC conditions,
# i.e. run calculation in a near-infinite box (333.3 nm).
# c.f.: https://pubmed.ncbi.nlm.nih.gov/29678588
config.append("pbc = xyz") # Simulate a fully periodic box.
config.append("cutoff-scheme = Verlet") # Use Verlet pair lists.
config.append("nstlist = 1") # Single neighbour list (all particles interact).
config.append("rlist = 333.3") # "Infinite" short-range cutoff.
config.append("rvdw = 333.3") # "Infinite" van der Waals cutoff.
config.append("rcoulomb = 333.3") # "Infinite" Coulomb cutoff.
config.append("coulombtype = Cut-off") # Plain cut-off.
config.append("vdwtype = Cut-off") # Twin-range van der Waals cut-off.
config.append("constraints = h-bonds") # Rigid water molecules.
config.append("constraint-algorithm = LINCS") # Linear constraint solver.
# Temperature control.
# No need for "berendsen" with integrator "sd".
config.append("tc-grps = system") # A single temperature group for the entire system.
config.append("tau-t = 2.0") # 2ps time constant for temperature coupling.
# Set the reference temperature.
config.append("ref-t = %.2f" % self._protocol.getTemperature().kelvin().value())
# Pressure control.
if self._protocol.getPressure() is not None and has_box and self._has_water:
config.append("pcoupl = berendsen") # Berendsen barostat.
config.append("tau-p = 1.0") # 1ps time constant for pressure coupling.
config.append("ref-p = %.5f" # Pressure in bar.
% self._protocol.getPressure().bar().value())
config.append("compressibility = 4.5e-5") # Compressibility of water.
# Create the PLUMED input file and copy auxiliary files to the working directory.
self._plumed = _Plumed(self._work_dir)
plumed_config, auxiliary_files = self._plumed.createConfig(self._system,
self._protocol,
self._property_map)
self._setPlumedConfig(plumed_config)
if auxiliary_files is not None:
for file in auxiliary_files:
file_name = _os.path.basename(file)
_shutil.copyfile(file, self._work_dir + f"/{file_name}")
self._input_files.append(self._plumed_config_file)
# Expose the PLUMED specific member functions.
setattr(self, "getPlumedConfig", self._getPlumedConfig)
setattr(self, "getPlumedConfigFile", self._getPlumedConfigFile)
setattr(self, "setPlumedConfig", self._setPlumedConfig)
setattr(self, "getCollectiveVariable", self._getCollectiveVariable)
setattr(self, "getTime", self._getTime)
# Set the configuration.
config = _Protocol.ConfigFactory(self._system, self._protocol)
self.addToConfig(config.generateGromacsConfig(extra_options={**config_options, **self._extra_options},
extra_lines=self._extra_lines))
# Flag that this isn't a custom protocol.
self._protocol._setCustomised(False)
def _generate_args(self):
"""Generate the dictionary of command-line arguments."""
# Clear the existing arguments.
self.clearArgs()
# Add the default arguments.
self.setArg("mdrun", True) # Use mdrun.
self.setArg("-deffnm", self._name) # Output file prefix.
# Metadynamics and steered MD arguments.
if isinstance(self._protocol, (_Protocol.Metadynamics, _Protocol.Steering)):
self.setArg("-plumed", "plumed.dat")
def _generate_binary_run_file(self):
"""Use grommp to generate the binary run input file."""
# Create the name of the output mdp file.
mdp_out = _os.path.dirname(self._config_file) + \
"/%s.out.mdp" % _os.path.basename(self._config_file).split(".")[0]
# Use grompp to generate the portable binary run input file.
if self._checkpoint_file is not None:
command = "%s grompp -f %s -po %s -c %s -p %s -r %s -t %s -o %s" \
% (self._exe, self._config_file, mdp_out, self._gro_file,
self._top_file, self._gro_file, self._checkpoint_file, self._tpr_file)
else:
command = "%s grompp -f %s -po %s -c %s -p %s -r %s -o %s" \
% (self._exe, self._config_file, mdp_out, self._gro_file,
self._top_file, self._gro_file, self._tpr_file)
# Warnings don't trigger an error. Set to a suitably large number.
if self._ignore_warnings:
command += " --maxwarn 1000"
# Run the command.
proc = _subprocess.run(_Utils.command_split(command), shell=False, text=True,
stdout=_subprocess.PIPE, stderr=_subprocess.PIPE)
# Check that grompp ran successfully.
if proc.returncode != 0:
# Handle errors and warnings.
if self._show_errors:
# Capture errors and warnings from the grompp output.
errors = []
warnings = []
is_error = False
is_warn = False
lines = proc.stderr.split("\n")
for line in lines:
line = line.strip()
if line[0:5] == "ERROR" or is_error:
if line == "":
is_error = False
continue
errors.append(line)
is_error = True
elif line[0:7] == "WARNING" or is_warn:
if line == "":
is_warn = False
continue
warnings.append(line)
is_warn = True
error_string = "\n ".join(errors)
warning_string = "\n ".join(warnings)
exception_string = "Unable to generate GROMACS binary run input file.\n"
if len(errors) > 0:
exception_string += "\n'gmx grompp' reported the following errors:\n" \
+ f"{error_string}\n"
if len(warnings) > 0:
exception_string += "\n'gmx grompp' reported the following warnings:\n" \
+ f"{warning_string}\n" \
+ "\nUse 'ignore_warnings' to ignore warnings."
raise RuntimeError(exception_string)
else:
raise RuntimeError("Unable to generate GROMACS binary run input file. "
"Use 'show_errors=True' to display errors/warnings.")
def addToConfig(self, config):
"""Add a string to the configuration list.
Parameters
----------
config : str, [str]
A configuration string, a list of configuration strings, or a
path to a configuration file.
"""
# Call the base class method.
super().addToConfig(config)
# Use grompp to generate the portable binary run input file.
self._generate_binary_run_file()
def resetConfig(self):
"""Reset the configuration parameters."""
self._generate_config()
# Use grompp to generate the portable binary run input file.
self._generate_binary_run_file()
def setConfig(self, config):
"""Set the list of configuration file strings.
Parameters
----------
config : str, [str]
The list of configuration strings, or a path to a configuration
file.
"""
# Call the base class method.
super().setConfig(config)
# Use grompp to generate the portable binary run input file.
self._generate_binary_run_file()
def start(self):
"""Start the GROMACS process.
Returns
-------
process : :class:`Process.Gromacs <BioSimSpace.Process.Gromacs>`
A handle to the GROMACS process.
"""
# The process is currently queued.
if self.isQueued():
return
# Process is already running.
if self._process is not None:
if self._process.isRunning():
return
# Clear any existing output.
self._clear_output()
# Run the process in the working directory.
with _Utils.cd(self._work_dir):
# Create the arguments string list.
args = self.getArgStringList()
# Write the command-line process to a README.txt file.
with open("README.txt", "w") as f:
# Set the command-line string.
self._command = "%s " % self._exe + self.getArgString()
# Write the command to file.
f.write("# GROMACS was run with the following command:\n")
f.write("%s\n" % self._command)
# Start the timer.
self._timer = _timeit.default_timer()
# Start the simulation.
self._process = _SireBase.Process.run(self._exe, args,
"%s.out" % self._name, "%s.out" % self._name)
# For historical reasons (console message aggregation with MPI), Gromacs
# writes the majority of its output to stderr. For user convenience, we
# redirect all output to stdout, and place a message in the stderr file
# to highlight this.
with open(self._stderr_file, "w") as f:
f.write("All output has been redirected to the stdout stream!\n")
return self
def getSystem(self, block="AUTO"):
"""Get the latest molecular system.
Parameters
----------
block : bool
Whether to block until the process has finished running.
Returns
-------
system : :class:`System <BioSimSpace._SireWrappers.System>`
The latest molecular system.
"""
# Wait for the process to finish.
if block is True:
self.wait()
elif block == "AUTO" and self._is_blocked:
self.wait()
# Warn the user if the process has exited with an error.
if self.isError():
_warnings.warn("The process exited with an error!")
# Minimisation trajectories have a single frame, i.e. the final state.
if isinstance(self._protocol, _Protocol.Minimisation):
time = 0*_Units.Time.nanosecond
# Get the current simulation time.
else:
time = self.getTime()
# Grab the most recent frame from the trajectory file.
return self._getFrame(time)
def getCurrentSystem(self):
"""Get the latest molecular system.
Returns
-------
system : :class:`System <BioSimSpace._SireWrappers.System>`
The latest molecular system.
"""
return self.getSystem(block=False)
def getTrajectory(self, block="AUTO"):
"""Return a trajectory object.
Parameters
----------
block : bool
Whether to block until the process has finished running.
Returns
-------
trajectory : :class:`System <BioSimSpace.Trajectory.Trajectory>`
The latest trajectory object.
"""
# Wait for the process to finish.
if block is True:
self.wait()
elif block == "AUTO" and self._is_blocked:
self.wait()
# Warn the user if the process has exited with an error.
if self.isError():
_warnings.warn("The process exited with an error!")
try:
# Locate the trajectory file.
traj_file = self._find_trajectory_file()
if traj_file is None:
return None
else:
self._traj_file = traj_file
return _Trajectory.Trajectory(process=self)
except:
return None