-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathhybridtop_units.py
More file actions
1668 lines (1476 loc) · 61.3 KB
/
hybridtop_units.py
File metadata and controls
1668 lines (1476 loc) · 61.3 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
# This code is part of OpenFE and is licensed under the MIT license.
# For details, see https://github.com/OpenFreeEnergy/openfe
"""
ProtocolUnits for Hybrid Topology methods using OpenMM and OpenMMTools in a
Perses-like manner.
Acknowledgements
----------------
These ProtocolUnits are based on, and leverage components originating from
the Perses toolkit (https://github.com/choderalab/perses).
"""
import logging
import os
import pathlib
import subprocess
from itertools import chain
from typing import Any
import gufe
import matplotlib.pyplot as plt
import mdtraj
import numpy as np
import numpy.typing as npt
import openmm
import openmmtools
from gufe import (
ChemicalSystem,
Component,
LigandAtomMapping,
ProteinComponent,
SmallMoleculeComponent,
SolventComponent,
)
from gufe.protocols.errors import ProtocolUnitExecutionError
from gufe.settings import (
SettingsBaseModel,
ThermoSettings,
)
from openff.toolkit.topology import Molecule as OFFMolecule
from openff.units import Quantity
from openff.units import unit as offunit
from openff.units.openmm import ensure_quantity, from_openmm, to_openmm
from openmmforcefields.generators import SystemGenerator
from openmmtools import multistate
import openfe
from openfe.protocols.openmm_utils.omm_settings import (
BasePartialChargeSettings,
)
from ...analysis import plotting
from ...utils import log_system_probe, without_oechem_backend
from ..openmm_utils import (
charge_generation,
multistate_analysis,
omm_compute,
settings_validation,
system_creation,
system_validation,
)
from ..openmm_utils.serialization import (
deserialize,
serialize,
)
from . import _rfe_utils
from ._rfe_utils.relative import HybridTopologyFactory
from .equil_rfe_settings import (
AlchemicalSettings,
IntegratorSettings,
LambdaSettings,
MultiStateOutputSettings,
MultiStateSimulationSettings,
OpenFFPartialChargeSettings,
OpenMMEngineSettings,
OpenMMSolvationSettings,
RelativeHybridTopologyProtocolSettings,
)
logger = logging.getLogger(__name__)
class HybridTopologyUnitMixin:
def _prepare(
self,
verbose: bool,
scratch_basepath: pathlib.Path | None,
shared_basepath: pathlib.Path | None,
):
"""
Set basepaths and do some initial logging.
Parameters
----------
verbose : bool
Verbose output of the simulation progress. Output is provided at the
INFO level logging.
scratch_basepath : pathlib.Path | None
Optional scratch base path to write scratch files to.
shared_basepath : pathlib.Path | None
Optional shared base path to write shared files to.
"""
self.verbose = verbose
if self.verbose:
self.logger.info("Setting up the hybrid topology simulation") # type: ignore[attr-defined]
# set basepaths
def _set_optional_path(basepath):
if basepath is None:
return pathlib.Path(".")
return basepath
self.scratch_basepath = _set_optional_path(scratch_basepath)
self.shared_basepath = _set_optional_path(shared_basepath)
@staticmethod
def _get_settings(
settings: RelativeHybridTopologyProtocolSettings,
) -> dict[str, SettingsBaseModel]:
"""
Get a dictionary of Protocol settings.
Returns
-------
protocol_settings : dict[str, SettingsBaseModel]
Notes
-----
We return a dict so that we can duck type behaviour between phases.
For example subclasses may contain both `solvent` and `complex`
settings, using this approach we can extract the relevant entry
to the same key and pass it to other methods in a seamless manner.
"""
protocol_settings: dict[str, SettingsBaseModel] = {}
protocol_settings["forcefield_settings"] = settings.forcefield_settings
protocol_settings["thermo_settings"] = settings.thermo_settings
protocol_settings["alchemical_settings"] = settings.alchemical_settings
protocol_settings["lambda_settings"] = settings.lambda_settings
protocol_settings["charge_settings"] = settings.partial_charge_settings
protocol_settings["solvation_settings"] = settings.solvation_settings
protocol_settings["simulation_settings"] = settings.simulation_settings
protocol_settings["output_settings"] = settings.output_settings
protocol_settings["integrator_settings"] = settings.integrator_settings
protocol_settings["engine_settings"] = settings.engine_settings
return protocol_settings
@staticmethod
def _verify_execution_environment(
setup_outputs: dict[str, Any],
) -> None:
"""
Check that the Python environment hasn't changed based on the
relevant Python library versions stored in the setup outputs.
"""
try:
if (
(gufe.__version__ != setup_outputs["gufe_version"])
or (openfe.__version__ != setup_outputs["openfe_version"])
or (openmm.__version__ != setup_outputs["openmm_version"])
):
errmsg = "Python environment has changed, cannot continue Protocol execution."
raise ProtocolUnitExecutionError(errmsg)
except KeyError:
errmsg = "Missing environment information from setup outputs."
raise ProtocolUnitExecutionError(errmsg)
class HybridTopologySetupUnit(gufe.ProtocolUnit, HybridTopologyUnitMixin):
"""
Setup unit for Hybrid Topology Protocol transformations.
"""
@staticmethod
def _get_components(
stateA: ChemicalSystem, stateB: ChemicalSystem
) -> tuple[SolventComponent, ProteinComponent, dict[SmallMoleculeComponent, OFFMolecule]]:
"""
Get the components from the ChemicalSystem inputs.
Parameters
----------
stateA : ChemicalSystem
ChemicalSystem defining the state A components.
stateB : CHemicalSystem
ChemicalSystem defining the state B components.
Returns
-------
solv_comp : SolventComponent
The solvent component.
protein_comp : ProteinComponent
The protein component.
small_mols : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
Dictionary of small molecule components paired
with their OpenFF Molecule.
"""
solvent_comp, protein_comp, smcs_A = system_validation.get_components(stateA)
_, _, smcs_B = system_validation.get_components(stateB)
small_mols = {m: m.to_openff() for m in set(smcs_A).union(set(smcs_B))}
return solvent_comp, protein_comp, small_mols
@staticmethod
def _assign_partial_charges(
charge_settings: OpenFFPartialChargeSettings,
small_mols: dict[SmallMoleculeComponent, OFFMolecule],
) -> None:
"""
Assign partial charges to the OpenFF Molecules associated with all
the SmallMoleculeComponents in the transformation.
Parameters
----------
charge_settings : OpenFFPartialChargeSettings
Settings for controlling how the partial charges are assigned.
small_mols : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
Dictionary of OpenFF Molecules to add, keyed by
their associated SmallMoleculeComponent.
"""
for smc, mol in small_mols.items():
charge_generation.assign_offmol_partial_charges(
offmol=mol,
overwrite=False,
method=charge_settings.partial_charge_method,
toolkit_backend=charge_settings.off_toolkit_backend,
generate_n_conformers=charge_settings.number_of_conformers,
nagl_model=charge_settings.nagl_model,
)
@staticmethod
def _get_system_generator(
settings: dict[str, SettingsBaseModel],
solvent_component: SolventComponent | None,
openff_molecules: list[OFFMolecule] | None,
ffcache: pathlib.Path | None,
) -> SystemGenerator:
"""
Get an OpenMM SystemGenerator.
Parameters
----------
settings : dict[str, SettingsBaseModel]
A dictionary of protocol settings.
solvent_component : SolventComponent | None
The solvent component of the system, if any.
openff_molecules : list[openff.toolkit.Molecule] | None
A list of openff molecules to generate templates for, if any.
ffcache : pathlib.Path | None
Path to the force field parameter cache.
Returns
-------
system_generator : openmmtools.SystemGenerator
The SystemGenerator for the protocol.
"""
system_generator = system_creation.get_system_generator(
forcefield_settings=settings["forcefield_settings"],
integrator_settings=settings["integrator_settings"],
thermo_settings=settings["thermo_settings"],
cache=ffcache,
has_solvent=solvent_component is not None,
)
# Handle openff Molecule templates
# TODO: revisit this once the SystemGenerator update happens
# and we start loading the whole protein into OpenFF Topologies
if openff_molecules is None:
return system_generator
# Register all the templates, pass unique molecules to avoid clashes
system_generator.add_molecules(list(set(openff_molecules)))
return system_generator
@staticmethod
def _create_stateA_system(
small_mols: dict[SmallMoleculeComponent, OFFMolecule],
protein_component: ProteinComponent | None,
solvent_component: SolventComponent | None,
system_generator: SystemGenerator,
solvation_settings: OpenMMSolvationSettings,
) -> tuple[
openmm.System, openmm.app.Topology, openmm.unit.Quantity, dict[Component, npt.NDArray]
]:
"""
Create an OpenMM System for state A.
Parameters
----------
small_mols : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
A list of small molecules to include in the System.
protein_component : ProteinComponent | None
Optionally, the protein component to include in the System.
solvent_component : SolventComponent | None
Optionally, the solvent component to include in the System.
system_generator : SystemGenerator
The SystemGenerator object ot use to construct the System.
solvation_settings : OpenMMSolvationSettings
Settings defining how to build the System.
Returns
-------
system : openmm.System
The System that defines state A.
topology : openmm.app.Topology
The Topology defining the returned System.
positions : openmm.unit.Quantity
The positions of the particles in the System.
comp_residues : dict[Component, npt.NDArray]
A dictionary defining which residues in the System
belong to which ChemicalSystem Component.
"""
modeller, comp_resids = system_creation.get_omm_modeller(
protein_comp=protein_component,
solvent_comp=solvent_component,
small_mols=small_mols,
omm_forcefield=system_generator.forcefield,
solvent_settings=solvation_settings,
)
topology = modeller.getTopology()
# Note: roundtrip positions to remove vec3 issues
positions = to_openmm(from_openmm(modeller.getPositions()))
system = system_generator.create_system(
modeller.topology,
molecules=list(small_mols.values()),
)
return system, topology, positions, comp_resids
@staticmethod
def _create_stateB_system(
small_mols: dict[SmallMoleculeComponent, OFFMolecule],
mapping: LigandAtomMapping,
stateA_topology: openmm.app.Topology,
exclude_resids: npt.NDArray,
system_generator: SystemGenerator,
) -> tuple[openmm.System, openmm.app.Topology, npt.NDArray]:
"""
Create the state B System from the state A Topology.
Parameters
----------
small_mols : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
Dictionary of OpenFF Molecules keyed by SmallMoleculeComponent
to be present in system B.
mapping : LigandAtomMapping
LigandAtomMapping defining the correspondance betwee state A
and B's alchemical ligand.
stateA_topology : openmm.app.Topology
The OpenMM topology for state A.
exclude_resids : npt.NDArray
A list of residues to exclude from state A when building state B.
system_generator : SystemGenerator
The SystemGenerator to use to build System B.
Returns
-------
system : openmm.System
The state B System.
topology : openmm.app.Topology
The OpenMM Topology associated with the state B System.
alchem_resids : npt.NDArray
The residue indices of the state B alchemical species.
"""
topology, alchem_resids = _rfe_utils.topologyhelpers.combined_topology(
topology1=stateA_topology,
topology2=small_mols[mapping.componentB].to_topology().to_openmm(),
exclude_resids=exclude_resids,
)
system = system_generator.create_system(
topology,
molecules=list(small_mols.values()),
)
return system, topology, alchem_resids
@staticmethod
def _handle_net_charge(
stateA_topology: openmm.app.Topology,
stateA_positions: openmm.unit.Quantity,
stateB_topology: openmm.app.Topology,
stateB_system: openmm.System,
charge_difference: int,
system_mappings: dict[str, dict[int, int]],
distance_cutoff: Quantity,
solvent_component: SolventComponent | None,
) -> None:
"""
Handle system net charge by adding an alchemical water.
Parameters
----------
stateA_topology : openmm.app.Topology
stateA_positions : openmm.unit.Quantity
stateB_topology : openmm.app.Topology
stateB_system : openmm.System
charge_difference : int
system_mappings : dict[str, dict[int, int]]
distance_cutoff : Quantity
solvent_component : SolventComponent | None
"""
# Base case, return if no net charge
if charge_difference == 0:
return
# Get the residue ids for waters to turn alchemical
alchem_water_resids = _rfe_utils.topologyhelpers.get_alchemical_waters(
topology=stateA_topology,
positions=stateA_positions,
charge_difference=charge_difference,
distance_cutoff=distance_cutoff,
)
# In-place modify state B alchemical waters to ions
_rfe_utils.topologyhelpers.handle_alchemical_waters(
water_resids=alchem_water_resids,
topology=stateB_topology,
system=stateB_system,
system_mapping=system_mappings,
charge_difference=charge_difference,
solvent_component=solvent_component,
)
def _get_omm_objects(
self,
stateA: ChemicalSystem,
stateB: ChemicalSystem,
mapping: LigandAtomMapping,
settings: dict[str, SettingsBaseModel],
protein_component: ProteinComponent | None,
solvent_component: SolventComponent | None,
small_mols: dict[SmallMoleculeComponent, OFFMolecule],
) -> tuple[
openmm.System,
openmm.app.Topology,
openmm.unit.Quantity,
openmm.System,
openmm.app.Topology,
openmm.unit.Quantity,
dict[str, dict[int, int]],
]:
"""
Get OpenMM objects for both end states A and B.
Parameters
----------
stateA : ChemicalSystem
ChemicalSystem defining end state A.
stateB : ChemicalSystem
ChemicalSystem defining end state B.
mapping : LigandAtomMapping
The mapping for alchemical components between state A and B.
settings : dict[str, SettingsBaseModel]
Settings for the transformation.
protein_component : ProteinComponent | None
The common ProteinComponent between the end states, if there is is one.
solvent_component : SolventComponent | None
The common SolventComponent between the end states, if there is one.
small_mols : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
The small molecules for both end states.
Returns
-------
stateA_system : openmm.System
OpenMM System for state A.
stateA_topology : openmm.app.Topology
OpenMM Topology for the state A System.
stateA_positions : openmm.unit.Quantity
Positions of partials for state A System.
stateB_system : openmm.System
OpenMM System for state B.
stateB_topology : openmm.app.Topology
OpenMM Topology for the state B System.
stateB_positions : openmm.unit.Quantity
Positions of partials for state B System.
system_mapping : dict[str, dict[int, int]]
Dictionary of mappings defining the correspondance between
the two state Systems.
"""
if self.verbose:
self.logger.info("Parameterizing systems")
def _filter_small_mols(smols, state):
return {smc: offmol for smc, offmol in smols.items() if state.contains(smc)}
states_inputs = {
"A": {"state": stateA, "mols": _filter_small_mols(small_mols, stateA)},
"B": {"state": stateB, "mols": _filter_small_mols(small_mols, stateB)},
}
# Everything involving systemgenerator handling has a risk of
# oechem <-> rdkit smiles conversion clashes, cautiously ban it.
with without_oechem_backend():
# Get the system generators with all the templates registered
for state in ["A", "B"]:
ffcache = settings["output_settings"].forcefield_cache
if ffcache is not None:
ffcache = self.shared_basepath / (f"{state}_" + ffcache)
states_inputs[state]["generator"] = self._get_system_generator(
settings=settings,
solvent_component=solvent_component,
openff_molecules=list(states_inputs[state]["mols"].values()),
ffcache=ffcache,
)
(stateA_system, stateA_topology, stateA_positions, comp_resids) = (
self._create_stateA_system(
small_mols=states_inputs["A"]["mols"],
protein_component=protein_component,
solvent_component=solvent_component,
system_generator=states_inputs["A"]["generator"],
solvation_settings=settings["solvation_settings"],
)
)
(stateB_system, stateB_topology, stateB_alchem_resids) = self._create_stateB_system(
small_mols=states_inputs["B"]["mols"],
mapping=mapping,
stateA_topology=stateA_topology,
exclude_resids=comp_resids[mapping.componentA],
system_generator=states_inputs["B"]["generator"],
)
# Get the mapping between the two systems
system_mappings = _rfe_utils.topologyhelpers.get_system_mappings(
old_to_new_atom_map=mapping.componentA_to_componentB,
old_system=stateA_system,
old_topology=stateA_topology,
old_resids=comp_resids[mapping.componentA],
new_system=stateB_system,
new_topology=stateB_topology,
new_resids=stateB_alchem_resids,
# These are non-optional settings for this method
fix_constraints=True,
)
# Net charge: add alchemical water if needed
# Must be done here as we in-place modify the particles of state B.
if settings["alchemical_settings"].explicit_charge_correction:
self._handle_net_charge(
stateA_topology=stateA_topology,
stateA_positions=stateA_positions,
stateB_topology=stateB_topology,
stateB_system=stateB_system,
charge_difference=mapping.get_alchemical_charge_difference(),
system_mappings=system_mappings,
distance_cutoff=settings["alchemical_settings"].explicit_charge_correction_cutoff,
solvent_component=solvent_component,
)
# Finally get the state B positions
stateB_positions = _rfe_utils.topologyhelpers.set_and_check_new_positions(
system_mappings,
stateA_topology,
stateB_topology,
old_positions=ensure_quantity(stateA_positions, "openmm"),
insert_positions=ensure_quantity(
small_mols[mapping.componentB].conformers[0], "openmm"
),
)
return (
stateA_system,
stateA_topology,
stateA_positions,
stateB_system,
stateB_topology,
stateB_positions,
system_mappings,
)
@staticmethod
def _get_alchemical_system(
stateA_system: openmm.System,
stateA_positions: openmm.unit.Quantity,
stateA_topology: openmm.app.Topology,
stateB_system: openmm.System,
stateB_positions: openmm.unit.Quantity,
stateB_topology: openmm.app.Topology,
system_mappings: dict[str, dict[int, int]],
alchemical_settings: AlchemicalSettings,
):
"""
Get the hybrid topology alchemical system.
Parameters
----------
stateA_system : openmm.System
State A OpenMM System
stateA_positions : openmm.unit.Quantity
Positions of state A System
stateA_topology : openmm.app.Topology
Topology of state A System
stateB_system : openmm.System
State B OpenMM System
stateB_positions : openmm.unit.Quantity
Positions of state B System
stateB_topology : openmm.app.Topology
Topology of state B System
system_mappings : dict[str, dict[int, int]]
Mapping of corresponding atoms between the two Systems.
alchemical_settings : AlchemicalSettings
The alchemical settings defining how the alchemical system
will be built.
Returns
-------
hybrid_factory : HybridTopologyFactory
The factory creating the hybrid system.
hybrid_system : openmm.System
The hybrid System.
"""
if alchemical_settings.softcore_LJ.lower() == "gapsys":
softcore_LJ_v2 = True
elif alchemical_settings.softcore_LJ.lower() == "beutler":
softcore_LJ_v2 = False
hybrid_factory = _rfe_utils.relative.HybridTopologyFactory(
stateA_system,
stateA_positions,
stateA_topology,
stateB_system,
stateB_positions,
stateB_topology,
old_to_new_atom_map=system_mappings["old_to_new_atom_map"],
old_to_new_core_atom_map=system_mappings["old_to_new_core_atom_map"],
use_dispersion_correction=alchemical_settings.use_dispersion_correction,
softcore_alpha=alchemical_settings.softcore_alpha,
softcore_LJ_v2=softcore_LJ_v2,
softcore_LJ_v2_alpha=alchemical_settings.softcore_alpha,
interpolate_old_and_new_14s=alchemical_settings.turn_off_core_unique_exceptions,
)
return hybrid_factory, hybrid_factory.hybrid_system
def _subsample_topology(
self,
hybrid_topology: openmm.app.Topology,
hybrid_positions: openmm.unit.Quantity,
output_selection: str,
output_filename: str,
atom_classes: dict[str, set[int]],
) -> npt.NDArray:
"""
Subsample the hybrid topology based on user-selected output selection
and write the subsampled topology to a PDB file.
Parameters
----------
hybrid_topology : openmm.app.Topology
The hybrid system topology to subsample.
hybrid_positions : openmm.unit.Quantity
The hybrid system positions.
output_selection : str
An MDTraj selection string to subsample the topology with.
output_filename : str
The name of the file to write the PDB to.
atom_classes : dict[str, set[int]]
A dictionary defining what atoms belong to the different
components of the hybrid system.
Returns
-------
selection_indices : npt.NDArray
The indices of the subselected system.
TODO
----
Modify this to also store the full system.
"""
selection_indices = hybrid_topology.select(output_selection)
# Write out a PDB containing the subsampled hybrid state
# We use bfactors as a hack to label different states
# bfactor of 0 is environment atoms
# bfactor of 0.25 is unique old atoms
# bfactor of 0.5 is core atoms
# bfactor of 0.75 is unique new atoms
bfactors = np.zeros_like(selection_indices, dtype=float)
bfactors[np.isin(selection_indices, list(atom_classes["unique_old_atoms"]))] = 0.25
bfactors[np.isin(selection_indices, list(atom_classes["core_atoms"]))] = 0.50
bfactors[np.isin(selection_indices, list(atom_classes["unique_new_atoms"]))] = 0.75
if len(selection_indices) > 0:
traj = mdtraj.Trajectory(
hybrid_positions[selection_indices, :],
hybrid_topology.subset(selection_indices),
).save_pdb(
self.shared_basepath / output_filename,
bfactors=bfactors,
)
return selection_indices
def run(
self,
*,
dry: bool = False,
verbose: bool = True,
scratch_basepath: pathlib.Path | None = None,
shared_basepath: pathlib.Path | None = None,
) -> dict[str, Any]:
"""Setup a hybrid topology system.
Parameters
----------
dry : bool
Do a dry run of the calculation, creating all necessary hybrid
system components (topology, system, sampler, etc...) but without
running the simulation.
verbose : bool
Verbose output of the simulation progress. Output is provided via
INFO level logging.
scratch_basepath: pathlib.Path | None
Where to store temporary files, defaults to current working directory
shared_basepath : pathlib.Path | None
Where to run the calculation, defaults to current working directory
Returns
-------
dict
Outputs created by the setup unit or the debug objects
(e.g. HybridTopologyFactory) if ``dry==True``.
Raises
------
error
Exception if anything failed
"""
# Prepare paths & verbosity
self._prepare(verbose, scratch_basepath, shared_basepath)
# Get settings
settings = self._get_settings(self._inputs["protocol"].settings)
# Get components
stateA = self._inputs["stateA"]
stateB = self._inputs["stateB"]
mapping = self._inputs["ligandmapping"]
alchem_comps = self._inputs["alchemical_components"]
solvent_comp, protein_comp, small_mols = self._get_components(stateA, stateB)
# Assign partial charges now to avoid any discrepancies later
self._assign_partial_charges(settings["charge_settings"], small_mols)
(
stateA_system,
stateA_topology,
stateA_positions,
stateB_system,
stateB_topology,
stateB_positions,
system_mappings,
) = self._get_omm_objects(
stateA=stateA,
stateB=stateB,
mapping=mapping,
settings=settings,
protein_component=protein_comp,
solvent_component=solvent_comp,
small_mols=small_mols,
)
# Get the hybrid factory & system
hybrid_factory, hybrid_system = self._get_alchemical_system(
stateA_system=stateA_system,
stateA_positions=stateA_positions,
stateA_topology=stateA_topology,
stateB_system=stateB_system,
stateB_positions=stateB_positions,
stateB_topology=stateB_topology,
system_mappings=system_mappings,
alchemical_settings=settings["alchemical_settings"],
)
# Subselect system based on user inputs & write initial PDB
selection_indices = self._subsample_topology(
hybrid_topology=hybrid_factory.hybrid_topology,
hybrid_positions=hybrid_factory.hybrid_positions,
output_selection=settings["output_settings"].output_indices,
output_filename=settings["output_settings"].output_structure,
atom_classes=hybrid_factory._atom_classes,
)
# Serialize things
# OpenMM System
system_outfile = self.shared_basepath / "hybrid_system.xml.bz2"
serialize(hybrid_system, system_outfile)
# Positions
positions_outfile = self.shared_basepath / "hybrid_positions.npy"
npy_positions = from_openmm(hybrid_factory.hybrid_positions).to("nanometer").m
np.save(positions_outfile, npy_positions)
unit_results_dict = {
"system": system_outfile,
"positions": positions_outfile,
"pdb_structure": self.shared_basepath / settings["output_settings"].output_structure,
"selection_indices": selection_indices,
"openmm_version": openmm.__version__,
"openfe_version": openfe.__version__,
"gufe_version": gufe.__version__,
}
if dry:
unit_results_dict |= {
# Adding unserialized objects so we can directly use them
# to chain units in tests
"hybrid_factory": hybrid_factory,
"hybrid_system": hybrid_system,
"hybrid_positions": hybrid_factory.hybrid_positions,
}
return unit_results_dict
def _execute(
self,
ctx: gufe.Context,
**inputs,
) -> dict[str, Any]:
log_system_probe(logging.INFO, paths=[ctx.scratch])
outputs = self.run(scratch_basepath=ctx.scratch, shared_basepath=ctx.shared)
return {
"repeat_id": self._inputs["repeat_id"],
"generation": self._inputs["generation"],
**outputs,
}
class HybridTopologyMultiStateSimulationUnit(gufe.ProtocolUnit, HybridTopologyUnitMixin):
"""
Multi-state simulation (e.g. multi replica methods like hamiltonian
replica exchange) unit for Hybrid Topology Protocol transformations.
"""
@staticmethod
def _check_restart(output_settings: SettingsBaseModel, shared_path: pathlib.Path):
"""
Check if we are doing a restart.
Parameters
----------
output_settings : SettingsBaseModel
The simulation output settings
shared_path : pathlib.Path
The shared directory where we should be looking for existing files.
Notes
-----
For now this just checks if the netcdf files are present in the
shared directory but in the future this may expand depending on
how warehouse works.
Raises
------
IOError
If either the checkpoint or trajectory files don't exist.
"""
trajectory = shared_path / output_settings.output_filename
checkpoint = shared_path / output_settings.checkpoint_storage_filename
if trajectory.is_file() ^ checkpoint.is_file():
errmsg = (
"One of either the trajectory or checkpoint files are missing but "
"the other is not. This should not happen under normal circumstances."
)
raise IOError(errmsg)
if trajectory.is_file() and checkpoint.is_file():
return True
return False
@staticmethod
def _get_integrator(
integrator_settings: IntegratorSettings,
simulation_settings: MultiStateSimulationSettings,
system: openmm.System,
) -> openmmtools.mcmc.LangevinDynamicsMove:
"""
Get and validate the integrator
Parameters
----------
integrator_settings : IntegratorSettings
Settings controlling the Langevin integrator.
simulation_settings : MultiStateSimulationSettings
Settings controlling the simulation.
system : openmm.System
The OpenMM System.
Returns
-------
integrator : openmmtools.mcmc.LangevinDynamicsMove
The LangevinDynamicsMove integrator.
Raises
------
ValueError
If there are virtual sites in the system, but velocities
are not being reassigned after every MCMC move.
"""
steps_per_iteration = settings_validation.convert_steps_per_iteration(
simulation_settings, integrator_settings
)
integrator = openmmtools.mcmc.LangevinDynamicsMove(
timestep=to_openmm(integrator_settings.timestep),
collision_rate=to_openmm(integrator_settings.langevin_collision_rate),
n_steps=steps_per_iteration,
reassign_velocities=integrator_settings.reassign_velocities,
n_restart_attempts=integrator_settings.n_restart_attempts,
constraint_tolerance=integrator_settings.constraint_tolerance,
)
# Validate for known issue when dealing with virtual sites
# and multistate simulations
if not integrator_settings.reassign_velocities:
for particle_idx in range(system.getNumParticles()):
if system.isVirtualSite(particle_idx):
errmsg = (
"Simulations with virtual sites without velocity "
"reassignments are unstable with MCMC integrators."
)
raise ValueError(errmsg)
return integrator
@staticmethod
def _get_reporter(
storage_path: pathlib.Path,
selection_indices: npt.NDArray,
output_settings: MultiStateOutputSettings,
simulation_settings: MultiStateSimulationSettings,
) -> multistate.MultiStateReporter:
"""
Get the multistate reporter.
Parameters
----------
storage_path : pathlib.Path
Path to the directory where files should be written.
selection_indices : npt.NDArray
The set of system indices to report positions & velocities for.
output_settings : MultiStateOutputSettings
Settings defining how outputs should be written.
simulation_settings : MultiStateSimulationSettings
Settings defining out the simulation should be run.
Notes
-----
All this does is create the reporter, it works for both
new reporters and if we are doing a restart.
"""
# Define the trajectory & checkpoint files
nc = storage_path / output_settings.output_filename
# The checkpoint file in openmmtools is taken as a file relative
# to the location of the nc file, so you only want the filename
chk = output_settings.checkpoint_storage_filename
if output_settings.positions_write_frequency is not None:
pos_interval = settings_validation.divmod_time_and_check(
numerator=output_settings.positions_write_frequency,
denominator=simulation_settings.time_per_iteration,
numerator_name="output settings' position_write_frequency",
denominator_name="simulation settings' time_per_iteration",
)
else:
pos_interval = 0
if output_settings.velocities_write_frequency is not None:
vel_interval = settings_validation.divmod_time_and_check(
numerator=output_settings.velocities_write_frequency,
denominator=simulation_settings.time_per_iteration,
numerator_name="output settings' velocity_write_frequency",
denominator_name="sampler settings' time_per_iteration",
)
else:
vel_interval = 0
chk_intervals = settings_validation.convert_checkpoint_interval_to_iterations(
checkpoint_interval=output_settings.checkpoint_interval,
time_per_iteration=simulation_settings.time_per_iteration,
)
return multistate.MultiStateReporter(
storage=nc,
analysis_particle_indices=selection_indices,
checkpoint_interval=chk_intervals,
checkpoint_storage=chk,
position_interval=pos_interval,
velocity_interval=vel_interval,
)