Repository navigation
Expand file tree
/
Copy path_plumed.py
More file actions
1770 lines (1428 loc) · 67 KB
/
Copy path_plumed.py
File metadata and controls
1770 lines (1428 loc) · 67 KB
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-2025
#
# 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 3 of the License, or
# (at your option) any later version.
#
# BioSimSpace 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/>.
#####################################################################
"""Utility class for interfacing with PLUMED."""
__author__ = "Lester Hedges"
__email__ = "lester.hedges@gmail.com"
__all__ = ["Plumed"]
from .. import Types as _Types
from .._Utils import Tail as _Tail
class Plumed:
"""A class for interfacing with PLUMED."""
def __init__(self, work_dir):
"""
Constructor.
Parameters
----------
work_dir : str
The working directory of the process that is interfacing
with PLUMED.
"""
import os as _os
import subprocess as _subprocess
from sire.legacy.Base import findExe as _findExe
from .. import _Exceptions, _Utils
from ._process import _MultiDict
# Check that the working directory is valid.
if not isinstance(work_dir, str):
raise TypeError("'work_dir' must be of type 'str'")
else:
if not _os.path.isdir(work_dir):
raise ValueError("'work_dir' doesn't exist: %s" % work_dir)
# Try to locate the PLUMED executable.
try:
self._exe = _findExe("plumed").absolute_file_path()
except:
raise _Exceptions.MissingSoftwareError(
"Metadynamics simulations required "
"that PLUMED is installed: www.plumed.org"
)
# Run a PLUMED as a background process to query the version number.
command = "%s info --version" % self._exe
process = _subprocess.run(
_Utils.command_split(command), shell=False, stdout=_subprocess.PIPE
)
if process.returncode == 0:
self._plumed_version = process.stdout.decode("ascii").strip()
# Get the major minor version.
major, minor = self._plumed_version.split(".")
major = int(major)
minor = int(minor)
if major < 2 or (major < 3 and minor < 5):
raise _Exceptions.IncompatibleError(
"PLUMED version >= 2.5 is required."
)
# Store the major and minor versions.
self._plumed_major = major
self._plumed_minor = minor
else:
raise _Exceptions.IncompatibleError("Could not determine PLUMED version!")
# Set the working directory of the process.
self._work_dir = work_dir
# Set the location of the HILLS and COLVAR files.
self._hills_file = _os.path.join(str(self._work_dir), "HILLS")
self._colvar_file = _os.path.join(str(self._work_dir), "COLVAR")
self._hills_tail = _Tail(self._hills_file)
self._colvar_tail = _Tail(self._colvar_file)
# The number of collective variables and total number of components.
self._num_colvar = 0
self._num_components = 0
# The number of lower/upper walls.
self._num_lower_walls = 0
self._num_upper_walls = 0
# Initialise a list of the collective variable argument names.
self._colvar_name = []
# Initialise a dictionary to map the collective variable names
# to their unit. This can be used when returning time series
# records from the log files.
self._colvar_unit = {}
# Initialise the list of configuration file strings and auxiliary files.
self._config = []
self._aux_files = []
# Initialise dictionaries to hold COLVAR and HILLS time-series records.
self._colvar_dict = _MultiDict()
self._hills_dict = _MultiDict()
# Initialise lists to store the keys used to index the above dictionary.
self._colvar_keys = []
self._hills_keys = []
# Whether to use the HILLS file to get COLVAR information.
self._use_hills = False
# Flag that we haven't yet got a valid config.
self._has_config = False
def createConfig(self, system, protocol, property_map={}):
"""
Create a PLUMED configuration file.
Parameters
----------
system : :class:`System <BioSimSpace._SireWrappers.System>`
A BioSimSpace system object.
protocol : :class:`Protocol.Metadynamics <BioSimSpace.Protocol.Metadynamics>`, \
:class:`Protocol.Steering <BioSimSpace.Protocol.Steering>`, \
The metadynamics or steered molecular dynamics protocol.
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" }
Returns
-------
config, auxiliary_files : [str], [str]
The list of PLUMED configuration strings and paths to any auxiliary
files required by the collective variables.
"""
from .._SireWrappers import System as _System
from ..Protocol import Metadynamics as _Metadynamics
from ..Protocol import Steering as _Steering
if not isinstance(system, _System):
raise TypeError(
"'system' must be of type 'BioSimSpace._SireWrappers.System'"
)
# Create a metadynamics protocol.
if isinstance(protocol, _Metadynamics):
return self._createMetadynamicsConfig(system, protocol, property_map)
# Create a steered molecular dynamics protocol.
if isinstance(protocol, _Steering):
return self._createSteeringConfig(system, protocol, property_map)
else:
raise TypeError(
"'protocol' must be of type 'BioSimSpace.Protocol.Metadynamics' "
" or 'BioSimSpace.Protocol.Steering'"
)
def _createMetadynamicsConfig(self, system, protocol, property_map={}):
"""
Create a PLUMED metadynamics configuration file.
Parameters
----------
system : :class:`System <BioSimSpace._SireWrappers.System>`
A BioSimSpace system object.
protocol : :class:`Protocol.Metadynamics <BioSimSpace.Protocol.Metadynamics>`
The metadynamics protocol.
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" }
Returns
-------
config, auxiliary_files : [str], [str]
The list of PLUMED configuration strings and paths to any auxiliary
files required by the collective variables.
"""
import os as _os
import sire.legacy.Vol as _SireVol
from sire.legacy.Maths import Vector as _Vector
from .. import Units as _Units
from .. import _Exceptions
from .._SireWrappers import System as _System
from ..Metadynamics import CollectiveVariable as _CollectiveVariable
from ..Protocol import Metadynamics as _Metadynamics
from ..Types import Coordinate as _Coordinate
if not isinstance(system, _System):
raise TypeError(
"'system' must be of type 'BioSimSpace._SireWrappers.System'"
)
if not isinstance(protocol, _Metadynamics):
raise TypeError(
"'protocol' must be of type 'BioSimSpace.Protocol.Metadynamics'"
)
if not isinstance(property_map, dict):
raise TypeError("'property_map' must be of type 'dict'")
# Clear data.
self._num_colvar = 0
self._num_lower_walls = 0
self._num_upper_walls = 0
self._colvar_name = []
self._colvar_unit = {}
self._config = []
self._aux_files = []
# Reset the incremental file readers.
self._colvar_tail = _Tail(self._colvar_file)
self._hills_tail = _Tail(self._hills_file)
# Restart if existing HILLS and COLVAR files are present.
if _os.path.isfile(self._colvar_file) and _os.path.isfile(self._hills_file):
is_restart = True
self._config.append("RESTART")
else:
is_restart = False
self._config.append("RESTART NO")
# Initialise molecule number to atom tally lookup dictionary in the system.
try:
system.getIndex(system[0].getAtoms()[0])
except:
raise ValueError("The system contains no molecules?")
# Store the collective variable(s).
colvars = protocol.getCollectiveVariable()
self._num_colvar = len(colvars)
for cv in colvars:
self._num_components += cv.nComponents()
# Loop over each collective variable and create WHOLEMOLECULES entities
# for any molecule that involve atoms in a collective variable. We only
# want to record each molecule once, so keep a list of the molecules
# that we've already seen.
molecules = []
for colvar in colvars:
# Store all of the atoms to which the collective variable applies.
atoms = []
# Distance.
if isinstance(colvar, _CollectiveVariable.Distance):
atom0 = colvar.getAtom0()
atom1 = colvar.getAtom1()
if type(atom0) is int:
atoms.append(atom0)
elif isinstance(atom0, list):
atoms.extend(atom0)
if type(atom1) is int:
atoms.append(atom1)
elif isinstance(atom1, list):
atoms.extend(atom1)
# Torsion.
elif isinstance(colvar, _CollectiveVariable.Torsion):
atoms = colvar.getAtoms()
# Funnel.
elif isinstance(colvar, _CollectiveVariable.Funnel):
# First we need to check that the funnel length is less
# than half the simulation box base length in any dimension.
# Get the upper bound on the collective variable.
upper_bound = colvar.getUpperBound()
if upper_bound is not None:
# Store the value of the bound in angstrom.
value = upper_bound.getValue().angstroms().value()
# Get the user-defined "space" property.
space_prop = property_map.get("space", "space")
# Check whether the system has a space. If not, vacuum
# simulations are okay.
if space_prop in system._sire_object.property_keys():
# Get the space property.
space = system._sire_object.property(space_prop)
# Handle PeriodicBox.
if isinstance(space, _SireVol.PeriodicBox):
# Get the x,y,z dimensions of th box in angstrom.
dimensions = space.dimensions()
# Check the upper bound is greater than dim/2 for
# each dimension.
for dim in dimensions:
if value >= 0.5 * dim.value():
message = (
"The simulation box is too small for the funnel. "
"Try reducing the upper bound of the collective "
"variable or increasing the box size."
)
raise _Exceptions.IncompatibleError(message)
# Handle TriclinicBox.
else:
# Get the magnitude of each box vector in angstrom.
m0 = _Vector.magnitude(space.vector0())
m1 = _Vector.magnitude(space.vector1())
m2 = _Vector.magnitude(space.vector2())
# Check the upper bound is greater than mag/2 for
for mag in [m0, m1, m2]:
if value >= 0.5 * mag:
message = (
"The simulation box is too small for the funnel. "
"Try reducing the upper bound of the collective "
"variable or increasing the box size."
)
raise _Exceptions.IncompatibleError(message)
# Here we assume that we have a solvated protein/ligand
# (or host/guest). The largest molecule in the system
# will be the protein, the second largest the ligand.
# Store the number of atoms in each molecule.
atom_nums = []
for mol in system:
atom_nums.append(mol.nAtoms())
# Sort the molecule indices by the number of atoms they contain.
sorted_nums = sorted(
(value, num) for value, num in zip(atom_nums, system._mol_nums)
)
# Store the indices of the largest and second largest molecules.
if sorted_nums[-1][1] not in molecules:
molecules.append(sorted_nums[-1][1])
if sorted_nums[-2][1] not in molecules:
molecules.append(sorted_nums[-2][1])
# The funnel collective variable requires an auxiliary file for
# PLUMED versions < 2.7.
if self._plumed_major < 2 or (
self._plumed_major < 3 and self._plumed_minor < 7
):
aux_file = "ProjectionOnAxis.cpp"
self._config.append(f"LOAD FILE={aux_file}")
aux_file = (
_os.path.dirname(_CollectiveVariable.__file__).replace(
"CollectiveVariable", "_aux"
)
+ "/"
+ aux_file
)
self._aux_files.append(aux_file)
# RMSD.
elif isinstance(colvar, _CollectiveVariable.RMSD):
for i in colvar.getMoleculeIndices():
num = system._mol_nums[i]
if num not in molecules:
molecules.append(num)
# Loop over all of the atoms. Make sure the index is valid and
# check if we need to create an entity for the molecule containing
# the atom.
for idx in atoms:
# The atom index is invalid.
if idx >= system.nAtoms():
raise _Exceptions.IncompatibleError(
"The collective variable is incompatible with the "
"system. Contains atom index %d, number of atoms in system is %d "
% (idx, system.nAtoms())
)
# Get the molecule numbers in this system.
mol_nums = system._sire_object.mol_nums()
# Loop over each molecule and find the one that contains this atom.
for x, num in enumerate(mol_nums):
# The atom was in the previous molecule.
if system._atom_index_tally[num] > idx:
num = mol_nums[x - 1]
break
# This is a new molecule.
if num not in molecules:
molecules.append(num)
# Initialise the configuration string.
string = "WHOLEMOLECULES"
# Create an entity for each unique molecule.
for x, molecule in enumerate(molecules):
# Get the start index.
idx = system._atom_index_tally[molecule]
# Get the number of atoms in the molecule.
num_atoms = system._sire_object.molecule(molecule).num_atoms()
# Create the entity record. Remember to one-index the atoms.
string += " ENTITY%d=%d-%d" % (x, idx + 1, idx + num_atoms)
# Append the string to the configuration list.
self._config.append("\n# Define the molecular entities.")
self._config.append(string)
# Initialise tally counters.
num_distance = 0
num_torsion = 0
num_rmsd = 0
num_center = 0
num_fixed = 0
# Initialise a list to store the grid data for each variable.
grid_data = []
# Initialise the METAD string.
metad_string = "metad: METAD ARG="
for idx, colvar in enumerate(colvars):
# Get the lower/upper bounds and the grid data.
lower_wall = colvar.getLowerBound()
upper_wall = colvar.getUpperBound()
grid = colvar.getGrid()
# Whether the collective variable is a torsion or funnel.
is_torsion = False
is_funnel = False
# Distance.
if isinstance(colvar, _CollectiveVariable.Distance):
num_distance += 1
# Create the argument name.
arg_name = "d%d" % num_distance
# Get the atoms between which the distance is measured.
# Also get the weights, and the center of mass flag.
# Start.
atom0 = colvar.getAtom0()
weights0 = colvar.getWeights0()
is_com0 = colvar.getCoM0()
# End.
atom1 = colvar.getAtom1()
weights1 = colvar.getWeights1()
is_com1 = colvar.getCoM1()
# Initialise the collective variable string.
colvar_string = "d%d: DISTANCE ATOMS=" % num_distance
# Process the first atom(s) or fixed coordinate.
# A single atom.
if type(atom0) is int:
colvar_string += "%d" % (atom0 + 1)
# A list of atom indices.
elif isinstance(atom0, list):
num_center += 1
colvar_string += "c%d" % num_center
center_string = "c%d: CENTER ATOMS=%s" % (
num_center,
",".join([str(x + 1) for x in atom0]),
)
# Center of mass weighting takes precedence.
if is_com0:
center_string += " MASS"
# User weights.
elif weights0 is not None:
center_string += " WEIGHTS=%s" % ",".join(
[str(x) for x in weights0]
)
self._config.append(center_string)
# A coordinate of a fixed point.
elif isinstance(atom0, _Coordinate):
# Convert to nanometers.
x = atom0.x().nanometers().value()
y = atom0.y().nanometers().value()
z = atom0.z().nanometers().value()
num_fixed += 1
self._config.append(
"f%d: FIXEDATOM AT=%s,%s,%s" % (num_fixed, x, y, z)
)
colvar_string += "f%d" % num_fixed
# Process the second atom(s) or fixed coordinate.
# A single atom.
if type(atom1) is int:
colvar_string += ",%d" % (atom1 + 1)
# A list of atom indices.
elif type(atom1) is int:
num_center += 1
colvar_string += ",c%d" % num_center
center_string = "c%d: CENTER ATOMS=%s" % (
num_center,
",".join([str(x + 1) for x in atom1]),
)
# Center of mass weighting takes precedence.
if is_com1:
center_string += " MASS"
# User weights.
elif weights1 is not None:
center_string += " WEIGHTS=%s" % ",".join(
[str(x) for x in weights1]
)
self._config.append(center_string)
# A coordinate of a fixed point.
elif isinstance(atom1, _Coordinate):
# Convert to nanometers.
x = atom1.x().nanometers().value()
y = atom1.y().nanometers().value()
z = atom1.z().nanometers().value()
num_fixed += 1
self._config.append(
"f%d: FIXEDATOM AT=%s,%s,%s" % (num_fixed, x, y, z)
)
colvar_string += ",f%d" % num_fixed
# Disable periodic boundaries.
if not colvar.getPeriodicBoundaries():
colvar_string += " NOPBC"
# Measure the x, y, and z distance components.
if colvar.getComponent() is not None:
colvar_string += " COMPONENT"
arg_name += ".%s" % colvar.getComponent()
# Append the collective variable record.
self._config.append("\n# Define the collective variable.")
self._config.append(colvar_string)
# Store the collective variable name and its unit.
self._colvar_name.append(arg_name)
self._colvar_unit[arg_name] = _Units.Length.nanometer
# Convert arg_name to a list so we can handle multi-component
# collective variables.
arg_name = [arg_name]
# Torsion.
elif isinstance(colvar, _CollectiveVariable.Torsion):
is_torsion = True
num_torsion += 1
arg_name = "t%d" % num_torsion
colvar_string = "%s: TORSION ATOMS=%s" % (
arg_name,
",".join([str(x + 1) for x in colvar.getAtoms()]),
)
# Store the collective variable name and its unit.
self._colvar_name.append(arg_name)
self._colvar_unit[arg_name] = _Units.Angle.radian
# Disable periodic boundaries.
if not colvar.getPeriodicBoundaries():
colvar_string += " NOPBC"
# Append the collective variable record.
self._config.append("\n# Define the collective variable.")
self._config.append(colvar_string)
# Convert arg_name to a list so we can handle multi-component
# collective variables.
arg_name = [arg_name]
# RMSD.
elif isinstance(colvar, _CollectiveVariable.RMSD):
num_rmsd += 1
arg_name = "r%d" % num_rmsd
colvar_string = "%s: RMSD REFERENCE=reference_%d.pdb" % (
arg_name,
num_rmsd,
)
colvar_string += " TYPE=%s" % colvar.getAlignmentType().upper()
# Write the reference PDB file.
with open(
_os.path.join(str(self._work_dir), f"reference_{num_rmsd}.pdb"),
"w",
) as file:
for line in colvar.getReferencePDB():
file.write(line + "\n")
# Store the collective variable name and its unit.
self._colvar_name.append(arg_name)
self._colvar_unit[arg_name] = None
# Disable periodic boundaries.
if not colvar.getPeriodicBoundaries():
colvar_string += " NOPBC"
# Append the collective variable record.
self._config.append("\n# Define the collective variable.")
self._config.append(colvar_string)
# Convert arg_name to a list so we can handle multi-component
# collective variables.
arg_name = [arg_name]
# Funnel.
elif isinstance(colvar, _CollectiveVariable.Funnel):
is_funnel = True
# Store the collective variable name and its unit.
# Funnel has two components, the projection and extent.
self._colvar_name.append("pp.proj")
self._colvar_unit["pp.proj"] = _Units.Length.nanometer
self._colvar_name.append("pp.ext")
self._colvar_unit["pp.ext"] = _Units.Length.nanometer
self._config.append("\n# Center-of-mass definitions.")
# Get the start index of the ligand.
idx = system._atom_index_tally[molecules[1]]
# Get the number of atoms in the ligand.
num_atoms = system._sire_object.molecule(molecule).num_atoms()
# Create the ligand record. Remember to one-index the atoms.
colvar_string = "lig: COM ATOMS=%d-%d" % (idx + 1, idx + num_atoms)
self._config.append(colvar_string)
# Create the center-of-mass record for the atoms that are used
# to define the funnel origin.
arg_name = "p1"
colvar_string = "%s: COM ATOMS=%s" % (
arg_name,
",".join([str(x + 1) for x in colvar.getAtoms0()]),
)
self._config.append(colvar_string)
# Create the center-of-mass record for the atoms that are used
# to define the funnel inflection point.
arg_name = "p2"
colvar_string = "%s: COM ATOMS=%s" % (
arg_name,
",".join([str(x + 1) for x in colvar.getAtoms1()]),
)
self._config.append(colvar_string)
# Create the "projection-on-axis" collective variable.
self._config.append("\n# Projection-on-axis collective variable.")
colvar_string = "pp: PROJECTION_ON_AXIS AXIS_ATOMS=p1,p2 ATOM=lig"
self._config.append(colvar_string)
# Add funnel parameters.
self._config.append("")
self._config.append("# Funnel parameters.")
self._config.append(
f"s_cent: CONSTANT VALUES={colvar.getInflection().value()}"
) # inflection
self._config.append(
f"beta_cent: CONSTANT VALUES={colvar.getSteepness()}"
) # steepness
self._config.append(
f"wall_width: CONSTANT VALUES={colvar.getWidth().value()}"
) # width
self._config.append(
f"wall_buffer: CONSTANT VALUES={colvar.getBuffer().value()}"
) # total = width + buffer
# Define the funnel calculation. This function returns the
# radius of the funnel at the current value of the collective
# variable.
self._config.append("\n# Calculate the funnel.")
self._config.append("MATHEVAL ...")
self._config.append(" LABEL=wall_center")
self._config.append(
" ARG=pp.proj,s_cent,beta_cent,wall_width,wall_buffer"
)
self._config.append(" VAR=s,sc,b,h,f")
self._config.append(" FUNC=h*(1./(1.+exp(b*(s-sc))))+f")
self._config.append(" PERIODIC=NO")
self._config.append("... MATHEVAL")
# Define the funnel potential.
self._config.append("\n# Define the potential.")
self._config.append("scaling: CONSTANT VALUES=1.0")
self._config.append("spring: CONSTANT VALUES=1000.0")
self._config.append("MATHEVAL ...")
self._config.append(" LABEL=wall_bias")
self._config.append(" ARG=pp.ext,spring,wall_center,scaling")
self._config.append(" VAR=z,k,zc,sf")
self._config.append(" FUNC=step(z-zc)*k*(z-zc)*(z-zc)/(sf*sf)")
self._config.append(" PERIODIC=NO")
self._config.append("... MATHEVAL")
self._config.append("finalbias: BIASVALUE ARG=wall_bias")
# Store the argument names in a list.
arg_name = ["pp.proj", "pp.ext"]
# Check for lower and upper bounds on the collective variable.
# This only applies to the first collective variable name.
if lower_wall is not None:
self._num_lower_walls += 1
lower_wall_string = "lwall%d: LOWER_WALLS ARG=%s" % (
self._num_lower_walls,
arg_name[0],
)
try:
# Unit based.
lower_wall_string += ", AT=%s" % lower_wall.getValue().value()
except:
# Dimensionless.
lower_wall_string += ", AT=%s" % lower_wall.getValue()
lower_wall_string += ", KAPPA=%s" % lower_wall.getForceConstant()
lower_wall_string += ", EXP=%s" % lower_wall.getExponent()
lower_wall_string += ", EPS=%s" % lower_wall.getEpsilon()
self._config.append("\n# Lower bound on collective variable.")
self._config.append(lower_wall_string)
# Check for lower and upper bounds on the collective variable.
# This only applies to the first collective variable name.
if upper_wall is not None:
self._num_upper_walls += 1
upper_wall_string = "uwall%d: UPPER_WALLS ARG=%s" % (
self._num_upper_walls,
arg_name[0],
)
try:
# Unit based.
upper_wall_string += ", AT=%s" % upper_wall.getValue().value()
except:
# Dimensionless.
upper_wall_string += ", AT=%s" % upper_wall.getValue()
upper_wall_string += ", KAPPA=%s" % upper_wall.getForceConstant()
upper_wall_string += ", EXP=%s" % upper_wall.getExponent()
upper_wall_string += ", EPS=%s" % upper_wall.getEpsilon()
self._config.append("\n# Upper bound on collective variable.")
self._config.append(upper_wall_string)
# Store grid data.
if grid is not None:
if is_torsion:
grid_data.append(("-pi", "pi", grid.getBins()))
elif is_funnel:
# Grid for "projection" component.
grid_data.append(
(
grid[0].getMinimum().value(),
grid[0].getMaximum().value(),
grid[0].getBins(),
)
)
# Grid for "extent" component.
grid_data.append(
(
grid[1].getMinimum().value(),
grid[1].getMaximum().value(),
grid[1].getBins(),
)
)
else:
try:
# Unit based.
grid_data.append(
(
grid.getMinimum().value(),
grid.getMaximum().value(),
grid.getBins(),
)
)
except:
# Dimensionless.
grid_data.append(
(grid.getMinimum(), grid.getMaximum(), grid.getBins())
)
# Add the argument to the METAD record. We join argument names with
# a "," to handle multi-component collective variables.
metad_string += "%s" % ",".join(arg_name)
# Update the METAD record to separate the collective variable arguments.
if idx < self._num_colvar - 1:
metad_string += ","
# Now complete the METAD record string.
# Hill width.
metad_string += " SIGMA="
for idx0, colvar in enumerate(colvars):
hill_width = colvar.getHillWidth()
if isinstance(hill_width, tuple):
last_hill = len(hill_width) - 1
for idx1, width in enumerate(hill_width):
metad_string += "%s" % width.value()
if idx1 < last_hill:
metad_string += ","
else:
# Handle dimensionless collective variables.
try:
metad_string += "%s" % hill_width.value()
except:
metad_string += "%s" % hill_width
if idx0 < self._num_colvar - 1:
metad_string += ","
# Hill height.
metad_string += " HEIGHT=%s" % protocol.getHillHeight().value()
# Hill frequency.
metad_string += " PACE=%s" % protocol.getHillFrequency()
# Grid parameters.
if len(grid_data) > 0:
grid_min_string = " GRID_MIN="
grid_max_string = " GRID_MAX="
grid_bin_string = " GRID_BIN="
for idx, grid in enumerate(grid_data):
grid_min_string += str(grid[0])
grid_max_string += str(grid[1])
grid_bin_string += str(grid[2])
if idx < self._num_components - 1:
grid_min_string += ","
grid_max_string += ","
grid_bin_string += ","
metad_string += grid_min_string + grid_max_string + grid_bin_string
metad_string += (
" GRID_WFILE=GRID GRID_WSTRIDE=%s" % protocol.getHillFrequency()
)
if is_restart and _os.path.isfile(
_os.path.join(str(self._work_dir), "GRID")
):
metad_string += " GRID_RFILE=GRID"
metad_string += " CALC_RCT"
# Temperature and bias parameters.
metad_string += " TEMP=%s" % protocol.getTemperature().kelvin().value()
if protocol.getBiasFactor() is not None:
metad_string += " BIASFACTOR=%s" % protocol.getBiasFactor()
# Append the METAD record to the config.
self._config.append("\n# Define the metadynamics simulation.")
self._config.append(metad_string)
# Print all record data to the COLVAR file.
print_string = "PRINT STRIDE=%s ARG=* FILE=COLVAR" % protocol.getHillFrequency()
self._config.append(print_string)
# Flag that we have a valid config.
self._has_config = True
return self._config, self._aux_files
def _createSteeringConfig(self, system, protocol, property_map={}):
"""
Create a PLUMED steering molecular dynamics configuration file.
Parameters
----------
system : :class:`System <BioSimSpace._SireWrappers.System>`
A BioSimSpace system object.
protocol : :class:`Protocol.Steering <BioSimSpace.Protocol.Steering>`
The metadynamics protocol.
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" }
Returns
-------
config, auxiliary_files : [str], [str]
The list of PLUMED configuration strings and paths to any auxiliary
files required by the collective variables.
"""
import os as _os
from .. import Units as _Units
from .. import _Exceptions
from .._SireWrappers import System as _System
from ..Metadynamics import CollectiveVariable as _CollectiveVariable
from ..Protocol import Steering as _Steering
from ..Types import Coordinate as _Coordinate
if not isinstance(system, _System):
raise TypeError(
"'system' must be of type 'BioSimSpace._SireWrappers.System'"
)
if not isinstance(protocol, _Steering):
raise TypeError(
"'protocol' must be of type 'BioSimSpace.Protocol.Steering'"
)
if not isinstance(property_map, dict):
raise TypeError("'property_map' must be of type 'dict'")
# Clear data.
self._num_colvar = 0
self._colvar_name = []
self._colvar_unit = {}
self._config = []
self._aux_files = []
# Reset the incremental file reader.
self._colvar_tail = _Tail(self._colvar_file)
# Restart if an existing COLVAR files is present.
if _os.path.isfile(self._colvar_file):
self._config.append("RESTART")
else:
self._config.append("RESTART NO")
# Initialise molecule number to atom tally lookup dictionary in the system.
try:
system.getIndex(system[0].getAtoms()[0])
except:
raise ValueError("The system contains no molecules?")
# Store the collective variable(s).
colvars = protocol.getCollectiveVariable()
self._num_colvar = len(colvars)
for cv in colvars:
self._num_components += cv.nComponents()
# Loop over each collective variable and create WHOLEMOLECULES entities
# for any molecule that involve atoms in a collective variable. We only
# want to record each molecule once, so keep a list of the molecules
# that we've already seen.
molecules = []
for colvar in colvars:
# Store all of the atoms to which the collective variable applies.
atoms = []
# Distance.
if isinstance(colvar, _CollectiveVariable.Distance):
atom0 = colvar.getAtom0()
atom1 = colvar.getAtom1()
if type(atom0) is int:
atoms.append(atom0)
elif isinstance(atom0, list):
atoms.extend(atom0)
if type(atom1) is int:
atoms.append(atom1)
elif isinstance(atom1, list):
atoms.extend(atom1)