-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrevDMSM.script.final.py
2366 lines (1941 loc) · 90.3 KB
/
revDMSM.script.final.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from IPython.display import display
import sys
import os
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import deeptime
import matplotlib.pyplot as plt
# import pytorch_lightning as pl
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset, TensorDataset
import gc
from contextlib import contextmanager
from tqdm import tqdm
from collections import OrderedDict
from torch.optim import Adam
from typing import Callable
from multiprocessing.pool import ThreadPool
import time
import pickle
from collections import ChainMap
from IPython.display import display
import scipy.stats as stats
import matplotlib.colors as colors
from itertools import repeat
import argparse
import importlib
import re
# from torch.Nested import nested_tensor ###dreaming of pytorch to drop nested tensor support
plt.rcParams['axes.linewidth'] = 3
def num_str(s, return_str=True, return_num=True):
s = ''.join(filter(str.isdigit, s))
if return_str and return_num:
return s, int(s)
if return_str:
return s
if return_num:
return int(s)
def make_symbols():
unicharacters = ["\u03B1",
"\u03B2",
"\u03B3",
"\u03B4",
"\u03B5",
"\u03B6",
"\u03B7",
"\u03B8",
"\u03B9",
"\u03BA",
"\u03BB",
"\u03BC",
"\u03BD",
"\u03BE",
"\u03BF",
"\u03C0",
"\u03C1",
"\u03C2",
"\u03C3",
"\u03C4",
"\u03C5",
"\u03C6",
"\u03C7",
"\u03C8",
"\u03C9",
"\u00C5"]
keys = "alpha,beta,gamma,delta,epsilon,zeta,eta,theta,iota,kappa,lambda,mu,nu,xi,omicron,pi,rho,final_sigma,sigma,tau,upsilon,phi,chi,psi,omega,angstrom"
return dict(zip(keys.split(","), unicharacters))
symbols = make_symbols()
def make_trial_dir(trial_dir):
"""recursive function to create the next iteration in a series of indexed directories
to save training results generated from repeated trials. Guarantees correctly indexed
directories and allows for lazy initialization (i.e. finds the next index automatically
assuming the "root" or "base" directory name remains the same)"""
if not os.path.exists(trial_dir):
os.makedirs(trial_dir)
return trial_dir
else:
path_list = trial_dir.split("/")
local_dir = path_list.pop()
global_dir = "/".join(path_list) + "/"
s, s_num = num_str(local_dir)
trial_dir = global_dir + local_dir.replace(s, str(s_num + 1))
trial_dir = make_trial_dir(trial_dir)
return trial_dir
def load_dict(file):
with open(file, "rb") as handle:
dic_loaded = pickle.load(handle)
return dic_loaded
def save_dict(file, dict):
with open(file, "wb") as handle:
pickle.dump(dict, handle)
return None
def check_mem():
for obj in gc.get_objects():
try:
if torch.is_tensor(obj) or hasattr(obj, "data") and torch.is_tensor(obj.data):
print(type(obj), obj.size())
except:
pass
def pmf1d(x, nbins, range=None, weights=None, return_bin_centers=True):
count, edge = np.histogram(x, bins=nbins, range=range, weights=weights)
if weights is None:
p = count / len(x)
else:
p = count
if return_bin_centers:
return p, edge[:-1] + np.diff(edge) / 2
else:
return p
class timer:
"""import time"""
def __init__(self, check_interval: "the time (hrs) after the call method should return True"):
self.start_time = time.time()
self.interval = check_interval * (60 ** 2)
def __call__(self):
if abs(time.time() - self.start_time) > self.interval:
self.start_time = time.time()
return True
else:
return False
def time_remaining(self):
sec = max(0, self.interval - abs(time.time() - self.start_time))
hrs = sec // (60 ** 2)
mins_remaining = (sec / 60 - hrs * 60)
mins = mins_remaining // 1
secs = (mins_remaining - mins) * 60
hrs, mins, secs = [int(i) for i in [hrs, mins, secs]]
print(f"{hrs}:{mins}:{secs}")
return None
# for context managment
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.interval = self.end - self.start
print(f"Time elapsed {self.interval} s")
return self.interval
def expectation(obs, p):
"""obs = time series vector or matrix with time in the zeroth dimension, features (or variables) in the second
time series (0 dim) probability assignments to each state (1 dim)"""
return (obs.T @ p) / p.sum(0)
def expectation_sd(obs, p, exp=None):
if exp is None:
exp = expectation(obs, p)
return np.sqrt(expectation(obs ** 2, p) - exp ** 2)
def pooled_sd(means: "1d array of trial means", sds: "1d array of trial sds",
n_samples: "1d array of the number of samples used to estimate each sd and mean" = None, ):
"""
For combining standard deviations.
Can be used for combining standard deviations estimated from datasets with differing number of samples.
If n_samples if None or a constant, then it's assumed that the number of samples is the same for all SDs and cancels out of the sum and reduces to the number of standard deviations
being combined. As a result, this parameter can be left as None if all standard deviations are estimated using the same number of samples
"""
if isinstance(n_samples, (float, int)) or n_samples is None:
# in this case the number of samples cancels out
return np.sqrt((sds ** 2 + (means - means.mean()) ** 2).sum() / len(means))
else:
n = n_samples.sum()
return np.sqrt((n_samples * (sds ** 2 + (means - means.mean()) ** 2)).sum() / n)
def moving_average(x: np.ndarray, n: int = 3):
ret = np.cumsum(x, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def ci(x, iv=.999, mean=True, return_one=None, single_value=False):
if mean:
loc = x.mean()
else:
loc = 0
l, u = stats.t.interval(alpha=iv, df=len(x) - 1, loc=loc, scale=stats.sem(x))
if single_value:
return np.array([abs(i) for i in [l, u]]).mean()
if return_one is None:
return l, u
else:
if return_one == "l":
return l
if return_one == "u":
return u
# helper functions for retrieving saved optimization runs
def max_str(files):
if isinstance(files, list):
files = np.array(files)
return files[np.argmax(np.array([num_str(f, return_str=False, return_num=True) for f in files]))]
def sort_strs(files, max=False):
if isinstance(files, list):
files = np.array(files)
if max:
return files[np.argsort(np.array([num_str(f, return_str=False, return_num=True) for f in files]))]
else:
return files[np.argsort(np.array([num_str(f, return_str=False, return_num=True) for f in files]))]
def get_ckpt(dir, keyword="ckpt"):
return dir + "/" + max_str(keyword_files(dir, keyword))
def lsdir(dir, keyword=None):
"""full path version of os.listdir with files/directories in order"""
if not keyword is None:
listed_dir = keyword_files(dir, keyword)
else:
listed_dir = os.listdir(dir)
return [dir + "/" + i for i in sort_strs(listed_dir)]
def keyword_files(dir, keyword):
files = os.listdir(dir)
return [dir + "/" + f for f in files if keyword in f]
# function to perform bootstrapping on data from all optimization runs
##notice that these functions are designed to work with data saved by the KoopmanModel class and looks for specifically named files!!!!
def bagged_stat(ckpt_dirs: list, file: str, name: str = None,
compute_sd=False, compute_ci=False,
distribution=False, hist2d=False,
make_df=False, display_df=False):
outs = {}
n_samples = len(ckpt_dirs)
trial_means = np.stack([np.load(i + f"/{file}_ensemble_ave.npy") for i in ckpt_dirs])
outs["mean"] = trial_means.mean(0)
if compute_ci:
ci95 = np.apply_along_axis(func1d=ci, axis=0, arr=trial_means,
mean=False, single_value=True)
outs["ci95"] = ci95
if compute_sd:
trial_sds = np.stack([np.load(i + f"/{file}_ensemble_sd.npy") for i in ckpt_dirs])
# gives almost the same as the alternative definition below
outs["sd"] = np.sqrt((np.power(trial_sds, 2) + np.power(trial_means - outs["mean"], 2)).sum(0) / n_samples)
if distribution:
"""Let's try having this accept a dictionary in order to keep track of bin edges"""
outs["dist"] = {}
dicts = [load_dict(i + f"/{file}_ensemble_dist.pkl") for i in ckpt_dirs]
trial_dists = np.stack([i["probs"] for i in dicts])
outs["dist"]["mean"] = trial_dists.mean(0)
outs["dist"]["ci95"] = np.apply_along_axis(func1d=ci, axis=0, arr=trial_dists, mean=True)
outs["dist"]["bin_centers"] = dicts[0]["bin_centers"]
if compute_sd and compute_ci and make_df and not distribution:
assert not name is None, "Must give a name to the state to make a dataframe"
df = pd.DataFrame(data=np.stack(list(outs.values()), axis=1),
columns=r"$<{}>$,95% CI of mean,${}_{{\sigma}}$".format(name, name).split(","),
index=np.arange(1, len(outs["mean"]) + 1))
if display_df:
display(df)
return df
else:
return outs
def bagged_hist2d(ckpt_dirs: list, file: str, name: str = None):
dist = {}
dicts = [load_dict(i + f"/{file}_ensemble_dist2d.pkl") for i in ckpt_dirs]
dist["x_centers"] = dicts[0]["x_centers"]
dist["y_centers"] = dicts[0]["y_centers"]
trial_dists = np.stack([i["probs"] for i in dicts])
dist["mean"] = trial_dists.mean(0)
return dist
# In[368]:
def source_module(module_file: str, local_module_name: str = None):
"""to add a module from a user defined python script into the local name space"""
#
if local_module_name is None:
local_module_name = module_file.split("/")[-1].replace(".py", "")
if len(module_file.split("/")) == 1 or module_file.split("/")[-2] == ".":
module_dir = os.getcwd()
else:
module_dir = "/".join(module_file.split("/")[:-1])
sys.path.insert(0, module_dir)
module = importlib.import_module(module_file.split("/")[-1].replace(".py", ""))
g = globals()
g[local_module_name] = module
pass
def source_module_attr(module_file: str, attr_name: str, local_attr_name: str = None):
"""to add a module from a user defined python script into the local name space"""
#
if local_attr_name is None:
local_attr_name = attr_name
if len(module_file.split("/")) == 1 or module_file.split("/")[-2] == ".":
module_dir = os.getcwd()
else:
module_dir = "/".join(module_file.split("/")[:-1])
sys.path.insert(0, module_dir)
module = importlib.import_module(module_file.split("/")[-1].replace(".py", ""))
g = globals()
g[local_attr_name] = getattr(module, attr_name)
pass
def multireplace(string, replacements, ignore_case=False):
"""
Given a string and a replacement map, it returns the replaced string.
:param str string: string to execute replacements on
:param dict replacements: replacement dictionary {value to find: value to replace}
:param bool ignore_case: whether the match should be case insensitive
:rtype: str
"""
if not replacements:
# Edge case that'd produce a funny regex and cause a KeyError
return string
if ignore_case:
def normalize_old(s):
return s.lower()
re_mode = re.IGNORECASE
else:
def normalize_old(s):
return s
re_mode = 0
replacements = {normalize_old(key): val for key, val in replacements.items()}
rep_sorted = sorted(replacements, key=len, reverse=True)
rep_escaped = map(re.escape, rep_sorted)
pattern = re.compile("|".join(rep_escaped), re_mode)
return pattern.sub(lambda match: replacements[normalize_old(match.group(0))], string)
def plain_state_dict(d, badwords=["module.","model."]):
replacements= dict(zip(badwords,[""]*len(badwords)))
new = OrderedDict()
for k, v in d.items():
name = multireplace(string=k, replacements=replacements, ignore_case=True)
new[name] = v
return new
def load_state_dict(model, file):
try:
model.load_state_dict(plain_state_dict(torch.load(file)))
#if we're trying to load from lightning state dict
except:
model.load_state_dict(plain_state_dict(torch.load(file)["state_dict"]))
return model
def proj2d(p, c, alpha: "float or array of floats" = None,
state_map=False, ax=None, filename=None, cmap="jet",
comp_type: str = "Comp.", cbar_label: str = "Magnitude",
x_label: str = None, y_label: str = None, title: str = None):
if ax is None:
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
if state_map:
nstates = c.max() + 1
color_list = plt.cm.jet
cs = [color_list(i) for i in range(color_list.N)]
cmap = colors.ListedColormap(cs)
boundaries = np.arange(nstates + 1).tolist()
norm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)
tick_locs = (np.arange(nstates) + 0.5)
ticklabels = np.arange(1, nstates + 1).astype(str).tolist()
s = ax.scatter(p[:, 0], p[:, 1], c=c, s=.5, cmap=cmap, norm=norm)
cbar = plt.colorbar(s, ax=ax)
cbar.set_label("State", size=10)
cbar.set_ticks(tick_locs)
cbar.set_ticklabels(ticklabels)
else:
if x_label is None and y_label is None:
x_label, y_label = [f"{comp_type} {i}" for i in range(1, 3)]
s = ax.scatter(p[:, 0], p[:, 1], c=c, s=.5, cmap=cmap, alpha=alpha)
cbar = plt.colorbar(s, ax=ax)
cbar.set_label(cbar_label, size=15)
if not title is None:
ax.set_title(title, size=20)
ax.set_xlabel(x_label, fontsize=15)
ax.set_ylabel(y_label, fontsize=15)
ax.tick_params(axis="x", labelsize=10)
ax.tick_params(axis="y", labelsize=10)
cbar.ax.tick_params(labelsize=8)
if not filename is None:
plt.savefig(filename)
plt.clf()
return
def plot_free_energy(hist2d: np.ndarray, T: float,
title: str, xlabel: str, ylabel: str,
x_centers: np.ndarray,
y_centers: np.ndarray,
ax=None,
cbar=True):
if ax is None:
fig, ax = plt.subplots(1, figsize=(10, 10))
free_energy = -T * 0.001987 * np.log(hist2d + .000001)
im = ax.imshow(free_energy, interpolation='gaussian',
extent=[x_centers[0], x_centers[-1],
y_centers[0], y_centers[-1]],
cmap='jet', aspect='auto',
vmin=.1, vmax=3)
ax.set_ylabel(ylabel, size=44, labelpad=15)
ax.set_xlabel(xlabel, size=44, labelpad=15)
ax.set_title(title, size=35)
# HARD CODED TO Q IN THE X-AXIS
ax.set_xticks(ticks=[.2, .4, .6, .8, 1], labels="0.2,0.4,0.6,0.8,1".split(","), fontsize=40)
ax.tick_params(labelsize="40")
if cbar:
cbar_ticks = [0, 1, 2, 3]
cb = plt.colorbar(mappable=im, ax=ax, ticks=cbar_ticks, format=('% .1f'), aspect=10)
cb.set_label("Free Energy / (kT)", size=45)
cb.ax.tick_params(labelsize=40)
# ax.set_xlim(0,1)
# plt.axes(cb.ax)
return im
def contact_maps_helix(flat_map: "average contact population", dssp: "average dsspH for state", dssp_error,
native_index: "indices of native distances", index: list, columns: list,
index_res_color: list, ci: int, cut: int,
xlabel: str, ylabel: str, title: str):
flat_map = np.copy(flat_map)
flat_map[native_index] *= -1
flat_map = flat_map.reshape(len(index), len(columns))
fig = plt.figure(figsize=(12, 16), constrained_layout=True)
grid = GridSpec(6, 3, hspace=.2, wspace=0.2)
ax = fig.add_subplot(grid[:-1, :])
im = ax.imshow(100 * np.flip(flat_map[cut:], axis=0), cmap='seismic', aspect='auto', vmin=-100, vmax=100)
# ax.grid(which="both",alpha=0.5)
ax.grid(which="both", alpha=1, lw=2)
ax.set_yticks(range(len(index[cut:]))[::2], np.flip(index[cut:])[::2], size=35)
ax.set_xticks(np.arange(21), ["" for i in range(21)], size=0)
ax.set_title(title + f" State {ci}", size=42)
ax.set_ylabel(ylabel, size=40)
cb = ax.inset_axes([1.05, 0, .08, 1], transform=ax.transAxes)
cbar = fig.colorbar(im, cax=cb, orientation="vertical")
cbar.ax.tick_params(labelsize=34)
cb_label = " Contact Population (%) \n\nNon-Native Native"
cbar.set_label(cb_label, size=36, rotation=270, labelpad=120, fontweight="bold")
cbar.set_ticklabels(abs(np.arange(-100, 101, 25)))
dp = fig.add_subplot(grid[-1, :], sharex=ax)
fig.execute_constrained_layout()
dp.fill_between(np.arange(21), dssp, color="darkgoldenrod", alpha=.4)
dp.set_xticks(np.arange(21), columns, rotation=-90, ha="center", size=35)
dp.plot(dssp, color="black", ls="--", marker=".", ms=10)
dp.errorbar(np.arange(21), dssp, yerr=dssp_error, alpha=1, color="black", capsize=5)
dp.set_xlabel(xlabel, size=40)
dp.set_ylim(0, 1)
dp.set_yticks([0, .5, 1], [0, .5, 1], size=30)
dp.grid(which="major", alpha=1, lw=2)
dp.set_ylabel("P(H)", size=38)
for i in ax.get_yticklabels():
if index_res_color[i.get_text()] != "black": i.set_alpha(.7)
i.set_color(index_res_color[i.get_text()])
def get_contact_data(pair: str,
state: int,
pairs: "np.ndarray or string residue pairs" = "d['pairs']",
mean_contact_data: np.ndarray = "ave_contacts['mean']",
ci_contact_data: np.ndarray = "ave_contacts['ci95']",
mean_dist_data: np.ndarray = "ave_distances['mean']",
ci_dist_data: np.ndarray = "ave_distances['ci95']"
):
"""contact data arrays are (Ncontacts,Nstates)
returns a list with [mean,CI] for a given distance and state
"""
idx = np.where(pairs == pair)[0][0]
##make contacts a percentage
mean_contact = 100 * mean_contact_data[idx, state]
ci_contact = 100 * ci_contact_data[idx, state]
##
mean_dist = mean_dist_data[idx, state]
ci_dist = ci_dist_data[idx, state]
return [mean_contact, ci_contact, mean_dist, ci_dist]
def combine_contact_stats(pairs: list, state: int, return_df=False,
prot_name_1: str = "XD", prot_name_2: str = "NT"):
data = np.array([get_contact_data(pair=i, state=state) for i in pairs])
pairs_display = [f"{prot_name_1}:{i.split(',')[0]}-{prot_name_2}:{i.split(',')[-1]}" for i in pairs]
combined_stats = np.array(
[[data[..., i].mean(), pooled_sd(means=data[..., i], sds=data[..., i + 1])] for i in [0, 2]]).reshape(
-1, 1)
data = np.concatenate([data.T, combined_stats], axis=1)
df = pd.DataFrame(data=data, columns=pairs_display + ["Cumulative Average (propogated error)"],
index="Contact Probability (%),95% CI contact,Ave Distance,95% CI Distance".split(","))
df = df.style.set_caption(f"State {state}")
display(df)
if return_df:
return df
else:
pass
def reindex_dtraj(dtraj, obs, maximize_obs=True):
"""given a discrete trajectory and an observable, we reindex the trajectory
based on the mean of the observable in each state (high to low)
maximize_obs has been added to increase flexibility as one might want to reindex
states in order of smallest mean value of observable"""
nstates = dtraj.max() + 1 # number of states
# get the sorted cluster indices based on mean of observable
if maximize_obs:
idx = np.array([obs[np.where(dtraj == i)[0]].mean() for i in range(nstates)]).argsort()[::-1]
else:
idx = np.array([obs[np.where(dtraj == i)[0]].mean() for i in range(nstates)]).argsort()
# make a mapping of old indices to new indices
mapping = np.zeros(nstates)
mapping[idx] = np.arange(nstates)
# map the states
new_dtraj = mapping[dtraj]
return new_dtraj, idx
def reindex_matrix(mat: np.ndarray, reindex: np.ndarray):
"""reindex matrix based on indices in idx"""
if len(mat.shape) == 2:
mat = mat[reindex, :]
mat = mat[:, reindex]
if len(mat.shape) == 3:
mat = mat[:, reindex, :]
mat = mat[:, :, reindex]
return mat
def sorted_eig(x, sym=False, real=True, return_check=False):
if sym:
lam, v = np.linalg.eigh(x)
else:
lam, v = np.linalg.eig(x)
check_real = {}
for i, name in zip([lam, v], "eigen_vals,eigen_vecs".split(",")):
check = np.iscomplex(i).any()
check_real[name] = check
if real:
lam, v = [i.real for i in [lam, v]]
idx = abs(lam).argsort()[::-1]
lam = lam[idx]
v = v[:, idx]
if return_check:
return lam, v, check_real
else:
return lam, v
# def ckpredict(tmat,nlags):
# nstates = tmat.shape[0]
# #decompose the transtition matrix into eigen values so we can propagate it by simply
# ##raising the eigen values to power
# lam, v = sorted_eig(tmat) #keep it all row stochastic, eigen vals will be the same either way
# lam = np.diag(lam)
# v_inv = np.linalg.inv(v)
# predictions = [np.eye(nstates),tmat]
# for i in range (2,nlags+1):
# predictions.append(v@(lam**i)@v_inv)
# return np.stack(predictions)
def cktest(mats: list):
"""relax each estimated matrix by one time step
See https://deeptime-ml.github.io/trunk/api/generated/deeptime.util.validation.ck_test.html"""
nlags = len(mats)
predict = np.stack([np.linalg.matrix_power(mats[0], i) for i in range(nlags + 2)])
estimate = np.concatenate([predict[:3], np.stack([np.linalg.matrix_power(i, 2) for i in mats[1:]])])
return predict, estimate
def get_its(mats, tau: int):
n = len(mats)
est_lams = np.stack([sorted_eig(mat)[0] for mat in mats], axis=1)[1:]
if (est_lams < 0).any():
est_lams = abs(est_lams)
predict = np.stack([-(tau * i) / np.log(est_lams[:, 0] ** i) for i in range(1, n + 1)], axis=1)
estimate = np.stack([-(tau * i) / np.log(est_lams[:, i - 1]) for i in range(1, n + 1)], axis=1)
return predict, estimate
def plot_its(estimate: np.ndarray, estimate_error=None, lag: int = 1, dt: float = .2, unit="ns",
cmap:str="jet", fig_width=10, fig_length=6, title: str = "Implied Timescales"):
"""estimate: eigen vals estimated at integrer multiples of the lag time
predict: eigen vals of the initial lagtime propogated via eponentiation"""
nprocs, nsteps = estimate.shape
cmap = getattr(plt.cm, cmap)
cs = [cmap(i) for i in range(cmap.N)]
color_list = [cs[int(i)] for i in np.linspace(10, len(cs) - 20, nprocs)]
color_list = color_list[::-1]
fig, ax = plt.subplots(1, 1, figsize=(fig_width, fig_length))
lag_dt = np.arange(1, nsteps + 1) * lag * dt
# each iteration plots a single process at all lag times
for est_proc, color in zip([estimate[i] for i in range(estimate.shape[0])], color_list):
ax.plot(lag_dt, est_proc, label="Estimate", color=color)
ax.scatter(lag_dt, est_proc, color=color)
if estimate_error is not None:
for est_error, color in zip([estimate_error[:, i] for i in range(estimate_error.shape[1])], color_list):
ax.fill_between(lag_dt, est_error[0], est_error[1], label="Estimate", color=color, alpha=.2)
ax.plot(lag_dt, lag_dt, color="black")
ax.fill_between(lag_dt, lag_dt, color="gray", alpha=.5)
ax.set_yscale("log")
ax.set_ylabel(f"ITS ({unit})", size=25)
ax.set_xlabel(rf"Lag time, $\tau$ ({unit})", size=25)
ax.tick_params(axis="both", labelsize=25)
ax.set_title(label=title, size=30)
return None
def plot_stat_dist(dist: np.ndarray, dist_err: np.ndarray = None, cmap: str = "viridis"):
# make the stationary distribution and it's error 1D vectors (assuming abs(upper) and abs(lower) errors have been averaged):
dist, dist_err = [i.squeeze() if i is not None else None for i in [dist, dist_err]]
assert len(dist.shape) == 1, "Need a stationary distribution that can be squeezed to one dimension"
nstates = len(dist)
state_labels = np.arange(1, nstates + 1)
cmap = getattr(plt.cm, cmap)
clist = [cmap(i) for i in range(cmap.N)]
clist = [clist[int(i)] for i in np.linspace(10, len(clist) - 20, nstates)][::-1]
plt.figure(figsize=(10, 6))
plt.bar(state_labels, dist, yerr=dist_err,
ecolor="grey", color=clist, capsize=10, width=.9, linewidth=3, edgecolor="black",
align="center", error_kw=dict(capthick=3, lw=3))
plt.xticks(state_labels, state_labels)
plt.xlabel("State", size=30)
plt.ylabel("Staionary Probability", size=30)
plt.title("Stationary Distribution", size=29)
plt.xticks(size=30)
plt.yticks(size=30)
plt.xlim(.5, nstates + .5)
def plot_cktest(predict: np.ndarray, estimate: np.ndarray, lag: int, dt: float, unit="ns",
predict_color="red", estimate_color="black", predict_errors=None, estimate_errors=None,
fill_estimate=True):
"""predict+errors should be of shape [2,predict/estimate.shape] where the 0th dim is upper and lower
confidence intervals"""
if not np.all(predict[0] == np.eye(predict.shape[1])):
predict, estimate = [np.concatenate([np.expand_dims(np.eye(predict.shape[1], predict.shape[1]), axis=0), i]) for
i in [predict, estimate]]
if not predict_errors is None:
predict_errors = np.concatenate(
[np.expand_dims(np.stack([np.eye(predict.shape[1])] * 2), axis=1), predict_errors], axis=1)
if not estimate_errors is None:
estimate_errors = np.concatenate(
[np.expand_dims(np.stack([np.zeros((predict.shape[1], predict.shape[1]))] * 2), axis=1),
estimate_errors], axis=1)
nsteps, nstates = predict.shape[:2]
fig, axes = plt.subplots(nstates, nstates, figsize=(15, 15), sharex=True, sharey=True)
dt_lag = np.arange(nsteps) * lag * dt
xaxis_marker = np.linspace(0, 1, nsteps)
padding_between = 0.2
padding_top = 0.065
predict_label = "Predict"
estimate_label = "Estimate"
for i in range(nstates):
for j in range(nstates):
if not predict_errors is None:
axes[i, j].fill_between(dt_lag, predict_errors[0][:, i, j], predict_errors[1][:, i, j],
color=predict_color, alpha=0.4)
predict_label += " conf. 95%"
if not estimate_errors is None:
if fill_estimate:
axes[i, j].fill_between(dt_lag[1:], estimate_errors[0][1:, i, j], estimate_errors[1][1:, i, j],
color=estimate_color, alpha=0.4)
else:
axes[i, j].errorbar(x=dt_lag, y=estimate[:, i, j],
yerr=abs(estimate_errors[:, :, i, j]),
color=estimate_color, alpha=1)
estimate_label += " conf. 95%"
axes[i, j].plot(dt_lag, predict[:, i, j], ls="--", color=predict_color, label=predict_label)
axes[i, j].plot(dt_lag, estimate[:, i, j], color=estimate_color, label=estimate_label)
axes[i, j].set_ylim(0, 1)
axes[i, j].text(0.1, 0.55, str(i + 1) + ' ->' + str(j + 1),
transform=axes[i, j].transAxes, weight='bold', size=12)
axes[i, j].set_yticks([0, .5, 1], ["0", "0.5", "1"], size=12)
axes[i, j].set_xticks(dt_lag[[1, -1]], dt_lag[[1, -1]], )
for axi in axes.flat:
axi.set_xlabel(None)
axi.set_ylabel(None)
fig.supxlabel(rf"Lag time, $\tau$ ({unit})", x=0.5, y=.07, size=25)
fig.supylabel("Probability", x=.06, y=.5, size=25)
handels, labels = axes[0, 0].get_legend_handles_labels()
fig.legend(handels, labels, ncol=7, loc="upper center", frameon=False, prop={'size': 25})
plt.subplots_adjust(top=1.0 - padding_top, wspace=padding_between, hspace=padding_between)
def plot_mat_error(mat, emat, title, unit, cbarlabel, textcolor: str = "white", cmap="viridis",
ticklabs: list = None, val_text_size: int = 40, err_text_size: int = 40,
clims: list = (None, None), decimals: int = 2, round_int=False):
"""mat = square matrix
emat = matrix of same dim as mat with errors of values in mat
unit = string specifying the units"""
fig, ax = plt.subplots(1, figsize=(20, 20))
s = ax.imshow(mat, cmap=cmap, vmin=clims[0], vmax=clims[1])
if ticklabs is None:
ticklabs = [f"{i + 1}" for i in range(mat.shape[0])]
for i in range(len(mat)):
for j in range(len(mat)):
if round_int:
val = int(mat[j, i])
err = int(emat[j, i])
else:
val = str(round(mat[j, i], decimals))
err = str(round(emat[j, i], decimals))
ax.text(i, j, "{}".format(val),
va='center', ha='center', color=textcolor, size=val_text_size, weight="bold")
ax.text(i, j, "\n\n $\pm${}{}".format(err, unit),
va='center', ha='center', color=textcolor, size=err_text_size, weight="bold")
ax.set_yticks(list(range(len(mat))), ticklabs, size=35)
ax.set_xticks(list(range(len(mat))), ticklabs, size=35)
ax.set_ylabel(r"$State_{i}$", size=45)
ax.set_xlabel(r"$State_{j}$", size=45)
cb = plt.colorbar(s, ax=ax, label=cbarlabel, fraction=0.046, pad=0.04)
cb.set_label(cbarlabel, size=40)
cb.ax.tick_params(labelsize=30)
ax.set_title(title, size=45)
return
def mfpt_mat(tmat, dt, lag):
nstates = tmat.shape[0]
mfpt = np.zeros((nstates, nstates))
for i in range(nstates):
mfpt[:, i] = deeptime.markov.tools.analysis.mfpt(tmat, i)
mfpt = mfpt * (dt * lag)
return mfpt
class DataSet(Dataset):
def __init__(self, data: np.ndarray):
super().__init__()
self.data = data
def __getitem__(self, idx):
x = torch.from_numpy(self.data[idx]).float()
return x
def __len__(self):
return len(self.data)
def fullset(self, numpy=False, split=False):
if split:
assert self.data.shape[-1] == 2, "can't split data that doesn't have size 2 in dim -1"
if numpy:
if split:
return [self.data[..., 0], self.data[..., 1]]
else:
return self.data
else:
if split:
return [torch.from_numpy(self.data[..., i]).float for i in range(2)]
else:
return torch.from_numpy(self.data).float()
class TimeSeriesData:
def __init__(self, data: np.ndarray, train_ratio: float = 0.9, dt: float = 1.0, shuffle=True,
indices: "np.ndarray or path to .npy file" = None):
self.data_ = data
self.n_ = len(self.data_)
self.ratio_ = train_ratio
self.dt_ = dt
if indices is None:
self.idx_ = np.arange(self.n_)
if shuffle:
self.shuffle_idx()
else:
if isinstance(indices, str):
indices = np.load(indices)
self.idx_ = indices
self.n_train_ = None
self.n_val_ = None
self.lag_ = None
@property
def shape(self):
"""return the shape of the input data"""
return self.data_.shape
def shuffle_idx(self):
np.random.shuffle(self.idx_)
def __call__(self, lag, data=None) -> "Tuple of train and validation np.ndarrays ":
assert lag < self.n_, "Lag is larger than the dataset"
if data is None: data = self.data_
self.lag_ = lag
lagged_idx = self.idx_[self.idx_ < self.n_ - lag]
n = len(lagged_idx)
self.n_train_ = int(n * self.ratio_)
self.n_val_ = n - self.n_train_
train_idx, val_idx = lagged_idx[:self.n_train_], lagged_idx[-self.n_val_:]
train_data, val_data = [np.stack([data[i], data[i + lag]], axis=-1) # stack on last axis
for i in [train_idx, val_idx]]
return train_data, val_data
@property
def idx(self):
return self.idx_
@property
def n_train(self):
return self.n_train_
@property
def n_val(self):
return self.n_val_
@property
def dt(self):
return self.dt_
@property
def lag(self):
return self.lag_
@property
def data(self):
return self.data_
@property
def ratio(self):
return self.ratio_
@ratio.setter
def ratio(self, ratio):
self.ratio_ = ratio
@property
def n(self):
return self.n_
# In[5]:
class vamp_u(nn.Module):
"""module to train the weight vector, u
the forward method should take pre-transformed instantaneous and time lagged data"""
def __init__(self, output_dim, weight_transformation=torch.exp):
super().__init__()
self.M = output_dim
# make the vector u a learnable parameter
self.u_kernel_ = nn.Parameter(torch.ones(self.M, requires_grad=True) / self.M)
# some function to keep weights positive
self.acti = weight_transformation
self.trainable_parameter_ = True
@property
def trainable_parameter(self):
return self.trainable_parameter_
@trainable_parameter.setter
def trainable_parameter(self, x):
"""input True or False a convenience function for making the u_kernel constant"""
assert isinstance(x, bool), "input True or False"
self.trainable_parameter_ = x
if x:
if self.u_kernel_.requires_grad:
print("u_kernel is already a trainable parameter")
pass
else:
self.u_kernel_.requires_grad = x
print("u_kernel is now a trainable parameter")
else:
if not self.u_kernel_.requires_grad:
print("u_kernel already does not require grad")
pass
else:
self.u_kernel_.requires_grad = x
print("u_kernel now does not require grad")
@property
def u_kernel(self):
if self.u_kernel_.device.type != "cpu":
return self.u_kernel_.detach().cpu().numpy()
else:
return self.u_kernel_.detach().numpy()
@u_kernel.setter
def u_kernel(self, u):
assert isinstance(u, (np.ndarray, torch.Tensor)), "u_kernel input must be a numpy array or torch tensor"
device = next(self.parameters()).device
if isinstance(u, np.ndarray): u = torch.from_numpy(u).float().to(device)
u = nn.Parameter(u, requires_grad=True)
with torch.no_grad():
self.u_kernel_.copy_(u)
def forward(self, x: "array[...,2] where the last dim is t,t+tau"):
chi_t, chi_tau = x[..., 0], x[..., 1]
chi_mean = chi_tau.mean(0)
n = chi_tau.shape[0]
corr_tau = 1 / n * torch.matmul(chi_tau.T, chi_tau) # unweighted cov mat of lagged data
kernel_u = self.acti(self.u_kernel_) # force vector u to be positive
u = kernel_u / (kernel_u * chi_mean).sum() # normalize u weights wrt to mean of time lagged data
v = torch.matmul(corr_tau, u) # correlation per state of timelagged data reweighted
mu = 1 / n * torch.matmul(chi_tau, u) # inner product of weight vector and all time lagged data
# print(mu.shape)
Sigma = torch.matmul((chi_tau * mu[:, None]).T,
chi_tau) # reweighted cov mat with transformed emerical stat dist
gamma = chi_tau * (torch.matmul(chi_tau, u))[:, None] # mult each column of the output data matrix
C_00 = 1 / n * torch.matmul(chi_t.T, chi_t)
C_01 = 1 / n * torch.matmul(chi_t.T, gamma)
C_11 = 1 / n * torch.matmul(gamma.T, gamma)
return [u, mu, Sigma, v, C_00, C_01, C_11]
# In[6]:
class vamp_S(nn.Module):