-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdaptiveSampling.py
More file actions
1032 lines (925 loc) · 41.4 KB
/
AdaptiveSampling.py
File metadata and controls
1032 lines (925 loc) · 41.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Definition of the base AdaptiveSampling class for REAP-like implementations.
Derived classes that implement more advanced adaptive sampling schemes will inherit from this class.
"""
import os
from abc import ABC, abstractmethod
from collections import Counter
import dill as pickle
import numpy as np
import torch
import torch.nn as nn
from deeptime.clustering import RegularSpace
from deeptime.decomposition import VAMP
from deeptime.decomposition.deep import VAMPNet, TVAEEncoder, TVAE
from deeptime.util.data import TrajectoryDataset
from deeptime.util.torch import MLP
from sklearn.cluster import MiniBatchKMeans, BisectingKMeans
from sklearn.metrics import pairwise_distances_argmin_min
from torch.utils.data import DataLoader
import utils
from FileHandler import FileHandler
class AdaptiveSampling(ABC):
"""Abstract class for adaptive sampling object.
"""
def __init__(self):
pass
@abstractmethod
def _reload(self):
pass
@abstractmethod
def define_cvs(self):
pass
@abstractmethod
def collect_initial_data(self):
pass
@abstractmethod
def _cluster(self):
pass
@abstractmethod
def _select_states(self):
pass
@abstractmethod
def run_round(self):
pass
class LeastCounts(AdaptiveSampling):
"""This class implements Least Counts adaptive sampling using KMeans clustering.
"""
def __init__(self,
system=None,
root="",
basename="",
save_format='.dcd',
save_rate=100,
features=None,
save_info=False,
cluster_args=None,
log_file=None):
"""LeastCounts constructor.
:param system: Simulation object.
Object that implements the dynamics to be simulated.
:param root: str.
Path to root directory where data will be saved.
:param basename: str.
Basename for saved trajectory files.
:param save_format: str, default = ".dcd".
Saved format to use for trajectories (not implemented yet).
:param save_rate: int, default = 100.
Save rate in frames for trajectory files.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
:param save_info: Bool, default = False.
Save logging info for each trajectory run.
:param cluster_args: list[float, float, int].
List of parameters for MiniBatchKMeans clustering (gamma, b, batch_size). Gamma and b affect the number of
clusters utilized, while batch_size is the number of samples to use per mini-batch.
:param log_file: str.
Path to log_file. Passing this argument will supersede all other parameters.
"""
if log_file is None:
self.system = system
self.fhandler = FileHandler(root, basename, save_format)
self.save_rate = save_rate
self.n_round = 0
self.features = features
self.n_features = len(features)
self.data = None
self.concat_data = None
self.states = None
self._cached_trajs = set() # Set of trajectory files already read into memory
self._cached_trajs_ordered = []
self._cluster_object = None
self.save_info = save_info # Used to output information about the run
if cluster_args is None:
self.cluster_args = [2e-3, 0.7, 10000] # Depends on clustering algorithm --> This is (gamma, b, batch_size)
else:
self.cluster_args = cluster_args
elif isinstance(log_file, str):
self._reload(log_file)
def save(self, path):
"""Saves the object serialized with dill (similar to pickle).
Warning: the object might take a large amount of memory.
:param path: str.
Path to output file.
:return: None.
"""
with open(path, "wb") as outfile:
pickle.dump(self, outfile)
def _save_logs(self, filename):
"""Save logging information of the run.
:param filename: str.
Name of output file.
:return: None.
"""
logs = dict(
system=self.system,
fhandler=self.fhandler,
save_rate=self.save_rate,
n_round=self.n_round,
features=self.features,
n_features=self.n_features,
cluster_args=self.cluster_args,
cluster_object=self._cluster_object,
states=self.states,
)
root_dir = self.fhandler.root
path = os.path.join(root_dir, filename)
with open(path, "wb") as outfile:
pickle.dump(logs, outfile)
def _reload(self, log_file):
"""Reset simulation object to state in log_file. Called in constructor.
For this method to work, trajectories should be found where self.fhandler expects them.
:param log_file: str.
Path to log file.
"""
with open(log_file, "rb") as infile:
logs = pickle.load(infile)
self.system = logs['system']
self.fhandler = logs['fhandler']
self.save_rate = logs['save_rate']
self.n_round = logs['n_round']
self.features = logs['features']
self.n_features = logs['n_features']
self.cluster_args = logs['cluster_args']
self._cluster_object = logs['cluster_object']
self.states = logs['states']
self.save_info = True # If loading from log file, assume that log files are required
self.data = None
self.concat_data = None
self._cached_trajs = set()
self._cached_trajs_ordered = []
self._cluster_object = None
self._update_data()
# TODO: Define subsample function to use every time the total number of frames surpasses threshold.
def define_cvs(self, features):
"""Use this function to redefine collective variables after a run has been started.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
"""
self.features = features
def collect_initial_data(self, init_states, n_steps, n_repeats=1):
"""Typically called when no preexisting data is available.
Calling this function will update n_round.
:param init_states: list[tuple(str, int, str)].
Order for tuple elements in list: [(fname, frame_idx, top_file)].
:param n_steps: int.
Number of steps per trajectory.
:param n_repeats: int.
Number of trajectories.
:return: None.
"""
fnames = self.fhandler.generate_new_round(init_states, n_repeats, n_steps, self.n_round, self.save_rate)
for fname in fnames:
state = self.fhandler.init_states[fname] # State is dict (see utils.py)
positions = utils.get_openmm_positions(state)
self.system.launch_trajectory(positions, n_steps, fname, self.save_rate)
self.fhandler.check_files(self.system.top_file)
self._update_data() # Update data from new trajectories
self.n_round += 1
def _update_data(self):
"""Update data with newly saved trajectories.
:return: None.
"""
fnames = self.fhandler.list_all_files()
new_fnames = []
for fn in fnames:
if fn not in self._cached_trajs:
new_fnames.append(fn)
if self.data is None:
self.data = self.system.project_cvs(self.features, new_fnames)
else:
new_data = self.system.project_cvs(self.features, new_fnames)
self.data.extend(new_data)
self.concat_data = np.concatenate(self.data, axis=0)
self._cached_trajs.update(new_fnames)
self._cached_trajs_ordered.extend(new_fnames)
def _cluster(self, min_clusters):
"""Perform clustering using MiniBatchKMeans.
:param min_clusters: int.
Minimum number of clusters required.
:return: None.
"""
total_frames = self.concat_data.shape[0]
b, gamma, max_frames = self.clustering_args
d = min(len(self.features), 3)
n_clusters = int(b * (min(total_frames, max_frames) ** (gamma * d)))
if n_clusters < min_clusters:
n_clusters = min_clusters
elif n_clusters > 1000: # Set a limit to avoid slow clustering
n_clusters = 1000
elif n_clusters > total_frames:
n_clusters = total_frames // 3 # In case of low data regime
self._cluster_object = \
MiniBatchKMeans(n_clusters=n_clusters, init='k-means++', batch_size=max_frames).fit(self.concat_data)
def _find_candidates(self, n_select):
"""Determine a representative simulation frame for each cluster.
:param n_select: int.
Maximum number of clusters to consider.
:return: least_counts (np.ndarray), central_frames_indices (np.ndarray)
least_counts: coordinates in collective variable space for representative frames.
central_frames_indices: indices for representative frames.
"""
self._cluster(n_select)
counts = Counter(self._cluster_object.labels_)
least_counts = np.asarray(counts.most_common()[::-1][:n_select])[:, 0]
least_counts_centers = self._cluster_object.cluster_centers_[least_counts]
central_frames_indices, _ = pairwise_distances_argmin_min(least_counts_centers,
self.concat_data)
return least_counts, central_frames_indices
def _select_states(self, n_select):
"""Select states to restart simulations.
:param n_select: int.
Number of states to select.
:return: starting_states_info (list[dict]).
List containing information to read a state (fname, frame_idx, and top_file).
"""
least_counts, central_frames_indices = self._find_candidates(n_select)
starting_states = central_frames_indices # In LeastCounts, no further sub-selection is performed
starting_states_info = self.fhandler.find_state_info(starting_states,
self._cached_trajs_ordered,
self.system.top_file)
return starting_states_info
def run_round(self, n_select, n_steps, n_repeats=1):
"""Perform round of simulations.
:param n_select: int.
Number of trajectories to run.
:param n_steps: int.
Number of steps per trajectory.
:param n_repeats: int.
Number of clones per trajectory.
:return: None.
"""
starting_states_info = self._select_states(n_select)
fnames = self.fhandler.generate_new_round(starting_states_info,
n_repeats,
n_steps,
self.n_round,
self.save_rate)
for fname in fnames:
state = self.fhandler.init_states[fname]
# State is a dictionary that contains at least keys "fname", "frame_idx", and "top_file"
positions = utils.get_openmm_positions(state)
self.system.launch_trajectory(positions, n_steps, fname, self.save_rate)
self.fhandler.check_files(self.system.top_file)
self._update_data() # Update data from new trajectories
self.n_round += 1
if self.save_info:
self._save_logs("logs_round_{}.pkl".format(self.n_round - 1))
class LeastCountsBis(LeastCounts):
"""This class implements Least Counts adaptive sampling using BisectingKMeans clustering.
"""
def _cluster(self, min_clusters):
"""Perform clustering using BisectingKMeans.
:param min_clusters: int.
Minimum number of clusters required.
:return: None.
"""
total_frames = self.concat_data.shape[0]
b, gamma, max_frames = self.clustering_args
d = min(len(self.features), 3)
n_clusters = int(b * (min(total_frames, max_frames) ** (gamma * d)))
if n_clusters < min_clusters:
n_clusters = min_clusters
elif n_clusters > 1000: # Set a limit to avoid slow clustering
n_clusters = 1000
elif n_clusters > total_frames:
n_clusters = total_frames // 3 # In case of low data regime
self._cluster_object = \
BisectingKMeans(n_clusters=n_clusters,
init="k-means++",
bisecting_strategy="largest_cluster").fit(self.concat_data)
class LeastCountsRegSpace(LeastCounts):
"""This class implements Least Counts adaptive sampling using RegularSpace clustering.
"""
def __init__(self,
system=None,
root="",
basename="",
save_format='.dcd',
save_rate=100,
features=None,
save_info=False,
cluster_args=None,
log_file=None):
"""Constructor for LeastCountsRegSpace.
:param system: Simulation object.
Object that implements the dynamics to be simulated.
:param root: str.
Path to root directory where data will be saved.
:param basename: str.
Basename for saved trajectory files.
:param save_format: str, default = ".dcd".
Saved format to use for trajectories (not implemented yet).
:param save_rate: int, default = 100.
Save rate in frames for trajectory files.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
:param save_info: Bool, default = False.
Save logging info for each trajectory run.
:param cluster_args: list[float, int].
List of parameters for RegularSpace clustering (dmin, max_centers). dmin is the minimum distance admissible
between two centers. max_centers is the maximum number of clusters that can be created.
:param log_file: str.
Path to log_file. Passing this argument will supersede all other parameters.
"""
LeastCounts.__init__(self,
system=system,
root=root,
basename=basename,
save_format=save_format,
save_rate=save_rate,
features=features,
save_info=save_info,
log_file=log_file)
if log_file is None:
if cluster_args is None:
self.cluster_args = [1e-3, 10000] # Depends on clustering algorithm --> This is (dmin, max_centers)
else:
self.cluster_args = cluster_args
def _cluster(self, min_clusters):
"""Perform clustering using BisectingKMeans.
:param min_clusters: int.
Minimum number of clusters required.
:return: None.
"""
dmin, max_centers = self.cluster_args
self._cluster_object = \
RegularSpace(dmin=dmin,
max_centers=max_centers).fit(self.concat_data)
def _find_candidates(self, n_select):
"""Determine a representative simulation frame for each cluster.
:param n_select: int.
Maximum number of clusters to consider.
:return: least_counts (np.ndarray), central_frames_indices (np.ndarray)
least_counts: coordinates in collective variable space for representative frames.
central_frames_indices: indices for representative frames.
"""
self._cluster(n_select)
counts = Counter(self._cluster_object.model.transform(self.concat_data))
least_counts = np.asarray(counts.most_common()[::-1][:n_select])[:, 0]
cluster_centers = np.squeeze(np.asarray(self._cluster_object._clustercenters))
least_counts_centers = cluster_centers[least_counts]
central_frames_indices, _ = pairwise_distances_argmin_min(least_counts_centers,
self.concat_data)
return least_counts, central_frames_indices
class VampLeastCounts(LeastCountsRegSpace):
"""This class implements Least Counts adaptive sampling using RegularSpace clustering in combination with VAMP
from the deeptime package.
"""
def __init__(self,
system=None,
root="",
basename="",
save_format='.dcd',
save_rate=100,
features=None,
save_info=False,
cluster_args=None,
ndim=2,
lagtime=1,
propagation_steps=1,
log_file=None):
"""Constructor for VampLeastCounts.
:param system: Simulation object.
Object that implements the dynamics to be simulated.
:param root: str.
Path to root directory where data will be saved.
:param basename: str.
Basename for saved trajectory files.
:param save_format: str, default = ".dcd".
Saved format to use for trajectories (not implemented yet).
:param save_rate: int, default = 100.
Save rate in frames for trajectory files.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
:param save_info: Bool, default = False.
Save logging info for each trajectory run.
:param cluster_args: list[float, int].
List of parameters for RegularSpace clustering (dmin, max_centers). dmin is the minimum distance admissible
between two centers. max_centers is the maximum number of clusters that can be created.
:param ndim: int, default = 2.
Number of reduction dimensions to use with VAMP.
:param lagtime: int, default = 1.
Lag time expressed as number of frames.
:param propagation_steps: int, default = 1.
This option allows to apply the Koopman operator propagation_steps times to the input conformation.
:param log_file: str.
Path to log_file. Passing this argument will supersede all other parameters.
"""
if log_file is None:
LeastCountsRegSpace.__init__(self,
system=system,
root=root,
basename=basename,
save_format=save_format,
save_rate=save_rate,
features=features,
save_info=save_info,
cluster_args=cluster_args
)
self.ndim = ndim
self.lagtime = lagtime
self.propagation_steps = propagation_steps
self.estimator = VAMP(lagtime=self.lagtime, dim=self.ndim, epsilon=1e-18) # Epsilon is set to a low
# number to prevent errors, but this may result in poor quality models.
elif isinstance(log_file, str):
self._reload(log_file)
def _save_logs(self, filename):
"""Save logging information of the run.
:param filename: str.
Name of output file.
:return: None.
"""
logs = dict(
system=self.system,
fhandler=self.fhandler,
save_rate=self.save_rate,
n_round=self.n_round,
features=self.features,
n_features=self.n_features,
cluster_args=self.cluster_args,
cluster_object=self._cluster_object,
states=self.states,
ndim=self.ndim,
lagtime=self.lagtime,
propagation_steps=self.propagation_steps,
estimator=self.estimator,
)
root_dir = self.fhandler.root
path = os.path.join(root_dir, filename)
with open(path, "wb") as outfile:
pickle.dump(logs, outfile)
def _reload(self, log_file):
"""Reset simulation object to state in log_file. Called in constructor.
For this method to work, trajectories should be found where self.fhandler expects them.
:param log_file: str.
Path to log file.
"""
with open(log_file, "rb") as infile:
logs = pickle.load(infile)
self.system = logs['system']
self.fhandler = logs['fhandler']
self.save_rate = logs['save_rate']
self.n_round = logs['n_round']
self.features = logs['features']
self.n_features = logs['n_features']
self.cluster_args = logs['cluster_args']
self._cluster_object = logs['cluster_object']
self.states = logs['states']
self.ndim = logs['ndim']
self.lagtime = logs['lagtime']
self.propagation_steps = logs['propagation_steps']
self.estimator = logs['estimator']
self.save_info = True # If loading from log file, assume that log files are required
self.data = None
self.concat_data = None
self._cached_trajs = set()
self._cached_trajs_ordered = []
self._cluster_object = None
self._update_data()
def _update_data(self):
"""Update data with newly saved trajectories.
:return: None.
"""
LeastCountsRegSpace._update_data(self)
self.estimator.fit(self.data)
self.concat_data = self._propagate_kinetic_model(np.concatenate(self.data, axis=0))
def _propagate_kinetic_model(self, frames):
"""Propagate the candidate frames using the kinetic model.
:param frames: np.ndarray of shape (n_frames, n_features).
Frames to transform applying Koopman operator.
:return: np.ndarray of shape (n_frames, ndim).
Transformed frames.
"""
model = self.estimator.fetch_model()
inst_obs = model.transform(frames)
propagated = inst_obs @ (model.operator ** self.propagation_steps)[:self.ndim, :self.ndim]
return propagated
class VampNetLeastCounts(VampLeastCounts):
"""This class implements Least Counts adaptive sampling using RegularSpace clustering in combination with VAMPNets
from the deeptime package.
"""
def __init__(self,
system=None,
root="",
basename="",
save_format='.dcd',
save_rate=100,
features=None,
save_info=False,
cluster_args=None,
ndim=2,
lagtime=1,
device="cuda",
vnet_lobe=None,
vnet_learning_rate=1e-4,
vnet_batch_size=64,
vnet_epochs=100,
vnet_num_threads=1,
log_file=None):
"""Constructor for VampNetLeastCounts.
:param system: Simulation object.
Object that implements the dynamics to be simulated.
:param root: str.
Path to root directory where data will be saved.
:param basename: str.
Basename for saved trajectory files.
:param save_format: str, default = ".dcd".
Saved format to use for trajectories (not implemented yet).
:param save_rate: int, default = 100.
Save rate in frames for trajectory files.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
:param save_info: Bool, default = False.
Save logging info for each trajectory run.
:param cluster_args: list[float, int].
List of parameters for RegularSpace clustering (dmin, max_centers). dmin is the minimum distance admissible
between two centers. max_centers is the maximum number of clusters that can be created.
:param ndim: int, default = 2.
Size of VAMPNet output layer.
:param lagtime: int, default = 1.
Lag time expressed as number of frames.
:param device: str.
Device where training of the VAMPNet will take place. See pytorch documentation for options.
:param vnet_lobe: deeptime.util.torch.MLP.
Multilayer perceptron model for VAMPNet. Lobe duplication is hard-coded.
:param vnet_learning_rate: float, default 1e-4.
Learning rate for VAMPNet.
:param vnet_batch_size: int, default = 64.
Batch size for VAMPNet.
:param vnet_epochs: int, default = 100.
Number of training epochs per adaptive sampling round.
:param vnet_num_threads: int, default = 1.
Number of threads available for VAMPNet fitting.
:param log_file: str.
Path to log_file. Passing this argument will supersede all other parameters.
"""
if log_file is None:
VampLeastCounts.__init__(self,
system=system,
root=root,
basename=basename,
save_format=save_format,
save_rate=save_rate,
features=features,
save_info=save_info,
cluster_args=cluster_args,
ndim=ndim,
lagtime=lagtime)
self.batch_size = vnet_batch_size
self.epochs = vnet_epochs
self.device_name = device
self.vnet_num_threads = vnet_num_threads
self._set_device(device, vnet_num_threads)
if vnet_lobe is None:
vnet_lobe = MLP(units=[self.n_features, 15, 10, 10, 5, self.ndim],
nonlinearity=nn.ReLU) # A default model
vnet_lobe = vnet_lobe.to(self.device)
self.estimator = VAMPNet(lobe=vnet_lobe, learning_rate=vnet_learning_rate, device=self.device)
elif isinstance(log_file, str):
self._reload(log_file)
def _save_logs(self, filename):
"""Save logging information of the run.
:param filename: str.
Name of output file.
:return: None.
"""
logs = dict(
system=self.system,
fhandler=self.fhandler,
save_rate=self.save_rate,
n_round=self.n_round,
features=self.features,
n_features=self.n_features,
cluster_args=self.cluster_args,
cluster_object=self._cluster_object,
states=self.states,
ndim=self.ndim,
lagtime=self.lagtime,
batch_size=self.batch_size,
epochs=self.epochs,
device_name=self.device_name,
vnet_num_threads=self.vnet_num_threads,
estimator=self.estimator,
)
root_dir = self.fhandler.root
path = os.path.join(root_dir, filename)
with open(path, "wb") as outfile:
pickle.dump(logs, outfile)
def _reload(self, log_file):
"""Reset simulation object to state in log_file. Called in constructor.
For this method to work, trajectories should be found where self.fhandler expects them.
:param log_file: str.
Path to log file.
"""
with open(log_file, "rb") as infile:
logs = pickle.load(infile)
self.system = logs['system']
self.fhandler = logs['fhandler']
self.save_rate = logs['save_rate']
self.n_round = logs['n_round']
self.features = logs['features']
self.n_features = logs['n_features']
self.cluster_args = logs['cluster_args']
self._cluster_object = logs['cluster_object']
self.states = logs['states']
self.ndim = logs['ndim']
self.lagtime = logs['lagtime']
self.batch_size = logs['batch_size']
self.epochs = logs['epochs']
self.device_name = logs['device_name']
self.vnet_num_threads = logs['vnet_num_threads']
self._set_device(self.device_name, self.vnet_num_threads)
self.estimator = logs['estimator']
self.save_info = True # If loading from log file, assume that log files are required
self.data = None
self.concat_data = None
self._cached_trajs = set()
self._cached_trajs_ordered = []
self._cluster_object = None
self._update_data()
def _set_device(self, device, num_threads):
"""Set the device for VAMPNet training.
:param device: str.
Device where training of the VAMPNet will take place. See pytorch documentation for options.
:param num_threads: int, default = 1.
Number of threads available for VAMPNet fitting.
:return: None.
"""
if (device == "cuda") and torch.cuda.is_available():
self.device = torch.device("cuda")
torch.backends.cudnn.benchmark = True
else:
self.device = torch.device("cpu")
torch.set_num_threads(num_threads)
def _propagate_kinetic_model(self, frames):
"""Transform specified simulation frames using the learned VAMPNet.
:param frames: np.ndarray of shape (n_frames, n_features).
Features to transform.
:return: np.ndarray of shape (n_frames, ndim).
Transformed frames.
"""
model = self.estimator.fetch_model()
propagated = model.transform(frames)
return propagated
def _lagged_dataset(self, data):
"""Convert trajectories to deeptime.util.data.TrajectoryDataset object.
:param data: list[np.ndarray].
List of trajectories.
:return: deeptime.util.data.TrajectoryDataset.
Lagged dataset object.
"""
data_float32 = list(map(lambda x: x.astype(np.float32), data))
return TrajectoryDataset.from_trajectories(self.lagtime, data_float32)
def _format_data(self, data, batch_size):
"""Format list of trajectories into the correct format to fit a VAMPNet.
:param data: list[np.ndarray].
List of trajectories.
:param batch_size: int.
Batch size for VAMPNet fitting.
:return: torch.utils.data.dataloader.DataLoader.
Data loader to train VAMPNet.
"""
lagged_data = self._lagged_dataset(data)
loader_train = DataLoader(lagged_data, batch_size=batch_size, shuffle=True)
return loader_train
def _fit_estimator(self):
"""Fit VAMPNet with list of trajectories currently stored in self.data.
:return: None.
"""
loader_train = self._format_data(self.data, self.batch_size)
self.estimator.fit(loader_train, n_epochs=self.epochs)
def _update_data(self):
"""Update data with newly saved trajectories.
:return: None.
"""
fnames = self.fhandler.list_all_files()
new_fnames = []
for fn in fnames:
if fn not in self._cached_trajs:
new_fnames.append(fn)
if self.data is None:
self.data = self.system.project_cvs(self.features, new_fnames)
else:
new_data = self.system.project_cvs(self.features, new_fnames)
self.data.extend(new_data)
self._fit_estimator()
self.concat_data = self._propagate_kinetic_model(np.concatenate(self.data, axis=0))
self._cached_trajs.update(new_fnames)
self._cached_trajs_ordered.extend(new_fnames)
class VaeLeastCounts(VampLeastCounts):
"""This class implements Least Counts adaptive sampling using RegularSpace clustering in combination with TVAEs
from the deeptime package.
"""
def __init__(self,
system=None,
root="",
basename="",
save_format='.dcd',
save_rate=100,
features=None,
save_info=False,
cluster_args=None,
ndim=2,
lagtime=1,
device="cuda",
tvae_encoder=None,
tvae_decoder=None,
tvae_learning_rate=1e-4,
tvae_batch_size=64,
tvae_epochs=100,
tvae_num_threads=1,
log_file=None):
"""Constructor for VaeLeastCounts.
:param system: Simulation object.
Object that implements the dynamics to be simulated.
:param root: str.
Path to root directory where data will be saved.
:param basename: str.
Basename for saved trajectory files.
:param save_format: str, default = ".dcd".
Saved format to use for trajectories (not implemented yet).
:param save_rate: int, default = 100.
Save rate in frames for trajectory files.
:param features: list[Callable].
List of callables that take a trajectory file as input and return a real number per frame.
:param save_info: Bool, default = False.
Save logging info for each trajectory run.
:param cluster_args: list[float, int].
List of parameters for RegularSpace clustering (dmin, max_centers). dmin is the minimum distance admissible
between two centers. max_centers is the maximum number of clusters that can be created.
:param ndim: int, default = 2.
Size of VAMPNet output layer.
:param lagtime: int, default = 1.
Lag time expressed as number of frames.
:param device: str.
Device where training of the VAMPNet will take place. See pytorch documentation for options.
:param tvae_encoder: deeptime.decomposition.deep._tae.TVAEEncoder.
Encoder for the TVAE. See deeptime documentation for details.
:param tvae_decoder: typically deeptime.util.torch.MLP.
Decoder for the TVAE. See deeptime documentation for details.
:param tvae_learning_rate: float, default 1e-4.
Learning rate for TVAE.
:param tvae_batch_size: int, default = 64.
Batch size for TVAE.
:param tvae_epochs: int, default = 100.
Number of training epochs per adaptive sampling round.
:param tvae_num_threads: int, default = 1.
Number of threads available for TVAE fitting.
:param log_file: str.
Path to log_file. Passing this argument will supersede all other parameters.
"""
VampLeastCounts.__init__(self,
system=system,
root=root,
basename=basename,
save_format=save_format,
save_rate=save_rate,
features=features,
save_info=save_info,
cluster_args=cluster_args,
ndim=ndim,
lagtime=lagtime)
if log_file is None:
self.batch_size = tvae_batch_size
self.epochs = tvae_epochs
self._set_device(device, tvae_num_threads)
# Set estimator
if tvae_encoder is None:
tvae_encoder = TVAEEncoder([self.n_features, 15, 10, 10, 5, self.ndim],
nonlinearity=torch.nn.ReLU) # A default encoder
if tvae_decoder is None:
tvae_decoder = MLP([self.ndim, 5, 10, 10, 15, self.n_features], nonlinearity=torch.nn.ReLU,
initial_batchnorm=False) # A default decoder
tvae_encoder = tvae_encoder.to(self.device)
tvae_decoder = tvae_decoder.to(self.device)
self.estimator = TVAE(tvae_encoder, tvae_decoder, learning_rate=tvae_learning_rate)
elif isinstance(log_file, str):
self._reload(log_file)
def _save_logs(self, filename):
"""Save logging information of the run.
:param filename: str.
Name of output file.
:return: None.
"""
logs = dict(
system=self.system,
fhandler=self.fhandler,
save_rate=self.save_rate,
n_round=self.n_round,
features=self.features,
n_features=self.n_features,
cluster_args=self.cluster_args,
cluster_object=self._cluster_object,
states=self.states,
ndim=self.ndim,
lagtime=self.lagtime,
device=self.device,
batch_size=self.batch_size,
epochs=self.epochs,
device_name=self.device_name,
tvae_num_threads=self.tvae_num_threads,
estimator=self.estimator,
)
root_dir = self.fhandler.root
path = os.path.join(root_dir, filename)
with open(path, "wb") as outfile:
pickle.dump(logs, outfile)
def _reload(self, log_file):
"""Reset simulation object to state in log_file. Called in constructor.
For this method to work, trajectories should be found where self.fhandler expects them.
:param log_file: str.
Path to log file.
"""
with open(log_file, "rb") as infile:
logs = pickle.load(infile)
self.system = logs['system']
self.fhandler = logs['fhandler']
self.save_rate = logs['save_rate']
self.n_round = logs['n_round']
self.features = logs['features']
self.n_features = logs['n_features']
self.cluster_args = logs['cluster_args']
self._cluster_object = logs['cluster_object']
self.states = logs['states']
self.ndim = logs['ndim']
self.lagtime = logs['lagtime']
self.device_name = logs['device_name']
self.tvae_num_threads = logs['tvae_num_threads']
self._set_device(self.device_name, self.tvae_num_threads)
self.estimator = logs['estimator']
self.save_info = True # If loading from log file, assume that log files are required
self.data = None
self.concat_data = None
self._cached_trajs = set()
self._cached_trajs_ordered = []
self._cluster_object = None
self._update_data()
def _set_device(self, device, num_threads):
"""Set the device for VAMPNet training.
:param device: str.
Device where training of the VAMPNet will take place. See pytorch documentation for options.
:param num_threads: int, default = 1.
Number of threads available for TVAE fitting.
:return: None.
"""
if (device == "cuda") and torch.cuda.is_available():
self.device = torch.device("cuda")
torch.backends.cudnn.benchmark = True
else:
self.device = torch.device("cpu")
torch.set_num_threads(num_threads)
def _propagate_kinetic_model(self, frames):
"""Transform specified simulation frames using the learned TVAE.
:param frames: np.ndarray of shape (n_frames, n_features).
Features to transform.
:return: np.ndarray of shape (n_frames, ndim).
Transformed frames.
"""
model = self.estimator.fetch_model()
propagated = model.transform(frames)
return propagated
def _lagged_dataset(self, data):
"""Convert trajectories to deeptime.util.data.TrajectoryDataset object.
:param data: list[np.ndarray].
List of trajectories.
:return: deeptime.util.data.TrajectoryDataset.
Lagged dataset object.
"""
data_float32 = list(map(lambda x: x.astype(np.float32), data))
return TrajectoryDataset.from_trajectories(self.lagtime, data_float32)
def _format_data(self, data, batch_size):
"""Format list of trajectories into the correct format to fit a TVAE.
:param data: list[np.ndarray].
List of trajectories.
:param batch_size: int.
Batch size for TVAE fitting.
:return: torch.utils.data.dataloader.DataLoader.
Data loader to train TVAE.