-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathexperiment.py
3097 lines (2628 loc) · 135 KB
/
experiment.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
#!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Experiment
==========
Tools to build Yank experiments from a YAML configuration file.
This is not something that should be normally invoked by the user, and instead
created by going through the Command Line Interface with the ``yank script`` command.
"""
# =============================================================================
# GLOBAL IMPORTS
# =============================================================================
import collections
import copy
import logging
import os
import numpy as np
import cerberus
import cerberus.errors
import openmmtools as mmtools
import openmoltools as moltools
import yaml
from simtk import unit, openmm
from simtk.openmm.app import PDBFile, AmberPrmtopFile
from . import utils, pipeline, mpi, restraints, schema, multistate
from .yank import AlchemicalPhase, Topography
logger = logging.getLogger(__name__)
# =============================================================================
# CONSTANTS
# =============================================================================
HIGHEST_VERSION = '1.3' # highest version of YAML syntax
# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================
def get_openmm_nonbonded_methods_strings():
"""
Get the list of valid OpenMM Nonbonded methods YANK can process
Returns
-------
valid_methods : list of str
"""
return ['NoCutoff', 'CutoffPeriodic', 'CutoffNonPeriodic', 'Ewald', 'PME']
def get_openmm_implicit_nb_method_strings():
"""
Get the subset of nonbonded method strings which work for implicit solvent
Returns
-------
valid_methods : list of str
"""
return get_openmm_nonbonded_methods_strings()[:1]
def get_openmm_explicit_nb_method_strings():
"""
Get the subset of nonbonded method strings which work for explicit solvent
Returns
-------
valid_methods : list of str
"""
return get_openmm_nonbonded_methods_strings()[1:]
def to_openmm_app(input_string):
"""
Converter function to be used with :func:`yank.utils.validate_parameters`.
Parameters
----------
input_string : str
Method name of openmm.app to fetch
Returns
-------
method : Method of openmm.app
Returns openmm.app.{input_string}
"""
return getattr(openmm.app, input_string)
def _is_phase_completed(status, number_of_iterations):
"""Check if the stored simulation is completed.
When the simulation is resumed, the number of iterations to run
in the YAML script could be updated, so we can't rely entirely on
the is_completed field in the ReplicaExchange.Status object.
Parameters
----------
status : namedtuple
The status object returned by ``yank.AlchemicalPhase``.
number_of_iterations : int
The total number of iterations that the simulation must perform.
"""
# TODO allow users to change online analysis options on resuming.
if status.target_error is None and status.iteration < number_of_iterations:
is_completed = False
else:
is_completed = status.is_completed
return is_completed
# ==============================================================================
# UTILITY CLASSES
# ==============================================================================
class YamlParseError(Exception):
"""Represent errors occurring during parsing of Yank YAML file."""
def __init__(self, message):
super(YamlParseError, self).__init__(message)
logger.error(message)
class YankLoader(yaml.Loader):
"""PyYAML Loader that recognized !Combinatorial nodes and load OrderedDicts."""
def __init__(self, *args, **kwargs):
super(YankLoader, self).__init__(*args, **kwargs)
self.add_constructor(u'!Combinatorial', self.combinatorial_constructor)
self.add_constructor(u'!Ordered', self.ordered_constructor)
@staticmethod
def combinatorial_constructor(loader, node):
"""Constructor for YAML !Combinatorial entries."""
return utils.CombinatorialLeaf(loader.construct_sequence(node))
@staticmethod
def ordered_constructor(loader, node):
"""Constructor for YAML !Ordered tag."""
loader.flatten_mapping(node)
return collections.OrderedDict(loader.construct_pairs(node))
class YankDumper(yaml.Dumper):
"""PyYAML Dumper that always return sequences in flow style and maps in block style."""
def __init__(self, *args, **kwargs):
super(YankDumper, self).__init__(*args, **kwargs)
self.add_representer(utils.CombinatorialLeaf, self.combinatorial_representer)
self.add_representer(collections.OrderedDict, self.ordered_representer)
def represent_sequence(self, tag, sequence, flow_style=None):
return yaml.Dumper.represent_sequence(self, tag, sequence, flow_style=True)
def represent_mapping(self, tag, mapping, flow_style=None):
return yaml.Dumper.represent_mapping(self, tag, mapping, flow_style=False)
@staticmethod
def combinatorial_representer(dumper, data):
"""YAML representer CombinatorialLeaf nodes."""
return dumper.represent_sequence(u'!Combinatorial', data)
@staticmethod
def ordered_representer(dumper, data):
"""YAML representer OrderedDict nodes."""
return dumper.represent_mapping(u'!Ordered', data)
# ==============================================================================
# BUILDER CLASS
# ==============================================================================
class AlchemicalPhaseFactory(object):
"""
YANK simulation phase entirely contained as one object.
Creates a full phase to simulate, expects Replica Exchange simulation for now.
Parameters
----------
sampler : yank.multistate.MultiStateSampler
Sampler which will carry out the simulation
thermodynamic_state : openmmtools.states.ThermodynamicState
Reference thermodynamic state without any alchemical modifications
sampler_states : openmmtools.states.SamplerState
Sampler state to initialize from, including the positions of the atoms
topography : yank.yank.Topography
Topography defining the ligand atoms and other atoms
protocol : dict of lists
Alchemical protocol to create states from.
Format should be ``{parameter_name : parameter_values}``
where ``parameter_name`` is the name of the specific alchemical
parameter (e.g. ``lambda_sterics``), and ``parameter_values`` is a list of values for that parameter where each
entry is one state.
Each of the ``parameter_values`` lists for every ``parameter_name`` should be the same length.
storage : yank.multistate.MultiStateReporter or str
Reporter object to use, or file path to create the reporter at
Will be a :class:`yank.multistate.MultiStateReporter` internally if str is given
restraint : yank.restraint.ReceptorLigandRestraint or None, Optional, Default: None
Optional restraint to apply to the system
alchemical_regions : openmmtools.alchemy.AlchemicalRegion or None, Optional, Default: None
Alchemical regions which define which atoms to modify.
alchemical_factory : openmmtools.alchemy.AbsoluteAlchemicalFactory, Optional, Default: None
Alchemical factory with which to create the alchemical system with if you don't want to use all the previously
defined options.
This is passed on to :class:`yank.yank.AlchemicalPhase`
metadata : dict
Additional metdata to pass on to :class:`yank.yank.AlchemicalPhase`
options : dict
Additional options to setup the rest of the process.
See the DEFAULT_OPTIONS for this class in the source code or look at the *options* header for the YAML options.
"""
DEFAULT_OPTIONS = {
'anisotropic_dispersion_cutoff': 'auto',
'minimize': True,
'minimize_tolerance': 1.0 * unit.kilojoules_per_mole/unit.nanometers,
'minimize_max_iterations': 1000,
'randomize_ligand': False,
'randomize_ligand_sigma_multiplier': 2.0,
'randomize_ligand_close_cutoff': 1.5 * unit.angstrom,
'number_of_equilibration_iterations': 0,
'equilibration_timestep': 1.0 * unit.femtosecond,
'checkpoint_interval': 10,
'store_solute_trajectory': True
}
def __init__(self, sampler, thermodynamic_state, sampler_states, topography,
protocol, storage, restraint=None, alchemical_regions=None,
alchemical_factory=None, metadata=None, **options):
self.sampler = sampler
self.thermodynamic_state = thermodynamic_state
self.sampler_states = sampler_states
self.topography = topography
self.protocol = protocol
self.storage = storage
self.restraint = restraint
self.alchemical_regions = alchemical_regions
self.alchemical_factory = alchemical_factory
self.metadata = metadata
self.options = self.DEFAULT_OPTIONS.copy()
self.options.update(options)
def create_alchemical_phase(self):
"""
Create the alchemical phase based on all the options
This only creates it, but does nothing else to prepare for simulations. The ``initialize_alchemical_phase``
will actually minimize, randomize ligand, and/or equilibrate if requested.
Returns
-------
alchemical_phase : yank.yank.AlchemicalPhase
See Also
--------
initialize_alchemical_phase
"""
alchemical_phase = AlchemicalPhase(self.sampler)
create_kwargs = self.__dict__.copy()
create_kwargs.pop('options')
create_kwargs.pop('sampler')
# Create a reporter if this is only a path.
if isinstance(self.storage, str):
checkpoint_interval = self.options['checkpoint_interval']
# Get the solute atoms
if self.options['store_solute_trajectory']:
# "Solute" is basically just not water. Includes all non-water atoms and ions
# Topography ensures the union of solute_atoms and ions_atoms is a null set
solute_atoms = self.topography.solute_atoms + self.topography.ions_atoms
if checkpoint_interval == 1:
logger.warning("WARNING! You have specified both a solute-only trajectory AND a checkpoint "
"interval of 1! You are about write the trajectory of the solute twice!\n"
"This can be okay if you are running explicit solvent and want faster retrieval "
"of the solute atoms, but in implicit solvent, this is redundant.")
else:
solute_atoms = ()
# We don't allow checkpoint file overwriting in YAML file
reporter = multistate.MultiStateReporter(self.storage, checkpoint_interval=checkpoint_interval,
analysis_particle_indices=solute_atoms)
create_kwargs['storage'] = reporter
self.storage = reporter
dispersion_cutoff = self.options['anisotropic_dispersion_cutoff'] # This will be None or an option
alchemical_phase.create(anisotropic_dispersion_cutoff=dispersion_cutoff,
**create_kwargs)
return alchemical_phase
def initialize_alchemical_phase(self):
"""
Create and set all the initial options for the alchemical phase
This minimizes, randomizes_ligand, and equilibrates the alchemical_phase on top of creating it, if the various
options are set
Returns
-------
alchemical_phase : yank.yank.AlchemicalPhase
"""
alchemical_phase = self.create_alchemical_phase()
# Minimize if requested.
if self.options['minimize']:
tolerance = self.options['minimize_tolerance']
max_iterations = self.options['minimize_max_iterations']
alchemical_phase.minimize(tolerance=tolerance, max_iterations=max_iterations)
# Randomize ligand if requested.
if self.options['randomize_ligand']:
sigma_multiplier = self.options['randomize_ligand_sigma_multiplier']
close_cutoff = self.options['randomize_ligand_close_cutoff']
alchemical_phase.randomize_ligand(sigma_multiplier=sigma_multiplier,
close_cutoff=close_cutoff)
# Equilibrate if requested.
if self.options['number_of_equilibration_iterations'] > 0:
n_iterations = self.options['number_of_equilibration_iterations']
# Get main propagation move. If this is a sequence, find first IntegratorMove.
mcmc_move = self.sampler.mcmc_moves[0]
try:
integrator_moves = [move for move in mcmc_move.move_list
if isinstance(move, mmtools.mcmc.BaseIntegratorMove)]
mcmc_move = copy.deepcopy(integrator_moves[0])
except AttributeError:
mcmc_move = copy.deepcopy(mcmc_move)
logger.debug('Using {} for equilibration.'.format(mcmc_move))
# Fix move parameters for equilibration.
move_parameters = dict(
n_steps=500,
n_restart_attempts=6,
timestep=self.options['equilibration_timestep'],
collision_rate=90.0/unit.picosecond,
measure_shadow_work=False,
measure_heat=False
)
for parameter_name, parameter_value in move_parameters.items():
if hasattr(mcmc_move, parameter_name):
setattr(mcmc_move, parameter_name, parameter_value)
# Run equilibration.
alchemical_phase.equilibrate(n_iterations, mcmc_moves=mcmc_move)
return alchemical_phase
class Experiment(object):
"""
An experiment built by :class:`ExperimentBuilder`.
This is a completely defined experiment with all parameters and settings ready to go.
It is highly recommended to **NOT** use this class directly, and instead rely on the :class:`ExperimentBuilder`
class to parse all options, configure all phases, properly set up the experiments, and even run them.
These experiments are frequently created with the :func:`ExperimentBuilder.build_experiments` method.
Parameters
----------
phases : list of yank.yank.AlchemicalPhases
Phases to run for the experiment
number_of_iterations : int or infinity
Total number of iterations each phase will be run for. Both
``float('inf')`` and ``numpy.inf`` are accepted for infinity.
switch_phase_interval : int
Number of iterations each phase will be run before the cycling to the next phase
Attributes
----------
iteration
See Also
--------
ExperimentBuilder
"""
def __init__(self, phases, number_of_iterations, switch_phase_interval):
self.phases = phases
self.number_of_iterations = number_of_iterations
self.switch_phase_interval = switch_phase_interval
self._phases_last_iterations = [None, None]
self._are_phases_completed = [False, False]
@property
def iteration(self):
"""pair of int, Current total number of iterations which have been run for each phase."""
if None in self._phases_last_iterations:
return 0, 0
return self._phases_last_iterations
@property
def is_completed(self):
return all(self._are_phases_completed)
def run(self, n_iterations=None):
"""
Run the experiment.
Runs until either the maximum number of iterations have been reached or the sampler
for that phase reports its own completion (e.g. online analysis)
Parameters
----------
n_iterations : int or None, Optional, Default: None
Optional parameter to run for a finite number of iterations instead of up to the maximum number of
iterations.
"""
# Handle default argument.
if n_iterations is None:
n_iterations = self.number_of_iterations
# Handle case in which we don't alternate between phases.
if self.switch_phase_interval <= 0:
switch_phase_interval = self.number_of_iterations
else:
switch_phase_interval = self.switch_phase_interval
# Count down the iterations to run.
iterations_left = [None, None]
while iterations_left != [0, 0]:
# Alternate phases every switch_phase_interval iterations.
for phase_id, phase in enumerate(self.phases):
# Phases may get out of sync if the user delete the storage
# file of only one phase and restart. Here we check that the
# phase still has iterations to run before creating it.
if self._are_phases_completed[phase_id]:
iterations_left[phase_id] = 0
continue
# If this is a new simulation, initialize alchemical phase.
if isinstance(phase, AlchemicalPhaseFactory):
alchemical_phase = phase.initialize_alchemical_phase()
self.phases[phase_id] = phase.storage # Should automatically be a Reporter class
else: # Resume previously created simulation.
# Check the status before loading the full alchemical phase object.
status = AlchemicalPhase.read_status(phase)
if _is_phase_completed(status, self.number_of_iterations):
self._are_phases_completed[phase_id] = True
iterations_left[phase_id] = 0
continue
alchemical_phase = AlchemicalPhase.from_storage(phase)
# TODO allow users to change online analysis options on resuming.
# Update total number of iterations. This may write the new number
# of iterations in the storage file so we do it only if necessary.
if alchemical_phase.number_of_iterations != self.number_of_iterations:
alchemical_phase.number_of_iterations = self.number_of_iterations
# Determine number of iterations to run in this function call.
if iterations_left[phase_id] is None:
total_iterations_left = self.number_of_iterations - alchemical_phase.iteration
iterations_left[phase_id] = min(n_iterations, total_iterations_left)
# Run simulation for iterations_left or until we have to switch phase.
iterations_to_run = min(iterations_left[phase_id], switch_phase_interval)
try:
alchemical_phase.run(n_iterations=iterations_to_run)
except multistate.SimulationNaNError:
# Simulation has NaN'd, this experiment is done, flag phases as done and send error up stack
self._are_phases_completed = [True] * len(self._are_phases_completed)
raise
# Check if the phase has converged.
self._are_phases_completed[phase_id] = alchemical_phase.is_completed
# Update phase iteration info. iterations_to_run may be infinity
# if number_of_iterations is.
if iterations_to_run == float('inf') and self._are_phases_completed[phase_id]:
iterations_left[phase_id] = 0
else:
iterations_left[phase_id] -= iterations_to_run
self._phases_last_iterations[phase_id] = alchemical_phase.iteration
# Delete alchemical phase and prepare switching.
del alchemical_phase
class ExperimentBuilder(object):
"""Parse YAML configuration file and build the experiment.
The relative paths indicated in the script are assumed to be relative to
the script directory. However, if ExperimentBuilder is initiated with a string
rather than a file path, the paths will be relative to the user's working
directory.
The class firstly perform a dry run to check if this is going to overwrite
some files and raises an exception if it finds already existing output folders
unless the options resume_setup or resume_simulation are True.
Parameters
----------
script : str or dict
A path to the YAML script or the YAML content. If not specified, you
can load it later by using :func:`parse` (default is None).
job_id : None or int
If you want to split the experiments among different executions,
you can set this to an integer 1 <= job_id <= n_jobs, and this
:class:`ExperimentBuilder` will run only 1/n_jobs of the experiments.
n_jobs : None or int
If ``job_id`` is specified, this is the total number of jobs that
you are running in parallel from your script.
See Also
--------
Experiment
Examples
--------
>>> import textwrap
>>> import openmmtools as mmtools
>>> import yank.utils
>>> setup_dir = yank.utils.get_data_filename(os.path.join('..', 'examples',
... 'p-xylene-implicit', 'input'))
>>> pxylene_path = os.path.join(setup_dir, 'p-xylene.mol2')
>>> lysozyme_path = os.path.join(setup_dir, '181L-pdbfixer.pdb')
>>> with mmtools.utils.temporary_directory() as tmp_dir:
... yaml_content = '''
... ---
... options:
... default_number_of_iterations: 1
... output_dir: {}
... molecules:
... T4lysozyme:
... filepath: {}
... p-xylene:
... filepath: {}
... antechamber:
... charge_method: bcc
... solvents:
... vacuum:
... nonbonded_method: NoCutoff
... systems:
... my_system:
... receptor: T4lysozyme
... ligand: p-xylene
... solvent: vacuum
... leap:
... parameters: [leaprc.gaff, leaprc.ff14SB]
... protocols:
... absolute-binding:
... complex:
... alchemical_path:
... lambda_electrostatics: [1.0, 0.9, 0.8, 0.6, 0.4, 0.2, 0.0]
... lambda_sterics: [1.0, 0.9, 0.8, 0.6, 0.4, 0.2, 0.0]
... solvent:
... alchemical_path:
... lambda_electrostatics: [1.0, 0.8, 0.6, 0.3, 0.0]
... lambda_sterics: [1.0, 0.8, 0.6, 0.3, 0.0]
... experiments:
... system: my_system
... protocol: absolute-binding
... '''.format(tmp_dir, lysozyme_path, pxylene_path)
>>> yaml_builder = ExperimentBuilder(textwrap.dedent(yaml_content))
>>> yaml_builder.run_experiments()
"""
# --------------------------------------------------------------------------
# Public API
# --------------------------------------------------------------------------
# These are options that can be specified only in the main "options" section.
GENERAL_DEFAULT_OPTIONS = {
'verbose': False,
'resume_setup': False,
'resume_simulation': False,
'output_dir': 'output',
'setup_dir': 'setup',
'experiments_dir': 'experiments',
'platform': 'fastest',
'precision': 'auto',
'max_n_contexts': 3,
'switch_experiment_interval': 0,
'processes_per_experiment': 'auto'
}
# These options can be overwritten also in the "experiment"
# section and they can be thus combinatorially expanded.
EXPERIMENT_DEFAULT_OPTIONS = {
'switch_phase_interval': 0,
'temperature': 298 * unit.kelvin,
'pressure': 1 * unit.atmosphere,
'constraints': openmm.app.HBonds,
'hydrogen_mass': 1 * unit.amu,
'default_nsteps_per_iteration': 500,
'default_timestep': 2.0 * unit.femtosecond,
'default_number_of_iterations': 5000
}
def __init__(self, script=None, job_id=None, n_jobs=None):
"""
Constructor.
"""
# Check consistency job_id and n_jobs.
if job_id is not None:
if n_jobs is None:
raise ValueError('n_jobs must be specified together with job_id')
if not 1 <= job_id <= n_jobs:
raise ValueError('job_id must be between 1 and n_jobs ({})'.format(n_jobs))
self._job_id = job_id
self._n_jobs = n_jobs
self._options = self.GENERAL_DEFAULT_OPTIONS.copy()
self._options.update(self.EXPERIMENT_DEFAULT_OPTIONS.copy())
self._version = None
self._script_dir = os.getcwd() # basic dir for relative paths
self._db = None # Database containing molecules created in parse()
self._raw_yaml = {} # Unconverted input YAML script, helpful for
self._expanded_raw_yaml = {} # Raw YAML with selective keys chosen and blank dictionaries for missing keys
self._protocols = {} # Alchemical protocols description
self._experiments = {} # Experiments description
# Parse YAML script
if script is not None:
self.parse(script)
def update_yaml(self, script):
"""
Update the current yaml content and reparse it
Parameters
----------
script : str or dict
String which accepts multiple forms of YAML content that is one of the following:
File path to the YAML file
String containing all the YAML data
Dict of yaml content you wish to replace
See Also
--------
utils.update_nested_dict
"""
current_content = self._raw_yaml
try:
with open(script, 'r') as f:
new_content = yaml.load(f, Loader=YankLoader)
except IOError: # string
new_content = yaml.load(script, Loader=YankLoader)
except TypeError: # dict
new_content = script.copy()
combined_content = utils.update_nested_dict(current_content, new_content)
self.parse(combined_content)
def parse(self, script):
"""Parse the given YAML configuration file.
Validate the syntax and load the script into memory. This does not build
the actual experiment.
Parameters
----------
script : str or dict
A path to the YAML script or the YAML content.
Raises
------
YamlParseError
If the input YAML script is syntactically incorrect.
"""
# TODO check version of yank-yaml language
# TODO what if there are multiple streams in the YAML file?
# Load YAML script and decide working directory for relative paths
try:
with open(script, 'r') as f:
yaml_content = yaml.load(f, Loader=YankLoader)
self._script_dir = os.path.dirname(script)
except IOError: # string
yaml_content = yaml.load(script, Loader=YankLoader)
except TypeError: # dict
yaml_content = script.copy()
self._raw_yaml = yaml_content.copy()
# Check that YAML loading was successful
if yaml_content is None:
raise YamlParseError('The YAML file is empty!')
if not isinstance(yaml_content, dict):
raise YamlParseError('Cannot load YAML from source: {}'.format(script))
# Check version (currently there's only one)
try:
self._version = yaml_content['version']
except KeyError:
self._version = HIGHEST_VERSION
else:
if self._version != HIGHEST_VERSION:
raise ValueError('Unsupported syntax version {}'.format(self._version))
# Expand combinatorial molecules and systems
yaml_content = self._expand_molecules(yaml_content)
yaml_content = self._expand_systems(yaml_content)
# Save raw YAML content that will be needed when generating the YAML files
self._expanded_raw_yaml = copy.deepcopy({key: yaml_content.get(key, {})
for key in ['options', 'molecules', 'solvents',
'systems', 'protocols']})
# Validate options and overwrite defaults
self._options.update(self._validate_options(yaml_content.get('options', {}),
validate_general_options=True))
# Setup general logging
utils.config_root_logger(self._options['verbose'], log_file_path=None)
# Configure ContextCache, platform and precision. A Yank simulation
# currently needs 3 contexts: 1 for the alchemical states and 2 for
# the states with expanded cutoff.
platform = self._configure_platform(self._options['platform'],
self._options['precision'])
try:
mmtools.cache.global_context_cache.platform = platform
except RuntimeError:
# The cache has been already used. Empty it before switching platform.
mmtools.cache.global_context_cache.empty()
mmtools.cache.global_context_cache.platform = platform
mmtools.cache.global_context_cache.capacity = self._options['max_n_contexts']
# Initialize and configure database with molecules, solvents and systems
setup_dir = os.path.join(self._options['output_dir'], self._options['setup_dir'])
self._db = pipeline.SetupDatabase(setup_dir=setup_dir)
self._db.molecules = self._validate_molecules(yaml_content.get('molecules', {}))
self._db.solvents = self._validate_solvents(yaml_content.get('solvents', {}))
self._db.systems = self._validate_systems(yaml_content.get('systems', {}))
# Validate protocols
self._mcmc_moves = self._validate_mcmc_moves(yaml_content)
self._samplers = self._validate_samplers(yaml_content)
self._protocols = self._validate_protocols(yaml_content.get('protocols', {}))
# Validate experiments
self._parse_experiments(yaml_content)
def run_experiments(self):
"""
Set up and run all the Yank experiments.
See Also
--------
Experiment
"""
# Throw exception if there are no experiments
if len(self._experiments) == 0:
raise YamlParseError('No experiments specified!')
# Setup and run all experiments with paths relative to the script directory.
with moltools.utils.temporary_cd(self._script_dir):
self._check_resume()
self._setup_experiments()
self._generate_experiments_protocols()
# Find all the experiments to distribute among mpicomms.
all_experiments = list(self._expand_experiments())
# Cycle between experiments every switch_experiment_interval iterations
# until all of them are done.
while len(all_experiments) > 0:
# Allocate the MPI processes to the experiments that still have to be completed.
group_size = self._get_experiment_mpi_group_size(all_experiments)
if group_size is None:
completed = [False] * len(all_experiments)
for exp_index, exp in enumerate(all_experiments):
completed[exp_index] = self._run_experiment(exp)
else:
completed = mpi.distribute(self._run_experiment,
distributed_args=all_experiments,
group_size=group_size,
send_results_to='all')
# Remove any completed experiments, releasing possible parallel resources
# to be reused. Evaluate in reverse order to avoid shuffling indices.
for exp_index in range(len(all_experiments)-1, -1, -1):
if completed[exp_index]:
all_experiments.pop(exp_index)
def build_experiments(self):
"""
Generator to configure, build, and yield an experiment
Yields
------
Experiment
"""
# Throw exception if there are no experiments
if len(self._experiments) == 0:
raise YamlParseError('No experiments specified!')
# Setup and iterate over all experiments with paths relative to the script directory
with moltools.utils.temporary_cd(self._script_dir):
self._check_resume()
self._setup_experiments()
self._generate_experiments_protocols()
for experiment_path, combination in self._expand_experiments():
yield self._build_experiment(experiment_path, combination)
def setup_experiments(self):
"""
Set up all systems required for the Yank experiments without running them.
"""
# All paths must be relative to the script directory
with moltools.utils.temporary_cd(self._script_dir):
self._check_resume(check_experiments=False)
self._setup_experiments()
def status(self):
"""Iterate over the status of all experiments in dictionary form.
The status of each experiment is set to "completed" if both phases
in the experiments have been completed, "pending" if they are both
pending, and "ongoing" otherwise.
Yields
------
experiment_status : namedtuple
The status of the experiment. It contains the following fields:
name : str
The name of the experiment.
status : str
One between "completed", "ongoing", or "pending".
number_of_iterations : int
The total number of iteration set for this experiment.
job_id : int or None
If njobs is specified, this includes the job id associated
to this experiment.
phases : dict
phases[phase_name] is a namedtuple describing the status
of phase ``phase_name``. The namedtuple has two fields:
``iteration`` and ``status``.
"""
# TODO use Python 3.6 namedtuple syntax when we drop Python 3.5 support.
PhaseStatus = collections.namedtuple('PhaseStatus', [
'status',
'iteration'
])
ExperimentStatus = collections.namedtuple('ExperimentStatus', [
'name',
'status',
'phases',
'number_of_iterations',
'job_id'
])
for experiment_idx, (exp_path, exp_description) in enumerate(self._expand_experiments()):
# Determine the final number of iterations for this experiment.
number_of_iterations = self._get_experiment_number_of_iterations(exp_description)
# Determine the phases status.
phases = collections.OrderedDict()
for phase_nc_path in self._get_nc_file_paths(exp_path, exp_description):
# Determine the status of the phase.
try:
phase_status = AlchemicalPhase.read_status(phase_nc_path)
except FileNotFoundError:
iteration = None
phase_status = 'pending'
else:
iteration = phase_status.iteration
if _is_phase_completed(phase_status, number_of_iterations):
phase_status = 'completed'
else:
phase_status = 'ongoing'
phase_name = os.path.splitext(os.path.basename(phase_nc_path))[0]
phases[phase_name] = PhaseStatus(status=phase_status, iteration=iteration)
# Determine the status of the whole experiment.
phase_statuses = [phase.status for phase in phases.values()]
if phase_statuses[0] == phase_statuses[1]:
# This covers the completed and pending status.
exp_status = phase_statuses[0]
else:
exp_status = 'ongoing'
# Determine jobid if requested.
if self._n_jobs is not None:
job_id = experiment_idx % self._n_jobs + 1
else:
job_id = None
yield ExperimentStatus(name=exp_path, status=exp_status,
phases=phases, job_id=job_id,
number_of_iterations=number_of_iterations)
# --------------------------------------------------------------------------
# Properties
# --------------------------------------------------------------------------
@property
def verbose(self):
"""bool: the log verbosity."""
return self._options['verbose']
@verbose.setter
def verbose(self, new_verbose):
self._options['verbose'] = new_verbose
utils.config_root_logger(self._options['verbose'], log_file_path=None)
@property
def output_dir(self):
"""The path to the main output directory."""
return self._options['output_dir']
@output_dir.setter
def output_dir(self, new_output_dir):
self._options['output_dir'] = new_output_dir
self._db.setup_dir = os.path.join(new_output_dir, self.setup_dir)
@property
def setup_dir(self):
"""The path to the setup files directory relative to the output folder.."""
return self._options['setup_dir']
@setup_dir.setter
def setup_dir(self, new_setup_dir):
self._options['setup_dir'] = new_setup_dir
self._db.setup_dir = os.path.join(self.output_dir, new_setup_dir)
# --------------------------------------------------------------------------
# Options handling
# --------------------------------------------------------------------------
def _determine_experiment_options(self, experiment):
"""Determine all the options required to build the experiment.
Merge the options specified in the experiment section with the ones
in the options section, and divide them into several dictionaries to
feed to different main classes necessary to create an AlchemicalPhase.
Parameters
----------
experiment : dict
The dictionary encoding the experiment.
Returns
-------
experiment_options : dict
The ExperimentBuilder experiment options. This does not contain
the general ExperimentBuilder options that are accessible through
self._options.
phase_options : dict
The options to pass to the AlchemicalPhaseFactory constructor.
alchemical_region_options : dict
The options to pass to AlchemicalRegion.
alchemical_factory_options : dict
The options to pass to AlchemicalFactory.
"""
# First discard general options.
options = {name: value for name, value in self._options.items()
if name not in self.GENERAL_DEFAULT_OPTIONS}
# Then update with specific experiment options.
options.update(self._validate_options(experiment.get('options', {}),
validate_general_options=False))
def _filter_options(reference_options):
return {name: value for name, value in options.items()
if name in reference_options}
experiment_options = _filter_options(self.EXPERIMENT_DEFAULT_OPTIONS)
phase_options = _filter_options(AlchemicalPhaseFactory.DEFAULT_OPTIONS)
alchemical_region_options = _filter_options(mmtools.alchemy._ALCHEMICAL_REGION_ARGS)
alchemical_factory_options = _filter_options(utils.get_keyword_args(
mmtools.alchemy.AbsoluteAlchemicalFactory.__init__))
return (experiment_options, phase_options,
alchemical_region_options, alchemical_factory_options)
# --------------------------------------------------------------------------
# Combinatorial expansion
# --------------------------------------------------------------------------
def _expand_molecules(self, yaml_content):