-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathtest_experiment.py
2953 lines (2571 loc) · 131 KB
/
test_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
# =============================================================================================
"""
Test YAML functions.
"""
# =============================================================================================
# GLOBAL IMPORTS
# =============================================================================================
import itertools
import shutil
import tempfile
import textwrap
import time
import unittest
import mdtraj
from nose.plugins.attrib import attr
from nose.tools import assert_raises, assert_equal, assert_raises_regexp
from yank.experiment import *
# silence the citations at a global level
multistate.MultiStateSampler._global_citation_silence = True
# ==============================================================================
# Subroutines for testing
# ==============================================================================
standard_protocol = """
absolute-binding:
complex:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]
solvent:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]"""
def indent(input_string):
"""Put 4 extra spaces in front of every line."""
return '\n '.join(input_string.split('\n'))
def examples_paths():
"""Return the absolute path to the Yank examples relevant to tests."""
data_dir = utils.get_data_filename(os.path.join('tests', 'data'))
p_xylene_dir = os.path.join(data_dir, 'p-xylene-implicit')
p_xylene_gro_dir = os.path.join(data_dir, 'p-xylene-gromacs-example')
ben_tol_dir = os.path.join(data_dir, 'benzene-toluene-explicit')
abl_imatinib_dir = os.path.join(data_dir, 'abl-imatinib-explicit')
tol_dir = os.path.join(data_dir, 'toluene-explicit')
benz_tol_dir = os.path.join(data_dir, 'benzene-toluene-standard-state')
paths = dict()
paths['lysozyme'] = os.path.join(p_xylene_dir, '181L-pdbfixer.pdb')
paths['p-xylene'] = os.path.join(p_xylene_dir, 'p-xylene.mol2')
paths['benzene'] = os.path.join(ben_tol_dir, 'benzene.tripos.mol2')
paths['toluene'] = os.path.join(ben_tol_dir, 'toluene.tripos.mol2')
paths['abl'] = os.path.join(abl_imatinib_dir, '2HYY-pdbfixer.pdb')
paths['imatinib'] = os.path.join(abl_imatinib_dir, 'STI02.mol2')
paths['bentol-complex'] = [os.path.join(ben_tol_dir, 'complex.prmtop'),
os.path.join(ben_tol_dir, 'complex.inpcrd')]
paths['bentol-solvent'] = [os.path.join(ben_tol_dir, 'solvent.prmtop'),
os.path.join(ben_tol_dir, 'solvent.inpcrd')]
paths['pxylene-complex'] = [os.path.join(p_xylene_gro_dir, 'complex.top'),
os.path.join(p_xylene_gro_dir, 'complex.gro')]
paths['pxylene-solvent'] = [os.path.join(p_xylene_gro_dir, 'solvent.top'),
os.path.join(p_xylene_gro_dir, 'solvent.gro')]
paths['pxylene-gro-include'] = os.path.join(p_xylene_gro_dir, 'top')
paths['toluene-solvent'] = [os.path.join(tol_dir, 'solvent.pdb'),
os.path.join(tol_dir, 'solvent.xml')]
paths['toluene-vacuum'] = [os.path.join(tol_dir, 'vacuum.pdb'),
os.path.join(tol_dir, 'vacuum.xml')]
paths['benzene-toluene-boxless'] = [os.path.join(benz_tol_dir, 'standard_state_complex_boxless.inpcrd'),
os.path.join(benz_tol_dir, 'standard_state_complex.prmtop')]
paths['benzene-toluene-nan'] = [os.path.join(benz_tol_dir, 'standard_state_complex_nan.inpcrd'),
os.path.join(benz_tol_dir, 'standard_state_complex.prmtop')]
return paths
def yank_load(script):
"""Shortcut to load a string YAML script with YankLoader."""
return yaml.load(textwrap.dedent(script), Loader=YankLoader)
def get_template_script(output_dir='.', keep_schrodinger=False, keep_openeye=False):
"""Return a YAML template script as a dict."""
paths = examples_paths()
template_script = """
---
options:
output_dir: {output_dir}
default_number_of_iterations: 0
temperature: 300*kelvin
pressure: 1*atmosphere
minimize: no
verbose: no
default_nsteps_per_iteration: 1
molecules:
benzene:
filepath: {benzene_path}
antechamber: {{charge_method: bcc}}
benzene-epik0:
filepath: {benzene_path}
epik:
select: 0
antechamber: {{charge_method: bcc}}
benzene-epikcustom:
filepath: {benzene_path}
epik:
select: 0
ph: 7.0
tautomerize: yes
antechamber: {{charge_method: bcc}}
p-xylene:
filepath: {pxylene_path}
antechamber: {{charge_method: bcc}}
p-xylene-name:
name: p-xylene
openeye: {{quacpac: am1-bcc}}
antechamber: {{charge_method: null}}
toluene:
filepath: {toluene_path}
antechamber: {{charge_method: bcc}}
toluene-smiles:
smiles: Cc1ccccc1
antechamber: {{charge_method: bcc}}
toluene-name:
name: toluene
antechamber: {{charge_method: bcc}}
Abl:
filepath: {abl_path}
T4Lysozyme:
filepath: {lysozyme_path}
solvents:
vacuum:
nonbonded_method: NoCutoff
GBSA-OBC2:
nonbonded_method: NoCutoff
implicit_solvent: OBC2
PME:
nonbonded_method: PME
nonbonded_cutoff: 1*nanometer
clearance: 10*angstroms
positive_ion: Na+
negative_ion: Cl-
leap:
parameters: [leaprc.water.tip4pew]
systems:
explicit-system:
receptor: benzene
ligand: toluene
solvent: PME
leap:
parameters: [leaprc.protein.ff14SB, leaprc.gaff]
implicit-system:
receptor: T4Lysozyme
ligand: p-xylene
solvent: GBSA-OBC2
leap:
parameters: [leaprc.protein.ff14SB, leaprc.gaff]
hydration-system:
solute: toluene
solvent1: PME
solvent2: vacuum
leap:
parameters: [leaprc.protein.ff14SB, leaprc.gaff]
mcmc_moves:
single:
type: LangevinSplittingDynamicsMove
sequence:
type: SequenceMove
move_list:
- type: MCDisplacementMove
- type: LangevinDynamicsMove
samplers:
repex:
type: ReplicaExchangeSampler
sams:
type: SAMSSampler
protocols:
absolute-binding:
complex:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]
solvent:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]
hydration-protocol:
solvent1:
alchemical_path:
lambda_electrostatics: [1.0, 0.0]
lambda_sterics: [1.0, 0.0]
solvent2:
alchemical_path:
lambda_electrostatics: [1.0, 0.0]
lambda_sterics: [1.0, 1.0]
experiments:
system: explicit-system
protocol: absolute-binding
""".format(output_dir=output_dir, benzene_path=paths['benzene'],
pxylene_path=paths['p-xylene'], toluene_path=paths['toluene'],
abl_path=paths['abl'], lysozyme_path=paths['lysozyme'])
# Load script as dictionary.
script_dict = yank_load(template_script)
# Find all molecules that require optional tools.
molecules_to_remove = []
for molecule_id, molecule_description in script_dict['molecules'].items():
need_schrodinger = 'epik' in molecule_description
need_openeye = any([k in molecule_description for k in ['name', 'smiles', 'openeye']])
if ((need_schrodinger and not keep_schrodinger) or
(need_openeye and not keep_openeye)):
molecules_to_remove.append(molecule_id)
# Remove molecules.
for molecule_id in molecules_to_remove:
del script_dict['molecules'][molecule_id]
return script_dict
def get_functionality_script(output_directory=',', number_of_iter=0, experiment_repeats=1, number_nan_repeats=0):
"""
A computationally simple pre-setup system which can be loaded to manipulate a formal experiment
Should not be used for scientific testing per-se, but can be used to test functional components of experiment
Parameters
==========
output_directory : str, Optional
Output directory to set in script
number_of_iter : int Optional, Default: 1
Number of iterations to run
experiment_repeats : int, Optional, Default: 1
Number of times the experiment is repeated in a "experiments" header
number_nan_repeats : int, Optional, Default: 0
Number of times the experiment with a NaN is repeated, this will be added to the end of the stack
"""
paths = examples_paths()
template_script = """
---
options:
minimize: no
verbose: no
output_dir: {output_directory}
default_number_of_iterations: {number_of_iter}
default_nsteps_per_iteration: 10
temperature: 300*kelvin
pressure: null
anisotropic_dispersion_cutoff: null
solvents:
vacuum:
nonbonded_method: NoCutoff
systems:
premade:
phase1_path: {boxless_path}
phase2_path: {boxless_path}
ligand_dsl: resname ene
solvent: vacuum
premade_nan:
phase1_path: {nan_path}
phase2_path: {nan_path}
ligand_dsl: resname ene
solvent: vacuum
protocols:
absolute-binding:
complex:
alchemical_path:
lambda_electrostatics: [0.0, 0.0]
lambda_sterics: [0.0, 0.0]
solvent:
alchemical_path:
lambda_electrostatics: [1.0, 1.0]
lambda_sterics: [1.0, 1.0]
the_exp:
system: premade
protocol: absolute-binding
restraint:
type: FlatBottom
the_nan_exp:
system: premade_nan
protocol: absolute-binding
restraint:
type: FlatBottom
experiments: [{repeating}]
"""
repeating_string = ', '.join(['the_exp'] * experiment_repeats)
repeating_nan_string = ', '.join(['the_nan_exp'] * number_nan_repeats)
if repeating_string != '':
repeating_string += ', '
repeating_string += repeating_nan_string
return yank_load(template_script.format(output_directory=output_directory,
number_of_iter=number_of_iter,
repeating=repeating_string,
boxless_path=paths['benzene-toluene-boxless'],
nan_path=paths['benzene-toluene-nan']))
# ==============================================================================
# YAML parsing and validation
# ==============================================================================
def test_yaml_parsing():
"""Check that YAML file is parsed correctly."""
# Parser handles no options
yaml_content = """
---
test: 2
"""
exp_builder = ExperimentBuilder(textwrap.dedent(yaml_content))
# The plus 1 is because we overwrite disable_alchemical_dispersion_correction.
expected_n_options = (len(exp_builder.GENERAL_DEFAULT_OPTIONS) +
len(exp_builder.EXPERIMENT_DEFAULT_OPTIONS) + 1)
assert len(exp_builder._options) == expected_n_options
# Correct parsing
yaml_content = """
---
options:
verbose: true
resume_setup: true
resume_simulation: true
output_dir: /path/to/output/
setup_dir: /path/to/output/setup/
experiments_dir: /path/to/output/experiments/
platform: CPU
precision: mixed
switch_experiment_interval: -2.0
processes_per_experiment: 2
max_n_contexts: 9
switch_phase_interval: 32
temperature: 300*kelvin
pressure: null
constraints: AllBonds
hydrogen_mass: 2*amus
randomize_ligand: yes
randomize_ligand_sigma_multiplier: 1.0e-2
randomize_ligand_close_cutoff: 1.5 * angstrom
anisotropic_dispersion_cutoff: null
default_timestep: 2.0 * femtosecond
default_nsteps_per_iteration: 2500
default_number_of_iterations: .inf
equilibration_timestep: 1.0 * femtosecond
number_of_equilibration_iterations: 100
minimize: False
minimize_tolerance: 1.0 * kilojoules_per_mole / nanometers
minimize_max_iterations: 0
annihilate_sterics: no
annihilate_electrostatics: true
alchemical_pme_treatment: direct-space
disable_alchemical_dispersion_correction: no
"""
exp_builder = ExperimentBuilder(textwrap.dedent(yaml_content))
assert len(exp_builder._options) == 32
# The global context cache has been set.
assert mmtools.cache.global_context_cache.capacity == 9
# Check correct types
assert exp_builder._options['output_dir'] == '/path/to/output/'
assert exp_builder._options['pressure'] is None
assert exp_builder._options['constraints'] == openmm.app.AllBonds
assert exp_builder._options['anisotropic_dispersion_cutoff'] is None
assert exp_builder._options['default_timestep'] == 2.0 * unit.femtoseconds
assert exp_builder._options['randomize_ligand_sigma_multiplier'] == 1.0e-2
assert exp_builder._options['default_nsteps_per_iteration'] == 2500
assert type(exp_builder._options['default_nsteps_per_iteration']) is int
assert exp_builder._options['default_number_of_iterations'] == float('inf')
assert exp_builder._options['number_of_equilibration_iterations'] == 100
assert type(exp_builder._options['number_of_equilibration_iterations']) is int
assert exp_builder._options['minimize'] is False
def test_paths_properties():
"""Test that setup directory is updated correctly when changing output paths."""
template_script = get_template_script(output_dir='output1')
template_script['options']['setup_dir'] = 'setup1'
exp_builder = ExperimentBuilder(template_script)
# The database path is configured correctly.
assert exp_builder._db.setup_dir == os.path.join('output1', 'setup1')
# Updating paths also updates the database main directory.
exp_builder.output_dir = 'output2'
exp_builder.setup_dir = 'setup2'
assert exp_builder._db.setup_dir == os.path.join('output2', 'setup2')
def test_online_reads_checkpoint():
"""Test that online analysis reads the checkpoint correctly in all cases"""
current_log_level = logger.level
logger.setLevel(logging.ERROR) # Temporarily suppress some of the logging output
raw_template_script = get_template_script()
# Pair down the processing
popables = []
for system in raw_template_script['systems'].keys():
if system != 'explicit-system':
popables.append(system)
for popable in popables:
raw_template_script['systems'].pop(popable)
allowed_molecules = [raw_template_script['systems']['explicit-system']['receptor'],
raw_template_script['systems']['explicit-system']['ligand']]
popables = []
for molecule in raw_template_script['molecules'].keys():
if molecule not in allowed_molecules:
popables.append(molecule)
for popable in popables:
raw_template_script['molecules'].pop(popable)
raw_template_script.pop('samplers')
sampler_entry = {'type': 'SAMSSampler'}
sampler = {'samplers': {'sams': sampler_entry}}
base_template_script = {**raw_template_script, **sampler}
base_template_script['experiments']['sampler'] = 'sams'
def spinup_sampler(script):
with mmtools.utils.temporary_directory() as tmp_dir:
template_script['options']['output_dir'] = tmp_dir
exp_builder = ExperimentBuilder(script)
experiment = [ex for ex in exp_builder.build_experiments()][0]
sampler = experiment.phases[0].sampler
return sampler
# Testing Note: All the test numbers for the checkpoint_interval below are different from the default and each
# other to ensure making changes actually has the intended effect odd settings get carried over between tests
# respectively.
# Test that setting "checkpoint" for online analysis gets the checkpoint interval default
template_script = copy.deepcopy(base_template_script)
template_script['options'].pop("checkpoint_interval", None)
template_script['samplers']['sams']['online_analysis_interval'] = "checkpoint"
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == AlchemicalPhaseFactory.DEFAULT_OPTIONS['checkpoint_interval']
# Test that setting "checkpoint" for online analysis gets the checkpoint interval that is set
template_script['options']["checkpoint_interval"] = 10
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == 10
# Test that not setting online analysis gets the checkpoint interval default
template_script = copy.deepcopy(base_template_script)
template_script['options'].pop("checkpoint_interval", None)
template_script['samplers']['sams'].pop('online_analysis_interval', None)
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == AlchemicalPhaseFactory.DEFAULT_OPTIONS['checkpoint_interval']
# Test that not setting online analysis gets the checkpoint interval that is set
template_script['options']["checkpoint_interval"] = 100
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == 100
# Test that setting online analysis still returns the set value
template_script = copy.deepcopy(base_template_script)
template_script['options']["checkpoint_interval"] = 70
template_script['samplers']['sams']['online_analysis_interval'] = 13
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == 13
# Test that setting online analysis to None keeps online analysis None
template_script = copy.deepcopy(base_template_script)
template_script['options']["checkpoint_interval"] = 80
template_script['samplers']['sams']['online_analysis_interval'] = None
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval is None
# Test that not setting a sampler gets a the checkpoint interval for online analysis
template_script = copy.deepcopy(base_template_script)
template_script['options']["checkpoint_interval"] = 90
template_script.pop('samplers', None)
template_script['experiments'].pop('sampler', None)
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == 90
# Test that setting the checkpoint_interval in *experiments:options* block correctly sets the checkpoint interval
template_script = copy.deepcopy(base_template_script)
template_script['options']["checkpoint_interval"] = 110
template_script.pop('samplers', None)
opts = {'checkpoint_interval': 120}
template_script['experiments'].pop('sampler', None)
template_script['experiments']['options'] = opts
sampler = spinup_sampler(template_script)
assert sampler.online_analysis_interval == 120
logger.setLevel(current_log_level) # Reset logging to normal
def test_processes_per_experiment():
"""Test the determination of processes_per_experiment option."""
# Create a script with 4 experiments.
template_script = get_template_script()
template_script['experiment1'] = copy.deepcopy(template_script['experiments'])
template_script['experiment1']['system'] = utils.CombinatorialLeaf(['explicit-system', 'implicit-system'])
# The first two experiments have less number of states than the other two.
template_script['experiment1']['protocol'] = 'hydration-protocol'
template_script['experiment2'] = copy.deepcopy(template_script['experiments'])
template_script['experiment2']['system'] = 'hydration-system'
# The last experiment uses SAMS.
template_script['experiment2']['sampler'] = utils.CombinatorialLeaf(['repex', 'sams'])
template_script['experiments'] = ['experiment1', 'experiment2']
exp_builder = ExperimentBuilder(template_script)
experiments = list(exp_builder._expand_experiments())
# The default is auto.
assert exp_builder._options['processes_per_experiment'] == 'auto'
# When there is no MPI environment the calculation is serial.
assert exp_builder._get_experiment_mpi_group_size(experiments) is None
# In an MPI environment, the MPI communicator is split according
# to the number of experiments still have to be completed. Each
# test case is pair (experiments, MPICOMM size, expected return value).
test_cases = [
(experiments, 5, 1), # This contains a SAMS sampler so only 1 MPI process is used.
(experiments[:-1], 4, [1, 1, 2]), # 3 repex samples, but last experiment has more intermediate states.
(experiments[1:-1], 4, [2, 2]), # 2 repex samples on 4 MPI processes.
(experiments[1:-1], 6, [3, 3]), # 2 repex samples on 4 MPI processes.
(list(reversed(experiments[1:-1])), 3, [2, 1]), # 2 repex samples on 3 MPI processes.
(experiments[:-1], 2, 1), # Less MPI processes than experiments, split everything.
]
for i, (exp, mpicomm_size, expected_result) in enumerate(test_cases):
with mpi._simulated_mpi_environment(size=mpicomm_size):
result = exp_builder._get_experiment_mpi_group_size(exp)
err_msg = ('experiments: {}\nMPICOMM size: {}\nexpected result: {}'
'\nresult: {}').format(*test_cases[i], result)
assert result == expected_result, err_msg
# Test manual setting of processes_per_experiments.
test_cases = [2, None]
for processes_per_experiment in test_cases:
exp_builder._options['processes_per_experiment'] = processes_per_experiment
# Serial execution is always None.
assert exp_builder._get_experiment_mpi_group_size(experiments) is None
with mpi._simulated_mpi_environment(size=5):
assert exp_builder._get_experiment_mpi_group_size(experiments[:-1]) == processes_per_experiment
# When there are SAMS sampler, it's always 1.
assert exp_builder._get_experiment_mpi_group_size(experiments) == 1
def test_validation_wrong_options():
"""YAML validation raises exception with wrong molecules."""
options = [
("found unknown parameter", {'unknown_options': 3}),
("parameter minimize=100 is incompatible with True", {'minimize': 100}),
("invalid literal for int", {'processes_per_experiment': 'incorrect_string'})
]
for regex, option in options:
yield assert_raises_regexp, YamlParseError, regex, ExperimentBuilder._validate_options, option, True
def test_validation_correct_molecules():
"""Correct molecules YAML validation."""
paths = examples_paths()
molecules = [
{'name': 'toluene', 'leap': {'parameters': 'leaprc.gaff'}},
{'name': 'toluene', 'leap': {'parameters': ['leaprc.gaff', 'toluene.frcmod']}},
{'name': 'p-xylene', 'antechamber': {'charge_method': 'bcc'}},
{'smiles': 'Cc1ccccc1', 'openeye': {'quacpac': 'am1-bcc'},
'antechamber': {'charge_method': None}},
{'name': 'p-xylene', 'antechamber': {'charge_method': 'bcc'},
'epik': {'ph': 7.6, 'ph_tolerance': 0.7, 'tautomerize': False, 'select': 0}},
{'smiles': 'Cc1ccccc1', 'openeye': {'quacpac': 'am1-bcc'},
'antechamber': {'charge_method': None}, 'epik': {'select': 1}},
{'filepath': paths['abl']},
{'filepath': paths['abl'], 'leap': {'parameters': 'leaprc.ff99SBildn'}},
{'filepath': paths['abl'], 'leap': {'parameters': 'leaprc.ff99SBildn'}, 'select': 1},
{'filepath': paths['abl'], 'select': 'all'},
{'filepath': paths['abl'], 'select': 'all', 'strip_protons': True},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'add_missing_residues': True}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'add_missing_atoms': 'all', 'ph': '8.0'}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'remove_heterogens': 'all'}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'replace_nonstandard_residues': True}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'apply_mutations': {'chain_id': 'A', 'mutations': 'T85I'}}},
{'filepath': paths['abl'], 'select': 'all', 'modeller': {'apply_mutations': {'chain_id': 'A', 'mutations': 'T85I'}}},
{'filepath': paths['abl'], 'select': 'all', 'modeller': {'apply_mutations': {'chain_id': 'A', 'mutations': 'WT'}}},
{'filepath': paths['abl'], 'select': 'all', 'pdbfixer': {'apply_mutations': {'chain_id': 'A', 'mutations': 'I8A/T9A'}}},
{'filepath': paths['toluene'], 'leap': {'parameters': 'leaprc.gaff'}},
{'filepath': paths['benzene'], 'epik': {'select': 1, 'tautomerize': False}},
# Regions tests, make sure all other combos still work
{'name': 'toluene', 'regions': {'a_region': 4}},
{'name': 'toluene', 'regions': {'a_region': 'dsl string'}},
{'name': 'toluene', 'regions': {'a_region': [0, 2, 3]}},
{'name': 'toluene', 'regions': {'a_region': [0, 2, 3], 'another_region': [5, 4, 3]}},
{'smiles': 'Cc1ccccc1', 'regions': {'a_region': 4}},
{'smiles': 'Cc1ccccc1', 'regions': {'a_region': 'dsl string'}},
{'smiles': 'Cc1ccccc1', 'regions': {'a_region': [0, 2, 3]}},
{'smiles': 'Cc1ccccc1', 'regions': {'a_region': [0, 2, 3], 'another_region': [5, 4, 3]}},
{'filepath': paths['abl'], 'regions': {'a_region': 4}},
{'filepath': paths['abl'], 'regions': {'a_region': 'dsl string'}},
{'filepath': paths['abl'], 'regions': {'a_region': [0, 2, 3]}},
{'filepath': paths['abl'], 'regions': {'a_region': [0, 2, 3], 'another_region': [5, 4, 3]}},
{'filepath': paths['toluene'], 'regions': {'a_region': 4}},
{'filepath': paths['toluene'], 'regions': {'a_region': 'dsl string'}},
{'filepath': paths['toluene'], 'regions': {'a_region': [0, 2, 3]}},
{'filepath': paths['toluene'], 'regions': {'a_region': [0, 2, 3], 'another_region': [5, 4, 3]}}
]
for molecule in molecules:
yield ExperimentBuilder._validate_molecules, {'mol': molecule}
def test_validation_wrong_molecules():
"""YAML validation raises exception with wrong molecules."""
paths = examples_paths()
paths['wrongformat'] = utils.get_data_filename(os.path.join('tests', 'data', 'README.md'))
molecules = [
{'antechamber': {'charge_method': 'bcc'}},
{'filepath': paths['wrongformat']},
{'name': 'p-xylene', 'antechamber': {'charge_method': 'bcc'}, 'unknown': 4},
{'smiles': 'Cc1ccccc1', 'openeye': {'quacpac': 'am1-bcc'}},
{'smiles': 'Cc1ccccc1', 'openeye': {'quacpac': 'invalid'},
'antechamber': {'charge_method': None}},
{'smiles': 'Cc1ccccc1', 'openeye': {'quacpac': 'am1-bcc'},
'antechamber': {'charge_method': 'bcc'}},
{'filepath': 'nonexistentfile.pdb', 'leap': {'parameters': 'leaprc.ff14SB'}},
{'filepath': paths['toluene'], 'smiles': 'Cc1ccccc1'},
{'filepath': paths['toluene'], 'strip_protons': True},
{'filepath': paths['abl'], 'leap': {'parameters': 'oldff/leaprc.ff14SB'}, 'epik': {'select': 0}},
{'name': 'toluene', 'epik': 0},
{'name': 'toluene', 'epik': {'tautomerize': 6}},
{'name': 'toluene', 'epik': {'extract_range': 1}},
{'name': 'toluene', 'smiles': 'Cc1ccccc1'},
{'name': 3},
{'smiles': 'Cc1ccccc1', 'select': 1},
{'name': 'Cc1ccccc1', 'select': 1},
{'filepath': paths['abl'], 'leap': {'parameters': 'oldff/leaprc.ff14SB'}, 'select': 'notanoption'},
{'filepath': paths['abl'], 'regions': 5},
{'filepath': paths['abl'], 'regions': {'a_region': [-56, 5.23]}},
{'filepath': paths['toluene'], 'leap': {'parameters': 'leaprc.gaff'}, 'strip_protons': True},
]
for molecule in molecules:
yield assert_raises, YamlParseError, ExperimentBuilder._validate_molecules, {'mol': molecule}
def test_validation_correct_solvents():
"""Correct solvents YAML validation."""
solvents = [
{'nonbonded_method': 'Ewald', 'nonbonded_cutoff': '3*nanometers'},
{'nonbonded_method': 'PME', 'solvent_model': 'tip4pew'},
{'nonbonded_method': 'PME', 'solvent_model': 'tip3p', 'leap': {'parameters': 'leaprc.water.tip3p'}},
{'nonbonded_method': 'PME', 'clearance': '3*angstroms'},
{'nonbonded_method': 'PME'},
{'nonbonded_method': 'NoCutoff', 'implicit_solvent': 'OBC2'},
{'nonbonded_method': 'CutoffPeriodic', 'nonbonded_cutoff': '9*angstroms',
'clearance': '9*angstroms', 'positive_ion': 'Na+', 'negative_ion': 'Cl-',
'ionic_strength': '200*millimolar'},
{'implicit_solvent': 'OBC2', 'implicit_solvent_salt_conc': '1.0*nanomolar'},
{'nonbonded_method': 'PME', 'clearance': '3*angstroms', 'ewald_error_tolerance': 0.001},
]
for solvent in solvents:
yield ExperimentBuilder._validate_solvents, {'solv': solvent}
def test_validation_wrong_solvents():
"""YAML validation raises exception with wrong solvents."""
solvents = [
{'nonbonded_cutoff': '3*nanometers'},
{'nonbonded_method': 'PME', 'solvent_model': 'unknown_solvent_model'},
{'nonbonded_method': 'PME', 'solvent_model': 'tip3p', 'leap': 'leaprc.water.tip3p'},
{'nonbonded_method': 'PME', 'clearance': '3*angstroms', 'implicit_solvent': 'OBC2'},
{'nonbonded_method': 'NoCutoff', 'blabla': '3*nanometers'},
{'nonbonded_method': 'NoCutoff', 'implicit_solvent': 'OBX2'},
{'implicit_solvent': 'OBC2', 'implicit_solvent_salt_conc': '1.0*angstrom'}
]
for solvent in solvents:
yield assert_raises, YamlParseError, ExperimentBuilder._validate_solvents, {'solv': solvent}
def test_validation_correct_systems():
"""Correct systems YAML validation."""
data_paths = examples_paths()
exp_builder = ExperimentBuilder()
basic_script = """
---
molecules:
rec: {{filepath: {0}, leap: {{parameters: leaprc.ff14SB}}}}
rec_reg: {{filepath: {0}, regions: {{receptregion: 'some dsl'}}, leap: {{parameters: leaprc.ff14SB}}}}
lig: {{name: lig, leap: {{parameters: leaprc.gaff}}}}
lig_reg: {{name: lig, regions: {{ligregion: [143, 123]}}, leap: {{parameters: leaprc.gaff}}}}
solvents:
solv: {{nonbonded_method: NoCutoff}}
solv2: {{nonbonded_method: NoCutoff, implicit_solvent: OBC2}}
solv3: {{nonbonded_method: PME, clearance: 10*angstroms}}
solv4: {{nonbonded_method: PME}}
""".format(data_paths['lysozyme'])
basic_script = yaml.load(textwrap.dedent(basic_script))
systems = [
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'solv'},
{'receptor': 'rec_reg', 'ligand': 'lig_reg', 'solvent': 'solv'},
{'receptor': 'rec_reg', 'ligand': 'lig', 'solvent': 'solv'},
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'solv', 'pack': True},
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'solv3',
'leap': {'parameters': ['leaprc.gaff', 'leaprc.ff14SB']}},
{'phase1_path': data_paths['bentol-complex'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent': 'solv'},
{'phase1_path': data_paths['bentol-complex'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent': 'solv4'},
{'phase1_path': data_paths['bentol-complex'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent1': 'solv3',
'solvent2': 'solv2'},
{'phase1_path': data_paths['pxylene-complex'],
'phase2_path': data_paths['pxylene-solvent'],
'ligand_dsl': 'resname p-xylene', 'solvent': 'solv',
'gromacs_include_dir': data_paths['pxylene-gro-include']},
{'phase1_path': data_paths['pxylene-complex'],
'phase2_path': data_paths['pxylene-solvent'],
'ligand_dsl': 'resname p-xylene', 'solvent': 'solv'},
{'phase1_path': data_paths['toluene-solvent'],
'phase2_path': data_paths['toluene-vacuum'],
'ligand_dsl': 'resname TOL'},
{'phase1_path': data_paths['toluene-solvent'],
'phase2_path': data_paths['toluene-vacuum'],
'ligand_dsl': 'resname TOL', 'solvent_dsl': 'not resname TOL'},
{'solute': 'lig', 'solvent1': 'solv', 'solvent2': 'solv'},
{'solute': 'lig_reg', 'solvent1': 'solv', 'solvent2': 'solv'},
{'solute': 'lig', 'solvent1': 'solv', 'solvent2': 'solv',
'leap': {'parameters': 'leaprc.gaff'}}
]
for system in systems:
modified_script = basic_script.copy()
modified_script['systems'] = {'sys': system}
yield exp_builder.parse, modified_script
def test_validation_wrong_systems():
"""YAML validation raises exception with wrong experiments specification."""
data_paths = examples_paths()
exp_builder = ExperimentBuilder()
basic_script = """
---
molecules:
rec: {{filepath: {0}, leap: {{parameters: oldff/leaprc.ff14SB}}}}
rec_region: {{filepath: {0}, regions: {{a_region: 'some string'}}, leap: {{parameters: oldff/leaprc.ff14SB}}}}
lig: {{name: lig, leap: {{parameters: leaprc.gaff}}}}
lig_region: {{name: lig, regions: {{a_region: 'some string'}}, leap: {{parameters: leaprc.gaff}}}}
solvents:
solv: {{nonbonded_method: NoCutoff}}
solv2: {{nonbonded_method: NoCutoff, implicit_solvent: OBC2}}
solv3: {{nonbonded_method: PME, clearance: 10*angstroms}}
solv4: {{nonbonded_method: PME}}
""".format(data_paths['lysozyme'])
basic_script = yaml.load(textwrap.dedent(basic_script))
# Each test case is a pair (regexp_error, system_description).
systems = [
("'solvent' is required",
{'receptor': 'rec', 'ligand': 'lig'}),
("regions\(s\) clashing",
{'receptor': 'rec_region', 'ligand': 'lig_region', 'solvent': 'solv'}),
("ligand: \[must be of string type\]",
{'receptor': 'rec', 'ligand': 1, 'solvent': 'solv'}),
("solvent: \[must be of string type\]",
{'receptor': 'rec', 'ligand': 'lig', 'solvent': ['solv', 'solv']}),
("unallowed value unknown",
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'unknown'}),
("solv4 does not specify clearance",
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'solv4',
'leap': {'parameters': ['leaprc.gaff', 'leaprc.ff14SB']}}),
("parameters: \[unknown field\]",
{'receptor': 'rec', 'ligand': 'lig', 'solvent': 'solv3',
'parameters': 'leaprc.ff14SB'}),
("phase1_path: \[must be of list type\]",
{'phase1_path': data_paths['bentol-complex'][0],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent': 'solv'}),
("File path nonexistingpath.prmtop does not exist.",
{'phase1_path': ['nonexistingpath.prmtop', 'nonexistingpath.inpcrd'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent': 'solv'}),
("ligand_dsl: \[must be of string type\]",
{'phase1_path': data_paths['bentol-complex'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 3.4, 'solvent': 'solv'}),
("unallowed value unknown",
{'phase1_path': data_paths['bentol-complex'],
'phase2_path': data_paths['bentol-solvent'],
'ligand_dsl': 'resname BEN', 'solvent1': 'unknown',
'solvent2': 'solv2'}),
("unallowed value cantbespecified",
{'phase1_path': data_paths['toluene-solvent'],
'phase2_path': data_paths['toluene-vacuum'],
'ligand_dsl': 'resname TOL', 'solvent': 'cantbespecified'}),
("field 'ligand' is required",
{'receptor': 'rec', 'solute': 'lig', 'solvent1': 'solv', 'solvent2': 'solv'}),
("''ligand'' must not be present with ''solute''",
{'ligand': 'lig', 'solute': 'lig', 'solvent1': 'solv', 'solvent2': 'solv'}),
("leap: \[must be of dict type\]",
{'solute': 'lig', 'solvent1': 'solv', 'solvent2': 'solv', 'leap': 'leaprc.gaff'})
]
for regexp, system in systems:
modified_script = basic_script.copy()
modified_script['systems'] = {'sys': system}
yield assert_raises_regexp, YamlParseError, regexp, exp_builder.parse, modified_script
def test_validation_correct_mcmc_moves():
"""Correct samplers YAML validation."""
mcmc_moves = [
{'type': 'LangevinSplittingDynamicsMove', 'reassign_velocities': False,
'splitting': 'VRORV', 'n_steps': 10, 'timestep': '2.0*femtosecond'},
{'type': 'SequenceMove', 'move_list': [
{'type': 'MCDisplacementMove', 'displacement_sigma': '5.0*nanometers'},
{'type': 'LangevinSplittingDynamicsMove'}
]},
]
for mcmc_move in mcmc_moves:
yield ExperimentBuilder._validate_mcmc_moves, {'mcmc_moves': {'mcmcmove1': mcmc_move}}
def test_validation_wrong_mcmc_moves():
"""YAML validation raises exception with wrong experiments specification."""
# Each test case is a pair (regexp_error, mcmc_move_description).
mcmc_moves = [
("The expression 2.0 must be\s+ a string",
{'type': 'LangevinSplittingDynamicsMove', 'timestep': 2.0}),
("Could not find class UnknownMoveClass",
{'type': 'UnknownMoveClass'}),
("Could not find class NestedUnknownMoveClass",
{'type': 'SequenceMove', 'move_list': [
{'type': 'MCDisplacementMove'},
{'type': 'NestedUnknownMoveClass'}
]})
]
for regexp, mcmc_move in mcmc_moves:
script = {'mcmc_moves': {'mcmc_move1': mcmc_move}}
yield assert_raises_regexp, YamlParseError, regexp, ExperimentBuilder._validate_mcmc_moves, script
def test_validation_correct_samplers():
"""Correct samplers YAML validation."""
samplers = [
{'type': 'MultiStateSampler', 'locality': 3},
{'type': 'ReplicaExchangeSampler'},
# MCMCMove 'single' is defined in get_template_script().
{'type': 'SAMSSampler', 'mcmc_moves': 'single'},
{'type': 'ReplicaExchangeSampler', 'number_of_iterations': 5, 'replica_mixing_scheme': 'swap-neighbors'},
{'type': 'ReplicaExchangeSampler', 'number_of_iterations': 5, 'replica_mixing_scheme': None}
]
exp_builder = ExperimentBuilder(get_template_script())
for sampler in samplers:
script = {'samplers': {'sampler1': sampler}}
yield exp_builder._validate_samplers, script
def test_validation_wrong_samplers():
"""YAML validation raises exception with wrong experiments specification."""
# Each test case is a pair (regexp_error, sampler_description).
samplers = [
("locality must be an int",
{'type': 'MultiStateSampler', 'locality': 3.0}),
("unallowed value unknown",
{'type': 'ReplicaExchangeSampler', 'mcmc_moves': 'unknown'}),
("Could not find class NonExistentSampler",
{'type': 'NonExistentSampler'}),
("found unknown parameter",
{'type': 'ReplicaExchangeSampler', 'unknown_kwarg': 5}),
]
exp_builder = ExperimentBuilder(get_template_script())
for regexp, sampler in samplers:
script = {'samplers': {'sampler1': sampler}}
yield assert_raises_regexp, YamlParseError, regexp, exp_builder._validate_samplers, script
def test_order_phases():
"""YankLoader preserves protocol phase order."""
yaml_content_template = """
---
absolute-binding:
{}:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]
{}:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]
{}:
alchemical_path:
lambda_electrostatics: [1.0, 0.5, 0.0]
lambda_sterics: [1.0, 0.5, 0.0]"""
# Find order of phases for which normal parsing is not ordered or the test is useless
for ordered_phases in itertools.permutations(['athirdphase', 'complex', 'solvent']):
yaml_content = yaml_content_template.format(*ordered_phases)
parsed = yaml.load(textwrap.dedent(yaml_content))
if tuple(parsed['absolute-binding'].keys()) != ordered_phases:
break
# Insert !Ordered tag
yaml_content = yaml_content.replace('binding:', 'binding: !Ordered')
parsed = yank_load(yaml_content)
assert tuple(parsed['absolute-binding'].keys()) == ordered_phases
def test_validation_correct_protocols():
"""Correct protocols YAML validation."""
basic_protocol = yank_load(standard_protocol)
# Alchemical paths
protocols = [
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 0.0]},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 0.0],
'lambda_torsions': [1.0, 0.5, 0.0], 'lambda_angles': [1.0, 0.5, 0.0]},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 0.0],
'temperature': ['300*kelvin', '340*kelvin', '300*kelvin']},
'auto',
]
for protocol in protocols:
modified_protocol = copy.deepcopy(basic_protocol)
modified_protocol['absolute-binding']['complex']['alchemical_path'] = protocol
yield ExperimentBuilder._validate_protocols, modified_protocol
# Phases
alchemical_path = copy.deepcopy(basic_protocol['absolute-binding']['complex'])
protocols = [
{'complex': alchemical_path, 'solvent': alchemical_path},
{'complex': alchemical_path, 'solvent': {'alchemical_path': 'auto'}},
{'my-complex': alchemical_path, 'my-solvent': alchemical_path},
{'solvent1': alchemical_path, 'solvent2': alchemical_path},
{'solvent1variant': alchemical_path, 'solvent2variant': alchemical_path},
collections.OrderedDict([('a', alchemical_path), ('z', alchemical_path)]),
collections.OrderedDict([('z', alchemical_path), ('a', alchemical_path)])
]
for protocol in protocols:
modified_protocol = copy.deepcopy(basic_protocol)
modified_protocol['absolute-binding'] = protocol
yield ExperimentBuilder._validate_protocols, modified_protocol
sorted_protocol = ExperimentBuilder._validate_protocols(modified_protocol)['absolute-binding']
if isinstance(protocol, collections.OrderedDict):
assert sorted_protocol.keys() == protocol.keys()
else:
assert isinstance(sorted_protocol, collections.OrderedDict)
first_phase = next(iter(sorted_protocol.keys())) # py2/3 compatible
assert 'complex' in first_phase or 'solvent1' in first_phase
def test_validation_wrong_protocols():
"""YAML validation raises exception with wrong alchemical protocols."""
basic_protocol = yank_load(standard_protocol)
# Alchemical paths
protocols = [
{'lambda_electrostatics': [1.0, 0.5, 0.0]},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 'wrong!']},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 11000.0]},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, -0.5]},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': 0.0},
{'lambda_electrostatics': [1.0, 0.5, 0.0], 'lambda_sterics': [1.0, 0.5, 0.0], 3: 2}
]
for protocol in protocols:
modified_protocol = copy.deepcopy(basic_protocol)
modified_protocol['absolute-binding']['complex']['alchemical_path'] = protocol
yield assert_raises, YamlParseError, ExperimentBuilder._validate_protocols, modified_protocol
# Phases
alchemical_path = copy.deepcopy(basic_protocol['absolute-binding']['complex'])