/
macros.py
2618 lines (2353 loc) · 111 KB
/
macros.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
"""@namespace IMP.pmi.macros
Protocols for sampling structures and analyzing them.
"""
from __future__ import print_function, division
import IMP
import IMP.pmi.tools
import IMP.pmi.samplers
import IMP.pmi.output
import IMP.pmi.analysis
import IMP.pmi.io
import IMP.pmi.alphabets
import IMP.rmf
import IMP.isd
import IMP.pmi.dof
import os
try:
from pathlib import Path
except ImportError: # Use bundled pathlib on Python 2 without pathlib
from IMP._compat_pathlib import Path
import glob
from operator import itemgetter
from collections import defaultdict
import numpy as np
import itertools
import warnings
import math
import pickle
class _MockMPIValues(object):
"""Replace samplers.MPI_values when in test mode"""
def get_percentile(self, name):
return 0.
class _RMFRestraints(object):
"""All restraints that are written out to the RMF file"""
def __init__(self, model, user_restraints):
self._rmf_rs = IMP.pmi.tools.get_restraint_set(model, rmf=True)
self._user_restraints = user_restraints if user_restraints else []
def __len__(self):
return (len(self._user_restraints)
+ self._rmf_rs.get_number_of_restraints())
def __bool__(self):
return len(self) > 0
__nonzero__ = __bool__ # Python 2 compatibility
def __getitem__(self, i):
class FakePMIWrapper(object):
def __init__(self, r):
self.r = IMP.RestraintSet.get_from(r)
def get_restraint(self):
return self.r
lenuser = len(self._user_restraints)
if 0 <= i < lenuser:
return self._user_restraints[i]
elif 0 <= i - lenuser < self._rmf_rs.get_number_of_restraints():
r = self._rmf_rs.get_restraint(i - lenuser)
return FakePMIWrapper(r)
else:
raise IndexError("Out of range")
class ReplicaExchange(object):
"""A macro to help setup and run replica exchange.
Supports Monte Carlo and molecular dynamics.
Produces trajectory RMF files, best PDB structures,
and output stat files.
"""
def __init__(self, model, root_hier,
monte_carlo_sample_objects=None,
molecular_dynamics_sample_objects=None,
output_objects=[],
rmf_output_objects=None,
monte_carlo_temperature=1.0,
simulated_annealing=False,
simulated_annealing_minimum_temperature=1.0,
simulated_annealing_maximum_temperature=2.5,
simulated_annealing_minimum_temperature_nframes=100,
simulated_annealing_maximum_temperature_nframes=100,
replica_exchange_minimum_temperature=1.0,
replica_exchange_maximum_temperature=2.5,
replica_exchange_swap=True,
num_sample_rounds=1,
number_of_best_scoring_models=500,
monte_carlo_steps=10,
self_adaptive=False,
molecular_dynamics_steps=10,
molecular_dynamics_max_time_step=1.0,
number_of_frames=1000,
save_coordinates_mode="lowest_temperature",
nframes_write_coordinates=1,
write_initial_rmf=True,
initial_rmf_name_suffix="initial",
stat_file_name_suffix="stat",
best_pdb_name_suffix="model",
mmcif=False,
do_clean_first=True,
do_create_directories=True,
global_output_directory="./",
rmf_dir="rmfs/",
best_pdb_dir="pdbs/",
replica_stat_file_suffix="stat_replica",
em_object_for_rmf=None,
atomistic=False,
replica_exchange_object=None,
test_mode=False,
score_moved=False,
use_nestor=False,
nestor_restraints=None,
nestor_rmf_fname_prefix="nested",):
"""Constructor.
@param model The IMP model
@param root_hier Top-level (System)hierarchy
@param monte_carlo_sample_objects Objects for MC sampling, which
should generally be a simple list of Mover objects, e.g.
from DegreesOfFreedom.get_movers().
@param molecular_dynamics_sample_objects Objects for MD sampling,
which should generally be a simple list of particles.
@param output_objects A list of structural objects and restraints
that will be included in output (ie, statistics "stat"
files). Any object that provides a get_output() method
can be used here. If None is passed
the macro will not write stat files.
@param rmf_output_objects A list of structural objects and
restraints that will be included in rmf. Any object
that provides a get_output() method can be used here.
@param monte_carlo_temperature MC temp (may need to be optimized
based on post-sampling analysis)
@param simulated_annealing If True, perform simulated annealing
@param simulated_annealing_minimum_temperature Should generally be
the same as monte_carlo_temperature.
@param simulated_annealing_minimum_temperature_nframes Number of
frames to compute at minimum temperature.
@param simulated_annealing_maximum_temperature_nframes Number of
frames to compute at
temps > simulated_annealing_maximum_temperature.
@param replica_exchange_minimum_temperature Low temp for REX; should
generally be the same as monte_carlo_temperature.
@param replica_exchange_maximum_temperature High temp for REX
@param replica_exchange_swap Boolean, enable disable temperature
swap (Default=True)
@param num_sample_rounds Number of rounds of MC/MD per cycle
@param number_of_best_scoring_models Number of top-scoring PDB/mmCIF
models to keep around for analysis.
@param mmcif If True, write best scoring models in mmCIF format;
if False (the default), write in legacy PDB format.
@param best_pdb_dir The directory under `global_output_directory`
where best-scoring PDB/mmCIF files are written.
@param best_pdb_name_suffix Part of the file name for best-scoring
PDB/mmCIF files.
@param monte_carlo_steps Number of MC steps per round
@param self_adaptive self adaptive scheme for Monte Carlo movers
@param molecular_dynamics_steps Number of MD steps per round
@param molecular_dynamics_max_time_step Max time step for MD
@param number_of_frames Number of REX frames to run
@param save_coordinates_mode string: how to save coordinates.
"lowest_temperature" (default) only the lowest temperatures
is saved
"25th_score" all replicas whose score is below the 25th
percentile
"50th_score" all replicas whose score is below the 50th
percentile
"75th_score" all replicas whose score is below the 75th
percentile
@param nframes_write_coordinates How often to write the coordinates
of a frame
@param write_initial_rmf Write the initial configuration
@param global_output_directory Folder that will be created to house
output.
@param test_mode Set to True to avoid writing any files, just test
one frame.
@param score_moved If True, attempt to speed up Monte Carlo
sampling by caching scoring function terms on particles
that didn't move.
@param use_nestor If True, follows the Nested Sampling workflow
of the NestOR module and skips writing stat files and
replica stat files.
@param nestor_restraints A list of restraints for which
likelihoods are to be computed for use by NestOR module.
@param nestor_rmf_fname_prefix Prefix to be used for storing .rmf3
files generated by NestOR .
"""
self.model = model
self.vars = {}
# add check hierarchy is multistate
if output_objects == []:
# The "[]" in the default parameters is a global object, so make
# our own copy here
self.output_objects = []
else:
self.output_objects = output_objects
self.rmf_output_objects = rmf_output_objects
if (isinstance(root_hier, IMP.atom.Hierarchy)
and not root_hier.get_parent()):
if self.output_objects is not None:
self.output_objects.append(
IMP.pmi.io.TotalScoreOutput(self.model))
if self.rmf_output_objects is not None:
self.rmf_output_objects.append(
IMP.pmi.io.TotalScoreOutput(self.model))
self.root_hier = root_hier
states = IMP.atom.get_by_type(root_hier, IMP.atom.STATE_TYPE)
self.vars["number_of_states"] = len(states)
if len(states) > 1:
self.root_hiers = states
self.is_multi_state = True
else:
self.root_hier = root_hier
self.is_multi_state = False
else:
raise TypeError("Must provide System hierarchy (root_hier)")
self._rmf_restraints = _RMFRestraints(model, None)
self.em_object_for_rmf = em_object_for_rmf
self.monte_carlo_sample_objects = monte_carlo_sample_objects
self.vars["self_adaptive"] = self_adaptive
self.molecular_dynamics_sample_objects = \
molecular_dynamics_sample_objects
self.replica_exchange_object = replica_exchange_object
self.molecular_dynamics_max_time_step = \
molecular_dynamics_max_time_step
self.vars["monte_carlo_temperature"] = monte_carlo_temperature
self.vars["replica_exchange_minimum_temperature"] = \
replica_exchange_minimum_temperature
self.vars["replica_exchange_maximum_temperature"] = \
replica_exchange_maximum_temperature
self.vars["replica_exchange_swap"] = replica_exchange_swap
self.vars["simulated_annealing"] = simulated_annealing
self.vars["simulated_annealing_minimum_temperature"] = \
simulated_annealing_minimum_temperature
self.vars["simulated_annealing_maximum_temperature"] = \
simulated_annealing_maximum_temperature
self.vars["simulated_annealing_minimum_temperature_nframes"] = \
simulated_annealing_minimum_temperature_nframes
self.vars["simulated_annealing_maximum_temperature_nframes"] = \
simulated_annealing_maximum_temperature_nframes
self.vars["num_sample_rounds"] = num_sample_rounds
self.vars[
"number_of_best_scoring_models"] = number_of_best_scoring_models
self.vars["monte_carlo_steps"] = monte_carlo_steps
self.vars["molecular_dynamics_steps"] = molecular_dynamics_steps
self.vars["number_of_frames"] = number_of_frames
if save_coordinates_mode not in ("lowest_temperature", "25th_score",
"50th_score", "75th_score"):
raise Exception("save_coordinates_mode has unrecognized value")
else:
self.vars["save_coordinates_mode"] = save_coordinates_mode
self.vars["nframes_write_coordinates"] = nframes_write_coordinates
self.vars["write_initial_rmf"] = write_initial_rmf
self.vars["initial_rmf_name_suffix"] = initial_rmf_name_suffix
self.vars["best_pdb_name_suffix"] = best_pdb_name_suffix
self.vars["mmcif"] = mmcif
self.vars["stat_file_name_suffix"] = stat_file_name_suffix
self.vars["do_clean_first"] = do_clean_first
self.vars["do_create_directories"] = do_create_directories
self.vars["global_output_directory"] = global_output_directory
self.vars["rmf_dir"] = rmf_dir
self.vars["best_pdb_dir"] = best_pdb_dir
self.vars["atomistic"] = atomistic
self.vars["replica_stat_file_suffix"] = replica_stat_file_suffix
self.vars["geometries"] = None
self.test_mode = test_mode
self.score_moved = score_moved
self.nest = use_nestor
self.nestor_restraints = nestor_restraints
self.nestor_rmf_fname = nestor_rmf_fname_prefix
def add_geometries(self, geometries):
if self.vars["geometries"] is None:
self.vars["geometries"] = list(geometries)
else:
self.vars["geometries"].extend(geometries)
def show_info(self):
print("ReplicaExchange: it generates initial.*.rmf3, stat.*.out, "
"rmfs/*.rmf3 for each replica ")
print("--- it stores the best scoring pdb models in pdbs/")
print("--- the stat.*.out and rmfs/*.rmf3 are saved only at the "
"lowest temperature")
print("--- variables:")
keys = list(self.vars.keys())
keys.sort()
for v in keys:
print("------", v.ljust(30), self.vars[v])
print("Use nestor: ", self.nest)
def get_replica_exchange_object(self):
return self.replica_exchange_object
def _add_provenance(self, sampler_md, sampler_mc):
"""Record details about the sampling in the IMP Hierarchies"""
iterations = 0
if sampler_md:
method = "Molecular Dynamics"
iterations += self.vars["molecular_dynamics_steps"]
if sampler_mc:
method = "Hybrid MD/MC" if sampler_md else "Monte Carlo"
iterations += self.vars["monte_carlo_steps"]
# If no sampling is actually done, no provenance to write
if iterations == 0 or self.vars["number_of_frames"] == 0:
return
iterations *= self.vars["num_sample_rounds"]
pi = self.model.add_particle("sampling")
p = IMP.core.SampleProvenance.setup_particle(
self.model, pi, method, self.vars["number_of_frames"],
iterations)
p.set_number_of_replicas(
self.replica_exchange_object.get_number_of_replicas())
IMP.pmi.tools._add_pmi_provenance(self.root_hier)
IMP.core.add_provenance(self.model, self.root_hier, p)
def execute_macro(self):
temp_index_factor = 100000.0
samplers = []
sampler_mc = None
sampler_md = None
if self.monte_carlo_sample_objects is not None:
print("Setting up MonteCarlo")
sampler_mc = IMP.pmi.samplers.MonteCarlo(
self.model, self.monte_carlo_sample_objects,
self.vars["monte_carlo_temperature"],
score_moved=self.score_moved)
if self.vars["simulated_annealing"]:
tmin = self.vars["simulated_annealing_minimum_temperature"]
tmax = self.vars["simulated_annealing_maximum_temperature"]
nfmin = self.vars[
"simulated_annealing_minimum_temperature_nframes"]
nfmax = self.vars[
"simulated_annealing_maximum_temperature_nframes"]
sampler_mc.set_simulated_annealing(tmin, tmax, nfmin, nfmax)
if self.vars["self_adaptive"]:
sampler_mc.set_self_adaptive(
isselfadaptive=self.vars["self_adaptive"])
if self.output_objects is not None:
self.output_objects.append(sampler_mc)
if self.rmf_output_objects is not None:
self.rmf_output_objects.append(sampler_mc)
samplers.append(sampler_mc)
if self.molecular_dynamics_sample_objects is not None:
print("Setting up MolecularDynamics")
sampler_md = IMP.pmi.samplers.MolecularDynamics(
self.model, self.molecular_dynamics_sample_objects,
self.vars["monte_carlo_temperature"],
maximum_time_step=self.molecular_dynamics_max_time_step)
if self.vars["simulated_annealing"]:
tmin = self.vars["simulated_annealing_minimum_temperature"]
tmax = self.vars["simulated_annealing_maximum_temperature"]
nfmin = self.vars[
"simulated_annealing_minimum_temperature_nframes"]
nfmax = self.vars[
"simulated_annealing_maximum_temperature_nframes"]
sampler_md.set_simulated_annealing(tmin, tmax, nfmin, nfmax)
if self.output_objects is not None:
self.output_objects.append(sampler_md)
if self.rmf_output_objects is not None:
self.rmf_output_objects.append(sampler_md)
samplers.append(sampler_md)
# -------------------------------------------------------------------------
print("Setting up ReplicaExchange")
rex = IMP.pmi.samplers.ReplicaExchange(
self.model, self.vars["replica_exchange_minimum_temperature"],
self.vars["replica_exchange_maximum_temperature"], samplers,
replica_exchange_object=self.replica_exchange_object)
self.replica_exchange_object = rex.rem
myindex = rex.get_my_index()
if self.output_objects is not None:
self.output_objects.append(rex)
if self.rmf_output_objects is not None:
self.rmf_output_objects.append(rex)
# must reset the minimum temperature due to the
# different binary length of rem.get_my_parameter double and python
# float
min_temp_index = int(min(rex.get_temperatures()) * temp_index_factor)
# -------------------------------------------------------------------------
globaldir = self.vars["global_output_directory"] + "/"
rmf_dir = globaldir + self.vars["rmf_dir"]
pdb_dir = globaldir + self.vars["best_pdb_dir"]
if not self.test_mode and not self.nest:
if self.vars["do_clean_first"]:
pass
if self.vars["do_create_directories"]:
try:
os.makedirs(globaldir)
except: # noqa: E722
pass
try:
os.makedirs(rmf_dir)
except: # noqa: E722
pass
if not self.is_multi_state:
try:
os.makedirs(pdb_dir)
except: # noqa: E722
pass
else:
for n in range(self.vars["number_of_states"]):
try:
os.makedirs(pdb_dir + "/" + str(n))
except: # noqa: E722
pass
# -------------------------------------------------------------------------
sw = IMP.pmi.tools.Stopwatch()
if self.output_objects is not None:
self.output_objects.append(sw)
if self.rmf_output_objects is not None:
self.rmf_output_objects.append(sw)
output = IMP.pmi.output.Output(atomistic=self.vars["atomistic"])
if not self.nest:
print("Setting up stat file")
low_temp_stat_file = globaldir + \
self.vars["stat_file_name_suffix"] + "." + \
str(myindex) + ".out"
# Ensure model is updated before saving init files
if not self.test_mode:
self.model.update()
if not self.test_mode and not self.nest:
if self.output_objects is not None:
output.init_stat2(low_temp_stat_file,
self.output_objects,
extralabels=["rmf_file", "rmf_frame_index"])
else:
print("Stat file writing is disabled")
if self.rmf_output_objects is not None and not self.nest:
print("Stat info being written in the rmf file")
if not self.test_mode and not self.nest:
print("Setting up replica stat file")
replica_stat_file = globaldir + \
self.vars["replica_stat_file_suffix"] + "." + \
str(myindex) + ".out"
if not self.test_mode:
output.init_stat2(replica_stat_file, [rex],
extralabels=["score"])
print("Setting up best pdb files")
if not self.is_multi_state:
if self.vars["number_of_best_scoring_models"] > 0:
output.init_pdb_best_scoring(
pdb_dir + "/" + self.vars["best_pdb_name_suffix"],
self.root_hier,
self.vars["number_of_best_scoring_models"],
replica_exchange=True,
mmcif=self.vars['mmcif'],
best_score_file=globaldir + "best.scores.rex.py")
pdbext = ".0.cif" if self.vars['mmcif'] else ".0.pdb"
output.write_psf(
pdb_dir + "/" + "model.psf",
pdb_dir + "/" +
self.vars["best_pdb_name_suffix"] + pdbext)
else:
if self.vars["number_of_best_scoring_models"] > 0:
for n in range(self.vars["number_of_states"]):
output.init_pdb_best_scoring(
pdb_dir + "/" + str(n) + "/" +
self.vars["best_pdb_name_suffix"],
self.root_hiers[n],
self.vars["number_of_best_scoring_models"],
replica_exchange=True,
mmcif=self.vars['mmcif'],
best_score_file=globaldir + "best.scores.rex.py")
pdbext = ".0.cif" if self.vars['mmcif'] else ".0.pdb"
output.write_psf(
pdb_dir + "/" + str(n) + "/" + "model.psf",
pdb_dir + "/" + str(n) + "/" +
self.vars["best_pdb_name_suffix"] + pdbext)
# ---------------------------------------------
if self.em_object_for_rmf is not None:
output_hierarchies = [
self.root_hier,
self.em_object_for_rmf.get_density_as_hierarchy(
)]
else:
output_hierarchies = [self.root_hier]
if not self.test_mode and not self.nest:
print("Setting up and writing initial rmf coordinate file")
init_suffix = globaldir + self.vars["initial_rmf_name_suffix"]
output.init_rmf(init_suffix + "." + str(myindex) + ".rmf3",
output_hierarchies,
listofobjects=self.rmf_output_objects)
if self._rmf_restraints:
output.add_restraints_to_rmf(
init_suffix + "." + str(myindex) + ".rmf3",
self._rmf_restraints)
output.write_rmf(init_suffix + "." + str(myindex) + ".rmf3")
output.close_rmf(init_suffix + "." + str(myindex) + ".rmf3")
if not self.test_mode:
mpivs = IMP.pmi.samplers.MPI_values(self.replica_exchange_object)
else:
mpivs = _MockMPIValues()
self._add_provenance(sampler_md, sampler_mc)
if not self.test_mode and not self.nest:
print("Setting up production rmf files")
rmfname = rmf_dir + "/" + str(myindex) + ".rmf3"
output.init_rmf(rmfname, output_hierarchies,
geometries=self.vars["geometries"],
listofobjects=self.rmf_output_objects)
if self._rmf_restraints:
output.add_restraints_to_rmf(rmfname, self._rmf_restraints)
if not self.test_mode and self.nest:
print("Setting up NestOR rmf files")
nestor_rmf_fname = str(self.nestor_rmf_fname) + '_' + \
str(self.replica_exchange_object.get_my_index()) + '.rmf3'
output.init_rmf(nestor_rmf_fname, output_hierarchies,
geometries=self.vars["geometries"],
listofobjects=self.rmf_output_objects)
ntimes_at_low_temp = 0
if myindex == 0 and not self.nest:
self.show_info()
self.replica_exchange_object.set_was_used(True)
nframes = self.vars["number_of_frames"]
if self.test_mode:
nframes = 1
sampled_likelihoods = []
for i in range(nframes):
if self.test_mode:
score = 0.
else:
for nr in range(self.vars["num_sample_rounds"]):
if sampler_md is not None:
sampler_md.optimize(
self.vars["molecular_dynamics_steps"])
if sampler_mc is not None:
sampler_mc.optimize(self.vars["monte_carlo_steps"])
score = IMP.pmi.tools.get_restraint_set(
self.model).evaluate(False)
mpivs.set_value("score", score)
if not self.nest:
output.set_output_entry("score", score)
my_temp_index = int(rex.get_my_temp() * temp_index_factor)
if self.vars["save_coordinates_mode"] == "lowest_temperature":
save_frame = (min_temp_index == my_temp_index)
elif self.vars["save_coordinates_mode"] == "25th_score":
score_perc = mpivs.get_percentile("score")
save_frame = (score_perc*100.0 <= 25.0)
elif self.vars["save_coordinates_mode"] == "50th_score":
score_perc = mpivs.get_percentile("score")
save_frame = (score_perc*100.0 <= 50.0)
elif self.vars["save_coordinates_mode"] == "75th_score":
score_perc = mpivs.get_percentile("score")
save_frame = (score_perc*100.0 <= 75.0)
# Ensure model is updated before saving output files
if save_frame and not self.test_mode:
self.model.update()
if save_frame:
print("--- frame %s score %s " % (str(i), str(score)))
if self.nest:
if math.isnan(score):
sampled_likelihoods.append(math.nan)
else:
likelihood_for_sample = 1
for rstrnt in self.nestor_restraints:
likelihood_for_sample *= rstrnt.get_likelihood()
sampled_likelihoods.append(likelihood_for_sample)
output.write_rmf(nestor_rmf_fname)
if not self.test_mode and not self.nest:
if i % self.vars["nframes_write_coordinates"] == 0:
print('--- writing coordinates')
if self.vars["number_of_best_scoring_models"] > 0:
output.write_pdb_best_scoring(score)
output.write_rmf(rmfname)
output.set_output_entry("rmf_file", rmfname)
output.set_output_entry("rmf_frame_index",
ntimes_at_low_temp)
else:
output.set_output_entry("rmf_file", rmfname)
output.set_output_entry("rmf_frame_index", '-1')
if self.output_objects is not None:
output.write_stat2(low_temp_stat_file)
ntimes_at_low_temp += 1
if not self.test_mode and not self.nest:
output.write_stat2(replica_stat_file)
if self.vars["replica_exchange_swap"]:
rex.swap_temp(i, score)
if self.nest and len(sampled_likelihoods) > 0:
with open("likelihoods_"
+ str(self.replica_exchange_object.get_my_index()),
"wb") as lif:
pickle.dump(sampled_likelihoods, lif)
output.close_rmf(nestor_rmf_fname)
for p, state in IMP.pmi.tools._all_protocol_outputs(self.root_hier):
p.add_replica_exchange(state, self)
if not self.test_mode and not self.nest:
print("closing production rmf files")
output.close_rmf(rmfname)
class BuildSystem(object):
"""A macro to build a IMP::pmi::topology::System based on a
TopologyReader object.
Easily create multi-state systems by calling this macro
repeatedly with different TopologyReader objects!
A useful function is get_molecules() which returns the PMI Molecules
grouped by state as a dictionary with key = (molecule name),
value = IMP.pmi.topology.Molecule
Quick multi-state system:
@code{.python}
model = IMP.Model()
reader1 = IMP.pmi.topology.TopologyReader(tfile1)
reader2 = IMP.pmi.topology.TopologyReader(tfile2)
bs = IMP.pmi.macros.BuildSystem(model)
bs.add_state(reader1)
bs.add_state(reader2)
bs.execute_macro() # build everything including degrees of freedom
IMP.atom.show_molecular_hierarchy(bs.get_hierarchy())
### now you have a two state system, you add restraints etc
@endcode
@note The "domain name" entry of the topology reader is not used.
All molecules are set up by the component name, but split into rigid bodies
as requested.
"""
_alphabets = {'DNA': IMP.pmi.alphabets.dna,
'RNA': IMP.pmi.alphabets.rna}
def __init__(self, model, sequence_connectivity_scale=4.0,
force_create_gmm_files=False, resolutions=[1, 10],
name='System'):
"""Constructor
@param model An IMP Model
@param sequence_connectivity_scale For scaling the connectivity
restraint
@param force_create_gmm_files If True, will sample and create GMMs
no matter what. If False, will only sample if the
files don't exist. If number of Gaussians is zero, won't
do anything.
@param resolutions The resolutions to build for structured regions
@param name The name of the top-level hierarchy node.
"""
self.model = model
self.system = IMP.pmi.topology.System(self.model, name=name)
self._readers = [] # the TopologyReaders (one per state)
# TempResidues for each domain key=unique name,
# value=(atomic_res,non_atomic_res).
self._domain_res = []
self._domains = [] # key = domain unique name, value = Component
self.force_create_gmm_files = force_create_gmm_files
self.resolutions = resolutions
def add_state(self, reader, keep_chain_id=False, fasta_name_map=None,
chain_ids=None):
"""Add a state using the topology info in a
IMP::pmi::topology::TopologyReader object.
When you are done adding states, call execute_macro()
@param reader The TopologyReader object
@param fasta_name_map dictionary for converting protein names
found in the fasta file
@param chain_ids A list or string of chain IDs for assigning to
newly-created molecules, e.g.
`string.ascii_uppercase+string.ascii_lowercase+string.digits`.
If not specified, chain IDs A through Z are assigned, then
AA through AZ, then BA through BZ, and so on, in the same
fashion as PDB.
"""
state = self.system.create_state()
self._readers.append(reader)
# key is unique name, value is (atomic res, nonatomicres)
these_domain_res = {}
these_domains = {} # key is unique name, value is _Component
if chain_ids is None:
chain_ids = IMP.pmi.output._ChainIDs()
numchain = 0
# setup representation
# loop over molecules, copies, then domains
for molname in reader.get_molecules():
copies = reader.get_molecules()[molname].domains
for nc, copyname in enumerate(copies):
print("BuildSystem.add_state: setting up molecule %s copy "
"number %s" % (molname, str(nc)))
copy = copies[copyname]
# option to not rename chains
if keep_chain_id:
all_chains = [c for c in copy if c.chain is not None]
if all_chains:
chain_id = all_chains[0].chain
else:
chain_id = chain_ids[numchain]
warnings.warn(
"No PDBs specified for %s, so keep_chain_id has "
"no effect; using default chain ID '%s'"
% (molname, chain_id), IMP.pmi.ParameterWarning)
else:
chain_id = chain_ids[numchain]
if nc == 0:
alphabet = IMP.pmi.alphabets.amino_acid
fasta_flag = copy[0].fasta_flag
if fasta_flag in self._alphabets:
alphabet = self._alphabets[fasta_flag]
seqs = IMP.pmi.topology.Sequences(
copy[0].fasta_file, fasta_name_map)
seq = seqs[copy[0].fasta_id]
print("BuildSystem.add_state: molecule %s sequence has "
"%s residues" % (molname, len(seq)))
orig_mol = state.create_molecule(
molname, seq, chain_id, alphabet=alphabet,
uniprot=seqs.uniprot.get(copy[0].fasta_id))
mol = orig_mol
numchain += 1
else:
print("BuildSystem.add_state: creating a copy for "
"molecule %s" % molname)
mol = orig_mol.create_copy(chain_id)
numchain += 1
for domainnumber, domain in enumerate(copy):
print("BuildSystem.add_state: ---- setting up domain %s "
"of molecule %s" % (domainnumber, molname))
# we build everything in the residue range, even if it
# extends beyond what's in the actual PDB file
these_domains[domain.get_unique_name()] = domain
if domain.residue_range == [] or \
domain.residue_range is None:
domain_res = mol.get_residues()
else:
start = domain.residue_range[0]+domain.pdb_offset
if domain.residue_range[1] == 'END':
end = len(mol.sequence)
else:
end = domain.residue_range[1]+domain.pdb_offset
domain_res = mol.residue_range(start-1, end-1)
print("BuildSystem.add_state: -------- domain %s of "
"molecule %s extends from residue %s to "
"residue %s "
% (domainnumber, molname, start, end))
if domain.pdb_file == "BEADS":
print("BuildSystem.add_state: -------- domain %s of "
"molecule %s represented by BEADS "
% (domainnumber, molname))
mol.add_representation(
domain_res,
resolutions=[domain.bead_size],
setup_particles_as_densities=(
domain.em_residues_per_gaussian != 0),
color=domain.color)
these_domain_res[domain.get_unique_name()] = \
(set(), domain_res)
elif domain.pdb_file == "IDEAL_HELIX":
print("BuildSystem.add_state: -------- domain %s of "
"molecule %s represented by IDEAL_HELIX "
% (domainnumber, molname))
emper = domain.em_residues_per_gaussian
mol.add_representation(
domain_res,
resolutions=self.resolutions,
ideal_helix=True,
density_residues_per_component=emper,
density_prefix=domain.density_prefix,
density_force_compute=self.force_create_gmm_files,
color=domain.color)
these_domain_res[domain.get_unique_name()] = \
(domain_res, set())
else:
print("BuildSystem.add_state: -------- domain %s of "
"molecule %s represented by pdb file %s "
% (domainnumber, molname, domain.pdb_file))
domain_atomic = mol.add_structure(domain.pdb_file,
domain.chain,
domain.residue_range,
domain.pdb_offset,
soft_check=True)
domain_non_atomic = domain_res - domain_atomic
if not domain.em_residues_per_gaussian:
mol.add_representation(
domain_atomic, resolutions=self.resolutions,
color=domain.color)
if len(domain_non_atomic) > 0:
mol.add_representation(
domain_non_atomic,
resolutions=[domain.bead_size],
color=domain.color)
else:
print("BuildSystem.add_state: -------- domain %s "
"of molecule %s represented by gaussians "
% (domainnumber, molname))
emper = domain.em_residues_per_gaussian
creategmm = self.force_create_gmm_files
mol.add_representation(
domain_atomic,
resolutions=self.resolutions,
density_residues_per_component=emper,
density_prefix=domain.density_prefix,
density_force_compute=creategmm,
color=domain.color)
if len(domain_non_atomic) > 0:
mol.add_representation(
domain_non_atomic,
resolutions=[domain.bead_size],
setup_particles_as_densities=True,
color=domain.color)
these_domain_res[domain.get_unique_name()] = (
domain_atomic, domain_non_atomic)
self._domain_res.append(these_domain_res)
self._domains.append(these_domains)
print('BuildSystem.add_state: State', len(self.system.states), 'added')
return state
def get_molecules(self):
"""Return list of all molecules grouped by state.
For each state, it's a dictionary of Molecules where key is the
molecule name
"""
return [s.get_molecules() for s in self.system.get_states()]
def get_molecule(self, molname, copy_index=0, state_index=0):
return self.system.get_states()[state_index].get_molecules()[
molname][copy_index]
def execute_macro(self, max_rb_trans=4.0, max_rb_rot=0.04,
max_bead_trans=4.0, max_srb_trans=4.0, max_srb_rot=0.04):
"""Builds representations and sets up degrees of freedom"""
print("BuildSystem.execute_macro: building representations")
self.root_hier = self.system.build()
print("BuildSystem.execute_macro: setting up degrees of freedom")
self.dof = IMP.pmi.dof.DegreesOfFreedom(self.model)
for nstate, reader in enumerate(self._readers):
rbs = reader.get_rigid_bodies()
srbs = reader.get_super_rigid_bodies()
csrbs = reader.get_chains_of_super_rigid_bodies()
# add rigid bodies
domains_in_rbs = set()
for rblist in rbs:
print("BuildSystem.execute_macro: -------- building rigid "
"body %s" % (str(rblist)))
all_res = IMP.pmi.tools.OrderedSet()
bead_res = IMP.pmi.tools.OrderedSet()
for dname in rblist:
domain = self._domains[nstate][dname]
print("BuildSystem.execute_macro: -------- adding %s"
% (str(dname)))
all_res |= self._domain_res[nstate][dname][0]
bead_res |= self._domain_res[nstate][dname][1]
domains_in_rbs.add(dname)
all_res |= bead_res
print("BuildSystem.execute_macro: -------- creating rigid "
"body with max_trans %s max_rot %s "
"non_rigid_max_trans %s"
% (str(max_rb_trans), str(max_rb_rot),
str(max_bead_trans)))
self.dof.create_rigid_body(all_res,
nonrigid_parts=bead_res,
max_trans=max_rb_trans,
max_rot=max_rb_rot,
nonrigid_max_trans=max_bead_trans,
name="RigidBody %s" % dname)
# if you have any domains not in an RB, set them as flexible beads
for dname, domain in self._domains[nstate].items():
if dname not in domains_in_rbs:
if domain.pdb_file != "BEADS":
warnings.warn(
"No rigid bodies set for %s. Residues read from "
"the PDB file will not be sampled - only regions "
"missing from the PDB will be treated flexibly. "
"To sample the entire sequence, use BEADS instead "
"of a PDB file name" % dname,
IMP.pmi.StructureWarning)
self.dof.create_flexible_beads(
self._domain_res[nstate][dname][1],
max_trans=max_bead_trans)
# add super rigid bodies
for srblist in srbs:
print("BuildSystem.execute_macro: -------- building "
"super rigid body %s" % (str(srblist)))
all_res = IMP.pmi.tools.OrderedSet()
for dname in srblist:
print("BuildSystem.execute_macro: -------- adding %s"
% (str(dname)))
all_res |= self._domain_res[nstate][dname][0]
all_res |= self._domain_res[nstate][dname][1]
print("BuildSystem.execute_macro: -------- creating super "
"rigid body with max_trans %s max_rot %s "
% (str(max_srb_trans), str(max_srb_rot)))
self.dof.create_super_rigid_body(
all_res, max_trans=max_srb_trans, max_rot=max_srb_rot)
# add chains of super rigid bodies
for csrblist in csrbs:
all_res = IMP.pmi.tools.OrderedSet()
for dname in csrblist:
all_res |= self._domain_res[nstate][dname][0]
all_res |= self._domain_res[nstate][dname][1]
all_res = list(all_res)
all_res.sort(key=lambda r: r.get_index())
self.dof.create_main_chain_mover(all_res)
return self.root_hier, self.dof
@IMP.deprecated_object("2.8", "Use AnalysisReplicaExchange instead")
class AnalysisReplicaExchange0(object):
"""A macro for running all the basic operations of analysis.
Includes clustering, precision analysis, and making ensemble density maps.
A number of plots are also supported.
"""
def __init__(self, model,
merge_directories=["./"],
stat_file_name_suffix="stat",
best_pdb_name_suffix="model",
do_clean_first=True,
do_create_directories=True,
global_output_directory="output/",
replica_stat_file_suffix="stat_replica",
global_analysis_result_directory="./analysis/",
test_mode=False):
"""Constructor.
@param model The IMP model
@param stat_file_name_suffix
@param merge_directories The directories containing output files
@param best_pdb_name_suffix
@param do_clean_first
@param do_create_directories
@param global_output_directory Where everything is
@param replica_stat_file_suffix
@param global_analysis_result_directory
@param test_mode If True, nothing is changed on disk
"""
try:
from mpi4py import MPI
self.comm = MPI.COMM_WORLD
self.rank = self.comm.Get_rank()
self.number_of_processes = self.comm.size
except ImportError:
self.rank = 0
self.number_of_processes = 1
self.test_mode = test_mode
self._protocol_output = []
self.cluster_obj = None
self.model = model
stat_dir = global_output_directory
self.stat_files = []
# it contains the position of the root directories
for rd in merge_directories:
stat_files = glob.glob(os.path.join(rd, stat_dir, "stat.*.out"))
if len(stat_files) == 0:
warnings.warn("no stat files found in %s"
% os.path.join(rd, stat_dir),
IMP.pmi.MissingFileWarning)
self.stat_files += stat_files
def add_protocol_output(self, p):
"""Capture details of the modeling protocol.
@param p an instance of IMP.pmi.output.ProtocolOutput or a subclass.
"""
# Assume last state is the one we're interested in
self._protocol_output.append((p, p._last_state))