-
Notifications
You must be signed in to change notification settings - Fork 2
/
deepmsm.py
2413 lines (2066 loc) · 109 KB
/
deepmsm.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
from typing import Optional, Union, Callable, Tuple, List
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset
from itertools import chain
from deeptime.base import Model, Transformer
from deeptime.base_torch import DLEstimatorMixin
from deeptime.util.torch import map_data
from deeptime.markov.tools.analysis import pcca_memberships
CLIP_VALUE = 1.
def symeig_reg(mat, epsilon: float = 1e-6, mode='regularize', eigenvectors=True) \
-> Tuple[torch.Tensor, Optional[torch.Tensor]]:
r""" Solves a eigenvector/eigenvalue decomposition for a hermetian matrix also if it is rank deficient.
Parameters
----------
mat : torch.Tensor
the hermetian matrix
epsilon : float, default=1e-6
Cutoff for eigenvalues.
mode : str, default='regularize'
Whether to truncate eigenvalues if they are too small or to regularize them by taking the absolute value
and adding a small positive constant. :code:`trunc` leads to truncation, :code:`regularize` leads to epsilon
being added to the eigenvalues after taking the absolute value
eigenvectors : bool, default=True
Whether to compute eigenvectors.
Returns
-------
(eigval, eigvec) : Tuple[torch.Tensor, Optional[torch.Tensor]]
Eigenvalues and -vectors.
"""
assert mode in sym_inverse.valid_modes, f"Invalid mode {mode}, supported are {sym_inverse.valid_modes}"
if mode == 'regularize':
identity = torch.eye(mat.shape[0], dtype=mat.dtype, device=mat.device)
mat = mat + epsilon * identity
# Calculate eigvalues and potentially eigvectors
eigval, eigvec = torch.symeig(mat, eigenvectors=True)
if eigenvectors:
eigvec = eigvec.transpose(0, 1)
if mode == 'trunc':
# Filter out Eigenvalues below threshold and corresponding Eigenvectors
mask = eigval > epsilon
eigval = eigval[mask]
if eigenvectors:
eigvec = eigvec[mask]
elif mode == 'regularize':
# Calculate eigvalues and eigvectors
eigval = torch.abs(eigval)
elif mode == 'clamp':
eigval = torch.clamp_min(eigval, min=epsilon)
else:
raise RuntimeError("Invalid mode! Should have been caught by the assertion.")
if eigenvectors:
return eigval, eigvec
else:
return eigval, eigvec
def sym_inverse(mat, epsilon: float = 1e-6, return_sqrt=False, mode='regularize', return_both=False):
""" Utility function that returns the inverse of a matrix, with the
option to return the square root of the inverse matrix.
Parameters
----------
mat: numpy array with shape [m,m]
Matrix to be inverted.
epsilon : float
Cutoff for eigenvalues.
return_sqrt: bool, optional, default = False
if True, the square root of the inverse matrix is returned instead
mode: str, default='trunc'
Whether to truncate eigenvalues if they are too small or to regularize them by taking the absolute value
and adding a small positive constant. :code:`trunc` leads to truncation, :code:`regularize` leads to epsilon
being added to the eigenvalues after taking the absolute value
return_both: bool, default=False
Whether to return the sqrt and its inverse or simply the inverse
Returns
-------
x_inv: numpy array with shape [m,m]
inverse of the original matrix
"""
eigval, eigvec = symeig_reg(mat, epsilon, mode)
# Build the diagonal matrix with the filtered eigenvalues or square
# root of the filtered eigenvalues according to the parameter
if return_sqrt:
diag_inv = torch.diag(torch.sqrt(1. / eigval))
if return_both:
diag = torch.diag(torch.sqrt(eigval))
else:
diag_inv = torch.diag(1. / eigval)
if return_both:
diag = torch.diag(eigval)
if not return_both:
return torch.chain_matmul(eigvec.t(), diag_inv, eigvec)
else:
return torch.chain_matmul(eigvec.t(), diag_inv, eigvec), torch.chain_matmul(eigvec.t(), diag, eigvec)
sym_inverse.valid_modes = ('trunc', 'regularize', 'clamp')
def covariances(x: torch.Tensor, y: torch.Tensor, remove_mean: bool = True):
"""Computes instantaneous and time-lagged covariances matrices.
Parameters
----------
x : (T, n) torch.Tensor
Instantaneous data.
y : (T, n) torch.Tensor
Time-lagged data.
remove_mean: bool, default=True
Whether to remove the mean of x and y.
Returns
-------
cov_00 : (n, n) torch.Tensor
Auto-covariance matrix of x.
cov_0t : (n, n) torch.Tensor
Cross-covariance matrix of x and y.
cov_tt : (n, n) torch.Tensor
Auto-covariance matrix of y.
See Also
--------
deeptime.covariance.Covariance : Estimator yielding these kind of covariance matrices based on raw numpy arrays
using an online estimation procedure.
"""
assert x.shape == y.shape, "x and y must be of same shape"
batch_size = x.shape[0]
if remove_mean:
x = x - x.mean(dim=0, keepdim=True)
y = y - y.mean(dim=0, keepdim=True)
# Calculate the cross-covariance
y_t = y.transpose(0, 1)
x_t = x.transpose(0, 1)
cov_01 = 1 / (batch_size - 1) * torch.matmul(x_t, y)
# Calculate the auto-correlations
cov_00 = 1 / (batch_size - 1) * torch.matmul(x_t, x)
cov_11 = 1 / (batch_size - 1) * torch.matmul(y_t, y)
return cov_00, cov_01, cov_11
valid_score_methods = ('VAMP1', 'VAMP2', 'VAMPE')
class U_layer(torch.nn.Module):
''' Neural network layer which implements the reweighting vector of the reversible deep MSM.
The trainable weights reweight each configuration in the state space spanned by a VAMPnet to
a learned stationary distribution.
Parameters
----------
output_dim : int
The output size of the VAMPnet.
activation : function
Activation function, where the trainable parameters are passed through. The function should map to the positive real axis
'''
def __init__(self, output_dim, activation):
super(U_layer, self).__init__()
self.M = output_dim
# using 0.5414 with softplus results in u being constant, expecting a trajectory in equilibrium
self.alpha = torch.Tensor(1, self.M).fill_(1.)
self.u_kernel = torch.nn.Parameter(data=self.alpha, requires_grad=True)
self.acti = activation
def forward(self, chi_t, chi_tau, return_u=False, return_mu=False):
r'''Call function of the layer. It maps the trainable parameters to the reweighting vector u and estimates
the correlation function in equilibrium.
Parameters
---------
chi_t : torch.Tensor with shape [T x n], where $T$ is the number of frames and n the size of the feature space.
Configurations at time $t$ mapped on the feature space. The function should represent a fuzzy clustering, i.e. each element
is positive and the vector is normalized to 1 when summing all feature values.
chi_tau : torch.Tensor with the same shape as chi_t.
Configurations at time $t+\tau$ passed through the same functions as chi_t.
return_u : bool, default=False.
Whether to return the reweighting vector $u$. Necessary for building consequtive coarse-graining layers.
return_mu: bool, default=False.
Whether to return the stationary distribution $\mu$. Necessary when working with observables.
Returns
---------
v : torch.Tensor with shape [1,n].
Necessary vector for normalizing the parameters for the S layer.
C_00 : torch.Tensor with shape [n,n].
Covariance matrix at time $t$
C_11 : torch.Tensor with shape [n,n].
Covariance matrix of the reweighted feature functions at time $t+\tau$
C_01 : torch.Tensor with shape [n,n].
Cross-correlation matrix between the feature vector at time $t$ with the reweighted one at time $t+\tau$
Sigma : torch.Tensor with shape [n,n].
Cross-correlation matrix between the feature wector at time $t+\tau$ and its reweighted form.
Necessary to estimate the transition matrix out of S.
u : torch.Tensor with shape [1,n]. Only if return_u=True.
The reweighting vector.
mu : torch.Tensor with shape [T]. Only if return_mu=True.
The stationary distribution of time shifed configurations.
'''
batchsize = chi_t.shape[0]
# note: corr_tau is the correlation matrix of the time-shifted data
# presented in the paper at page 6, "Normalization of transition density"
corr_tau = 1. / batchsize * torch.matmul(chi_tau.T, chi_tau)
chi_mean = torch.mean(chi_tau, dim=0, keepdim=True)
kernel_u = self.acti(self.u_kernel)
# u is the normalized and transformed kernel of this layer
u = kernel_u / torch.sum(chi_mean * kernel_u, dim=1, keepdim=True)
v = torch.matmul(corr_tau, u.T)
# estimate the stationary distribution of x_t+tau
mu = 1. / batchsize * torch.matmul(chi_tau, u.T)
Sigma = torch.matmul((chi_tau * mu).T, chi_tau)
# estimate the stationary distribtuion for x_t
chi_mean_t = torch.mean(chi_t, dim=0, keepdim=True)
gamma = chi_tau * (torch.matmul(chi_tau, u.T))
C_00 = 1. / batchsize * torch.matmul(chi_t.T, chi_t)
C_11 = 1. / batchsize * torch.matmul(gamma.T, gamma)
C_01 = 1. / batchsize * torch.matmul(chi_t.T, gamma)
ret = [
v,
C_00,
C_11,
C_01,
Sigma,
]
if return_u:
ret += [
u
]
if return_mu:
ret += [
mu
]
return ret
class S_layer(torch.nn.Module):
''' Neural network layer which implements the symmetric trainable matrix S of the reversible deep MSM.
The matrix S represents the transition matrix and a normalization matrix necessary to normalize the learned
transition density.
Parameters
----------
output_dim : int
The output size of the VAMPnet.
activation : function
Activation function, where the trainable parameters are passed through. The function should map to the positive real axis.
renorm : bool, default=True
Whether a elemtwise positive matrix S should be enforced. Necessary for a deep (reversible) MSM, but not for a Koopman model.
'''
def __init__(self, output_dim, activation, renorm=True):
super(S_layer, self).__init__()
self.M = output_dim
self.alpha = torch.Tensor(self.M, self.M).fill_(0.1)
self.S_kernel = torch.nn.Parameter(data=self.alpha, requires_grad=True)
self.acti = activation
self.renorm = renorm
def forward(self, v, C_00, C_11, C_01, Sigma, return_K=False, return_S=False):
r'''Call function of the layer. It maps the trainable parameters to the symmetric matrix S and estimates the VAMP-E score
of the model.
Parameters
---------
v : torch.Tensor with shape [1,n].
Necessary vector for normalizing the parameters for the S layer. It is part of the output of the u-layer.
C_00 : torch.Tensor with shape [n,n]. It is part of the output of the u-layer.
Covariance matrix at time $t$
C_11 : torch.Tensor with shape [n,n]. It is part of the output of the u-layer.
Covariance matrix of the reweighted feature functions at time $t+\tau$
C_01 : torch.Tensor with shape [n,n]. It is part of the output of the u-layer.
Cross-correlation matrix between the feature vector at time $t$ with the reweighted one at time $t+\tau$
Sigma : torch.Tensor with shape [n,n]. It is part of the output of the u-layer.
Cross-correlation matrix between the feature wector at time $t+\tau$ and its reweighted form.
Necessary to estimate the transition matrix out of S.
return_K : bool, default=False.
Whether to return the estimated transition matrix learned via S.
return_S : bool, default=False.
Whether to return the matrix S. Necessary for further calculations like coarse-graining.
Returns
---------
VAMP-E matrix : torch.Tensor with shape [n,n].
The trace of the matrix is the VAMP-E score.
K : torch.Tensor with shape [n,n]. Only if return_K=True.
Transition matrix propagating the state space in time.
S : torch.Tensor with shape [n,n]. Only if return_S=True.
The learned matrix S.
'''
batchsize = v.shape[0]
# transform the kernel weights
kernel_w = self.acti(self.S_kernel)
# enforce symmetry
W1 = kernel_w + kernel_w.T
# normalize the weights
norm = W1 @ v
w2 = (1 - torch.squeeze(norm)) / torch.squeeze(v)
S_temp = W1 + torch.diag(w2)
if self.renorm:
# if (S_temp < 0).sum() > 0: # check if actually non-negativity is violated
# make sure that the largest value of norm is < 1
quasi_inf_norm = lambda x: torch.sum((x ** 20)) ** (1. / 20)
# print(norm, quasi_inf_norm(norm))
W1 = W1 / quasi_inf_norm(norm)
norm = W1 @ v
w2 = (1 - torch.squeeze(norm)) / torch.squeeze(v)
S_temp = W1 + torch.diag(w2)
S = S_temp
# calculate K
K = S @ Sigma
# VAMP-E matrix for the computation of the loss
VampE_matrix = S.T @ C_00 @ S @ C_11 - 2 * S.T @ C_01
# stack outputs so that the first dimension is = batchsize, keras requirement
ret = [VampE_matrix]
if return_K:
ret += [K]
if return_S:
ret += [S]
return ret
class Coarse_grain(torch.nn.Module):
r'''Layer to coarse grain a state space. The layer can be used with deep reversible MSM, but also for simple VAMPnets.
Parameters
---------
input_dim : int.
The number of dimension of the previous layer which should be coarse grained to output_dim.
output_dim : int.
Number of dimension the system should be coarse grained to. Should be strictly smaller than input_dim.
'''
def __init__(self, input_dim, output_dim):
super(Coarse_grain, self).__init__()
self.N = input_dim
self.M = output_dim
self.alpha = torch.ones((self.N, self.M))
self.weight = torch.nn.Parameter(data=self.alpha, requires_grad=True)
def forward(self, x):
'''
Call function of the layer, which transforms x from input_dim dimensions to output_dim. Where each input state is probabilisticly assigned
to each output state.
Parameters
----------
x : torch.Tensor of shape [T, input_dim].
Fuzzy state assigned from a VAMPnet with a softmax output function, where T are the number of frames.
Returns
---------
y : torch.Tensor of shape [T, output_dim].
Fuzzy state assignment but now with output_dim states.
'''
kernel = torch.softmax(self.weight, dim=1)
ret = x @ kernel
return ret
def get_softmax(self):
'''
Helper function to plot the coarse-graining matrix.
Returns:
M : torch.Tensor of shape [input_dim, output_dim].
Element (M)_ij is the probability that state i belongs to state j in the coarse grained representation.
'''
return torch.softmax(self.weight, dim=1)
def get_cg_uS(self, chi_n, chi_tau_n, u_n, S_n, renorm=True,
return_chi=False, return_K=False):
r'''
Coarse graining function, when using a deep reversible MSM. Since the coarse-grained representation should be consistant with
respect to the learned stationary distribution and transition density in the larger space, $u_m$ and $S_m$ of the coarse grained
space can be estimated given $u_n$ and $S_n$ of the original feature space given the coarse-grain matrix.
Parameters
---------
chi_n : torch.Tensor of shape [T,n].
The feature functions of the original space at time $t$.
chi_tau_n : torch.Tensor of shape [T,n].
The feature functions of the original space at time $t+\tau$.
u_n : torch.Tensor of shape [1,n].
The reweighting vector of the original space.
S_n : torch.Tensor of shape [n,n].
The symmetric matrix S of the original space.
renorm : bool, default=True.
Should be the same as for the original S-layer. Enforces positive elements in S.
return_chi : bool, default=False.
Whether to return the new feature functions, $u_m$, and $S_m$. Necessary if a consequtive coarse-grain layer is implemented.
return_K : bool, default=False.
Whether to return the transition matrix in the coarse-grained state space.
Returns
---------
VampE_matrix : torch.Tensor of shape [m,m].
Taking the trace of the VAMP-E matrix yields the VAMP-E score in the coarse grained space.
chi_m : torch.Tensor of shape [T,m]. Only if return_chi=True.
The feature functions of the coarse grained space at time $t$.
chi_tau_m : torch.Tensor of shape [T,m]. Only if return_chi=True.
The feature functions of the coarse grained space at time $t+\tau$.
u_m : torch.Tensor of shape [1,m]. Only if return_chi=True.
The reweighting vecor in the coarse-grained space.
S_m : torch.Tensor of shape [m,m]. Only if return_chi=True.
The matrix S in the coarse-grained space.
K : torch.Tensor of shape [m,m]. Only if return_K=True.
Transition matrix in the coarse-grained space.
'''
batchsize = chi_n.shape[0]
M = torch.softmax(self.weight, dim=1)
chi_t_m = chi_n @ M
chi_tau_m = chi_tau_n @ M
# estimate the pseudo inverse of M
U, S_vec, V = torch.svd(M)
s_nonzero = S_vec > 0
s_zero = S_vec <= 0
S_star = torch.cat((1/S_vec[s_nonzero], S_vec[s_zero]))
U_star = torch.cat((U[:,s_nonzero], U[:,s_zero]), dim=1)
V_star = torch.cat((V[:,s_nonzero], V[:,s_zero]), dim=1)
G = V_star @ torch.diag(S_star) @ U_star.T
# estimate the new u and S
u_m = (G @ u_n.T).T
# renormalize
u_m = torch.relu(u_m)
chi_mean = torch.mean(chi_tau_m, dim=0, keepdim=True)
u_m = u_m / torch.sum(chi_mean * u_m, dim=1, keepdim=True)
W1 = G @ S_n @ G.T
W1 = torch.relu(W1)
#renormalize
batchsize = chi_n.shape[0]
corr_tau = 1./batchsize * torch.matmul(chi_tau_m.T, chi_tau_m)
v = torch.matmul(corr_tau, u_m.T)
norm = W1 @ v
w2 = (1 - torch.squeeze(norm)) / torch.squeeze(v)
S_temp = W1 + torch.diag(w2)
if renorm:
# make sure that the largest value of norm is < 1
quasi_inf_norm = lambda x: torch.sum((x**20))**(1./20)
W1 = W1 / quasi_inf_norm(norm)
norm = W1 @ v
w2 = (1 - torch.squeeze(norm)) / torch.squeeze(v)
S_temp = W1 + torch.diag(w2)
S_m = S_temp
# estimate the VAMP-E matrix and other helpful instances
mu = 1./batchsize * torch.matmul(chi_tau_m, u_m.T)
Sigma = torch.matmul((chi_tau_m * mu).T, chi_tau_m)
gamma = chi_tau_m * (torch.matmul(chi_tau_m, u_m.T))
C_00 = 1./batchsize * torch.matmul(chi_t_m.T, chi_t_m)
C_11 = 1./batchsize * torch.matmul(gamma.T, gamma)
C_01 = 1./batchsize * torch.matmul(chi_t_m.T, gamma)
K = S_m @ Sigma
# VAMP-E matrix for the computation of the loss
VampE_matrix = S_m.T @ C_00 @ S_m @ C_11 - 2*S_m.T @ C_01
ret = [VampE_matrix]
if return_chi:
ret += [
chi_t_m,
chi_tau_m,
u_m,
S_m,
]
if return_K:
ret += [
K
]
return ret
def vampe_loss_rev(chi_t, chi_tau, ulayer, slayer, return_mu=False, return_Sigma=False, return_K=False, return_S=False):
'''
VAMP-E score for a reversible deep MSM.
Parameters
---------
chi_t : torch.Tensor of shape [T,n].
The fuzzy state assignment for all $T$ time frames at time $t$
chi_tau : torch.Tensor of shape [T,n].
The fuzzy state assignment for all $T$ time frames at time $t+\tau$
ulayer : torch.nn.Module.
The layer which implements the reweighting vector $u$.
slayer : torch.nn.Module.
The layer which implements the symmetric matrix $S$.
return_mu : bool, default=False.
Whether the stationary distribution should be returned.
return_Sigma : bool, default=False.
Whether the cross-correlation matrix should be returned.
return_K : bool, default=False.
Whether the transition matrix should be returned.
return_S : bool, default=False.
Whether the matrix S should be returned.
Returns
---------
vampe : torch.Tensor of shape [1,1]
VAMP-E score.
K : torch.Tensor of shape [n,n]. Only if return_K=True.
Transition matrix.
S : torch.Tensor of shape [n,n]. Only if return_S=True.
Symmetric matrix S.
'''
ret2 = []
output_u = ulayer(chi_t, chi_tau, return_mu=return_mu)
if return_mu:
ret2.append(output_u[-1])
if return_Sigma:
ret2.append(output_u[4])
output_S = slayer(*output_u[:5], return_K=return_K, return_S=return_S)
vampe = torch.trace(output_S[0])
ret1 = [-vampe]
if return_K:
ret1.append(output_S[1])
if return_S:
ret1.append(output_S[-1])
ret = ret1 + ret2
return ret
def vampe_loss_rev_only_S(v, C_00, C_11, C_01, Sigma, slayer, return_K=False, return_S=False):
output_S = slayer(v, C_00, C_11, C_01, Sigma, return_K=return_K, return_S=return_S)
# print(K)
vampe = torch.trace(output_S[0])
ret = [-vampe]
if return_K:
ret.append(output_S[1])
if return_S:
ret.append(output_S[-1])
return ret
def get_process_eigval(S, Sigma, state1, state2, epsilon=1e-6, mode='regularize'):
''' state can be int or list of int'''
Sigma_sqrt_inv, Sigma_sqrt = sym_inverse(Sigma, epsilon, return_sqrt=True, mode=mode, return_both=True)
S_similar = Sigma_sqrt @ S @ Sigma_sqrt
eigval_all, eigvec_all = torch.symeig(S_similar, eigenvectors=True)
eigvecs_K = Sigma_sqrt_inv @ eigvec_all
# Find the relevant process which is changing most between state1 and state2
process_id = torch.argmin(eigvecs_K[state1,:]*eigvecs_K[state2,:], dim=1).detach()
return eigval_all[process_id]
def obs_its_loss(S, Sigma, state1, state2, exp_value, lam, epsilon=1e-6, mode='regularize'):
obs_value = get_process_eigval(S, Sigma, state1, state2, epsilon=epsilon, mode=mode)
error = torch.sum(lam*torch.abs(exp_value - obs_value))
return error, obs_value
def obs_ev(obs_value, mu):
exp_value_estimated = torch.sum(obs_value * mu, dim=0)
return exp_value_estimated
def obs_ev_loss(obs_value, mu, exp_value, lam):
exp_value_estimated = obs_ev(obs_value, mu)
error = torch.sum(lam*torch.abs(exp_value - exp_value_estimated))
return error, exp_value_estimated
def obs_ac(obs_value, mu, chi, K, Sigma):
state_weight = mu*chi
pi = torch.sum(state_weight, dim=0) # prob to be in a state
# obs value within a state, the weighting factor needs to be normalized for each state
ai = torch.sum(state_weight[:,None,:]*obs_value[:,:,None], dim=0) / torch.sum(state_weight, dim=0)[None,:]
# prob to observe an unconditional jump state i to j
X = Sigma @ K
a_sim = torch.sum(ai * torch.matmul(X, ai.T).T, dim=1)
return a_sim
def obs_ac_loss(obs_value, mu, chi, K, Sigma, exp_value, lam):
a_sim = obs_ac(obs_value, mu, chi, K, Sigma)
error = torch.sum(lam*torch.abs(a_sim - exp_value))
return error, a_sim
class DeepMSMModel(Transformer, Model):
r"""
A VAMPNet model which can be fit to data optimizing for one of the implemented VAMP scores.
Parameters
----------
lobe : torch.nn.Module
One of the lobes of the VAMPNet. See also :class:`deeptime.util.torch.MLP`.
lobe_timelagged : torch.nn.Module, optional, default=None
The timelagged lobe. Can be left None, in which case the lobes are shared.
dtype : data type, default=np.float32
The data type for which operations should be performed. Leads to an appropriate cast within fit and
transform methods.
device : device, default=None
The device for the lobe(s). Can be None which defaults to CPU.
See Also
--------
VAMPNet : The corresponding estimator.
"""
def __init__(self, lobe: nn.Module, ulayer, slayer, cg_list=None, mask=torch.nn.Identity(),
dtype=np.float32, device=None, epsilon=1e-6, mode='regularize'):
super().__init__()
self._lobe = lobe
self._ulayer = ulayer
self._slayer = slayer
if cg_list is not None:
self._cg_list = cg_list
self.mask = mask
if dtype == np.float32:
self._lobe = self._lobe.float()
elif dtype == np.float64:
self._lobe = self._lobe.double()
self._dtype = dtype
self._device = device
self._epsilon = epsilon
self._mode = mode
def transform(self, data, **kwargs):
self._lobe.eval()
net = self._lobe
out = []
for data_tensor in map_data(data, device=self._device, dtype=self._dtype):
out.append(net(self.mask(data_tensor)).cpu().numpy())
return out if len(out) > 1 else out[0]
def get_mu(self, data_t):
self._lobe.eval()
net = self._lobe
with torch.no_grad():
x_t = net(self.mask(torch.Tensor(data_t).to(self._device)))
mu = self._ulayer(x_t, x_t, return_mu=True)[-1] # use dummy x_0
return mu.detach().to('cpu').numpy()
def get_transition_matrix(self, data_0, data_t):
self._lobe.eval()
net = self._lobe
with torch.no_grad():
x_0 = net(self.mask(torch.Tensor(data_0).to(self._device)))
x_t = net(self.mask(torch.Tensor(data_t).to(self._device)))
_, K = vampe_loss_rev(x_0, x_t, self._ulayer, self._slayer, return_K=True)
K = K.to('cpu').numpy().astype('float64')
# Converting to double precision destroys the normalization
T = K / K.sum(axis=1)[:, None]
return T
def timescales(self, data_0, data_t, tau):
T = self.get_transition_matrix(data_0, data_t)
eigvals = np.linalg.eigvals(T)
eigvals_sort = np.sort(eigvals)[:-1] # remove eigenvalue 1
its = - tau/np.log(np.abs(eigvals_sort[::-1]))
return its
def get_transition_matrix_cg(self, data_0, data_t, idx=0):
self._lobe.eval()
net = self._lobe
with torch.no_grad():
chi_t = net(self.mask(torch.Tensor(data_0).to(self._device)))
chi_tau = net(self.mask(torch.Tensor(data_t).to(self._device)))
v, C00, Ctt, C0t, Sigma, u_n = self._ulayer(chi_t, chi_tau, return_u=True)
_, S_n = self._slayer(v, C00, Ctt, C0t, Sigma, return_S=True)
for cg_id in range(idx+1):
_ , chi_t, chi_tau, u_n, S_n, K = self._cg_list[cg_id].get_cg_uS(chi_t, chi_tau, u_n, S_n, return_chi=True, return_K=True)
K = K.to('cpu').numpy().astype('float64')
# Converting to double precision destroys the normalization
T = K / K.sum(axis=1)[:, None]
return T
def timescales_cg(self, data_0, data_t, tau, idx=0):
T = self.get_transition_matrix_cg(data_0, data_t, idx=idx)
eigvals = np.linalg.eigvals(T)
eigvals_sort = np.sort(eigvals)[:-1] # remove eigenvalue 1
its = - tau/np.log(np.abs(eigvals_sort[::-1]))
return its
def observables(self, data_0, data_t, data_ev=None, data_ac=None, state1=None, state2=None):
return_mu = False
return_K = False
return_S = False
if data_ev is not None:
return_mu = True
if data_ac is not None:
return_mu = True
return_K = True
if state1 is not None:
return_S = True
self._lobe.eval()
net = self._lobe
with torch.no_grad():
x_0 = net(self.mask(torch.Tensor(data_0).to(self._device)))
x_t = net(self.mask(torch.Tensor(data_t).to(self._device)))
output_u = self._ulayer(x_0, x_t, return_mu=return_mu)
if return_mu:
mu = output_u[5]
Sigma = output_u[4]
output_S = self._slayer(*output_u[:5], return_K=return_K, return_S=return_S)
if return_K:
K = output_S[1]
if return_S:
S = output_S[-1]
ret = []
if data_ev is not None:
x_ev = torch.Tensor(data_ev).to(self._device)
ev_est = obs_ev(x_ev,mu)
ret.append(ev_est.detach().to('cpu').numpy())
if data_ac is not None:
x_ac = torch.Tensor(data_ac).to(self._device)
ac_est = obs_ac(x_ac, mu, x_t, K, Sigma)
ret.append(ac_est.detach().to('cpu').numpy())
if state1 is not None:
its_est = get_process_eigval(S, Sigma, state1, state2, epsilon=self._epsilon, mode=self._mode)
ret.append(its_est.detach().to('cpu').numpy())
return ret
class DeepMSM(DLEstimatorMixin, Transformer):
r""" Implementation of VAMPNets :cite:`vnet-mardt2018vampnets` which try to find an optimal featurization of
data based on a VAMP score :cite:`vnet-wu2020variational` by using neural networks as featurizing transforms
which are equipped with a loss that is the negative VAMP score. This estimator is also a transformer
and can be used to transform data into the optimized space. From there it can either be used to estimate
Markov state models via making assignment probabilities crisp (in case of softmax output distributions) or
to estimate the Koopman operator using the :class:`VAMP <deeptime.decomposition.VAMP>` estimator.
Parameters
----------
lobe : torch.nn.Module
A neural network module which maps input data to some (potentially) lower-dimensional space.
lobe_timelagged : torch.nn.Module, optional, default=None
Neural network module for timelagged data, in case of None the lobes are shared (structure and weights).
device : torch device, default=None
The device on which the torch modules are executed.
optimizer : str or Callable, default='Adam'
An optimizer which can either be provided in terms of a class reference (like `torch.optim.Adam`) or
a string (like `'Adam'`). Defaults to Adam.
learning_rate : float, default=5e-4
The learning rate of the optimizer.
score_method : str, default='VAMP2'
The scoring method which is used for optimization.
score_mode : str, default='regularize'
The mode under which inverses of positive semi-definite matrices are estimated. Per default, the matrices
are perturbed by a small constant added to the diagonal. This makes sure that eigenvalues are not too
small. For a complete list of modes, see :meth:`sym_inverse`.
epsilon : float, default=1e-6
The strength of the regularization under which matrices are inverted. Meaning depends on the score_mode,
see :meth:`sym_inverse`.
dtype : dtype, default=np.float32
The data type of the modules and incoming data.
shuffle : bool, default=True
Whether to shuffle data during training after each epoch.
See Also
--------
deeptime.decomposition.VAMP
References
----------
.. bibliography:: /references.bib
:style: unsrt
:filter: docname in docnames
:keyprefix: vnet-
"""
_MUTABLE_INPUT_DATA = True
def __init__(self, lobe: nn.Module, output_dim: int, coarse_grain: list = None, mask=None,
device=None, optimizer: Union[str, Callable] = 'Adam', learning_rate: float = 5e-4,
score_mode: str = 'regularize', epsilon: float = 1e-6,
dtype=np.float32, shuffle: bool = True):
super().__init__()
self.lobe = lobe
self.output_dim = output_dim
self.coarse_grain = coarse_grain
self.ulayer = U_layer(output_dim=output_dim, activation=torch.nn.ReLU()).to(device)
self.slayer = S_layer(output_dim=output_dim, activation=torch.nn.ReLU(), renorm=True).to(device)
if self.coarse_grain is not None:
self.cg_list = []
self.cg_opt_list = []
for i, dim_out in enumerate(self.coarse_grain):
if i==0:
dim_in = self.output_dim
else:
dim_in = self.coarse_grain[i-1]
self.cg_list.append(Coarse_grain(dim_in, dim_out).to(device))
self.cg_opt_list.append(torch.optim.Adam(self.cg_list[-1].parameters(), lr=0.1))
else:
self.cg_list=None
if mask is not None:
self.mask = mask
self.optimizer_mask = torch.optim.Adam(self.mask.parameters(), lr=self.learning_rate)
else:
self.mask = torch.nn.Identity()
self.optimizer_mask = None
self.score_mode = score_mode
self._step = 0
self.shuffle = shuffle
self._epsilon = epsilon
self.device = device
self.learning_rate = learning_rate
self.dtype = dtype
self.setup_optimizer(optimizer, list(self.lobe.parameters()))
self.optimizer_u = torch.optim.Adam(self.ulayer.parameters(), lr=self.learning_rate*10)
self.optimizer_s = torch.optim.Adam(self.slayer.parameters(), lr=self.learning_rate*100)
self.optimizer_lobe = torch.optim.Adam(self.lobe.parameters(), lr=self.learning_rate)
self.optimimzer_all = torch.optim.Adam(chain(self.ulayer.parameters(), self.slayer.parameters(), self.lobe.parameters()), lr=self.learning_rate)
self._train_scores = []
self._validation_scores = []
self._train_vampe = []
self._train_ev = []
self._train_ac = []
self._train_its = []
self._validation_vampe = []
self._validation_ev = []
self._validation_ac = []
self._validation_its = []
@property
def train_scores(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.array(self._train_scores)
@property
def train_vampe(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.array(self._train_vampe)
@property
def train_ev(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._train_ev).reshape(-1,self._train_ev[0].shape[0])
@property
def train_ac(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._train_ac).reshape(-1,self._train_ac[0].shape[0])
@property
def train_its(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._train_its).reshape(-1,self._train_its[0].shape[0])
@property
def validation_scores(self) -> np.ndarray:
r""" The collected validation scores. First dimension contains the step, second dimension the score.
Initially empty.
:type: (T, 2) ndarray
"""
return np.array(self._validation_scores)
@property
def validation_vampe(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.array(self._validation_vampe)
@property
def validation_ev(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._validation_ev).reshape(-1,self._validation_ev[0].shape[0])
@property
def validation_ac(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._validation_ac).reshape(-1,self._validation_ac[0].shape[0])
@property
def validation_its(self) -> np.ndarray:
r""" The collected train scores. First dimension contains the step, second dimension the score. Initially empty.
:type: (T, 2) ndarray
"""
return np.concatenate(self._validation_its).reshape(-1,self._validation_its[0].shape[0])
@property
def epsilon(self) -> float:
r""" Regularization parameter for matrix inverses.
:getter: Gets the currently set parameter.
:setter: Sets a new parameter. Must be non-negative.
:type: float
"""
return self._epsilon
@epsilon.setter
def epsilon(self, value: float):
assert value >= 0
self._epsilon = value
@property
def score_method(self) -> str:
r""" Property which steers the scoring behavior of this estimator.