-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathbase_units.py
More file actions
1829 lines (1616 loc) · 66.8 KB
/
Copy pathbase_units.py
File metadata and controls
1829 lines (1616 loc) · 66.8 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
"""OpenMM Equilibrium SepTop Protocol base classes
==================================================
Base classes for the equilibrium OpenMM SepTop free energy ProtocolUnits.
This mostly implements BaseSepTopUnit whose methods can be
overridden to define different types of alchemical transformations.
TODO
----
* Add in all the AlchemicalFactory and AlchemicalRegion kwargs
as settings.
"""
import abc
import logging
import pathlib
from typing import Any, Literal, Optional
import gufe
import matplotlib.pyplot as plt
import MDAnalysis as mda
import netCDF4 as nc
import numpy as np
import numpy.typing as npt
import openmm
import openmmtools
from gufe import (
ChemicalSystem,
ProteinComponent,
SmallMoleculeComponent,
SolventComponent,
)
from gufe.components import Component
from gufe.protocols.errors import ProtocolUnitExecutionError
from openfe_analysis.utils import plotting
from openff.toolkit.topology import Molecule as OFFMolecule
from openff.units import unit as offunit
from openff.units.openmm import ensure_quantity, from_openmm, to_openmm
from openmm import unit as omm_unit
from openmmforcefields.generators import SystemGenerator
from openmmtools import multistate
from openmmtools.alchemy import AbsoluteAlchemicalFactory, AlchemicalRegion
from openmmtools.states import (
SamplerState,
ThermodynamicState,
create_thermodynamic_state_protocol,
)
from rdkit import Chem
import openfe
from openfe.protocols.openmm_afe.equil_afe_settings import (
AlchemicalSettings,
BaseSolvationSettings,
IntegratorSettings,
MultiStateOutputSettings,
MultiStateSimulationSettings,
OpenFFPartialChargeSettings,
OpenMMEngineSettings,
OpenMMSystemGeneratorFFSettings,
ThermoSettings,
)
from openfe.protocols.openmm_md.plain_md_methods import PlainMDSimulationUnit
from openfe.protocols.openmm_utils import omm_compute
from openfe.protocols.openmm_utils.omm_settings import MultiStateAnalysisSettings, SettingsBaseModel
from openfe.protocols.openmm_utils.serialization import deserialize
from openfe.utils import log_system_probe, without_oechem_backend
from ..openmm_utils import (
charge_generation,
multistate_analysis,
settings_validation,
system_creation,
system_validation,
)
from ..openmm_utils.mdtraj_utils import mdtraj_from_openmm
from .utils import SepTopParameterState
logger = logging.getLogger(__name__)
def _pre_equilibrate(
system: openmm.System,
topology: openmm.app.Topology,
positions: omm_unit.Quantity,
settings: dict[str, SettingsBaseModel],
endstate: Literal["A", "B", "AB"],
dry: bool,
shared_basepath: pathlib.Path,
platform: openmm.Platform,
verbose: bool,
logger,
) -> tuple[omm_unit.Quantity, omm_unit.Quantity]:
"""
Run a non-alchemical equilibration to get a stable system.
Parameters
----------
system : openmm.System
An OpenMM System to equilibrate.
topology : openmm.app.Topology
OpenMM Topology of the System.
positions : openmm.unit.Quantity
Initial positions for the system.
settings : dict[str, SettingsBaseModel]
A dictionary of settings objects. Expects the
following entries:
* `engine_settings`
* `thermo_settings`
* `integrator_settings`
* `equil_simulation_settings`
* `equil_output_settings`
endstate: Literal['A', 'B', 'AB']
The endstate that is pre-equilibrated,can be 'A', 'B' or 'AB'.
dry: bool
Whether or not this is a dry run.
shared_basepath: pathlib.Path
The Path to the shared storage.
verbose: bool
Whether to print extra information
logger: logging.getLogger
Name of the logger
Returns
-------
equilibrated_positions : npt.NDArray
Equilibrated system positions
box : openmm.unit.Quantity
Box vectors of the equilibrated system.
"""
# Prep the simulation object
integrator = openmm.LangevinMiddleIntegrator(
to_openmm(settings["thermo_settings"].temperature),
to_openmm(settings["integrator_settings"].langevin_collision_rate),
to_openmm(settings["integrator_settings"].timestep),
)
simulation = openmm.app.Simulation(
topology=topology,
system=system,
integrator=integrator,
platform=platform,
)
# Get the necessary number of steps
if settings["equil_simulation_settings"].equilibration_length_nvt is not None:
equil_steps_nvt = settings_validation.get_simsteps(
sim_length=settings["equil_simulation_settings"].equilibration_length_nvt,
timestep=settings["integrator_settings"].timestep,
mc_steps=1,
)
else:
equil_steps_nvt = None
equil_steps_npt = settings_validation.get_simsteps(
sim_length=settings["equil_simulation_settings"].equilibration_length,
timestep=settings["integrator_settings"].timestep,
mc_steps=1,
)
prod_steps_npt = settings_validation.get_simsteps(
sim_length=settings["equil_simulation_settings"].production_length,
timestep=settings["integrator_settings"].timestep,
mc_steps=1,
)
if verbose:
logger.info("running non-alchemical equilibration MD")
# Don't do anything if we're doing a dry run
if dry:
box = system.getDefaultPeriodicBoxVectors()
return positions, to_openmm(from_openmm(box))
# TODO: Refactor this part to live outside the method call
# We have to modify the output settings to have different output
# names for the files from the two end states
unfrozen_outsettings = settings["equil_output_settings"].unfrozen_copy()
if endstate == "A" or endstate == "B" or endstate == "AB":
if unfrozen_outsettings.production_trajectory_filename:
unfrozen_outsettings.production_trajectory_filename = (
unfrozen_outsettings.production_trajectory_filename + f"_state{endstate}.xtc"
)
if unfrozen_outsettings.preminimized_structure:
unfrozen_outsettings.preminimized_structure = (
unfrozen_outsettings.preminimized_structure + f"_state{endstate}.pdb"
)
if unfrozen_outsettings.minimized_structure:
unfrozen_outsettings.minimized_structure = (
unfrozen_outsettings.minimized_structure + f"_state{endstate}.pdb"
)
if unfrozen_outsettings.equil_nvt_structure:
unfrozen_outsettings.equil_nvt_structure = (
unfrozen_outsettings.equil_nvt_structure + f"_state{endstate}.pdb"
)
if unfrozen_outsettings.equil_npt_structure:
unfrozen_outsettings.equil_npt_structure = (
unfrozen_outsettings.equil_npt_structure + f"_state{endstate}.pdb"
)
if unfrozen_outsettings.log_output:
unfrozen_outsettings.log_output = (
unfrozen_outsettings.log_output + f"_state{endstate}.log"
)
else:
errmsg = f"Only 'A', 'B', and 'AB' are accepted as endstates. Got {endstate}"
raise ValueError(errmsg)
# Use the _run_MD method from the PlainMDSimulationUnit
# Should in-place modify the simulation
PlainMDSimulationUnit._run_MD(
simulation=simulation,
positions=positions,
simulation_settings=settings["equil_simulation_settings"],
output_settings=unfrozen_outsettings,
temperature=settings["thermo_settings"].temperature,
barostat_frequency=settings["integrator_settings"].barostat_frequency,
timestep=settings["integrator_settings"].timestep,
equil_steps_nvt=equil_steps_nvt,
equil_steps_npt=equil_steps_npt,
prod_steps=prod_steps_npt,
verbose=verbose,
shared_basepath=shared_basepath,
)
state = simulation.context.getState(
getPositions=True,
)
equilibrated_positions = state.getPositions(asNumpy=True)
box = state.getPeriodicBoxVectors()
# cautiously delete out contexts & integrator
del simulation.context, integrator
return equilibrated_positions, to_openmm(from_openmm(box))
class SepTopUnitMixin:
"""
Mixin for SepTop ProtocolUnits, defining some of the common methods.
"""
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 via
INFO level logging.
scratch_basepath : pathlib.Path | None
Optional base path to write scratch files to.
shared_basepath : pathlib.Path | None
Optional base path to write shared files to.
"""
self.verbose = verbose
# 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)
@abc.abstractmethod
def _get_settings(self) -> dict[str, SettingsBaseModel]:
"""
Get a dictionary with the following entries:
* forcefield_settings : OpenMMSystemGeneratorFFSettings
* thermo_settings : ThermoSettings
* solvation_settings : BaseSolvationSettings
* alchemical_settings : AlchemicalSettings
* lambda_settings : LambdaSettings
* engine_settings : OpenMMEngineSettings
* integrator_settings : IntegratorSettings
* equil_simulation_settings : MDSimulationSettings
* equil_output_settings : MDOutputSettings
* simulation_settings : MultiStateSimulationSettings
* output_settings : MultiStateOutputSettings
Settings may change depending on what type of simulation you are
running. Cherry pick them and return them to be available later on.
This method should also add various validation checks as necessary.
Note
----
Must be implemented in the child class.
"""
...
@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 as e:
errmsg = "Missing environment information from setup outputs."
raise ProtocolUnitExecutionError(errmsg) from e
class BaseSepTopSetupUnit(gufe.ProtocolUnit, SepTopUnitMixin):
"""
Base class for the setup of ligand SepTop RBFE free energy transformations.
"""
def _get_alchemical_system(
self,
system: openmm.System,
alchem_indices_A: list[int],
alchem_indices_B: list[int],
alchemical_settings: AlchemicalSettings,
) -> tuple[AbsoluteAlchemicalFactory, openmm.System]:
"""
Get an alchemically modified system and its associated factory
Parameters
----------
system : openmm.System
System to alchemically modify.
alchem_indices_A : list[int]
A list of atom indices for the alchemically modified
ligand A in the system.
alchem_indices_B : list[int]
A list of atom indices for the alchemically modified
ligand B in the system.
alchemical_settings : AlchemicalSettings
Settings controlling how the alchemical system will be built.
Returns
-------
alchemical_factory : AbsoluteAlchemicalFactory
Factory for creating an alchemically modified system.
alchemical_system : openmm.System
Alchemically modified system
"""
alchemical_factory = AbsoluteAlchemicalFactory(
consistent_exceptions=False,
switch_width=1.0 * offunit.angstroms,
alchemical_pme_treatment="exact",
alchemical_rf_treatment="switched",
disable_alchemical_dispersion_correction=alchemical_settings.disable_alchemical_dispersion_correction,
split_alchemical_forces=True,
)
# Alchemical Region for ligand A
alchemical_region_A = AlchemicalRegion(
alchemical_atoms=alchem_indices_A,
name="A",
softcore_alpha=alchemical_settings.softcore_alpha,
annihilate_electrostatics=True,
annihilate_sterics=alchemical_settings.annihilate_sterics,
softcore_a=alchemical_settings.softcore_a,
softcore_b=alchemical_settings.softcore_b,
softcore_c=alchemical_settings.softcore_c,
softcore_beta=0.0,
softcore_d=1.0,
softcore_e=1.0,
softcore_f=2.0,
)
# Alchemical Region for ligand B
alchemical_region_B = AlchemicalRegion(
alchemical_atoms=alchem_indices_B,
name="B",
softcore_alpha=alchemical_settings.softcore_alpha,
annihilate_electrostatics=True,
annihilate_sterics=alchemical_settings.annihilate_sterics,
softcore_a=alchemical_settings.softcore_a,
softcore_b=alchemical_settings.softcore_b,
softcore_c=alchemical_settings.softcore_c,
softcore_beta=0.0,
softcore_d=1.0,
softcore_e=1.0,
softcore_f=2.0,
)
alchemical_system = alchemical_factory.create_alchemical_system(
system, [alchemical_region_A, alchemical_region_B]
)
return alchemical_factory, alchemical_system
@abc.abstractmethod
def _get_components(
self,
) -> tuple[
dict[str, list[Component]],
Optional[gufe.SolventComponent],
Optional[gufe.ProteinComponent],
dict[SmallMoleculeComponent, OFFMolecule],
]:
"""
Get the relevant components to create the alchemical system with.
Note
----
Must be implemented in the child class.
"""
...
def _get_system_generator(
self,
settings: dict[str, SettingsBaseModel],
solvent_comp: Optional[SolventComponent],
) -> SystemGenerator:
"""
Get a system generator through the system creation
utilities
Parameters
----------
settings : dict[str, SettingsBaseModel]
A dictionary of settings object for the unit.
solvent_comp : Optional[SolventComponent]
The solvent component of this system, if there is one.
Returns
-------
system_generator : openmmforcefields.generator.SystemGenerator
System Generator to parameterise this unit.
"""
ffcache = settings["output_settings"].forcefield_cache
if ffcache is not None:
ffcache = self.shared_basepath / ffcache
# Block out oechem backend to avoid any issues with
# smiles roundtripping between rdkit and oechem
with without_oechem_backend():
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_comp is not None,
)
return system_generator
@staticmethod
def _assign_partial_charges(
partial_charge_settings: OpenFFPartialChargeSettings,
smc_components: dict[SmallMoleculeComponent, OFFMolecule],
) -> None:
"""
Assign partial charges to OFFMolecules inplace.
Parameters
----------
charge_settings : OpenFFPartialChargeSettings
Settings for controlling how the partial charges are assigned.
smc_components : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
Dictionary of OpenFF Molecules to add, keyed by
SmallMoleculeComponent.
"""
for mol in smc_components.values():
charge_generation.assign_offmol_partial_charges(
offmol=mol,
overwrite=False,
method=partial_charge_settings.partial_charge_method,
toolkit_backend=partial_charge_settings.off_toolkit_backend,
generate_n_conformers=partial_charge_settings.number_of_conformers,
nagl_model=partial_charge_settings.nagl_model,
)
def _get_modeller(
self,
protein_component: Optional[ProteinComponent],
solvent_component: SolventComponent,
smc_components: dict[SmallMoleculeComponent, OFFMolecule],
system_generator: SystemGenerator,
solvation_settings: BaseSolvationSettings,
) -> tuple[openmm.app.Modeller, dict[Component, npt.NDArray]]:
"""
Get an OpenMM Modeller object and a list of residue indices
for each component in the system.
Parameters
----------
protein_component : Optional[ProteinComponent]
Protein Component, if it exists.
solvent_component : SolventComponent
Solvent Component.
smc_components : dict[SmallMoleculeComponent, openff.toolkit.Molecule]
Dictionary of OpenFF Molecules to add, keyed by
SmallMoleculeComponent.
system_generator : openmmforcefields.generator.SystemGenerator
System Generator to parameterise this unit.
partial_charge_settings : BasePartialChargeSettings
Settings detailing how to assign partial charges to the
SMCs of the system.
solvation_settings : BaseSolvationSettings
Settings detailing how to solvate the system.
Returns
-------
system_modeller : openmm.app.Modeller
OpenMM Modeller object generated from ProteinComponent and
OpenFF Molecules.
comp_resids : dict[Component, npt.NDArray]
Dictionary of residue indices for each component in system.
"""
if self.verbose:
self.logger.info("Parameterizing molecules")
# TODO: guard the following from non-RDKit backends
# force the creation of parameters for the small molecules
# this is necessary because we need to have the FF generated ahead
# of solvating the system.
# Block out oechem backend to avoid any issues with
# smiles roundtripping between rdkit and oechem
with without_oechem_backend():
for mol in smc_components.values():
system_generator.create_system(mol.to_topology().to_openmm(), molecules=[mol])
# get OpenMM modeller + dictionary of resids for each component
system_modeller, comp_resids = system_creation.get_omm_modeller(
protein_comp=protein_component,
solvent_comp=solvent_component,
small_mols=smc_components,
omm_forcefield=system_generator.forcefield,
solvent_settings=solvation_settings,
)
return system_modeller, comp_resids
def _get_omm_objects(
self,
system_modeller: openmm.app.Modeller,
system_generator: SystemGenerator,
smc_components: list[OFFMolecule],
) -> tuple[openmm.app.Topology, openmm.unit.Quantity, openmm.System]:
"""
Get the OpenMM Topology, Positions and System of the
parameterised system.
Parameters
----------
system_modeller : openmm.app.Modeller
OpenMM Modeller object representing the system to be
parametrized.
system_generator : SystemGenerator
The SystemGenerator object to create a System with.
smc_components : list[openff.toolkit.Molecule]
A list of openff Molecules to add to the system.
Returns
-------
topology : openmm.app.Topology
Topology object describing the parameterized system
system : openmm.System
An OpenMM System of the alchemical system.
positions : openmm.unit.Quantity
Positions of the system.
"""
topology = system_modeller.getTopology()
# roundtrip positions to remove vec3 issues
positions = to_openmm(from_openmm(system_modeller.getPositions()))
# Block out oechem backend to avoid any issues with
# smiles roundtripping between rdkit and oechem
with without_oechem_backend():
system = system_generator.create_system(
system_modeller.topology,
molecules=smc_components,
)
return topology, system, positions
@staticmethod
def _get_atom_indices(
omm_topology: openmm.app.Topology,
comp_resids: dict[Component, npt.NDArray],
) -> dict[Component, list]:
"""
Get all the atom indices for each component in the system, based on
the dictionary of residue indices for each component.
Parameters
----------
omm_topology: openmm.app.Topology
OpenMM Topology object with the full system.
comp_resids: dict[Component, npt.NDArray]
Dictionary of the components in the topology with their residue indices.
Returns
-------
comp_atomids: dict[Component, list]
A dictionary of atom indices for each component in the System.
"""
comp_atomids = {}
for key, values in comp_resids.items():
atom_indices = []
for residue in omm_topology.residues():
if residue.index in values:
atom_indices.extend([atom.index for atom in residue.atoms()])
comp_atomids[key] = atom_indices
return comp_atomids
@staticmethod
def get_smc_comps(
alchem_comps: dict[str, list[Component]],
smc_comps: dict[SmallMoleculeComponent, OFFMolecule],
) -> tuple[
dict[SmallMoleculeComponent, OFFMolecule],
dict[SmallMoleculeComponent, OFFMolecule],
dict[SmallMoleculeComponent, OFFMolecule],
]:
# Get smcs for the different states and the common smcs
smc_off_A = {m: m.to_openff() for m in alchem_comps["stateA"]}
smc_off_B = {m: m.to_openff() for m in alchem_comps["stateB"]}
# Common smcs could e.g. be cofactors
smc_off_both = {
m: m.to_openff()
for m in smc_comps
if (m not in alchem_comps["stateA"] and m not in alchem_comps["stateB"])
}
smc_comps_A = smc_off_A | smc_off_both
smc_comps_B = smc_off_B | smc_off_both
smc_comps_AB = smc_off_A | smc_off_B | smc_off_both
return smc_comps_A, smc_comps_B, smc_comps_AB
def get_system(
self,
solv_comp: SolventComponent,
prot_comp: ProteinComponent,
smc_comp: dict[SmallMoleculeComponent, OFFMolecule],
settings: dict[str, SettingsBaseModel],
):
"""
Creates an OpenMM system, topology, positions, modeller and also
residue IDs of the different components
Parameters
----------
solv_comp: SolventComponent
prot_comp: Optional[ProteinComponent]
smc_comp: dict[SmallMoleculeComponent,OFFMolecule]
settings: dict[str, SettingsBaseModel]
A dictionary of settings object for the unit.
Returns
-------
omm_system: openmm.app.System
omm_topology: openmm.app.Topology
positions: openmm.unit.Quantity
system_modeller: openmm.app.Modeller
comp_resids: dict[Component, npt.NDArray]
A dictionary of residues for each component in the System.
"""
# Get system generator
system_generator = self._get_system_generator(settings, solv_comp)
# Get modeller
system_modeller, comp_resids = self._get_modeller(
prot_comp,
solv_comp,
smc_comp,
system_generator,
settings["solvation_settings"],
)
# Get OpenMM topology, positions and system
omm_topology, omm_system, positions = self._get_omm_objects(
system_modeller, system_generator, list(smc_comp.values())
)
return omm_system, omm_topology, positions, system_modeller, comp_resids
@staticmethod
def _subsample_topology(
topology: openmm.app.Topology,
positions: openmm.unit.Quantity,
output_selection: str,
output_file: pathlib.Path,
) -> npt.NDArray:
"""
Subsample the system based on user-selected output selection
and write the subsampled topology to a PDB file.
Parameters
----------
topology : openmm.app.Topology
The system topology to subsample.
positions : openmm.unit.Quantity
The system positions.
output_selection : str
An MDTraj selection string to subsample the topology with.
output_file : pathlib.Path
Path to the file to write the PDB to.
Returns
-------
selection_indices : npt.NDArray
The indices of the subselected system.
"""
traj = mdtraj_from_openmm(topology, positions)
selection_indices = traj.topology.select(output_selection)
# Write out the subselected structure to PDB if not empty
if len(selection_indices) > 0:
sub_traj = traj.atom_slice(selection_indices)
sub_traj.save_pdb(output_file)
return selection_indices
def _execute(
self,
ctx: gufe.Context,
**kwargs,
) -> 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"],
"simtype": self.simtype,
"openmm_version": openmm.__version__,
"openfe_version": openfe.__version__,
"gufe_version": gufe.__version__,
**outputs,
}
class BaseSepTopRunUnit(gufe.ProtocolUnit, SepTopUnitMixin):
"""
Base class for running ligand SepTop RBFE free energy 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.
Raises
------
IOError
If one of the trajectory or checkpoint files are present
without the other.
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.
"""
trajectory = shared_path / output_settings.output_filename
checkpoint = shared_path / output_settings.checkpoint_storage_filename
if trajectory.is_file() and checkpoint.is_file():
return True
elif trajectory.is_file() ^ checkpoint.is_file():
if trajectory.is_file():
errmsg = "the trajectory file is present but not the checkpoint file. "
else:
errmsg = "the checkpoint file is present but not the trajectory file. "
errmsg = (
"Attempting to restart but "
+ errmsg
+ "This should not happen under normal circumstances."
)
raise IOError(errmsg)
else:
return False
@abc.abstractmethod
def _get_components(
self,
) -> tuple[
dict[str, list[Component]],
Optional[gufe.SolventComponent],
Optional[gufe.ProteinComponent],
dict[SmallMoleculeComponent, OFFMolecule],
]:
"""
Get the relevant components to create the alchemical system with.
Note
----
Must be implemented in the child class.
"""
...
@abc.abstractmethod
def _get_lambda_schedule(
self, settings: dict[str, SettingsBaseModel]
) -> dict[str, list[float]]:
"""
Create the lambda schedule
Parameters
----------
settings : dict[str, SettingsBaseModel]
Settings for the unit.
Returns
-------
lambdas : dict[str, list[float]]
Note
----
Must be implemented in the child class.
"""
...
def _get_states(
self,
alchemical_system: openmm.System,
positions: openmm.unit.Quantity,
box_vectors: Optional[openmm.unit.Quantity],
settings: dict[str, SettingsBaseModel],
lambdas: dict[str, list[float]],
solvent_comp: Optional[SolventComponent],
) -> tuple[list[SamplerState], list[ThermodynamicState]]:
"""
Get a list of sampler and thermodynmic states from an
input alchemical system.
Parameters
----------
alchemical_system : openmm.System
Alchemical system to get states for.
positions : openmm.unit.Quantity
Positions of the alchemical system.
box_vectors : Optional[openmm.unit.Quantity]
Box vectors of the alchemical system.
settings : dict[str, SettingsBaseModel]
A dictionary of settings for the protocol unit.
lambdas : dict[str, list[float]]
A dictionary of lambda scales.
solvent_comp : Optional[SolventComponent]
The solvent component of the system, if there is one.
Returns
-------
sampler_states : list[SamplerState]
A list of SamplerStates for each replica in the system.
cmp_states : list[ThermodynamicState]
A list of ThermodynamicState for each replica in the system.
"""
alchemical_state = SepTopParameterState.from_system(alchemical_system)
# Set up the system constants
temperature = settings["thermo_settings"].temperature
pressure = settings["thermo_settings"].pressure
constants = dict()
constants["temperature"] = ensure_quantity(temperature, "openmm")
if solvent_comp is not None:
constants["pressure"] = ensure_quantity(pressure, "openmm")
cmp_states = create_thermodynamic_state_protocol(
alchemical_system,
protocol=lambdas,
constants=constants,
composable_states=[alchemical_state],
)
sampler_state = SamplerState(positions=positions)
if alchemical_system.usesPeriodicBoundaryConditions():
sampler_state.box_vectors = box_vectors
sampler_states = [sampler_state for _ in cmp_states]
return sampler_states, cmp_states
@staticmethod
def _get_integrator(
integrator_settings: IntegratorSettings,
simulation_settings: MultiStateSimulationSettings,
system: openmm.System,
) -> openmmtools.mcmc.LangevinDynamicsMove:
"""
Return a LangevinDynamicsMove integrator
Parameters
----------
integrator_settings : IntegratorSettings
Settings controlling the Langevin integrator.
simulation_settings : MultiStateSimulationSettings
Settings controlling the simulation.
system: openmm.System
The OpenMM System being simulated.
Returns
-------
integrator : openmmtools.mcmc.LangevinDynamicsMove
A configured integrator object.
"""
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 mutltistate 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. "
"You can set `reassign_velocities` to ``True`` in the "
"`integrator_settings` to avoid this issue."
)
raise ValueError(errmsg)
return integrator
@staticmethod
def _get_reporter(
storage_path: pathlib.Path,
selection_indices: npt.NDArray,
simulation_settings: MultiStateSimulationSettings,
output_settings: MultiStateOutputSettings,
) -> multistate.MultiStateReporter:
"""
Get a MultistateReporter for the simulation you are running.
Parameters
----------
storage_path : pathlib.Path
Path to the directory where files should be written.
selection_indices : npt.NDArray
Array of system particle indices to subsample the system by.
simulation_settings : MultiStateSimulationSettings
Multistate simulation control settings, specifically containing
the amount of time per state sampling iteration.
output_settings: MultiStateOutputSettings
Output settings for the simulations
Returns
-------
reporter : multistate.MultiStateReporter
The reporter for the simulation.
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 the 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="simulation settings' time_per_iteration",