-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathOpenMMMD.py
2588 lines (2115 loc) · 79 KB
/
OpenMMMD.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
"""RUN SCRIPT to perform an MD simulation in Sire with OpenMM
"""
import os
import sys
import re
import math
import time
import platform as pf
import warnings
import numpy as np
import openmm.app as app
import openmm
import openmm.unit as units
import Sire.Base
# Make sure that the OPENMM_PLUGIN_DIR enviroment variable is set correctly if
# unset.
try:
# The user has already set the plugin location.
openmm_dir = os.environ["OPENMM_PLUGIN_DIR"]
except KeyError:
# Set to the default location of the bundled OpenMM package.
openmm_dir = os.environ["OPENMM_PLUGIN_DIR"] = \
Sire.Base.getLibDir() + "/plugins"
finally:
if not os.path.isdir(openmm_dir):
warnings.warn('OPENMM_PLUGIN_DIR is not accessible')
print(f'OPENMM_PLUGIN_DIR = {openmm_dir}')
import Sire.IO
#import Sire.Mol
import Sire.CAS
import Sire.System
import Sire.Move
import Sire.MM
import Sire.FF
import Sire.Units
import Sire.Maths
import Sire.Qt
import Sire.Analysis
from Sire.Tools.DCDFile import *
from Sire.Tools import Parameter, resolveParameters
import Sire.Stream
__author__ = 'Julien Michel, Gaetano Calabro, Antonia Mey, Hannes H Loeffler'
__version__ = '0.2'
__license__ = 'GPL'
__maintainer__ = 'Julien Michel'
__email__ = '[email protected]'
__status__ = 'Development'
HMR_MIN = 1.0
HMR_MAX = 4.0
###############################################################################
#
# Config file parameters
#
###############################################################################
gpu = Parameter(
"gpu", 0, """The device ID of the GPU on which to run the simulation."""
)
rf_dielectric = Parameter(
"reaction field dielectric",
78.3,
"Dielectric constant to use if the reaction field cutoff method is used."
)
temperature = Parameter(
"temperature", 25.0 * Sire.Units.celsius, """Simulation temperature"""
)
pressure = Parameter("pressure", 1.0 * Sire.Units.atm,
"""Simulation pressure""")
topfile = Parameter(
"topfile",
"SYSTEM.top",
"File name of the topology file containing the system to be simulated."
)
crdfile = Parameter(
"crdfile",
"SYSTEM.crd",
"File name of the coordinate file containing the coordinates of the"
"system to be simulated."
)
s3file = Parameter(
"s3file",
"SYSTEM.s3",
"Filename for the system state file. The system state after topology "
"and coordinates were loaded are saved in this file.",
)
restart_file = Parameter(
"restart file",
"sim_restart.s3",
"Filename of the restart file to use to save progress during the "
"simulation."
)
dcd_root = Parameter(
"dcd root",
"traj",
"""Root of the filename of the output DCD trajectory files.""",
)
nmoves = Parameter(
"nmoves",
1000,
"Number of Molecular Dynamics moves to be performed during the "
"simulation."
)
debug_seed = Parameter(
"debug seed",
0,
"Debugging seed number seed. Set this if you want to reproduce a single "
"cycle. Don't use this seed for production simulations since the same "
"seed will be used for all cycles! A value of zero means that a unique "
"seed will be generated for each cycle."
)
ncycles = Parameter(
"ncycles",
1,
"The number of MD cycles. The total elapsed time will be "
"nmoves*ncycles*timestep"
)
maxcycles = Parameter(
"maxcycles",
99999,
"The maximum number of MD cycles to carry out. Useful to restart "
"simulations from a checkpoint"
)
ncycles_per_snap = Parameter(
"ncycles_per_snap", 1, """Number of cycles between saving snapshots"""
)
save_coords = Parameter(
"save coordinates", True, """Whether or not to save coordinates."""
)
buffered_coords_freq = Parameter(
"buffered coordinates frequency",
1,
"The number of time steps between saving of coordinates during a cycle "
"of MD. 0 disables buffering."
)
minimal_coordinate_saving = Parameter(
"minimal coordinate saving",
False,
"Reduce the number of coordiantes writing for states"
"with lambda in ]0,1[",
)
time_to_skip = Parameter(
"time to skip", 0.0 * Sire.Units.picosecond,
"""Time to skip in picoseconds"""
)
minimise = Parameter(
"minimise",
False,
"""Whether or not to perform minimization before the simulation.""",
)
minimise_tol = Parameter(
"minimise tolerance",
1,
"""Tolerance used to know when minimization is complete.""",
)
minimise_max_iter = Parameter(
"minimise maximum iterations",
1000,
"""Maximum number of iterations for minimization.""",
)
equilibrate = Parameter(
"equilibrate",
False,
"""Whether or not to perform equilibration before dynamics.""",
)
equil_iterations = Parameter(
"equilibration iterations",
2000,
"""Number of equilibration steps to perform.""",
)
equil_timestep = Parameter(
"equilibration timestep",
0.5 * Sire.Units.femtosecond,
"""Timestep to use during equilibration.""",
)
combining_rules = Parameter(
"combining rules",
"arithmetic",
"""Combining rules to use for the non-bonded interactions.""",
)
timestep = Parameter(
"timestep", 2.0 * Sire.Units.femtosecond,
"""Timestep for the dynamics simulation."""
)
platform = Parameter(
"platform",
"CUDA",
"""Which OpenMM platform should be used to perform the dynamics.""",
)
precision = Parameter(
"precision",
"mixed",
"""The floating point precision model to use during dynamics.""",
)
constraint = Parameter(
"constraint", "hbonds", """The constraint model to use during dynamics."""
)
# types: nocutoff, cutoffnonperiodic, cutoffperiodic
# added: PME for FEP only
cutoff_type = Parameter(
"cutoff type",
"cutoffperiodic",
"""The cutoff method to use during the simulation.""",
)
cutoff_dist = Parameter(
"cutoff distance",
10.0 * Sire.Units.angstrom,
"""The cutoff distance to use for the non-bonded interactions.""",
)
integrator_type = Parameter(
"integrator", "leapfrogverlet", """The integrator to use for dynamics."""
)
inverse_friction = Parameter(
"inverse friction",
0.1 * Sire.Units.picosecond,
"""Inverse friction time for the Langevin thermostat.""",
)
andersen = Parameter(
"thermostat",
True,
"Whether or not to use the Andersen thermostat (needed for NVT or NPT "
"simulation)."
)
barostat = Parameter(
"barostat",
True,
"""Whether or not to use a barostat (needed for NPT simulation).""",
)
andersen_frequency = Parameter(
"andersen frequency", 10.0, """Collision frequency in units of (1/ps)"""
)
barostat_frequency = Parameter(
"barostat frequency",
25,
"""Number of steps before attempting box changes if using the barostat.""",
)
lj_dispersion = Parameter(
"lj dispersion",
False,
"""Whether or not to calculate and include the LJ dispersion term.""",
)
cmm_removal = Parameter(
"center of mass frequency",
10,
"""Frequency of which the system center of mass motion is removed.""",
)
center_solute = Parameter(
"center solute",
False,
"Whether or not to centre the centre of geometry of the solute in the box."
)
use_restraints = Parameter(
"use restraints",
False,
"""Whether or not to use harmonic restaints on the solute atoms.""",
)
k_restraint = Parameter(
"restraint force constant",
100.0,
"""Force constant to use for the harmonic restaints.""",
)
heavy_mass_restraint = Parameter(
"heavy mass restraint",
1.10,
"""Only restrain solute atoms whose mass is greater than this value.""",
)
unrestrained_residues = Parameter(
"unrestrained residues",
["WAT", "HOH"],
"""Names of residues that are never restrained.""",
)
freeze_residues = Parameter(
"freeze residues", False, """Whether or not to freeze certain residues."""
)
frozen_residues = Parameter(
"frozen residues",
["LGR", "SIT", "NEG", "POS"],
"""List of residues to freeze if 'freeze residues' is True.""",
)
use_distance_restraints = Parameter(
"use distance restraints",
False,
"""Whether or not to use restraints distances between pairs of atoms.""",
)
distance_restraints_dict = Parameter(
"distance restraints dictionary",
{},
"Dictionary of pair of atoms whose distance is restrained, and restraint "
"parameters. Syntax is {(atom0,atom1):(reql, kl, Dl)} where atom0, atom1 "
"are atomic indices. reql the equilibrium distance. Kl the force constant "
"of the restraint. D the flat bottom radius. WARNING: PBC distance checks "
"not implemented, avoid restraining pair of atoms that may diffuse out of "
"the box."
)
hydrogen_mass_repartitioning_factor = Parameter(
"hydrogen mass repartitioning factor",
1.0,
f"If larger than {HMR_MIN} (maximum is {HMR_MAX}), all hydrogen "
"atoms in the molecule will have their mass increased by this "
"factor. The atomic mass of the heavy atom bonded to the "
"hydrogen is decreased to keep the total mass constant "
"(except when this would lead to a heavy atom to be lighter "
"than a minimum mass).",
)
# Free energy specific keywords
morphfile = Parameter(
"morphfile",
"MORPH.pert",
"Name of the morph file containing the perturbation to apply to the "
"system."
)
lambda_val = Parameter(
"lambda_val",
0.0,
"Value of the lambda parameter at which to evaluate free energy gradients."
)
delta_lambda = Parameter(
"delta_lambda",
0.001,
"Value of the lambda interval used to evaluate free energy gradients by "
"finite difference."
)
lambda_array = Parameter(
"lambda array",
[],
"Array with all lambda values lambda_val needs to be part of the array."
)
shift_delta = Parameter(
"shift delta", 2.0, """Value of the Lennard-Jones soft-core parameter."""
)
coulomb_power = Parameter(
"coulomb power", 0, """Value of the Coulombic soft-core parameter."""
)
energy_frequency = Parameter(
"energy frequency",
1,
"The number of time steps between evaluation of free energy gradients."
)
simfile = Parameter(
"outdata_file",
"simfile.dat",
"Filename that records all output needed for the free energy analysis"
)
perturbed_resnum = Parameter(
"perturbed residue number",
1,
"""The residue number of the molecule to morph.""",
)
charge_diff = Parameter('charge difference', 0,
'The difference in net charge between the two states')
verbose = Parameter('verbose', False, 'Print debug output')
###############################################################################
#
# Helper functions
#
###############################################################################
def setupDCD(system):
r"""
Parameters:
----------
system : sire system
sire system to be saved
Return:
------
trajectory : trajectory
"""
files = os.listdir(os.getcwd())
dcds = []
for f in files:
if f.endswith(".dcd"):
dcds.append(f)
dcds.sort()
index = len(dcds) + 1
dcd_filename = dcd_root.val + "%0009d" % index + ".dcd"
softcore_almbda = True
if lambda_val.val in (0.0, 1.0):
softcore_almbda = False
if minimal_coordinate_saving.val and softcore_almbda:
interval = ncycles.val * nmoves.val
Trajectory = Sire.Tools.DCDFile.DCDFile(
dcd_filename,
system[MGName("all")],
system.property("space"),
timestep.val,
interval,
)
else:
Trajectory = Sire.Tools.DCDFile.DCDFile(
dcd_filename,
system[MGName("all")],
system.property("space"),
timestep.val,
interval=buffered_coords_freq.val * ncycles_per_snap.val,
)
return Trajectory
def writeSystemData(system, moves, Trajectory, block, softcore_lambda=False):
if softcore_lambda:
if block == ncycles.val or block == 1:
Trajectory.writeModel(
system[MGName("all")], system.property("space")
)
else:
if block % ncycles_per_snap.val == 0:
if buffered_coords_freq.val > 0:
dimensions = {}
sysprops = system.propertyKeys()
for prop in sysprops:
if prop.startswith("buffered_space"):
dimensions[str(prop)] = system.property(prop)
Trajectory.writeBufferedModels(
system[MGName("all")], dimensions
)
else:
Trajectory.writeModel(
system[MGName("all")], system.property("space")
)
# Write a PDB coordinate file each cycle.
pdb = Sire.IO.PDB2(system)
pdb.writeToFile("latest.pdb")
moves_file = open("moves.dat", "w")
print("%s" % moves, file=moves_file)
moves_file.close()
def getSolute(system):
"""Find the solute molecule based on the perturbed residue number.
Args:
system (system): The Sire system
Returns:
molecule: Molecule matching perturbed residue number assumed to be solvent
"""
# Search the system for a single molcule containing a residue
# matching the perturbed_resnum.val.
# Create the query string.
query = f"resnum {perturbed_resnum.val}"
# Perform the search.
search = system.search(query).molecules()
# Make sure there is only one result.
if len(search) != 1:
msg = ("FATAL! Could not find a solute to perturb with residue "
f"number {perturbed_resnum.val} in the input! Check the value of "
"your config keyword 'perturbed residue number' The system should "
"contain a single molecule with this residue number.")
raise Exception(msg)
# Return the matching molecule, i.e. the solute.
return search[0]
def centerSolute(system, space):
if space.isPeriodic():
# Periodic box.
try:
box_center = space.dimensions() / 2
# TriclincBox.
except:
box_center = 0.5 * (
space.vector0() + space.vector1() + space.vector2()
)
else:
box_center = Sire.Maths.Vector(0.0, 0.0, 0.0)
# FIXME: we assume that the solute is the first in the returned list
solute_num = system.getMoleculeNumbers()[0]
solute = system.molecules().at(solute_num)[0].molecule()
assert(solute.hasProperty('perturbations'))
solute_cog = Sire.FF.CenterOfGeometry(solute).point()
delta = box_center - solute_cog
molNums = system.molNums()
for molnum in molNums:
mol = system.molecule(molnum)[0].molecule()
molcoords = mol.property("coordinates")
molcoords.translate(delta)
mol = mol.edit().setProperty("coordinates", molcoords).commit()
system.update(mol)
return system
def createSystem(molecules):
# print("Applying flexibility and zmatrix templates...")
print("Creating the system...")
moleculeNumbers = molecules.molNums()
moleculeList = []
for moleculeNumber in moleculeNumbers:
molecule = molecules.molecule(moleculeNumber)[0].molecule()
moleculeList.append(molecule)
molecules = MoleculeGroup("molecules")
ions = MoleculeGroup("ions")
for molecule in moleculeList:
natoms = molecule.nAtoms()
if natoms == 1:
ions.add(molecule)
else:
molecules.add(molecule)
all = MoleculeGroup("all")
all.add(molecules)
all.add(ions)
# Add these groups to the System
system = Sire.System.System()
system.add(all)
system.add(molecules)
system.add(ions)
return system
def setupForcefields(system, space):
"""
No PME support here.
"""
print("Creating force fields... ")
molecules = system[MGName("molecules")]
ions = system[MGName("ions")]
# - first solvent-solvent coulomb/LJ (CLJ) energy
internonbondedff = Sire.MM.InterCLJFF("molecules:molecules")
if cutoff_type.val != "nocutoff":
internonbondedff.setUseReactionField(True)
internonbondedff.setReactionFieldDielectric(rf_dielectric.val)
internonbondedff.add(molecules)
inter_ions_nonbondedff = Sire.MM.InterCLJFF("ions:ions")
if cutoff_type.val != "nocutoff":
inter_ions_nonbondedff.setUseReactionField(True)
inter_ions_nonbondedff.setReactionFieldDielectric(rf_dielectric.val)
inter_ions_nonbondedff.add(ions)
inter_ions_molecules_nonbondedff = \
Sire.MM.InterGroupCLJFF("ions:molecules")
if cutoff_type.val != "nocutoff":
inter_ions_molecules_nonbondedff.setUseReactionField(True)
inter_ions_molecules_nonbondedff.setReactionFieldDielectric(
rf_dielectric.val
)
inter_ions_molecules_nonbondedff.add(ions, MGIdx(0))
inter_ions_molecules_nonbondedff.add(molecules, MGIdx(1))
# Now solute bond, angle, dihedral energy
intrabondedff = Sire.MM.InternalFF("molecules-intrabonded")
intrabondedff.add(molecules)
# Now solute intramolecular CLJ energy
intranonbondedff = Sire.MM.IntraCLJFF("molecules-intranonbonded")
if cutoff_type.val != "nocutoff":
intranonbondedff.setUseReactionField(True)
intranonbondedff.setReactionFieldDielectric(rf_dielectric.val)
intranonbondedff.add(molecules)
# solute restraint energy
#
# We restrain atoms based ont he contents of the property "restrainedatoms"
#
restraintff = Sire.MM.RestraintFF("restraint")
if use_restraints.val:
molnums = molecules.molecules().molNums()
for molnum in molnums:
mol = molecules.molecule(molnum)[0].molecule()
try:
mol_restrained_atoms = propertyToAtomNumVectorList(
mol.property("restrainedatoms")
)
except UserWarning as error:
error_type = re.search(r"(Sire\w*::\w*)", str(error)).group(0)
if error_type == "SireBase::missing_property":
continue
else:
raise error
for restrained_line in mol_restrained_atoms:
atnum = restrained_line[0]
restraint_atom = mol.select(atnum)
restraint_coords = restrained_line[1]
restraint_k = (
restrained_line[2] * Sire.Units.kcal_per_mol /
(Sire.Units.angstrom * Sire.Units.angstrom)
)
restraint = Sire.MM.DistanceRestraint.harmonic(
restraint_atom, restraint_coords, restraint_k
)
restraintff.add(restraint)
# Here is the list of all forcefields
forcefields = [
internonbondedff,
intrabondedff,
intranonbondedff,
inter_ions_nonbondedff,
inter_ions_molecules_nonbondedff,
restraintff,
]
for forcefield in forcefields:
system.add(forcefield)
system.setProperty("space", space)
system.setProperty(
"switchingFunction", Sire.MM.CHARMMSwitchingFunction(cutoff_dist.val)
)
system.setProperty("combiningRules",
Sire.Base.VariantProperty(combining_rules.val))
total_nrg = (
internonbondedff.components().total()
+ intranonbondedff.components().total()
+ intrabondedff.components().total()
+ inter_ions_nonbondedff.components().total()
+ inter_ions_molecules_nonbondedff.components().total()
+ restraintff.components().total()
)
e_total = system.totalComponent()
system.setComponent(e_total, total_nrg)
# Add a monitor that calculates the average total energy and average energy
# deltas - we will collect both a mean average and an zwanzig average
system.add("total_energy",
Sire.System.MonitorComponent(e_total, Sire.Maths.Average()))
return system
def setupMoves(system, debug_seed, GPUS):
"""
No PME support here.
"""
print("Setting up moves...")
molecules = system[MGName("all")]
Integrator_OpenMM = Sire.Move.OpenMMMDIntegrator(molecules)
Integrator_OpenMM.setPlatform(platform.val)
Integrator_OpenMM.setConstraintType(constraint.val)
Integrator_OpenMM.setCutoffType(cutoff_type.val)
Integrator_OpenMM.setIntegrator(integrator_type.val)
Integrator_OpenMM.setFriction(
inverse_friction.val
) # Only meaningful for Langevin/Brownian integrators
Integrator_OpenMM.setPrecision(precision.val)
Integrator_OpenMM.setTimetoSkip(time_to_skip.val)
Integrator_OpenMM.setDeviceIndex(str(GPUS))
Integrator_OpenMM.setLJDispersion(lj_dispersion.val)
if cutoff_type.val != "nocutoff":
Integrator_OpenMM.setCutoffDistance(cutoff_dist.val)
if cutoff_type.val == "cutoffperiodic":
Integrator_OpenMM.setFieldDielectric(rf_dielectric.val)
Integrator_OpenMM.setCMMremovalFrequency(cmm_removal.val)
Integrator_OpenMM.setBufferFrequency(buffered_coords_freq.val)
if use_restraints.val:
Integrator_OpenMM.setRestraint(True)
if andersen.val:
Integrator_OpenMM.setTemperature(temperature.val)
Integrator_OpenMM.setAndersen(andersen.val)
Integrator_OpenMM.setAndersenFrequency(andersen_frequency.val)
if barostat.val:
Integrator_OpenMM.setPressure(pressure.val)
Integrator_OpenMM.setMCBarostat(barostat.val)
Integrator_OpenMM.setMCBarostatFrequency(barostat_frequency.val)
# print Integrator_OpenMM.getDeviceIndex()
Integrator_OpenMM.initialise()
mdmove = Sire.Move.MolecularDynamics(
molecules,
Integrator_OpenMM,
timestep.val,
{"velocity generator": Sire.Move.MaxwellBoltzmann(temperature.val)},
)
print("Created a MD move that uses OpenMM for all molecules on %s " % GPUS)
moves = Sire.Move.WeightedMoves()
moves.add(mdmove, 1)
# Choose a random seed for Sire if a debugging seed hasn't been set.
if debug_seed == 0:
seed = Sire.Maths.RanGenerator().randInt(100000, 1000000)
else:
seed = debug_seed
print("Using debugging seed number %d " % debug_seed)
moves.setGenerator(Sire.Maths.RanGenerator(seed))
return moves
def atomNumListToProperty(list):
prop = Sire.Base.Properties()
i = 0
for value in list:
prop.setProperty(str(i), Sire.Base.VariantProperty(value.value()))
i += 1
return prop
def atomNumVectorListToProperty(list):
prop = Sire.Base.Properties()
i = 0
for value in list:
prop.setProperty("AtomNum(%d)" % i,
Sire.Base.VariantProperty(value[0].value()))
prop.setProperty("x(%d)" % i, Sire.Base.VariantProperty(value[1].x()))
prop.setProperty("y(%d)" % i, Sire.Base.VariantProperty(value[1].y()))
prop.setProperty("z(%d)" % i, Sire.Base.VariantProperty(value[1].z()))
prop.setProperty("k(%d)" % i, Sire.Base.VariantProperty(value[2].val))
i += 1
prop.setProperty("nrestrainedatoms", Sire.Base.VariantProperty(i))
return prop
def linkbondVectorListToProperty(list):
prop = Sire.Base.Properties()
i = 0
for value in list:
prop.setProperty("AtomNum0(%d)" % i,
Sire.Base.VariantProperty(value[0]))
prop.setProperty("AtomNum1(%d)" % i,
Sire.Base.VariantProperty(value[1]))
prop.setProperty("reql(%d)" % i, Sire.Base.VariantProperty(value[2]))
prop.setProperty("kl(%d)" % i, Sire.Base.VariantProperty(value[3]))
prop.setProperty("dl(%d)" % i, Sire.Base.VariantProperty(value[4]))
i += 1
prop.setProperty("nbondlinks", Sire.Base.VariantProperty(i))
return prop
def propertyToAtomNumList(prop):
list = []
i = 0
try:
while True:
list.append(AtomNum(prop[str(i)].toInt()))
i += 1
except:
pass
return list
def propertyToAtomNumVectorList(prop):
list = []
i = 0
try:
while True:
num = AtomNum(prop["AtomNum(%d)" % i].toInt())
x = prop["x(%d)" % i].toDouble()
y = prop["y(%d)" % i].toDouble()
z = prop["z(%d)" % i].toDouble()
k = prop["k(%d)" % i].toDouble()
list.append((num, Sire.Maths.Vector(x, y, z), k))
i += 1
except:
pass
return list
def setupRestraints(system):
molecules = system[MGName("all")].molecules()
molnums = molecules.molNums()
for molnum in molnums:
mol = molecules.molecule(molnum)[0].molecule()
nats = mol.nAtoms()
atoms = mol.atoms()
restrainedAtoms = []
#
# This will apply a restraint to every atom that is
# A) NOT a hydrogen
# B) NOT in an unrestrained residue.
#
for x in range(0, nats):
at = atoms[x]
atnumber = at.number()
# print at, atnumber
if at.residue().name().value() in unrestrained_residues.val:
continue
# print at, at.property("mass"), heavyMass
if at.property("mass").value() < heavy_mass_restraint.val:
# print "LIGHT, skip"
continue
atcoords = at.property("coordinates")
# print at
restrainedAtoms.append((atnumber, atcoords, k_restraint))
# restrainedAtoms.append( atnumber )
if len(restrainedAtoms) > 0:
mol = (
mol.edit()
.setProperty(
"restrainedatoms",
atomNumVectorListToProperty(restrainedAtoms),
)
.commit()
)
system.update(mol)
return system
def setupDistanceRestraints(system, restraints=None):
prop_list = []
molecules = system[MGName("all")].molecules()
if restraints is None:
# dic_items = list(distance_restraints_dict.val.items())
dic_items = list(dict(distance_restraints_dict.val).items())
else:
dic_items = list(restraints.items())
molecules = system[MGName("all")].molecules()
moleculeNumbers = molecules.molNums()
for moleculeNumber in moleculeNumbers:
mol = molecules.molecule(moleculeNumber)[0].molecule()
atoms_mol = mol.atoms()
natoms_mol = mol.nAtoms()
for j in range(0, natoms_mol):
at = atoms_mol[j]
atnumber = at.number()
for k in range(len(dic_items)):
if dic_items[k][0][0] == dic_items[k][0][1]:
print(
"Error! It is not possible to place a distance "
"restraint on the same atom"
)
sys.exit(-1)
if atnumber.value() - 1 in dic_items[k][0]:
print(at)
# atom0index atom1index, reql, kl, dl
prop_list.append(
(
dic_items[k][0][0] + 1,
dic_items[k][0][1] + 1,
dic_items[k][1][0],
dic_items[k][1][1],
dic_items[k][1][2],
)
)
unique_prop_list = []
[unique_prop_list.append(item) for item in prop_list if item not in unique_prop_list]
print (unique_prop_list)
# The solute will store all the information related to the receptor-ligand restraints
solute = getSolute(system)
solute = solute.edit().setProperty("linkbonds", linkbondVectorListToProperty(unique_prop_list)).commit()
system.update(solute)
return system
def freezeResidues(system):
molecules = system[MGName("all")].molecules()
molnums = molecules.molNums()
for molnum in molnums:
mol = molecules.molecule(molnum)[0].molecule()
nats = mol.nAtoms()
atoms = mol.atoms()
for x in range(0, nats):