-
Notifications
You must be signed in to change notification settings - Fork 18
/
paprika.py
1676 lines (1376 loc) · 63.3 KB
/
paprika.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
"""
A collection of protocols for performing free energy calculations using
the pAPRika software package.
"""
import logging
import os
import os.path
import shutil
import traceback
import typing
from queue import Queue
from threading import Thread
import numpy as np
import parmed as pmd
import pint
from simtk.openmm import XmlSerializer
from simtk.openmm.app import PME, AmberPrmtopFile, HBonds, PDBFile
from openff.evaluator import unit
from openff.evaluator.attributes import UNDEFINED
from openff.evaluator.backends import ComputeResources
from openff.evaluator.forcefield import (
ForceFieldSource,
SmirnoffForceFieldSource,
TLeapForceFieldSource,
)
from openff.evaluator.protocols import (
coordinates,
forcefield,
groups,
miscellaneous,
openmm,
)
from openff.evaluator.substances import Component, Substance
from openff.evaluator.thermodynamics import Ensemble, ThermodynamicState
from openff.evaluator.utils.exceptions import EvaluatorException
from openff.evaluator.utils.openmm import pint_unit_to_openmm
from openff.evaluator.utils.utils import temporarily_change_directory
from openff.evaluator.workflow import Protocol, workflow_protocol
from openff.evaluator.workflow.attributes import (
InequalityMergeBehaviour,
InputAttribute,
OutputAttribute,
)
from openff.evaluator.workflow.utils import ProtocolPath
logger = logging.getLogger(__name__)
@workflow_protocol()
class BasePaprikaProtocol(Protocol):
"""A protocol which will setup and run a pAPRika host-guest
binding affinity calculation, starting from a host and guest
`taproom` style .yaml definition file.
"""
substance = InputAttribute(
docstring="The substance which defines the host, guest and solvent.",
type_hint=Substance,
default_value=UNDEFINED,
)
thermodynamic_state = InputAttribute(
docstring="The thermodynamic conditions to simulate under",
type_hint=ThermodynamicState,
default_value=UNDEFINED,
)
force_field_path = InputAttribute(
docstring="A path to the force field to use in the calculation.",
type_hint=str,
default_value=UNDEFINED,
)
water_model = InputAttribute(
docstring="The water model to use for the calculation. This is "
"temporarily treated as separate from the force field "
"until the two are better integrated.",
type_hint=forcefield.BaseBuildSystem.WaterModel,
default_value=forcefield.BaseBuildSystem.WaterModel.TIP3P,
)
taproom_host_name = InputAttribute(
docstring="The taproom three letter identifier of the host. This "
"is temporary until this protocol is decoupled from taproom.",
type_hint=str,
default_value=UNDEFINED,
)
taproom_guest_name = InputAttribute(
docstring="The taproom three letter identifier of the guest. This "
"is temporary until this protocol is decoupled from taproom.",
type_hint=typing.Union[str, None],
default_value=None,
)
taproom_guest_orientation = InputAttribute(
docstring="The taproom one letter identifier of the orientation of "
"the guest. This is temporary until this protocol is decoupled "
"from taproom.",
type_hint=typing.Union[str, None],
default_value=None,
)
thermalisation_timestep = InputAttribute(
docstring="The timestep to evolve the system during thermalisation "
"by at each step.",
type_hint=unit.Quantity,
merge_behavior=InequalityMergeBehaviour.SmallestValue,
default_value=1.0 * unit.femtosecond,
)
equilibration_timestep = InputAttribute(
docstring="The timestep to evolve the system by at each step.",
type_hint=unit.Quantity,
merge_behavior=InequalityMergeBehaviour.SmallestValue,
default_value=2.0 * unit.femtosecond,
)
production_timestep = InputAttribute(
docstring="The timestep to evolve the system by at each step.",
type_hint=unit.Quantity,
merge_behavior=InequalityMergeBehaviour.SmallestValue,
default_value=2.0 * unit.femtosecond,
)
number_of_thermalisation_steps = InputAttribute(
docstring="The number of NPT thermalisation steps to take. Data from "
"the equilibration simulations will be discarded.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=50000,
)
thermalisation_output_frequency = InputAttribute(
docstring="The frequency with which to write statistics during "
"thermalisation. Data from the thermalisation simulations "
"will be discarded.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=5000,
)
number_of_equilibration_steps = InputAttribute(
docstring="The number of NPT equilibration steps to take. Data from "
"the equilibration simulations will be discarded.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=200000,
)
equilibration_output_frequency = InputAttribute(
docstring="The frequency with which to write statistics during "
"equilibration. Data from the equilibration simulations "
"will be discarded.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=5000,
)
number_of_production_steps = InputAttribute(
docstring="The number of NPT production steps to take.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=1000000,
)
production_output_frequency = InputAttribute(
docstring="The frequency with which to write statistics during production.",
type_hint=int,
merge_behavior=InequalityMergeBehaviour.LargestValue,
default_value=5000,
)
number_of_solvent_molecules = InputAttribute(
docstring="The number of solvent molecules to solvate the host and guest with.",
type_hint=int,
default_value=3000,
)
packmol_tolerance = InputAttribute(
docstring="The distance tolerance for packing molecules in packmol.",
type_hint=unit.Quantity,
merge_behavior=InequalityMergeBehaviour.SmallestValue,
default_value=2.4 * unit.angstrom,
)
simulation_box_aspect_ratio = InputAttribute(
docstring="The aspect ratio of the box. This should be a list of three "
"floats, corresponding to the relative length of each side of "
"the box.",
type_hint=list,
default_value=[1.0, 1.0, 2.0],
)
hydrogen_mass = InputAttribute(
docstring="The mass of hydrogen atoms for the host and guest. This is variable is used for hydrogen mass repartitioning.",
type_hint=float,
merge_behavior=InequalityMergeBehaviour.SmallestValue,
default_value=1.008,
)
attach_free_energy = OutputAttribute(
docstring="The free energy of...", type_hint=pint.Measurement
)
pull_free_energy = OutputAttribute(
docstring="The free energy of...", type_hint=pint.Measurement
)
release_free_energy = OutputAttribute(
docstring="The free energy of...", type_hint=pint.Measurement
)
symmetry_correction = OutputAttribute(
docstring="The free energy of...", type_hint=pint.Measurement
)
reference_free_energy = OutputAttribute(
docstring="The free energy of...", type_hint=pint.Measurement
)
def __init__(self, protocol_id):
"""Initializes a new BasePaprikaProtocol object.
"""
super().__init__(protocol_id)
self._force_field_source = None
self._paprika_setup = None
self._solvated_coordinate_paths = {}
self._results_dictionary = None
# Useful debug variables for either enabling or disabling parts of
# this protocol.
self.setup = True
self.simulate = True
self.analyze = True
def _setup_paprika(self, directory):
import paprika
generate_gaff_files = isinstance(
self._force_field_source, TLeapForceFieldSource
)
gaff_version = "gaff2"
if generate_gaff_files:
gaff_version = self._force_field_source.leap_source.replace("leaprc.", "")
self._paprika_setup = paprika.Setup(
host=self.taproom_host_name,
guest=self.taproom_guest_name,
guest_orientation=self.taproom_guest_orientation,
directory_path=directory,
generate_gaff_files=generate_gaff_files,
gaff_version=gaff_version,
)
def _solvate_windows(self, directory, available_resources):
# Extract out only the solvent components of the substance (e.g H2O,
# Na+, Cl-...)
filter_solvent = miscellaneous.FilterSubstanceByRole("filter_solvent")
filter_solvent.input_substance = self.substance
filter_solvent.component_roles = [Component.Role.Solvent]
filter_solvent.execute(directory, available_resources)
reference_structure_path = None
for index, window_file_path in enumerate(
self._paprika_setup.desolvated_window_paths
):
window_directory = os.path.dirname(window_file_path)
os.makedirs(window_directory, exist_ok=True)
self._solvated_coordinate_paths[index] = os.path.join(
window_directory, "restrained.pdb"
)
if os.path.isfile(self._solvated_coordinate_paths[index]):
logger.info(
f"Skipping the setup of window {index + 1} as "
f"{self._solvated_coordinate_paths[index]} already "
f"exists."
)
continue
# Solvate the window.
solvate_complex = coordinates.SolvateExistingStructure("solvate_window")
solvate_complex.max_molecules = self.number_of_solvent_molecules
solvate_complex.box_aspect_ratio = self.simulation_box_aspect_ratio
solvate_complex.tolerance = self.packmol_tolerance
solvate_complex.center_solute_in_box = False
if self.number_of_solvent_molecules < 20:
solvate_complex.mass_density = 0.005 * unit.grams / unit.milliliters
solvate_complex.substance = filter_solvent.filtered_substance
solvate_complex.solute_coordinate_file = window_file_path
solvate_complex.execute(window_directory, available_resources)
# Store the path to the structure of the first window, which will
# serve as a reference point when adding the dummy atoms.
if index == 0:
reference_structure_path = solvate_complex.coordinate_file_path
# Add the aligning dummy atoms to the solvated pdb files.
self._add_dummy_atoms(
index, solvate_complex.coordinate_file_path, reference_structure_path
)
# Extra step to create GAFF1/2 structures properly
if isinstance(self._force_field_source, TLeapForceFieldSource):
# Fix atom names of guest molecule for Tleap processing
if self._paprika_setup.guest is self.taproom_guest_name:
gaff_version = self._force_field_source.leap_source.replace(
"leaprc.", ""
)
structure_mol = pmd.load_file(
os.path.join(
window_directory[: len(window_directory) - 13],
f"{self._paprika_setup.guest}.{gaff_version}.mol2",
)
)
structure_pdb = pmd.load_file(
self._solvated_coordinate_paths[index]
)
# Get atom names of guest molecule from restrained.pdb and *.gaff.mol2
mol_name = []
pdb_name = []
for original, guest in zip(
structure_mol,
structure_pdb[f":{self._paprika_setup.guest.upper()}"],
):
mol_name.append(original.name)
pdb_name.append(guest.name)
# Change guest atom names of restrained.pdb to that of *.gaff.mol2
fin = open(self._solvated_coordinate_paths[index], "r")
pdb_lines = fin.readlines()
i_atom = 0
i_file = 0
for line in pdb_lines:
if line.startswith("HETATM"):
if (
line.split()[3].upper()
== f"{self._paprika_setup.guest.upper()}"
):
if len(pdb_name[i_atom]) - len(mol_name[i_atom]) == 2:
pdb_lines[i_file] = line.replace(
pdb_name[i_atom], " " + mol_name[i_atom] + " "
)
elif len(pdb_name[i_atom]) - len(mol_name[i_atom]) == 1:
pdb_lines[i_file] = line.replace(
pdb_name[i_atom], " " + mol_name[i_atom]
)
elif len(pdb_name[i_atom]) < len(mol_name[i_atom]):
pdb_lines[i_file] = line.replace(
pdb_name[i_atom] + " ", mol_name[i_atom]
)
else:
pdb_lines[i_file] = line.replace(
pdb_name[i_atom], mol_name[i_atom]
)
i_atom += 1
i_file += 1
fin.close()
# Overwrite restrained.pdb with the correct guest atom names
fout = open(self._solvated_coordinate_paths[index], "w")
for line in pdb_lines:
fout.writelines(line)
fout.close()
# Extract water and ions from restrained.pdb
structure = pmd.load_file(
self._solvated_coordinate_paths[index], structure=True
)
water_ions_sel = f"!(@DUM,:MGO,:{self._paprika_setup.guest.upper()})"
structure[water_ions_sel].save(
os.path.join(window_directory, "water_ions.pdb"),
)
# Create *.mol2 file for water and ions
from paprika.tleap import System
system = System()
system.output_path = window_directory
system.pbc_type = None
system.neutralize = False
system.template_lines = [
f"source leaprc.water.tip3p",
f"HOH = loadpdb water_ions.pdb",
f"savemol2 HOH water_ions.mol2 1",
f"quit",
]
system.build()
# Delete water_ions.pdb
os.remove(os.path.join(window_directory, "water_ions.pdb"))
logger.info(
f"Set up window {index + 1} of "
f"{len(self._paprika_setup.desolvated_window_paths)}"
)
def _add_dummy_atoms(
self, index, solvated_structure_path, reference_structure_path
):
self._paprika_setup.add_dummy_atoms(
reference_structure_path,
solvated_structure_path,
None,
self._solvated_coordinate_paths[index],
None,
)
def _apply_restraint_masks(self, use_amber_indices):
from paprika.utils import index_from_mask
for index, window in enumerate(self._paprika_setup.window_list):
window_directory = os.path.join(
self._paprika_setup.directory, "windows", window
)
build_pdb_file = pmd.load_file(
os.path.join(window_directory, "structure.pdb"), structure=True
)
for restraint in (
self._paprika_setup.static_restraints
+ self._paprika_setup.conformational_restraints
+ self._paprika_setup.symmetry_restraints
+ self._paprika_setup.wall_restraints
+ self._paprika_setup.guest_restraints
):
restraint.index1 = index_from_mask(
build_pdb_file, restraint.mask1, use_amber_indices
)
restraint.index2 = index_from_mask(
build_pdb_file, restraint.mask2, use_amber_indices
)
if restraint.mask3:
restraint.index3 = index_from_mask(
build_pdb_file, restraint.mask3, use_amber_indices
)
if restraint.mask4:
restraint.index4 = index_from_mask(
build_pdb_file, restraint.mask4, use_amber_indices
)
def _setup_restraints(self):
(
self._paprika_setup.static_restraints,
self._paprika_setup.conformational_restraints,
self._paprika_setup.symmetry_restraints,
self._paprika_setup.wall_restraints,
self._paprika_setup.guest_restraints,
) = self._paprika_setup.initialize_restraints(
self._solvated_coordinate_paths[0]
)
def _apply_parameters(self):
if not isinstance(self._force_field_source, TLeapForceFieldSource):
# Due to the OpenFF toolkit's lack of support for dummy particles we
# assign the SMIRNOFF parameters while adding the dummy particules,
# so we can skip this step.
return
for index, window_file_path in enumerate(
self._paprika_setup.desolvated_window_paths
):
window_directory = os.path.dirname(window_file_path)
self._build_amber_parameters(index, window_directory)
@staticmethod
def _create_dummy_files(directory):
dummy_frcmod_lines = [
"Parameters for dummy atom with type Du\n",
"MASS\n",
"Du 208.00\n",
"\n",
"BOND\n",
"\n",
"ANGLE\n",
"\n",
"DIHE\n",
"\n",
"IMPROPER\n",
"\n",
"NONBON\n",
" Du 0.000 0.0000000\n",
]
with open(os.path.join(directory, "dummy.frcmod"), "w") as file:
file.writelines(dummy_frcmod_lines)
dummy_mol2_template = (
"@<TRIPOS>MOLECULE\n"
"{0:s}\n"
" 1 0 1 0 1\n"
"SMALL\n"
"USER_CHARGES\n"
"\n"
"@<TRIPOS>ATOM\n"
" 1 DUM 0.000000 0.000000 0.000000 Du 1 {0:s} 0.0000 ****\n"
"@<TRIPOS>BOND\n"
"@<TRIPOS>SUBSTRUCTURE\n"
" 1 {0:s} 1 **** 0 **** **** 0 ROOT\n"
)
for dummy_name in ["DM1", "DM2", "DM3"]:
with open(
os.path.join(directory, f"{dummy_name.lower()}.mol2"), "w"
) as file:
file.write(dummy_mol2_template.format(dummy_name))
def _build_amber_parameters(self, index, window_directory):
from paprika.tleap import System
window_directory_to_base = os.path.relpath(
os.path.abspath(self._paprika_setup.directory), window_directory
)
window_coordinates = os.path.relpath(
self._solvated_coordinate_paths[index], window_directory
)
self._create_dummy_files(self._paprika_setup.directory)
os.makedirs(window_directory, exist_ok=True)
system = System()
system.output_path = window_directory
system.output_prefix = "structure"
system.pbc_type = None
system.neutralize = False
gaff_version = self._force_field_source.leap_source.replace("leaprc.", "")
# Host definition
host_frcmod = os.path.join(
window_directory_to_base,
f"{self._paprika_setup.host}.{gaff_version}.frcmod",
)
host_mol2 = os.path.join(
window_directory_to_base, f"{self._paprika_setup.host}.{gaff_version}.mol2"
)
load_host_frcmod = f"loadamberparams {host_frcmod}"
load_host_mol2 = (
f'{self._paprika_setup.host_yaml["resname"].upper()} = loadmol2 {host_mol2}'
)
load_host_def = [
load_host_mol2,
'set MGO name "MGO"',
"set MGO head MGO.1.C4",
"set MGO tail MGO.1.O1",
"set MGO.1 connect0 MGO.1.C4",
"set MGO.1 connect1 MGO.1.O1",
"set MGO.1 restype saccharide",
'set MGO.1 name "MGO"',
]
load_host_chain = ""
model_bond = ""
if self._paprika_setup.host.lower() == "acd":
load_host_chain = [
"ACDOH = sequence {MGO MGO MGO MGO MGO MGO MGO}",
"set ACDOH head ACDOH.1.C4",
"set ACDOH tail ACDOH.6.O1",
"impose ACDOH {1 2 3 4 5 6} {{O5 C1 O1 C4 90.0} {C1 O1 C4 C5 -95.0}}",
"bond ACDOH.1.C4 ACDOH.6.O1",
]
model_bond = "bond model.1.C4 model.6.O1"
elif self._paprika_setup.host.lower() == "bcd":
load_host_chain = [
"BCDOH = sequence {MGO MGO MGO MGO MGO MGO MGO MGO}",
"set BCDOH head BCDOH.1.C4",
"set BCDOH tail BCDOH.7.O1",
"impose BCDOH {1 2 3 4 5 6 7} {{O5 C1 O1 C4 98.0} {C1 O1 C4 C5 -103.0}}",
"bond BCDOH.1.C4 BCDOH.7.O1",
]
model_bond = "bond model.1.C4 model.7.O1"
# Solvent definition
load_solvent_mol2 = f"SOL = loadmol2 water_ions.mol2"
# Guest definition
load_guest_frcmod = ""
load_guest_mol2 = ""
if self.taproom_guest_name is not None:
guest_frcmod = os.path.join(
window_directory_to_base,
f"{self._paprika_setup.guest}.{gaff_version}.frcmod",
)
guest_mol2 = os.path.join(
window_directory_to_base,
f"{self._paprika_setup.guest}.{gaff_version}.mol2",
)
load_guest_frcmod = f"loadamberparams {guest_frcmod}"
load_guest_mol2 = f'{self._paprika_setup.guest_yaml["name"].upper()} = loadmol2 {guest_mol2}'
# window_pdb_file = PDBFile(self._solvated_coordinate_paths[index])
# cell_vectors = window_pdb_file.topology.getPeriodicBoxVectors()
force_field_lines = [
f"source leaprc.{gaff_version}",
f"source leaprc.water.tip3p",
f"source leaprc.protein.ff14SB",
load_host_frcmod,
load_guest_frcmod,
f"loadamberparams {os.path.join(window_directory_to_base, 'dummy.frcmod')}",
]
host_def_lines = load_host_def + load_host_chain
hetatom_lines = [
load_guest_mol2,
load_solvent_mol2,
f"DM1 = loadmol2 {os.path.join(window_directory_to_base, 'dm1.mol2')}",
f"DM2 = loadmol2 {os.path.join(window_directory_to_base, 'dm2.mol2')}",
f"DM3 = loadmol2 {os.path.join(window_directory_to_base, 'dm3.mol2')}",
]
model_lines = [
f"model = loadpdb {window_coordinates}",
model_bond,
f'setBox model "centers"',
"check model",
]
system.template_lines = (
force_field_lines + host_def_lines + hetatom_lines + model_lines
)
system.build()
# HMR
if self.hydrogen_mass > 1.008:
system.repartition_hydrogen_mass(options=f"{self.hydrogen_mass}")
# Delete water_ions.mol2
os.remove(os.path.join(window_directory, "water_ions.mol2"))
def _run_windows(self, available_resources):
# Create the queue which will pass the run arguments to the created
# threads.
queue = Queue(maxsize=0)
chunk_size = max(1, available_resources.number_of_gpus)
# Start the threads.
for _ in range(chunk_size):
worker = Thread(target=self._run_window, args=(queue,))
worker.setDaemon(True)
worker.start()
exceptions = []
window_indices = [
index for index in range(len(self._paprika_setup.window_list))
]
# Determine how many 'chunks' to break the full window list into depending
# on the available compute resources.
full_multiples = int(np.floor(len(window_indices) / chunk_size))
chunks = [
[i * chunk_size, (i + 1) * chunk_size] for i in range(full_multiples)
] + [[full_multiples * chunk_size, len(window_indices)]]
counter = 0
for chunk in chunks:
for window_index in sorted(window_indices)[chunk[0] : chunk[1]]:
logger.info(
f"Running window {window_index + 1} out of {len(self._paprika_setup.window_list)}"
)
resources = ComputeResources(number_of_threads=1)
if available_resources.number_of_gpus > 0:
resources = ComputeResources(
number_of_threads=1,
number_of_gpus=1,
preferred_gpu_toolkit=ComputeResources.GPUToolkit.CUDA,
)
resources._gpu_device_indices = f"{counter}"
self._enqueue_window(queue, window_index, resources, exceptions)
counter += 1
if counter == chunk_size:
queue.join()
counter = 0
if len(exceptions) > 0:
message = ", ".join(
[f"{exception.message}" for exception in exceptions]
)
raise RuntimeError(message)
if not queue.empty():
queue.join()
if len(exceptions) > 0:
message = ", ".join([f"{exception.message}" for exception in exceptions])
raise RuntimeError(message)
return None
def _enqueue_window(self, queue, index, available_resources, exceptions):
raise NotImplementedError()
@staticmethod
def _run_window(queue):
raise NotImplementedError()
def _perform_analysis(self, directory):
if self._results_dictionary is None:
raise ValueError("The results dictionary is empty.")
if "attach" in self._results_dictionary:
self.attach_free_energy = unit.Measurement(
-self._results_dictionary["attach"]["ti-block"]["fe"]
* unit.kilocalorie
/ unit.mole,
self._results_dictionary["attach"]["ti-block"]["sem"]
* unit.kilocalorie
/ unit.mole,
)
if "pull" in self._results_dictionary:
self.pull_free_energy = unit.Measurement(
-self._results_dictionary["pull"]["ti-block"]["fe"]
* unit.kilocalorie
/ unit.mole,
self._results_dictionary["pull"]["ti-block"]["sem"]
* unit.kilocalorie
/ unit.mole,
)
if "release" in self._results_dictionary:
self.release_free_energy = unit.Measurement(
self._results_dictionary["release"]["ti-block"]["fe"]
* unit.kilocalorie
/ unit.mole,
self._results_dictionary["release"]["ti-block"]["sem"]
* unit.kilocalorie
/ unit.mole,
)
if "ref_state_work" in self._results_dictionary:
self.reference_free_energy = unit.Measurement(
-self._results_dictionary["ref_state_work"]
* unit.kilocalorie
/ unit.mole,
0 * unit.kilocalorie / unit.mole,
)
if "symmetry_correction" in self._results_dictionary:
self.symmetry_correction = unit.Measurement(
self._results_dictionary["symmetry_correction"]
* unit.kilocalorie
/ unit.mole,
0 * unit.kilocalorie / unit.mole,
)
return None
def _setup(self, directory, available_resources):
from paprika.io import save_restraints
# Create a new setup object which will load in a pAPRika host
# and guest yaml file, setup a directory structure for the
# paprika calculations, and create a set of coordinates for
# each of the windows along the pathway (without any solvent).
self._setup_paprika(directory)
# Define where the final restraints definition file should be written
restraints_path = os.path.join(self._paprika_setup.directory, "restraints.json")
if os.path.isfile(restraints_path):
# We can skip setup if the restraints file already exists as this is the
# last step of setup.
return
# Solvate each of the structures along the calculation path.
self._solvate_windows(directory, available_resources)
if len(self._solvated_coordinate_paths) == 0:
raise RuntimeError(
"There were no defined windows to a/p/r the guest along.",
)
# Apply parameters to each of the windows.
self._apply_parameters()
# Setup the actual restraints.
self._setup_restraints()
# Save the restraints to a file, ready for analysis.
save_restraints(
restraint_list=self._paprika_setup.static_restraints
+ self._paprika_setup.conformational_restraints
+ self._paprika_setup.symmetry_restraints
+ self._paprika_setup.wall_restraints
+ self._paprika_setup.guest_restraints,
filepath=restraints_path,
)
def _simulate(self, directory, available_resources):
import paprika
if not self._paprika_setup:
self._paprika_setup = paprika.setup(
host=self.taproom_host_name,
guest=self.taproom_guest_name,
guest_orientation=self.taproom_guest_orientation,
build=False,
directory_path=directory,
)
base_path = os.path.join(
directory,
self._paprika_setup.host,
f"{self._paprika_setup.guest}-{self.taproom_guest_orientation}"
if self._paprika_setup.guest
else "",
"windows",
)
window_directories = [
os.path.join(base_path, window)
for window in self._paprika_setup.window_list
]
else:
window_directories = [
os.path.dirname(window_path)
for window_path in self._paprika_setup.desolvated_window_paths
]
for index, window_directory in enumerate(window_directories):
self._solvated_coordinate_paths[index] = os.path.join(
window_directory, "restrained.pdb"
)
self._solvated_system_xml_paths[index] = os.path.join(
window_directory, "restrained.xml"
)
if not os.path.isfile(self._solvated_coordinate_paths[index]):
raise RuntimeError(
f"The {self._solvated_coordinate_paths[index]} file "
f"does not exist. Make sure setup ran successfully.",
)
if not os.path.isfile(self._solvated_system_xml_paths[index]):
raise RuntimeError(
f"The {self._solvated_system_xml_paths[index]} file "
f"does not exist. Make sure setup ran successfully.",
)
# HMR
if self.hydrogen_mass > 1.008:
# Load 'restrained.xml' and 'restrained.pdb'
with open(self._solvated_system_xml_paths[index], "r") as file:
system = XmlSerializer.deserialize(file.read())
structure = pmd.load_file(
self._solvated_coordinate_paths[index], structure=True
)
# Repartition masses
for bond in structure.bonds:
if (
bond.atom1.residue.name != "HOH"
or bond.atom2.residue.name != "HOH"
):
if bond.atom1.element == 1:
(bond.atom1, bond.atom2) = (bond.atom2, bond.atom1)
if bond.atom2.element == 1 and bond.atom1.element != 1:
transfer_mass = self.hydrogen_mass - system.getParticleMass(
bond.atom2.idx
) / pint_unit_to_openmm(unit.dalton)
system.setParticleMass(bond.atom2.idx, self.hydrogen_mass)
system.setParticleMass(
bond.atom1.idx,
system.getParticleMass(bond.atom1.idx)
/ pint_unit_to_openmm(unit.dalton)
- transfer_mass,
)
# Overwrite 'restrained.xml' with modified masses
system_xml = XmlSerializer.serialize(system)
with open(self._solvated_system_xml_paths[index], "w") as file:
file.write(system_xml)
# Run the simulations
self._run_windows(available_resources)
def _analyse(self, directory):
import paprika
if not self._paprika_setup:
self._paprika_setup = paprika.setup(
host=self.taproom_host_name,
guest=self.taproom_guest_name,
guest_orientation=self.taproom_guest_orientation,
build=False,
directory_path=directory,
)
# Finally, do the analysis to extract the free energy of binding.
self._perform_analysis(directory)
def _execute(self, directory, available_resources):
# Make sure the available resources are commensurate with the
# implemented parallelisation scheme.
if (
available_resources.number_of_gpus > 0
and available_resources.number_of_gpus
!= available_resources.number_of_threads
):
raise RuntimeError(
"The number of available CPUs must match the number"
"of available GPUs for this parallelisation scheme.",
)
# Load in the force field to use.
with open(self.force_field_path) as file:
self._force_field_source = ForceFieldSource.parse_json(file.read())
if not isinstance(
self._force_field_source, SmirnoffForceFieldSource
) and not isinstance(self._force_field_source, TLeapForceFieldSource):
raise RuntimeError(
"Only SMIRNOFF and TLeap based force fields may "
"be used with this protocol.",
)
with temporarily_change_directory(directory):
original_force_field_path = self.force_field_path
self.force_field_path = os.path.relpath(
original_force_field_path, directory
)
if self.setup:
self._setup("", available_resources)
if self.simulate:
self._simulate("", available_resources)
if self.analyze:
self._analyse("")
self.force_field_path = original_force_field_path
@workflow_protocol()
class OpenMMPaprikaProtocol(BasePaprikaProtocol):
"""A protocol which will setup and run a pAPRika host-guest
binding affinity calculation using OpenMM, starting from a
host and guest `taproom` style .yaml definition file.
"""
def __init__(self, protocol_id):
super().__init__(protocol_id)
self._solvated_system_xml_paths = {}
def _add_dummy_atoms(
self, index, solvated_structure_path, reference_structure_path
):
# We pull the host charges from the specified mol2 file.
host_mol2_path = str(
self._paprika_setup.benchmark_path.joinpath(
self._paprika_setup.host_yaml["structure"]
)
)
window_directory = os.path.dirname(solvated_structure_path)
unrestrained_xml_path = None
self._solvated_system_xml_paths[index] = os.path.join(