-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.py
1250 lines (1050 loc) · 53 KB
/
utils.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 rpy2 import robjects
from rpy2.robjects import r, pandas2ri
# Basic libraries
import pandas as pd
import math
import os
import urllib3, certifi
import urllib.parse
import requests, json
import sys
import geode
import random
from time import sleep
import time
import numpy as np
import warnings
import base64
# Visualization
import plotly
from plotly import tools
import plotly.express as px
import plotly.graph_objs as go
plotly.offline.init_notebook_mode() # To embed plots in the output cell of the notebook
import matplotlib.pyplot as plt; plt.rcdefaults()
from matplotlib import rcParams
from matplotlib.lines import Line2D
from matplotlib_venn import venn2, venn3
import IPython
from IPython.display import HTML, display, Markdown, IFrame
import chart_studio
import chart_studio.plotly as py
# Data analysis
from itertools import combinations
import scipy.spatial.distance as dist
import scipy.stats as ss
from sklearn.decomposition import PCA
from maayanlab_bioinformatics.normalization.quantile import quantile_normalize
from maayanlab_bioinformatics.dge.characteristic_direction import characteristic_direction
#import umap
from sklearn.manifold import TSNE
http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
def check_files(fname):
if fname == "":
raise IOError
if fname.endswith(".txt") == False and fname.endswith(".csv") ==False and fname.endswith(".tsv")==False:
raise IOError
def find_remote_file(fname):
r = http.request('HEAD', fname)
http.clear()
if r.status != 200:
fname = fname +".gz"
r = http.request('HEAD', fname)
http.clear()
if r.status != 200:
raise IOError
else:
return fname
else:
return fname
def to_float(x):
try:
return float(x)
except:
return float('nan')
def parse_xena_expr(fin, samples):
columns = fin.readline()[:-1].split('\t')
# find the columns to keep
keep_pos =[]
keep_samples =[]
ids =[]
for i in range(1, len(columns)):
if columns[i] in samples:
keep_pos.append(i)
keep_samples.append(columns[i])
big_list = []
while 1:
line = fin.readline()
if line == '':
break
data = line[:-1].split('\t')
id = data[0]
ids.append(id)
big_list.append(list(map(to_float, map(data.__getitem__, keep_pos))))
fin.close()
df = pd.DataFrame(big_list, index = ids, columns=keep_samples)
return df
def check_subgroups (control_group, case_group):
if len(case_group) == 0:
return 'Subgroup 1 has no samples.'
if len(control_group) == 0:
return 'Subgroup 2 has no samples.'
if control_group == case_group:
return 'You selected the same categories \"' + '_'.join(control_group)+ '\" for both subgroups.'
if len(list(set(control_group) & set(case_group))) != 0:
return 'There can not be shared samples between the two subgroups.'
return 0
def check_probe_level(probemap_df):
counter = 0
counter_gene_level = 0
gene_pos = 1
for probe in probemap_df.index:
if type(probemap_df.loc[probe][gene_pos]) == str and probe == probemap_df.loc[probe][gene_pos]:
counter_gene_level += 1
counter += 1
if counter == 1000:
break
if counter_gene_level/counter > 0.5:
probe_level = "HUGO"
else:
probe_level = "probe"
return probe_level
def convert_to_hugo(expr_df, probemap_df):
'''
convert expr_df matrix to HUGO gene_level expr_df using probemap_df
'''
big_list= []
gene_list = []
gene_pos = 1
for probe in expr_df.index:
try:
if type(probemap_df.loc[probe][gene_pos]) == str:
genes = probemap_df.loc[probe][gene_pos].split(",")
gene_list += genes
for gene in genes:
big_list.append(list(expr_df.loc[probe]))
except:
pass
df_copy = pd.DataFrame(big_list, index = gene_list, columns=expr_df.columns)
df_copy = df_copy.groupby(df_copy.index).mean()
return df_copy
def build_meta_df(samples, values, codes):
big_list= []
for i in range (0, len(samples)):
sample = samples[i]
data = values[i]
if data is None:
value = ''
else:
value = codes[values[i]]
big_list.append([sample, value])
return pd.DataFrame(big_list, columns=['sample', 'category'])
def check_df(df, col):
if col not in df.columns:
raise IOError
def CPM(data):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
data = (data/data.sum())*10**6
data = data.fillna(0)
return data
def logCPM(data):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
data = (data/data.sum())*10**6
data = data.fillna(0)
data = np.log10(data+1)
# Return
return data
def log(data):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
data = data.fillna(0)
data = np.log10(data+1)
return data
def qnormalization(data):
X_quantile_norm = quantile_normalize(data)
return X_quantile_norm
def normalize(dataset, current_dataset, logCPM_normalization, log_normalization, z_normalization, q_normalization):
normalization = current_dataset
if logCPM_normalization == True:
data = dataset[normalization]
normalization += '+logCPM'
dataset[normalization] = logCPM(data)
if log_normalization == True:
data = dataset[normalization]
normalization += '+log'
dataset[normalization] = log(data)
if z_normalization == True:
data = dataset[normalization]
normalization += '+z_norm'
dataset[normalization] = data.T.apply(ss.zscore, axis=0).T.dropna()
if q_normalization == True:
data = dataset[normalization]
normalization += '+q_norm'
dataset[normalization] = qnormalization(data)
return dataset, normalization
def create_download_link(df, title = "Download CSV file: {}", filename = "data.csv"):
df.to_csv(filename)
html = "<a href=\"./{}\" target='_blank'>{}</a>".format(filename, title.format(filename))
return HTML(html)
def display_link(url):
raw_html = '<a href="%s" target="_blank">%s</a>' % (url, url)
return display(HTML(raw_html))
def display_object(counter, caption, df=None, istable=True):
if df is not None:
display(df)
if istable == True:
display(Markdown("*Table {}. {}*".format(counter, caption)))
else:
display(Markdown("*Figure {}. {}*".format(counter, caption)))
counter += 1
return counter
def run_dimension_reduction(dataset, meta_id_column_name, method='PCA', normalization='logCPM', nr_genes=2500, filter_samples=True, plot_type='interactive'):
# Get data
before_norm = normalization.replace("+z_norm", "").replace("+q_norm", "")
top_genes = dataset[before_norm].var(axis=1).sort_values(ascending=False)
expression_dataframe = dataset[normalization]
# Filter columns
if filter_samples and dataset.get('signature_metadata'):
selected_samples = [sample for samples in list(dataset['signature_metadata'].values())[0].values() for sample in samples]
expression_dataframe = expression_dataframe[selected_samples]
# Filter rows
expression_dataframe = expression_dataframe.loc[top_genes.index[:nr_genes]]
result=None
axis = None
if method == 'PCA':
# Run PCA
pca=PCA(n_components=3)
result = pca.fit(expression_dataframe)
# Get Variance
axis = ['PC'+str((i+1))+'('+str(round(e*100, 1))+'% var. explained)' for i, e in enumerate(pca.explained_variance_ratio_)]
#elif method == "UMAP":
# u = umap.UMAP(n_components=3)
# result = u.fit_transform(expression_dataframe.T)
# axis = ['UMAP 1', 'UMAP 2', 'UMAP 3']
elif method == "t-SNE":
u = TSNE(n_components=3)
result = u.fit_transform(expression_dataframe.T)
axis = ['t-SNE 1', 't-SNE 2', 't-SNE 3']
# Add signature groups
if dataset.get('signature_metadata'):
A_label, B_label = list(dataset.get('signature_metadata').keys())[0].split(' vs ')
col = []
group_dict = list(dataset.get('signature_metadata').values())[0]
for gsm in dataset['sample_metadata'].index:
if gsm in group_dict['A']:
col.append(A_label)
elif gsm in group_dict['B']:
col.append(B_label)
else:
col.append('Other')
dataset['dataset_metadata']['Sample Group'] = col
# Return
results = {'method': method, 'result': result, 'axis': axis,
'dataset_metadata': dataset['dataset_metadata'][dataset['dataset_metadata'][meta_id_column_name] == expression_dataframe.columns],
'nr_genes': nr_genes,
'normalization': normalization, 'signature_metadata': dataset.get('signature_metadata'),
'plot_type': plot_type}
return results
def plot_samples(pca_results, meta_id_column_name, meta_class_column_name, counter, plot_type='interactive',):
pca_transformed = pca_results['result']
axis = pca_results['axis']
meta_df = pca_results['dataset_metadata']
if pca_results["method"] == "PCA":
meta_df['x'] = pca_transformed.components_[0]
meta_df['y'] = pca_transformed.components_[1]
meta_df['z'] = pca_transformed.components_[2]
else:
meta_df['x'] = [x[0] for x in pca_transformed]
meta_df['y'] = [x[1] for x in pca_transformed]
meta_df['z'] = [x[2] for x in pca_transformed]
caption = '3D {} plot for samples using {} genes having largest variance. \
The figure displays an interactive, three-dimensional scatter plot of the data. \
Each point represents an gene expression sample. \
Samples with similar gene expression profiles are closer in the three-dimensional space. \
If provided, sample groups are indicated using different colors, allowing for easier interpretation of the results.'.format(pca_results["method"], pca_results['nr_genes'])
display(IPython.core.display.HTML('''
<script src="/static/components/requirejs/require.js"></script>
<script>
requirejs.config({
paths: {
base: '/static/base',
plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
},
});
</script>
'''))
classes = meta_df[meta_class_column_name].unique().tolist()
SYMBOLS = ['circle', 'square']
if len(classes) > 10:
def r(): return random.randint(0, 255)
COLORS = ['#%02X%02X%02X' % (r(), r(), r())
for i in range(len(classes))]
else:
COLORS = [
'#1f77b4',
'#ff7f0e',
'#2ca02c',
'#d62728',
'#9467bd',
'#8c564b',
'#e377c2',
'#7f7f7f',
'#bcbd22',
'#17becf',
]
data = [] # To collect all Scatter3d instances
for (cls), meta_df_sub in meta_df.groupby([meta_class_column_name]):
# Iteratate through samples grouped by class
display_name = '%s' % (cls)
# Initiate a Scatter3d instance for each group of samples specifying their coordinates
# and displaying attributes including color, shape, size and etc.
trace = go.Scatter3d(
x = meta_df_sub['x'],
y = meta_df_sub['y'],
z = meta_df_sub['z'],
text=meta_df_sub[meta_id_column_name],
mode='markers',
marker=dict(
size=10,
color=COLORS[classes.index(cls)], # Color by infection status
opacity=.8,
),
# name=meta_df_sub[meta_id_column_name]
name=display_name,
)
data.append(trace)
# Configs for layout and axes
layout=dict(height=1000, width=1000,
title='3D {} plot for samples'.format(pca_results["method"]),
scene=dict(
xaxis=dict(title=axis[0]),
yaxis=dict(title=axis[1]),
zaxis=dict(title=axis[2])
)
)
fig=dict(data=data, layout=layout)
if plot_type == "interactive":
plotly.offline.iplot(fig)
else:
py.image.ishow(fig)
display(Markdown("*Figure {}. {}*".format(counter, caption)))
counter += 1
return counter
def run_clustergrammer(dataset, meta_class_column_name, normalization='logCPM', z_score=True, nr_genes=1500, metadata_cols=None, filter_samples=True,gene_list=None):
# Subset the expression DataFrame using top 800 genes with largest variance
data = dataset[normalization]
variances = np.var(data, axis=1)
srt_idx = variances.argsort()[::-1]
if gene_list == None or len(gene_list) == 0:
expr_df_sub = data.iloc[srt_idx].iloc[:nr_genes]
else:
gene_list = gene_list.split("\n")
common_gene_list = list(set(gene_list).intersection(set(data.index)))
expr_df_sub = data.loc[common_gene_list, :]
assert len(expr_df_sub.index) > 0
# prettify sample names
sample_names = ['::'.join([y, x]) for x,y in
zip(dataset["dataset_metadata"][meta_class_column_name], expr_df_sub.columns)]
expr_df_sub.columns = sample_names
expr_df_sub.index = ["Gene: "+str(x) for x in expr_df_sub.index]
sample_name = ["Sample: "+x for x in sample_names]
expr_df_sub.columns = sample_name
treatment_type = ["Class: "+ x.split("::")[1] for x in sample_names]
new_series = pd.DataFrame(treatment_type).T
new_series.columns = expr_df_sub.columns
expr_df_sub = pd.concat([new_series, expr_df_sub], axis=0)
index_list = list(expr_df_sub.index)
index_list = ["" if "Gene" not in str(x) else x for x in index_list]
expr_df_sub.index = index_list
expr_df_sub_file = "expr_df_sub_file.txt"
expr_df_sub.to_csv("expr_df_sub_file.txt", sep='\t')
# POST the expression matrix to Clustergrammer and get the URL
clustergrammer_url = 'https://amp.pharm.mssm.edu/clustergrammer/matrix_upload/'
r = requests.post(clustergrammer_url, files={'file': open(expr_df_sub_file, 'rb')}).text
return r
#############################################
########## 2. Plot
#############################################
def plot_clustergrammar(clustergrammer_url):
clustergrammer_url = clustergrammer_url.replace("http:", "https:")
display_link(clustergrammer_url)
# Embed
display(IPython.display.IFrame(clustergrammer_url, width="1000", height="1000"))
def plot_2D_scatter(x, y, text='', title='', xlab='', ylab='', hoverinfo='text', color='black', colorscale='Blues', size=8, showscale=False, symmetric_x=False, symmetric_y=False, pad=0.5, hline=False, vline=False, return_trace=False, labels=False, plot_type='interactive', de_type='ma'):
range_x = [-max(abs(x))-pad, max(abs(x))+pad]if symmetric_x else None
range_y = [-max(abs(y))-pad, max(abs(y))+pad]if symmetric_y else None
trace = go.Scattergl(x=x, y=y, mode='markers', text=text, hoverinfo=hoverinfo, marker={'color': color, 'colorscale': colorscale, 'showscale': showscale, 'size': size})
if return_trace:
return trace
else:
if de_type == 'ma':
annotations = [
{'x': 1, 'y': 0.1, 'text':'<span style="color: blue; font-size: 10pt; font-weight: 600;">Down-regulated in '+labels[0]+'</span>', 'showarrow': False, 'xref': 'paper', 'yref': 'paper', 'xanchor': 'right', 'yanchor': 'top'},
{'x': 1, 'y': 0.9, 'text':'<span style="color: red; font-size: 10pt; font-weight: 600;">Up-regulated in '+labels[0]+'</span>', 'showarrow': False, 'xref': 'paper', 'yref': 'paper', 'xanchor': 'right', 'yanchor': 'bottom'}
] if labels else []
elif de_type == 'volcano':
annotations = [
{'x': 0.25, 'y': 1.07, 'text':'<span style="color: blue; font-size: 10pt; font-weight: 600;">Down-regulated in '+labels[0]+'</span>', 'showarrow': False, 'xref': 'paper', 'yref': 'paper', 'xanchor': 'center'},
{'x': 0.75, 'y': 1.07, 'text':'<span style="color: red; font-size: 10pt; font-weight: 600;">Up-regulated in '+labels[0]+'</span>', 'showarrow': False, 'xref': 'paper', 'yref': 'paper', 'xanchor': 'center'}
] if labels else []
layout = go.Layout(title=title, xaxis={'title': xlab, 'range': range_x}, yaxis={'title': ylab, 'range': range_y}, hovermode='closest', annotations=annotations)
fig = go.Figure(data=[trace], layout=layout)
if plot_type=='interactive':
plotly.offline.iplot(fig)
else:
py.image.ishow(fig)
robjects.r('''limma_voom <- function(rawcount_dataframe, design_dataframe, adjust="BH") {
# Load packages
suppressMessages(require(limma))
suppressMessages(require(edgeR))
# Convert design matrix
design <- as.matrix(design_dataframe)
# Create DGEList object
dge <- DGEList(counts=rawcount_dataframe)
# Filter genes
keep <- filterByExpr(dge, design)
dge <- dge[keep,]
# Calculate normalization factors
dge <- calcNormFactors(dge)
# Run VOOM
v <- voom(dge, plot=FALSE)
# Fit linear model
fit <- lmFit(v, design)
# Make contrast matrix
cont.matrix <- makeContrasts(de=B-A, levels=design)
# Fit
fit2 <- contrasts.fit(fit, cont.matrix)
# Run DE
fit2 <- eBayes(fit2)
# Get results
limma_dataframe <- topTable(fit2, adjust=adjust, number=nrow(rawcount_dataframe))
# Return
results <- list("limma_dataframe"= limma_dataframe, "rownames"=rownames(limma_dataframe))
return (results)
}
''')
robjects.r('''limma <- function(rawcount_dataframe, design_dataframe, adjust="BH") {
# Load packages
suppressMessages(require(limma))
suppressMessages(require(edgeR))
# Convert design matrix
design <- as.matrix(design_dataframe)
# Create DGEList object
dge <- DGEList(counts=rawcount_dataframe)
# Filter genes
keep <- filterByExpr(dge, design)
dge <- dge[keep,]
# Calculate normalization factors
dge <- calcNormFactors(dge)
# Fit linear model
fit <- lmFit(normalizeMedianValues(dge$counts), design) # Normalization so that each column has the same median value
# Make contrast matrix
cont.matrix <- makeContrasts(de=B-A, levels=design)
# Fit
fit2 <- contrasts.fit(fit, cont.matrix)
# Run DE
fit2 <- eBayes(fit2)
# Get results
limma_dataframe <- topTable(fit2, adjust=adjust, number=nrow(rawcount_dataframe))
# Return
results <- list("limma_dataframe"= limma_dataframe, "rownames"=rownames(limma_dataframe))
return (results)
}
''')
robjects.r('''edgeR <- function(rawcount_dataframe, g1, g2) {
# Load packages
suppressMessages(require(limma))
suppressMessages(require(edgeR))
suppressMessages(require(dbplyr))
colData <- as.data.frame(c(rep(c("Control"),length(g1)),rep(c("Condition"),length(g2))))
rownames(colData) <- c(g1,g2)
colnames(colData) <- c("group")
colData$group = relevel(as.factor(colData$group), "Control")
target <- colnames(rawcount_dataframe)
DT <- colData %>% dplyr::slice(match(target, rownames(colData)))
rownames(DT) <- target
colData <- DT
y <- DGEList(counts=rawcount_dataframe, group=colData$group)
# Filter genes
keep <- filterByExpr(y)
y <- y[keep,]
y <- calcNormFactors(y)
y <- estimateCommonDisp(y)
y <- estimateTagwiseDisp(y)
et <- exactTest(y)
res <- topTags(et, n=Inf)
# Return
res <- as.data.frame(res)
results <- list("edgeR_dataframe"= res, "rownames"=rownames(res))
return (results)
}
''')
robjects.r('''deseq2 <- function(rawcount_dataframe, g1, g2) {
# Load packages
suppressMessages(require(DESeq2))
suppressMessages(require(edgeR))
suppressMessages(require(dbplyr))
colData <- as.data.frame(c(rep(c("Control"),length(g1)),rep(c("Condition"),length(g2))))
rownames(colData) <- c(g1,g2)
colnames(colData) <- c("group")
colData$group = relevel(as.factor(colData$group), "Control")
dge <- DGEList(counts=rawcount_dataframe, group=colData$group)
# Filter genes
keep <- filterByExpr(dge)
dge <- dge[keep,]
target <- colnames(rawcount_dataframe)
DT <- colData %>% dplyr::slice(match(target, rownames(colData)))
rownames(DT) <- target
colData <- DT
dds <- DESeqDataSetFromMatrix(countData = dge$counts +1 , colData = colData, design=~(group)) # add pseudocount =1
dds <- DESeq(dds)
res <- results(dds)
res[which(is.na(res$padj)),] <- 1
res <- as.data.frame(res)
results <- list("DESeq_dataframe"= res, "rownames"=rownames(res))
return(results)
}
''')
robjects.r('''preprocessing <- function(expr_matrix, max_gene) {
# normalize, most variable genes
# Load packages
suppressMessages(require(statmod))
suppressMessages(require(limma))
# http://pklab.med.harvard.edu/scw2014/subpop_tutorial.html
norm_matrix <- normalizeQuantiles(expr_matrix)
if (nrow(expr_matrix) > max_gene) {
winsorize <- function (x, fraction=0.05) {
if(length(fraction) != 1 || fraction < 0 || fraction > 0.5) {
stop("bad value for 'fraction'")
}
lim <- quantile(x, probs=c(fraction, 1-fraction), na.rm = TRUE,)
x[ x < lim[1] ] <- lim[1]
x[ x > lim[2] ] <- lim[2]
x
}
# winsorize to remove 2 most extreme cells (from each side)
wed <- t(apply(norm_matrix, 1, winsorize, fraction=2/ncol(norm_matrix)))
means <- rowMeans(wed, na.rm = TRUE)
vars <- apply(wed, 1, var, na.rm = TRUE)
cv2 <- vars/means^2
minMeanForFit <- unname( quantile( means[ which( cv2 > .3 ) ], .95 ) )
useForFit <- means >= minMeanForFit # & spikeins
fit <- glmgam.fit( cbind( a0 = 1, a1tilde = 1/means[useForFit] ),cv2[useForFit] )
a0 <- unname( fit$coefficients["a0"] )
a1 <- unname( fit$coefficients["a1tilde"])
afit <- a1/means+a0
varFitRatio <- vars/(afit*means^2)
varorder <- order(varFitRatio,decreasing=T)
return(as.data.frame(norm_matrix[varorder[0:max_gene],]))
} else {
return(as.data.frame(norm_matrix))
}
}
''')
def get_signatures(classes, dataset, normalization, method, meta_class_column_name, meta_id_column_name, filter_genes, logData, pseudocount):
expr_df = dataset['rawdata']
if filter_genes == True:
expr_df = dataset['rawdata+filter_genes']
signatures = dict()
for cls1, cls2 in combinations(classes, 2):
cls1_sample_ids = dataset["dataset_metadata"].loc[dataset["dataset_metadata"][meta_class_column_name]==cls1, meta_id_column_name].tolist() #control
cls2_sample_ids = dataset["dataset_metadata"].loc[dataset["dataset_metadata"][meta_class_column_name]==cls2, meta_id_column_name].tolist() #case
signature_label = " vs. ".join([cls2, cls1])
print (signature_label)
# check values all non-negative for limma_voom, edgeR and DESeq2
if method == "limma_voom" or method == "edgeR" or method == "DESeq2":
if logData: # transform back to non-log data
unlog_expr_df = np.exp2(expr_df) - pseudocount
print(f"Info. Log transformed data. Base 2 exponentiation is applied")
if (unlog_expr_df < 0).any().any(): # requires non-negative values
unlog_expr_df = np.exp2(expr_df) # the entire matrix is shifted by pseudocount
print(f"Warning! {method} requires all non-negative values. Negative values detected, only apply base2 exponentiation to log data, pseudocount ignored.")
expr_df = unlog_expr_df
if (expr_df < 0).any().any():
print(f"Error! {method} requires non-negative gene expression values. Negative values detected")
sleep(10)
raise SystemExit(1)
# check values all integer for DESeq2
if method == "DESeq2":
if (expr_df.fillna(-999) % 1 == 0).all().all():
pass
else:
expr_df = expr_df.round() # requires all non-negative integer counts
print(f"Warning! {method} requires all non-negative integer count values. Non integer values detected, round to integer values.")
if method == "limma_voom":
limma_voom = robjects.r['limma_voom']
design_dataframe = pd.DataFrame([{'index': x, 'A': int(x in cls1_sample_ids), 'B': int(x in cls2_sample_ids)} for x in expr_df.columns]).set_index('index')
processed_data = {"expression": expr_df, 'design': design_dataframe}
limma_results = pandas2ri.conversion.rpy2py(limma_voom(pandas2ri.conversion.py2rpy(processed_data['expression']), pandas2ri.conversion.py2rpy(processed_data['design'])))
signature = pd.DataFrame(limma_results[0])
signature.index = limma_results[1]
signature = signature.sort_values("t", ascending=False)
elif method == "characteristic_direction":
max_gene = 25 * 1000
if len(expr_df) > max_gene:
max_gene = int(len(expr_df) * 0.50) # top 50% most variable genes
print (f'Using the most variable {max_gene} genes')
preprocessing = robjects.r['preprocessing']
processed_data = pandas2ri.conversion.rpy2py(preprocessing(pandas2ri.conversion.py2rpy(expr_df), pandas2ri.conversion.py2rpy(max_gene)))
signature = characteristic_direction(processed_data.loc[:, cls1_sample_ids], processed_data.loc[:, cls2_sample_ids], calculate_sig=True)
signature = signature.sort_values("CD-coefficient", ascending=False)
elif method == "edgeR":
edgeR = robjects.r['edgeR']
edgeR_results = pandas2ri.conversion.rpy2py(edgeR(pandas2ri.conversion.py2rpy(expr_df), pandas2ri.conversion.py2rpy(cls1_sample_ids), pandas2ri.conversion.py2rpy(cls2_sample_ids)))
signature = pd.DataFrame(edgeR_results[0])
signature.index = edgeR_results[1]
signature = signature.sort_values("logFC", ascending=False)
elif method == "DESeq2":
DESeq2 = robjects.r['deseq2']
DESeq2_results = pandas2ri.conversion.rpy2py(DESeq2(pandas2ri.conversion.py2rpy(expr_df), pandas2ri.conversion.py2rpy(cls1_sample_ids), pandas2ri.conversion.py2rpy(cls2_sample_ids)))
signature = pd.DataFrame(DESeq2_results[0])
signature.index = DESeq2_results[1]
signature = signature.sort_values("log2FoldChange", ascending=False)
signatures[signature_label] = signature
return signatures
def run_volcano(signature, signature_label, dataset, pvalue_threshold, logfc_threshold, plot_type):
color = []
text = []
for index, rowData in signature.iterrows():
if "AveExpr" in rowData.index: # limma limma_voom
expr_colname = "AveExpr"
pval_colname = "P.Value"
logfc_colname = "logFC"
elif "logCPM" in rowData.index: #edgeR
expr_colname = "logCPM"
pval_colname = "PValue"
logfc_colname = "logFC"
elif "baseMean" in rowData.index: #DESeq2
expr_colname = "baseMean"
pval_colname = "pvalue"
logfc_colname = "log2FoldChange"
# Text
text.append('<b>'+index+'</b><br>Avg Expression = '+str(round(rowData[expr_colname], ndigits=2))+'<br>logFC = '+str(round(rowData[logfc_colname], ndigits=2))+'<br>p = '+'{:.2e}'.format(rowData[pval_colname])+'<br>FDR = '+'{:.2e}'.format(rowData[pval_colname]))
# Color
if rowData[pval_colname] < pvalue_threshold:
if rowData[logfc_colname] < -logfc_threshold:
color.append('blue')
elif rowData[logfc_colname] > logfc_threshold:
color.append('red')
else:
color.append('grey')
else:
color.append('grey')
volcano_plot_results = {'x': signature[logfc_colname], 'y': -np.log10(signature[pval_colname]), 'text':text, 'color': color, 'signature_label': signature_label, 'plot_type': plot_type}
return volcano_plot_results
def plot_volcano(volcano_plot_results):
spacer = ' '*50
plot_2D_scatter(
x=volcano_plot_results['x'],
y=volcano_plot_results['y'],
text=volcano_plot_results['text'],
color=volcano_plot_results['color'],
symmetric_x=True,
xlab='log2FC',
ylab='-log10P',
title='<b>{volcano_plot_results[signature_label]} Signature | Volcano Plot</b>'.format(**locals()),
labels=volcano_plot_results['signature_label'].split(' vs. '),
plot_type=volcano_plot_results['plot_type'],
de_type='volcano'
)
def run_maplot(signature, signature_label='', pvalue_threshold=0.05, logfc_threshold=1.5, plot_type='interactive'):
# Loop through signature
color = []
text = []
for index, rowData in signature.iterrows():
if "AveExpr" in rowData.index: # limma
expr_colname = "AveExpr"
pval_colname = "adj.P.Val"
logfc_colname = "logFC"
elif "logCPM" in rowData.index: #edgeR
expr_colname = "logCPM"
pval_colname = "PValue"
logfc_colname = "logFC"
elif "baseMean" in rowData.index: #DESeq2
expr_colname = "baseMean"
pval_colname = "padj"
logfc_colname = "log2FoldChange"
# Text
text.append('<b>'+index+'</b><br>Avg Expression = '+str(round(rowData[expr_colname], ndigits=2))+'<br>logFC = '+str(round(rowData[logfc_colname], ndigits=2))+'<br>p = '+'{:.2e}'.format(rowData[pval_colname])+'<br>FDR = '+'{:.2e}'.format(rowData[pval_colname]))
# Color
if rowData[pval_colname] < pvalue_threshold:
if rowData[logfc_colname] < -logfc_threshold:
color.append('blue')
elif rowData[logfc_colname] > logfc_threshold:
color.append('red')
else:
color.append('black')
else:
color.append('black')
# Return
volcano_plot_results = {'x': signature[expr_colname], 'y': signature[logfc_colname], 'text':text, 'color': color, 'signature_label': signature_label, 'plot_type': plot_type}
return volcano_plot_results
def plot_maplot(volcano_plot_results):
plot_2D_scatter(
x=volcano_plot_results['x'],
y=volcano_plot_results['y'],
text=volcano_plot_results['text'],
color=volcano_plot_results['color'],
symmetric_y=True,
xlab='Average Expression',
ylab='logFC',
title='<b>{volcano_plot_results[signature_label]} Signature | MA Plot</b>'.format(**locals()),
labels=volcano_plot_results['signature_label'].split(' vs. '),
plot_type=volcano_plot_results['plot_type']
)
def run_enrichr(signature, signature_label, geneset_size=500, fc_colname = 'logFC', sort_genes_by='t', up_ascending=True, down_ascending=True):
'''
if diff_gex_method == "characteristic_direction":
fc_colname = "CD-coefficient"
sort_genes_by = "CD-coefficient"
up_ascending = False
down_ascending = True
elif diff_gex_method == "limma" or diff_gex_method == "limma_voom":
fc_colname = "logFC"
sort_genes_by = "t"
up_ascending = False
down_ascending = True
elif diff_gex_method == "edgeR":
fc_colname = "logFC"
sort_genes_by = "PValue"
up_ascending = True
down_ascending = True
elif diff_gex_method == "DESeq2":
fc_colname = "log2FoldChange"
sort_genes_by = "padj"
up_ascending = True
down_ascending = True
'''
# Sort signature
up_signature = signature[signature[fc_colname] > 0].sort_values(sort_genes_by, ascending= up_ascending)
down_signature = signature[signature[fc_colname] < 0].sort_values(sort_genes_by, ascending= down_ascending)
# Get genesets
genesets = {
'upregulated': up_signature.index[:geneset_size],
'downregulated': down_signature.index[:geneset_size]
}
# Submit to Enrichr
enrichr_ids = {geneset_label: submit_enrichr_geneset(geneset=geneset, label=signature_label+', '+geneset_label+', from Xena DGE Appyter') for geneset_label, geneset in genesets.items()}
enrichr_ids['signature_label'] = signature_label
return enrichr_ids
def submit_enrichr_geneset(geneset, label=''):
ENRICHR_URL = 'http://maayanlab.cloud/Enrichr/addList'
genes_str = '\n'.join(geneset)
payload = {
'list': (None, genes_str),
'description': (None, label)
}
response = requests.post(ENRICHR_URL, files=payload)
if not response.ok:
raise Exception('Error analyzing gene list')
time.sleep(0.5)
data = json.loads(response.text)
return data
def get_enrichr_results(user_list_id, gene_set_libraries, overlappingGenes=True, geneset=None):
ENRICHR_URL = 'http://maayanlab.cloud/Enrichr/enrich'
query_string = '?userListId=%s&backgroundType=%s'
results = []
for gene_set_library, label in gene_set_libraries.items():
response = requests.get(
ENRICHR_URL +
query_string % (user_list_id, gene_set_library)
)
if not response.ok:
raise Exception('Error fetching enrichment results')
data = json.loads(response.text)
resultDataframe = pd.DataFrame(data[gene_set_library], columns=[
'rank', 'term_name', 'pvalue', 'zscore', 'combined_score', 'overlapping_genes', 'FDR', 'old_pvalue', 'old_FDR'])
selectedColumns = ['term_name', 'zscore', 'combined_score', 'pvalue', 'FDR'] if not overlappingGenes else [
'term_name', 'zscore', 'combined_score', 'FDR', 'pvalue', 'overlapping_genes']
resultDataframe = resultDataframe.loc[:, selectedColumns]
resultDataframe['gene_set_library'] = label
resultDataframe['log10P'] = -np.log10(resultDataframe['pvalue'])
results.append(resultDataframe)
concatenatedDataframe = pd.concat(results)
if geneset:
concatenatedDataframe['geneset'] = geneset
return concatenatedDataframe
def get_enrichr_results_by_library(enrichr_results, signature_label, plot_type='interactive', library_type='go', version='2018', sort_results_by='pvalue'):
# Libraries
if library_type == 'go':
go_version = str(version)
libraries = {
'GO_Biological_Process_'+go_version: 'Gene Ontology Biological Process ('+go_version+' version)',
'GO_Molecular_Function_'+go_version: 'Gene Ontology Molecular Function ('+go_version+' version)',
'GO_Cellular_Component_'+go_version: 'Gene Ontology Cellular Component ('+go_version+' version)'
}
elif library_type == "pathway":
# Libraries
libraries = {
'KEGG_2019_Human': 'KEGG Pathways',
'WikiPathways_2019_Human': 'WikiPathways',
'Reactome_2016': 'Reactome Pathways'
}
# Get Enrichment Results
enrichment_results = {geneset: get_enrichr_results(enrichr_results[geneset]['userListId'], gene_set_libraries=libraries, geneset=geneset) for geneset in ['upregulated', 'downregulated']}
enrichment_results['signature_label'] = signature_label
enrichment_results['plot_type'] = plot_type
enrichment_results['sort_results_by'] = sort_results_by
# Return
return enrichment_results
def get_enrichr_result_tables_by_library(enrichr_results, signature_label, library_type='tf'):
# Libraries
if library_type == 'tf':
# Libraries
libraries = {
'ChEA_2016': 'A. ChEA (experimentally validated targets)',
'ENCODE_TF_ChIP-seq_2015': 'B. ENCODE (experimentally validated targets)',
'ARCHS4_TFs_Coexp': 'C. ARCHS4 (coexpressed genes)'
}
elif library_type == "ke":
# Libraries
libraries = {
'KEA_2015': 'A. KEA (experimentally validated targets)',
'ARCHS4_Kinases_Coexp': 'B. ARCHS4 (coexpressed genes)'
}
elif library_type == "mirna":
libraries = {
'TargetScan_microRNA_2017': 'A. TargetScan (experimentally validated targets)',
'miRTarBase_2017': 'B. miRTarBase (experimentally validated targets)'
}
# Initialize results
results = []
# Loop through genesets
for geneset in ['upregulated', 'downregulated']:
# Append ChEA results
enrichment_dataframe = get_enrichr_results(enrichr_results[geneset]['userListId'], gene_set_libraries=libraries, geneset=geneset)
results.append(enrichment_dataframe)
# Concatenate results
enrichment_dataframe = pd.concat(results)
return {'enrichment_dataframe': enrichment_dataframe, 'signature_label': signature_label}
def plot_library_barchart(enrichr_results, gene_set_library, signature_label, sort_results_by='pvalue', nr_genesets=15, height=400, plot_type='interactive'):
sort_results_by = 'log10P' if sort_results_by == 'pvalue' else 'combined_score'
fig = tools.make_subplots(rows=1, cols=2, print_grid=False)
for i, geneset in enumerate(['upregulated', 'downregulated']):
# Get dataframe
enrichment_dataframe = enrichr_results[geneset]
plot_dataframe = enrichment_dataframe[enrichment_dataframe['gene_set_library'] == gene_set_library].sort_values(sort_results_by, ascending=False).iloc[:nr_genesets].iloc[::-1]
# Format
n = 7
plot_dataframe['nr_genes'] = [len(genes) for genes in plot_dataframe['overlapping_genes']]
plot_dataframe['overlapping_genes'] = ['<br>'.join([', '.join(genes[i:i+n]) for i in range(0, len(genes), n)]) for genes in plot_dataframe['overlapping_genes']]
# Get Bar
bar = go.Bar(
x=plot_dataframe[sort_results_by],
y=plot_dataframe['term_name'],
orientation='h',
name=geneset.title(),
showlegend=False,
hovertext=['<b>{term_name}</b><br><b>P-value</b>: <i>{pvalue:.2}</i><br><b>FDR</b>: <i>{FDR:.2}</i><br><b>Z-score</b>: <i>{zscore:.3}</i><br><b>Combined score</b>: <i>{combined_score:.3}</i><br><b>{nr_genes} Genes</b>: <i>{overlapping_genes}</i><br>'.format(**rowData) for index, rowData in plot_dataframe.iterrows()],
hoverinfo='text',
marker={'color': '#FA8072' if geneset == 'upregulated' else '#87CEFA'}
)
fig.append_trace(bar, 1, i+1)
# Get text
text = go.Scatter(
x=[max(bar['x'])/50 for x in range(len(bar['y']))],
y=bar['y'],
mode='text',
hoverinfo='none',
showlegend=False,
text=['*<b>{}</b>'.format(rowData['term_name']) if rowData['FDR'] < 0.1 else '{}'.format(