-
Notifications
You must be signed in to change notification settings - Fork 1
/
DeepReGraph.py
2180 lines (1712 loc) · 93.5 KB
/
DeepReGraph.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
'''
Copyright 2022 Jesús Cevallos
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The following code constains parts of the code available at https://github.com/hyzhang98/AdaGAE
which is an implementation of the paper "Adaptive Graph Auto-Encoder for General Data Clustering"
available at https://ieeexplore.ieee.org/document/9606581
Some parts of the code were modified by Jesús Cevallos to implement the DeepReGraph Algorithm.
'''
import torch
from torch.utils.tensorboard import SummaryWriter
import pandas as pd
import numpy as np
import cProfile
import pstats
from functools import wraps
import io
import os
import math
import PIL.Image
from torchvision.transforms import ToTensor
# import hdbscan
from sklearn.cluster import SpectralClustering
from sklearn.cluster import KMeans
from sklearn.utils import _safe_indexing
from sklearn import linear_model
#import umap
#import umap.plot
import networkx as nx
import matplotlib as mpl
import matplotlib.pyplot as plt
import colorsys
import random
from sklearn.metrics import confusion_matrix
from sklearn.decomposition import PCA
from zipfile import ZipFile
import shutil
import gdown
import pickle
#######################
# HELPER FUNCTIONS#####
#######################
def get_primitive_ccre_clusters(ccre_ds, primitive_ccre_path=''):
ccre_agglomerative_ds = pd.read_csv(primitive_ccre_path+'agglomerative_clust_cCRE_8.csv')
prim_ccre_ds = ccre_ds.set_index('cCRE_ID').join(ccre_agglomerative_ds.set_index('cCRE_ID'))[['cluster']]
prim_ccre_ds.columns = ['primitive_cluster']
return np.array(prim_ccre_ds.primitive_cluster.to_list())
def make_confusion_matrix(cf,
group_names=None,
categories='auto',
count=True,
percent=True,
cbar=True,
xyticks=True,
xyplotlabels=True,
sum_stats=True,
figsize=None,
cmap='Blues',
title=None,
ref='True label',
comp='Predicted label'):
'''
This function is copy-pasted from https://medium.com/@dtuk81/confusion-matrix-visualization-fc31e3f30fea
and will make a pretty plot of an sklearn Confusion Matrix cm using a Seaborn heatmap visualization.
Arguments
---------
cf: confusion matrix to be passed in
group_names: List of strings that represent the labels row by row to be shown in each square.
categories: List of strings containing the categories to be displayed on the x,y axis. Default is 'auto'
count: If True, show the raw number in the confusion matrix. Default is True.
normalize: If True, show the proportions for each category. Default is True.
cbar: If True, show the color bar. The cbar values are based off the values in the confusion matrix.
Default is True.
xyticks: If True, show x and y ticks. Default is True.
xyplotlabels: If True, show 'True Label' and 'Predicted Label' on the figure. Default is True.
sum_stats: If True, display summary statistics below the figure. Default is True.
figsize: Tuple representing the figure size. Default will be the matplotlib rcParams value.
cmap: Colormap of the values displayed from matplotlib.pyplot.cm. Default is 'Blues'
See http://matplotlib.org/examples/color/colormaps_reference.html
title: Title for the heatmap. Default is None.
'''
# CODE TO GENERATE TEXT INSIDE EACH SQUARE
blanks = ['' for i in range(cf.size)]
if group_names and len(group_names) == cf.size:
group_labels = ["{}\n".format(value) for value in group_names]
else:
group_labels = blanks
if count:
group_counts = ["{0:0.0f}\n".format(value) for value in cf.flatten()]
else:
group_counts = blanks
if percent:
group_percentages = ["{0:.2%}".format(value) for value in cf.flatten() / np.sum(cf)]
else:
group_percentages = blanks
box_labels = [f"{v1}{v2}{v3}".strip() for v1, v2, v3 in zip(group_labels, group_counts, group_percentages)]
box_labels = np.asarray(box_labels).reshape(cf.shape[0], cf.shape[1])
# CODE TO GENERATE SUMMARY STATISTICS & TEXT FOR SUMMARY STATS
if sum_stats:
# Accuracy is sum of diagonal divided by total observations
accuracy = np.trace(cf) / float(np.sum(cf))
# if it is a binary confusion matrix, show some more stats
if len(cf) == 2:
# Metrics for Binary Confusion Matrices
precision = cf[1, 1] / sum(cf[:, 1])
recall = cf[1, 1] / sum(cf[1, :])
f1_score = 2 * precision * recall / (precision + recall)
stats_text = "\n\nAccuracy={:0.3f}\nPrecision={:0.3f}\nRecall={:0.3f}\nF1 Score={:0.3f}".format(
accuracy, precision, recall, f1_score)
else:
stats_text = "\n\nAccuracy={:0.3f}".format(accuracy)
else:
stats_text = ""
# SET FIGURE PARAMETERS ACCORDING TO OTHER ARGUMENTS
if figsize == None:
# Get default figure size if not set
figsize = plt.rcParams.get('figure.figsize')
if xyticks == False:
# Do not show categories if xyticks is False
categories = False
# MAKE THE HEATMAP VISUALIZATION
plt.figure(figsize=figsize)
sns.heatmap(cf, annot=box_labels, fmt="", cmap=cmap, cbar=cbar, xticklabels=categories, yticklabels=categories)
if xyplotlabels:
plt.ylabel(ref)
# plt.xlabel(comp + stats_text)
plt.xlabel(comp)
else:
plt.xlabel(stats_text)
if title:
plt.title(title)
def profile(output_file=None, sort_by='cumulative', lines_to_print=None, strip_dirs=False):
"""A time profiler decorator.
Inspired by and modified the profile decorator of Giampaolo Rodola:
http://code.activestate.com/recipes/577817-profile-decorator/
Args:
output_file: str or None. Default is None
Path of the output file. If only name of the file is given, it's
saved in the current directory.
If it's None, the name of the decorated function is used.
sort_by: str or SortKey enum or tuple/list of str/SortKey enum
Sorting criteria for the Stats object.
For a list of valid string and SortKey refer to:
https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats
lines_to_print: int or None
Number of lines to print. Default (None) is for all the lines.
This is useful in reducing the size of the printout, especially
that sorting by 'cumulative', the time consuming operations
are printed toward the top of the file.
strip_dirs: bool
Whether to remove the leading path info from file names.
This is also useful in reducing the size of the printout
Returns:
Profile of the decorated function
"""
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
_output_file = output_file or func.__name__ + '.prof'
pr = cProfile.Profile()
pr.enable()
retval = func(*args, **kwargs)
pr.disable()
pr.dump_stats(_output_file)
with open(_output_file, 'w') as f:
ps = pstats.Stats(pr, stream=f)
if strip_dirs:
ps.strip_dirs()
if isinstance(sort_by, (tuple, list)):
ps.sort_stats(*sort_by)
else:
ps.sort_stats(sort_by)
ps.print_stats(lines_to_print)
return retval
return wrapper
return inner
def get_hybrid_feature_matrix(link_ds, ccre_ds):
ge_values = link_ds.reset_index().drop_duplicates('EnsembleID')[['Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5',
'Heart_E13_5', 'Heart_E14_5', 'Heart_E15_5',
'Heart_E16_5', 'Heart_P0']].values
ge_count = ge_values.shape[0]
ge_values_new = np.zeros((ge_values.shape[0], 32))
ge_values_new[:, 0:8] = ge_values
ccre_activity = ccre_ds.set_index('cCRE_ID').values
ccre_count = ccre_activity.shape[0]
ccre_activity_new = np.zeros((ccre_activity.shape[0], 32))
ccre_activity_new[:, 8:32] = ccre_activity
return torch.Tensor(np.concatenate((ge_values_new, ccre_activity_new))).cpu(), ge_count, ccre_count
def get_distance_matrices(X, ge_count):
cpu_X = X.cpu()
gene_exp = cpu_X[:ge_count, 0:8]
met = cpu_X[ge_count:, 8:16]
acet = cpu_X[ge_count:, 16:24]
atac = cpu_X[ge_count:, 24:32]
ge_distances = distance(gene_exp.t(), gene_exp.t())
ge_distances = torch.max(ge_distances, torch.t(ge_distances))
#abs scaling
ge_distances /= ge_distances.max()
met_distances = distance(met.t(), met.t())
met_distances = torch.max(met_distances, torch.t(met_distances))
met_distances /= met_distances.max()
acet_distances = distance(acet.t(), acet.t())
acet_distances = torch.max(acet_distances, torch.t(acet_distances))
acet_distances /= acet_distances.max()
atac_distances = distance(atac.t(), atac.t())
atac_distances = torch.max(atac_distances, torch.t(atac_distances))
atac_distances /= atac_distances.max()
return ge_distances, atac_distances, acet_distances, met_distances
def get_slopes(X, ge_count):
numpy_X = X.cpu().numpy()
time_steps = np.array([0, 1, 2, 3, 4, 5, 6, 7])
gene_exp = numpy_X[:ge_count, 0:8]
met = numpy_X[ge_count:, 8:16]
acet = numpy_X[ge_count:, 16:24]
atac = numpy_X[ge_count:, 24:32]
gene_exp_slopes = []
reg = linear_model.LinearRegression()
for gene_exp_row in gene_exp:
reg.fit(time_steps.reshape(-1, 1), gene_exp_row)
Y_pred = reg.predict(time_steps.reshape(-1, 1))
gene_exp_slopes.append(reg.coef_[0])
# plt.scatter(time_steps.reshape(-1,1),gene_exp_row)
# plt.plot(time_steps.reshape(-1,1), Y_pred, color='red')
# plt.show()
met_slopes = []
reg = linear_model.LinearRegression()
for met_row in met:
reg.fit(time_steps.reshape(-1, 1), met_row)
Y_pred = reg.predict(time_steps.reshape(-1, 1))
met_slopes.append(reg.coef_[0])
# plt.scatter(time_steps.reshape(-1,1),met_row)
# plt.plot(time_steps.reshape(-1,1), Y_pred, color='red')
# plt.show()
acet_slopes = []
reg = linear_model.LinearRegression()
for acet_row in acet:
reg.fit(time_steps.reshape(-1, 1), acet_row)
Y_pred = reg.predict(time_steps.reshape(-1, 1))
acet_slopes.append(reg.coef_[0])
# plt.scatter(time_steps.reshape(-1,1),acet_row)
# plt.plot(time_steps.reshape(-1,1), Y_pred, color='red')
# plt.show()
atac_slopes = []
reg = linear_model.LinearRegression()
for atac_row in atac:
reg.fit(time_steps.reshape(-1, 1), atac_row)
Y_pred = reg.predict(time_steps.reshape(-1, 1))
atac_slopes.append(reg.coef_[0])
# plt.scatter(time_steps.reshape(-1,1),atac_row)
# plt.plot(time_steps.reshape(-1,1), Y_pred, color='red')
# plt.show()
gene_exp_slopes = np.array(gene_exp_slopes)
gene_exp_slopes = np.sign(gene_exp_slopes)
# gene_exp_slopes = (gene_exp_slopes - gene_exp_slopes.min()) / (gene_exp_slopes.max()- gene_exp_slopes.min())
atac_slopes = np.array(atac_slopes)
atac_slopes = np.sign(atac_slopes)
# atac_slopes = (atac_slopes - atac_slopes.min()) / (atac_slopes.max()- atac_slopes.min())
met_slopes = np.array(met_slopes)
met_slopes = np.sign(met_slopes)
# met_slopes = (met_slopes - met_slopes.min()) / (met_slopes.max()- met_slopes.min())
acet_slopes = np.array(acet_slopes)
acet_slopes = np.sign(acet_slopes)
# acet_slopes = (acet_slopes - acet_slopes.min()) / (acet_slopes.max()- acet_slopes.min())
return gene_exp_slopes, atac_slopes, acet_slopes, met_slopes
def distance(X, Y, square=True):
"""
Compute Euclidean distances between two sets of samples
Basic framework: pytorch
:param X: d * n, where d is dimensions and n is number of data points in X
:param Y: d * m, where m is number of data points in Y
:param square: whether distances are squared, default value is True
:return: n * m, distance matrix
"""
n = X.shape[1]
m = Y.shape[1]
x = torch.norm(X, dim=0)
x = x * x # n * 1
x = torch.t(x.repeat(m, 1))
y = torch.norm(Y, dim=0)
y = y * y # m * 1
y = y.repeat(n, 1)
crossing_term = torch.t(X).matmul(Y)
result = x + y - 2 * crossing_term
# result = result.max(torch.zeros(result.shape).cuda())
result = result.relu()
if not square:
result = torch.sqrt(result)
# result = torch.max(result, result.t())
return result
def get_normalized_adjacency_matrix(weights):
# We don't create self loops with 1 (nor with any value)
# because we want the embeddings to adaptively learn
# the self-loop weights.
# W = torch.eye(weights.shape[0]).cuda() + weights
# degree = torch.sum(W, dim=1).pow(-0.5)
# return (W * degree).t()*degree
degree = (torch.sum(weights, dim=1)+1e-10).pow(-0.5)
return (weights * degree).t() * degree
def get_weight_initial(shape):
bound = np.sqrt(6.0 / (shape[0] + shape[1]))
ini = torch.rand(shape) * 2 * bound - bound
return torch.nn.Parameter(ini, requires_grad=True)
def fast_genomic_distance_to_similarity(link_matrix, c, d):
'''
The parametric function can be found at https://www.desmos.com/calculator/bmxxh8sqra
'''
return 1 / (((link_matrix / c) ** (10 * d)) + 1)
def get_genomic_distance_matrix(link_ds, add_self_loops_genomic, genomic_C, genomic_slope, G):
genes = link_ds.index.unique().tolist()
ccres = link_ds.cCRE_ID.unique().tolist()
entity_number = len(genes + ccres)
entities_df = pd.DataFrame(genes + ccres, columns=['EntityID'])
entities_df['entity_index'] = range(0, entity_number)
entities_df.set_index('EntityID', inplace=True)
dense_A = np.zeros((entity_number, entity_number))
if add_self_loops_genomic:
np.fill_diagonal(dense_A, 1)
print('processing genomic distances...')
for index, row in link_ds.reset_index().iterrows():
gene_idx = entities_df.loc[row.EnsembleID][0]
ccre_idx = entities_df.loc[row.cCRE_ID][0]
#see https://www.desmos.com/calculator/bmxxh8sqra
distance_score = 1 / (((row.Distance / genomic_C) ** (10 * genomic_slope)) + 1)
dense_A[gene_idx, ccre_idx] = distance_score
dense_A[ccre_idx, gene_idx] = distance_score
G.add_edge(gene_idx, ccre_idx, weight=distance_score)
dense_A = torch.Tensor(dense_A)
return dense_A, G
def load_data(link_ds, datapath='', num_of_genes=0, chr_to_filter=None):
print('Pre-processing Gene Expression Dataset...')
var_log_ge_ds = pd.read_csv(datapath + 'tight_var_log_fpkm_GE_ds')
X = var_log_ge_ds[['Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5',
'Heart_E13_5', 'Heart_E14_5', 'Heart_E15_5', 'Heart_E16_5', 'Heart_P0']].values
'''
Mean substraction: (For each row)
'''
X = np.stack([data_row - data_row.mean() for data_row in X])
working_genes_ds = var_log_ge_ds.reset_index()[['EnsembleID', 'Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5',
'Heart_E13_5', 'Heart_E14_5', 'Heart_E15_5', 'Heart_E16_5',
'Heart_P0']].copy()
working_genes_ds[['Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5',
'Heart_E13_5', 'Heart_E14_5', 'Heart_E15_5', 'Heart_E16_5', 'Heart_P0']] = X
# if tight:
# ccre_ds = pd.read_csv(datapath + 'tight_cCRE_variational_mean_reduced.csv')
# else:
# ccre_ds = pd.read_csv(datapath + 'cCRE_variational_mean_reduced.csv')
print('Pre-processing candidate-CREs\' Actitivy Dataset...')
ccre_ds = pd.read_csv(datapath + 'cCRE_variational_mean_reduced.csv')
if chr_to_filter != None:
filtered_ccre_ds = pd.DataFrame()
for chr_number in chr_to_filter:
filtered_ccre_ds = pd.concat(
[filtered_ccre_ds, ccre_ds[ccre_ds['cCRE_ID'].str.startswith('chr' + str(chr_number))]])
ccre_ds = filtered_ccre_ds
if num_of_genes == 0:
var_ge_list = working_genes_ds['EnsembleID'].tolist()
else:
var_ge_list = working_genes_ds['EnsembleID'].tolist()[:num_of_genes]
link_ds = link_ds[link_ds['EnsembleID'].isin(var_ge_list)]
link_ds = link_ds[link_ds['cCRE_ID'].isin(ccre_ds['cCRE_ID'].tolist())]
link_ds = link_ds.set_index('EnsembleID').join(
working_genes_ds[['EnsembleID', 'Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5', 'Heart_E13_5',
'Heart_E14_5', 'Heart_E15_5', 'Heart_E16_5', 'Heart_P0']].set_index('EnsembleID'))
ccres = link_ds.cCRE_ID.unique().tolist()
ccre_ds = ccre_ds[ccre_ds['cCRE_ID'].isin(ccres)]
return link_ds, ccre_ds
def get_primitive_gene_clusters(datapath, link_ds):
gene_primitive_clusters_path = datapath
kmeans_ds = pd.read_csv(gene_primitive_clusters_path + 'kmeans_clustered_genes_4.csv')
primitive_ge_clustered_ds = kmeans_ds.set_index('EnsembleID').drop('Unnamed: 0', axis=1)
primitive_ge_clustered_ds.columns = ['primitive_cluster']
gene_ds = link_ds.reset_index().drop_duplicates('EnsembleID').set_index('EnsembleID')
prim_gene_ds = gene_ds.join(primitive_ge_clustered_ds)['primitive_cluster'].reset_index()
return np.array(prim_gene_ds.primitive_cluster.to_list())
def build_graph(X,ge_count,ccre_count, primitive_gene_clusters, primitive_ccre_clusters):
G = nx.Graph()
for ge_node_idx in range(0, ge_count):
G.add_node(ge_node_idx, ge_exp=X[ge_node_idx][:8], primitive_cluster=primitive_gene_clusters[ge_node_idx])
for ccre_node_idx in range(ge_count, ge_count + ccre_count):
G.add_node(ccre_node_idx, meth=X[ccre_node_idx][8:16], acet=X[ccre_node_idx][16:24],
atac=X[ccre_node_idx][24:32], primitive_cluster=primitive_ccre_clusters[ccre_node_idx-ge_count])
return G
def data_preprocessing(link_ds, genes_to_pick, device, datapath='',
genomic_C = 3e5, genomic_slope = 0.4,
add_self_loops_genomic=False, chr_to_filter=None, google_colab=False):
if google_colab:
datapath = '/content/'+datapath
## Data preprocessing:
link_ds, ccre_ds = load_data(link_ds, datapath, genes_to_pick, chr_to_filter=chr_to_filter)
X, ge_count, ccre_count = get_hybrid_feature_matrix(link_ds, ccre_ds)
primitive_gene_clusters = get_primitive_gene_clusters(datapath, link_ds)
primitive_ccre_clusters = get_primitive_ccre_clusters(ccre_ds, datapath)
ge_class_labels = ['genes_' + str(ge_cluster_label) for ge_cluster_label in primitive_gene_clusters]
ccre_class_labels = ['ccres_' + str(ccre_cluster_label) for ccre_cluster_label in primitive_ccre_clusters]
print('Initializing heterogeneous Graph with euclidean distances...')
G = build_graph(X, ge_count,ccre_count, ge_class_labels, ccre_class_labels)
print('Computing trend-aware base-pair distance scores...')
gene_exp_slopes, atac_slopes, acet_slopes, met_slopes = get_slopes(X, ge_count)
slopes = [gene_exp_slopes, atac_slopes, acet_slopes, met_slopes]
gen_dist_score, G = get_genomic_distance_matrix(link_ds, add_self_loops_genomic, genomic_C, genomic_slope, G )
print('Using a data-set containing ', ge_count, ' genes and ', ccre_count, ' ccres for a total of ', ge_count + ccre_count,
' elements.')
D_G, D_ATAC, D_ACET, D_MET = get_distance_matrices(X, ge_count)
distance_matrices = [D_G, D_ATAC, D_ACET, D_MET]
X /= torch.max(X)
X = torch.Tensor(X).to(device)
gene_ds = link_ds.reset_index().drop_duplicates('EnsembleID')[['EnsembleID','Heart_E10_5', 'Heart_E11_5', 'Heart_E12_5',
'Heart_E13_5', 'Heart_E14_5', 'Heart_E15_5',
'Heart_E16_5', 'Heart_P0']]
return X, G, ge_count, ccre_count, distance_matrices, slopes, gen_dist_score, ccre_ds, ge_class_labels, ccre_class_labels, gene_ds
def get_disctinct_colors(n):
# https://www.quora.com/How-do-I-generate-n-visually-distinct-RGB-colours-in-Python
huePartition = 1.0 / (n + 1)
colors = np.zeros((n,1,3))
color_list = []
for value in range(0, n):
color_list.append(np.array(colorsys.hsv_to_rgb(huePartition * value, 1.0, 1.0)).reshape(1,3))
random.shuffle(color_list)
for pos in range(0, n):
colors[pos] = color_list.pop()
return colors
#####
# DEEPREGRAPH OBJECT
########
SPARSITY_LABEL: str = 'Sparsity'
GENE_SPARSITY_LABEL: str = 'Gene_Sparsity'
SLOPE_LABEL: str = 'GeneticSlope'
REPULSIVE_CE_TERM: str = 'Repulsive_CE_loss'
ATTRACTIVE_CE_TERM: str = 'Attractive_CE_loss'
RQ_QUOTIENT_LOSS: str = 'RQ Quotient Loss'
RP_AGGRESSIVE_LOSS: str = 'Rep Aggressive Loss'
RP_AGGRESSIVE_LOSS_WEIGHT: str = 'Rep Aggressive Loss Weight'
TOTAL_LOSS_LABEL: str = 'Total_Loss'
ALPHA_D: str = 'Alpha_D'
ALPHA_G: str = 'Alpha_G'
ALPHA_METH: str = 'Alpha_METH'
ALPHA_ACET: str = 'Alpha_ACET'
ALPHA_ATAC: str = 'Alpha_ATAC'
WK_ATAC: str = 'WK_ATAC'
WK_ACET: str = 'WK_ACET'
WK_METH: str = 'WK_METH'
ALPHA_Z: str = 'Alpha_Z'
GENOMIC_C_LABEL: str = 'GenomicC'
REPULSIVE_CE_LOSS_WEIGHT_LABEL: str = 'RepulsiveCELossWeight'
ATTRACTIVE_CE_LOSS_WEIGHT_LABEL: str = 'AttractiveCELossWeight'
GE_CC_SCORE_TAG: str = 'GeneCCScore'
CCRE_CC_SCORE_TAG: str = 'CCRECCScore'
HETEROGENEITY_SCORE_TAG: str = 'HeterogeneityScore'
EMBEDDING_DIAMETER: str = 'EmbeddingDiameter'
DISTANCE_TO_KNN_TAG: str = 'Mean Distance to knn'
REWARD_TAG: str = 'Reward'
UMAP_CLASS_PLOT_TAG: str = 'ClassPlot'
UMAP_CLUSTER_PLOT_TAG: str = 'ClusterPlot'
GRAPH_PLOT_TAG: str = 'GraphPlot'
CLUSTER_NUMBER_LABEL: str = 'ClusterNumber'
GENE_CLUSTERING_COMPLETENESS_TAG: str = 'GeneClusteringCompleteness'
CCRE_CLUSTERING_COMPLETENESS_TAG: str = 'CCREClusteringCompleteness'
DISTANCE_SCORE_TAG: str = 'DistanceScore'
LAMBDA_REPULSIVE_LABEL: str = 'Lambda Repulsive'
LAMBDA_ATTRACTIVE_LABEL: str = 'Lambda Attractive'
LAMBDA_RQ_LABEL: str = 'Lambda RQ'
class GAE_NN(torch.nn.Module):
def __init__(self,
data_matrix,
device,
pre_trained,
pre_trained_state_dict,
pre_computed_embedding,
gcn,
layers,
learning_rate,
datapath
):
super(GAE_NN, self).__init__()
self.device = device
self.embedding_dim = layers[-1]
self.embedding = None
self.mid_dim = layers[1]
self.input_dim = layers[0]
self.data_matrix = data_matrix.to(device)
self.gcn = gcn
if self.gcn:
self.W1 = get_weight_initial([self.input_dim, self.mid_dim])
self.W2 = get_weight_initial([self.mid_dim, self.embedding_dim])
else:
# basic GNN model (hamilton's book)
self.W1_neigh = get_weight_initial([self.input_dim, self.mid_dim])
self.W1_self = get_weight_initial([self.input_dim, self.mid_dim])
self.W1_bias = get_weight_initial([self.data_matrix.shape[0], self.mid_dim])
self.W2_neigh = get_weight_initial([self.mid_dim, self.embedding_dim])
self.W2_self = get_weight_initial([self.mid_dim, self.embedding_dim])
self.W2_bias = get_weight_initial([self.data_matrix.shape[0], self.embedding_dim])
if pre_trained:
self.load_state_dict(torch.load(datapath + pre_trained_state_dict, map_location=torch.device(self.device)))
self.embedding = torch.load(datapath + pre_computed_embedding, map_location=torch.device(self.device))
self.optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate)
def forward(self, norm_adj_matrix):
if self.gcn:
embedding = norm_adj_matrix.mm(self.data_matrix.matmul(self.W1))
embedding = torch.relu(embedding)
self.embedding = norm_adj_matrix.mm(embedding.matmul(self.W2))
else:
# basic GNN model (hamilton's book)
embedding_1 = norm_adj_matrix.mm(self.data_matrix.matmul(self.W1_neigh))
embedding_1 += self.data_matrix.matmul(self.W1_self) + self.W1_bias
embedding_1 = torch.relu(embedding_1)
embedding = (norm_adj_matrix.matmul(embedding_1)).matmul(self.W2_neigh)
embedding += embedding_1.matmul(self.W2_self) + self.W2_bias
self.embedding = torch.relu(embedding)
distances = distance(self.embedding.t(), self.embedding.t())
softmax = torch.nn.Softmax(dim=1)
recons_w = softmax(-distances)
return recons_w + 10 ** -10
def start_tensorboad(log_dir):
'''Tensorboard is an interactive dashboard that helps visualizing results for various runs of a ML model:
The following code will activate it on this Google Colab environment
'''
os.makedirs(log_dir, exist_ok=True)
os.system('tensorboard --logdir {} --host 0.0.0.0 --port 6006 &'
.format(log_dir))
def get_link_matrix(data_path='preprocessed_data/Link_Matrix_Splitted/'):
print('Assembling link matrix...')
# We assemble it together:
link_ds_part_0 = pd.read_csv(data_path + 'Link_Matrix_piece_0.csv', index_col=0)
link_ds_part_1 = pd.read_csv(data_path + 'Link_Matrix_piece_1.csv', index_col=0)
link_ds_part_2 = pd.read_csv(data_path + 'Link_Matrix_piece_2.csv', index_col=0)
link_ds_part_3 = pd.read_csv(data_path + 'Link_Matrix_piece_3.csv', index_col=0)
link_ds_part_4 = pd.read_csv(data_path + 'Link_Matrix_piece_4.csv', index_col=0)
link_ds = pd.concat([link_ds_part_0, link_ds_part_1, link_ds_part_2, link_ds_part_3, link_ds_part_4])
return link_ds
def initialize_DeepReGraph(modelname,
device = None,
datapath='preprocessed_data/',
google_colab=False,
init_sparsity=300,
genes_to_pick=0,
genomic_C = 3e5,
genomic_slope = 0.4,
chr_to_filter = None,
add_self_loops_genomic=False,
log_dir='tensorboard_logs/',
pre_trained=False,
pre_trained_state_dict='',
pre_computed_embedding='',
global_step=0,
layers=None,
gcn=False,
init_omega_BP=0,
init_attractive_loss_weight=0.1,
init_repulsive_loss_weight=1,
init_lambda_repulsive=0.5,
init_lambda_attractive=0.5,
clusterize=True,
learning_rate = 5 * 10 ** -3,
init_alpha_Z=0,
init_alpha_G=1,
init_alpha_ATAC=1,
init_alpha_ACET=1,
init_alpha_METH=1,
omega_ATAC=1,
omega_ACET=0,
omega_METH=0,
differential_sparsity=False,
eval_flag=False,
update_graph_option=False):
if device is None:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if google_colab:
datapath = '/content/'+datapath
link_ds = get_link_matrix(data_path=datapath+'Link_Matrix_Splitted/')
plt.rcParams["figure.figsize"] = (15, 15)
X, \
G, \
ge_count, \
ccre_count, \
distance_matrices, \
slopes, \
gen_dist_score, \
ccre_ds, \
ge_class_labels, \
ccre_class_labels, \
gene_ds = \
data_preprocessing(link_ds, genes_to_pick,
device=device,
datapath=datapath,
genomic_C=genomic_C,
add_self_loops_genomic=add_self_loops_genomic,
genomic_slope=genomic_slope,
chr_to_filter=chr_to_filter)
tensorboard = SummaryWriter(log_dir + modelname)
DeepReGrapher = DeepReGraph(X,
G,
ge_count,
ccre_count,
distance_matrices,
slopes,
gen_dist_score,
init_sparsity,
ge_class_labels,
ccre_class_labels,
tensorboard,
gene_ds,
ccre_ds,
device=device,
pre_trained=pre_trained,
pre_trained_state_dict=pre_trained_state_dict,
pre_computed_embedding=pre_computed_embedding,
global_step=global_step,
layers=layers,
gcn=gcn,
init_genomic_slope=genomic_slope,
init_genomic_C=genomic_C,
init_omega_BP=init_omega_BP,
init_attractive_loss_weight=init_attractive_loss_weight,
init_repulsive_loss_weight=init_repulsive_loss_weight,
init_lambda_repulsive=init_lambda_repulsive,
init_lambda_attractive=init_lambda_attractive,
clusterize=clusterize,
learning_rate=learning_rate,
datapath=datapath,
init_alpha_Z=init_alpha_Z,
init_alpha_G=init_alpha_G,
init_alpha_ATAC=init_alpha_ATAC,
init_alpha_ACET=init_alpha_ACET,
init_alpha_METH=init_alpha_METH,
omega_ATAC=omega_ATAC,
omega_ACET=omega_ACET,
omega_METH=omega_METH,
differential_sparsity=differential_sparsity,
eval_flag=eval_flag,
update_graph_option=update_graph_option)
print('Succesfully created DeepReGraph Object')
return DeepReGrapher
class DeepReGraph():
def __init__(self,
X,
G,
ge_count,
ccre_count,
distance_matrices,
slopes,
gen_dist_score,
init_sparsity,
ge_class_labels,
ccre_class_labels,
tensorboard,
gene_ds,
ccre_ds,
device=None,
pre_trained=False,
pre_trained_state_dict='',
pre_computed_embedding='',
global_step=0,
layers=None,
gcn=False,
init_genomic_slope=0.4,
init_genomic_C=3e5,
init_omega_BP=0,
init_attractive_loss_weight=0.1,
init_repulsive_loss_weight=1,
init_lambda_repulsive=0.5,
init_lambda_attractive=0.5,
clusterize=True,
learning_rate = 5 * 10 ** -3,
datapath="/content/DIAGdrive/MyDrive/GE_Datasets/",
init_alpha_Z=0,
init_alpha_G=1,
init_alpha_ATAC=1,
init_alpha_ACET=1,
init_alpha_METH=1,
omega_ATAC=.5,
omega_ACET=.1,
omega_METH=.5,
differential_sparsity=False,
eval_flag=False,
update_graph_option=False):
super(DeepReGraph, self).__init__()
self.ge_count = ge_count
self.ccre_count = ccre_count
self.D_G = distance_matrices[0]
self.D_ATAC = distance_matrices[1]
self.D_ACET = distance_matrices[2]
self.D_METH = distance_matrices[3]
self.gene_exp_slopes = slopes[0]
self.atac_slopes = slopes[1]
self.acet_slopes = slopes[2]
self.met_slopes = slopes[3]
self.init_alpha_Z = init_alpha_Z
self.init_alpha_G = init_alpha_G
self.init_alpha_ATAC = init_alpha_ATAC
self.init_alpha_ACET = init_alpha_ACET
self.init_alpha_METH = init_alpha_METH
self.omega_ATAC = omega_ATAC
self.omega_ACET = omega_ACET
self.omega_METH = omega_METH
self.S_D = gen_dist_score
self.ge_class_labels = ge_class_labels
self.ccre_class_labels = ccre_class_labels
self.eval_flag = eval_flag
self.device = device
if self.device is None: self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.X = X
self.G = G
self.pre_trained = pre_trained
self.pre_trained_state_dict = pre_trained_state_dict
self.pre_computed_embedding = pre_computed_embedding
self.global_step = global_step
self.global_ccres_over_genes_ratio = (self.ccre_count / self.ge_count)
self.differential_sparsity = differential_sparsity
self.layers = [X.shape[0], 12, 2]
self.init_sparsity = init_sparsity
self.gcn = gcn
self.init_genomic_slope =init_genomic_slope
self.init_genomic_C = init_genomic_C
self.init_omega_BP = init_omega_BP
self.init_attractive_loss_weight = init_attractive_loss_weight
self.init_repulsive_loss_weight = init_repulsive_loss_weight
self.init_lambda_repulsive = init_lambda_repulsive
self.init_lambda_attractive = init_lambda_attractive
self.tensorboard = tensorboard
self.clusterize = clusterize
self.learning_rate = learning_rate
self.datapath = datapath
self.gene_ds = gene_ds
self.ccre_ds = ccre_ds
# the following option turns on the fancy graph link update
# based on the actual "kendall discounted" weights.
# NOTE: It slows down a lot the programm... Use with CAUTION
self.update_graph_option = update_graph_option
self.reset()
classes = ['gene', 'ccre']
self.class_label_array = np.array([classes[0]] * self.ge_count + [classes[1]] * self.ccre_count)
self.init_graph_plot_conf()
def reset(self):
self.iteration = 0
self.gae_nn = None
torch.cuda.empty_cache()
data_matrix_for_nn = torch.eye(self.X.shape[0],self.X.shape[0]).to(self.device)
self.gae_nn = GAE_NN(data_matrix_for_nn,
self.device,
self.pre_trained,
self.pre_trained_state_dict,
self.pre_computed_embedding,
self.gcn,
self.layers,
self.learning_rate,
self.datapath).to(self.device)
self.current_prediction = None
self.current_sparsity = self.prev_sparsity = self.init_sparsity
self.current_gene_sparsity = math.ceil(self.current_sparsity / self.global_ccres_over_genes_ratio)
if self.current_gene_sparsity == 0: self.current_gene_sparsity += 1
self.current_genomic_slope = self.init_genomic_slope
self.current_genomic_C = self.init_genomic_C
self.omega_BP = self.init_omega_BP
self.alpha_G = self.init_alpha_G
self.alpha_ATAC = self.init_alpha_ATAC
self.alpha_ACET = self.init_alpha_ACET
self.alpha_METH = self.init_alpha_METH
self.wk_ATAC = self.prev_wk_ATAC = self.omega_ATAC
self.wk_ACET = self.prev_wk_ACET = self.omega_ACET
self.wk_METH = self.prev_wk_METH = self.omega_METH
self.alpha_Z = self.init_alpha_Z
self.current_cluster_number = math.ceil((self.ge_count + self.ccre_count) / self.current_sparsity)
self.init_adj_matrices()
self.current_attractive_loss_weight = self.init_attractive_loss_weight
self.current_repulsive_loss_weight = self.init_repulsive_loss_weight
self.current_lambda_repulsive = self.init_lambda_repulsive
self.current_lambda_attractive = self.init_lambda_attractive
if not self.pre_trained: self.init_embedding()
def get_kendall_matrix(self):
dim = self.ge_count + self.ccre_count
kendall_matrix = torch.zeros(dim, dim)
ccre_slopes = ((self.wk_ATAC * self.atac_slopes) + (self.wk_ACET * self.acet_slopes) - (self.wk_METH * self.met_slopes))
ccre_trend_upright_submatrix = np.repeat(ccre_slopes.reshape(-1, 1), self.ge_count).reshape(self.ccre_count,
-1).transpose()
gene_trend_upright_submatrix = np.repeat(self.gene_exp_slopes.reshape(1, -1), self.ccre_count).reshape(self.ge_count, -1)
kendall_matrix[:self.ge_count, self.ge_count:] = torch.Tensor(gene_trend_upright_submatrix + ccre_trend_upright_submatrix)
gene_trend_downleft_submatrix = np.repeat(self.gene_exp_slopes.reshape(-1, 1), self.ccre_count).reshape(-1,
self.ccre_count).transpose()
ccre_trend_downleft_submatrix = np.repeat(ccre_slopes.reshape(1, -1), self.ge_count).reshape(self.ccre_count, -1)
kendall_matrix[self.ge_count:, :self.ge_count] = torch.Tensor(
gene_trend_downleft_submatrix + ccre_trend_downleft_submatrix)
kendall_matrix.abs_()
# row-wise scaling
kendall_matrix /= (kendall_matrix.max(dim=1)[0] + 1e-10).reshape(-1, 1)
return kendall_matrix
def init_graph_plot_conf(self):
self.primitive_clusters = list(set(nx.get_node_attributes(self.G, 'primitive_cluster').values()))
self.primitive_clusters.sort()
cluster_count = len(self.primitive_clusters)
#cluster_colors = torch.rand((cluster_count, 1, 3)).numpy()
cluster_colors = get_disctinct_colors(cluster_count)
self.cluster_colors = {k: v for k, v in zip(self.primitive_clusters, cluster_colors)}
self.cluster_nodes_dict = {}
for primitive_cluster in self.primitive_clusters:
self.cluster_nodes_dict[primitive_cluster] = [x for x, y in self.G.nodes(data=True) if
y['primitive_cluster'] == primitive_cluster]
def plot_gene_pca(self):
pca = PCA(n_components=2)
Z = pca.fit_transform(self.gene_ds.values[:, 1:-1])
# generate a list of markers and another of colors
plt.rcParams["figure.figsize"] = (20, 10)
for cluster in np.sort(self.gene_ds['cluster'].unique()):
cluster_points = Z[self.current_prediction[:self.ge_count] == cluster]
plt.scatter(cluster_points[:, 0],
cluster_points[:, 1],
label='Cluster' + str(cluster))
plt.legend()
plt.title('Explained Variance Ratio: ' + str(pca.explained_variance_ratio_) + ' Singluar Values: ' + str(
pca.singular_values_))
plt.show()
def plot_ccre_pca(self):
pca = PCA(n_components=3)