forked from sahoo00/BoNE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbone.py
3735 lines (3505 loc) · 135 KB
/
bone.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
# coding: utf-8
# In[1]:
import cv2
import re
import numpy as np
import scipy
import matplotlib
#matplotlib.use('agg')
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
from mpl_toolkits.axes_grid1 import SubplotDivider, Size
from mpl_toolkits.axes_grid1.mpl_axes import Axes
import matplotlib.patches as patches
import matplotlib.colors as colors
from matplotlib.transforms import *
import PIL
import math
import array
#get_ipython().magic(u'matplotlib inline')
import pandas as pd
import seaborn as sns
import json
from sklearn.metrics import *
from scipy.stats import fisher_exact, ttest_ind
from pprint import pprint
import os
import pickle
import sys
sys.path.append("Hegemon")
import StepMiner as smn
import HegemonUtil as hu
acolor = ["#00CC00", "#D8A03D","#EC008C",
'cyan', "#B741DC", "#808285",
'blue', 'black', 'green', 'red',
'orange', 'brown', 'pink', 'purple']
try:
reload # Python 2.7
except NameError:
try:
from importlib import reload # Python 3.4+
except ImportError:
from imp import reload # Python 3.0 - 3.3
def getRealpath(cfile):
return os.path.realpath(os.path.join(os.getcwd(),
os.path.dirname(__file__), cfile))
def asciiNorm(ah):
if sys.version_info[0] >= 3:
keys = list(ah.keys())
for k in keys:
ah[bytes(k, encoding='latin-1').decode('utf-8')] = ah[k]
return ah
def reactome(idlist):
import requests
reactomeURI = 'http://www.reactome.org/AnalysisService/identifiers/projection?pageSize=100&page=1';
response = requests.post(reactomeURI, data = idlist, \
headers = { "Content-Type": "text/plain", "dataType" : "json" })
obj = json.loads(response.text)
df = pd.DataFrame()
df['name'] = [p["name"] for p in obj["pathways"]]
df['count'] = [p["entities"]["found"] for p in obj["pathways"]]
df['pValue'] = [p["entities"]["pValue"] for p in obj["pathways"]]
df['fdr'] = [p["entities"]["fdr"] for p in obj["pathways"]]
return df
def getPDF(cfile):
import bone
reload(bone)
from matplotlib.backends.backend_pdf import PdfPages
pdf = PdfPages(cfile)
return pdf
def closePDF(pdf):
import datetime
d = pdf.infodict()
d['Title'] = 'Plots'
d['Author'] = 'Debashis Sahoo'
d['Subject'] = "BoNE"
d['Keywords'] = 'disease training validation ROC'
d['CreationDate'] = datetime.datetime(2021, 10, 18)
d['ModDate'] = datetime.datetime.today()
pdf.close()
def getGene(ana, name):
id1 = ana.h.getBestID(ana.h.getIDs(name).keys())
expr = ana.h.getExprData(id1)
lval = [[] for i in ana.atypes]
if expr is None:
print("Not Found")
return lval
aval = ana.aval
for i in ana.h.aRange():
if aval[i] is None:
continue
lval[aval[i]] += [float(expr[i])]
return lval
def getBoolean(cfile, sthr, pthr, code):
res = []
with open(cfile, "r") as bFile:
for ln in bFile:
ll = ln.strip().split("\t")
bs = [ [int(ll[i]) for i in range(2, 6)] ]
bs += [ [int(ll[i]) for i in range(2, 6)] ]
bs += [ [float(ll[i]) for i in range(6, 10)] ]
bs += [ [float(ll[i]) for i in range(10, 14)] ]
rel, stats = hu.getBooleanRelationType(bs, sthr, pthr)
if rel == code:
res.append(ll[1])
return res
def plotViolinBar(ana, desc=None):
fig = plt.figure(figsize=(4,4), dpi=100)
plt.subplots_adjust(hspace=0.5, wspace=0.5)
ax1 = plt.subplot2grid((4, 1), (0, 0))
ax2 = plt.subplot2grid((4, 1), (1, 0), rowspan=3)
params = {'spaceAnn': len(ana.order)/len(ana.atypes), 'tAnn': 1, 'widthAnn':1,
'genes': [], 'ax': ax1, 'acolor': acolor}
ax = ana.printTitleBar(params)
res = ana.getROCAUC()
ax.text(len(ana.cval[0]), 4, res)
if desc is not None:
ax.text(-1, 2, desc, horizontalalignment='right',
verticalalignment='center')
params = {'spaceAnn': len(ana.order)/len(ana.atypes), 'tAnn': 1, 'widthAnn':1,
'genes': [], 'ax': ax2, 'acolor': acolor, 'vert': 0}
ax = ana.printViolin(None, params)
return fig
def plotDensityBar(ana, desc=None):
fig = plt.figure(figsize=(4,4), dpi=100)
plt.subplots_adjust(hspace=0.5, wspace=0.5)
ax1 = plt.subplot2grid((4, 1), (0, 0))
ax2 = plt.subplot2grid((4, 1), (1, 0), rowspan=3)
params = {'spaceAnn': len(ana.order)/len(ana.atypes), 'tAnn': 1, 'widthAnn':1,
'genes': [], 'ax': ax1, 'acolor': acolor}
ax = ana.printTitleBar(params)
res = ana.getMetrics(ana.cval[0])
ax.text(len(ana.cval[0]), 4, ",".join(res))
if desc is not None:
ax.text(-1, 2, desc, horizontalalignment='right',
verticalalignment='center')
ax = ana.densityPlot(ax2, acolor)
return fig
def processData(ana, l1, wt1, desc=None, violin=1):
ana.orderData(l1, wt1)
if (violin == 1):
return plotViolinBar(ana, desc)
return plotDensityBar(ana, desc)
def rugplot(data, pos=0, height=.1, ax=None, **kwargs):
from matplotlib.collections import LineCollection
ax = ax or plt.gca()
zero = np.zeros_like(data)
kwargs.setdefault("linewidth", 1)
segs = np.stack((np.c_[data, data],
np.c_[zero+pos*height, zero+(pos+1)*height]),
axis=-1)
lc = LineCollection(segs, transform=ax.get_xaxis_transform(), **kwargs)
ax.add_collection(lc)
return
def plotSingle(expr, pG):
fig = plt.figure(figsize=(6,4), dpi=100)
plt.subplots_adjust(hspace=0.5, wspace=0.5)
ax1 = plt.subplot2grid((4, 1), (0, 0), rowspan=3)
ax2 = plt.subplot2grid((4, 1), (3, 0))
ax2.axison = False
ax2.set_xticklabels([])
ax2.set_yticklabels([])
ax2.grid(False)
ax2.tick_params(top=False, left=False, bottom=False, right=False)
for i in range(len(pG)):
name, col, order = pG[i]
if len(order) <= 0:
continue
vals = [expr[j] for j in order]
ax = sns.kdeplot(vals, bw = 1, cut = 2, color=col, label=name, ax=ax1)
ax1.axvline(x=np.mean(vals), c=col)
rugplot(vals, pos=i, color=col, ax=ax2, height=1/len(pG))
lims = ax2.axis(ax1.axis())
return fig
def getCode(p):
if p <= 0:
return '0'
if p <= 0.001:
return '***'
if p <= 0.01:
return '**'
if p <= 0.05:
return '*'
if p <= 0.1:
return '.'
return ''
def printOLS(fm, df1):
import statsmodels.formula.api as smf
lm1 = smf.ols(formula=fm, data=df1).fit()
print(lm1.summary())
idx = lm1.params.index
ci = lm1.conf_int()
ci_1 = [ ci[0][i] for i in range(len(idx))]
ci_2 = [ ci[1][i] for i in range(len(idx))]
c_1 = [ getCode(p) for p in lm1.pvalues]
df = pd.DataFrame({'Name': idx,
'coeff' : lm1.params, 'lower 0.95' : ci_1,
'upper 0.95' : ci_2, 'pvalues' : lm1.pvalues, 'codes': c_1},
columns=['Name', 'coeff', 'lower 0.95',
'upper 0.95', 'pvalues', 'codes'])
for i in range(len(idx)):
print('%s\t%.2f\t(%0.2f - %0.2f)\t%0.3f' % \
(idx[i], lm1.params[i], ci[0][i], ci[1][i], lm1.pvalues[i]))
print(df.to_string(formatters={'coeff':'{:,.2f}'.format,
'lower 0.95':'{:,.2f}'.format, 'upper 0.95':'{:,.2f}'.format,
'pvalues': '{:,.3f}'.format}))
return df
def printStats(cfile, thr):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
numhigh = 0
numlow = 0
total = 0
for line in fp:
line = line.strip();
ll = re.split("[\t]", line);
if float(ll[2]) >= 0 and float(ll[3]) < thr:
numhigh += 1
if float(ll[2]) < 0 and float(ll[3]) < thr:
numlow += 1
total += 1
fp.close();
print(cfile, numhigh, numlow, total)
def getStats(cfile, thr, index):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
high = set()
low = set()
for line in fp:
line = line.strip();
ll = re.split("[\t]", line);
if float(ll[2]) >= 0 and float(ll[3]) < thr:
high.add(ll[index])
if float(ll[2]) < 0 and float(ll[3]) < thr:
low.add(ll[index])
fp.close();
return high, low
def getEntries(cfile, index):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
res = []
for line in fp:
line = line.strip();
ll = re.split("[\t]", line);
res += [ll[index]]
fp.close();
return res
def getPVal(cfile):
return [float(i) for i in getEntries(cfile, 3)]
def getFdrStats(cfile, thr, index):
pval = getPVal(cfile)
ids = getEntries(cfile, index)
stat = getEntries(cfile, 2)
from statsmodels.stats import multitest
mstat = multitest.multipletests(pval, thr, 'fdr_bh')
high = set()
low = set()
for i in range(len(pval)):
if mstat[0][i] and float(stat[i]) >= 0:
high.add(ids[i])
if mstat[0][i] and float(stat[i]) < 0:
low.add(ids[i])
return high, low
def readGenes(cfile):
genes = ""
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
nodelist = re.split("[\[\]()\s]", genes)
for line in fp:
line = line.strip();
ll = re.split("[\[\]()\s]", line);
nodelist += ll
fp.close();
return [i for i in hu.uniq(nodelist) if i != '']
def plotSizes(csizes):
w,h, dpi = (6, 4, 100)
fig = plt.figure(figsize=(w,h), dpi=dpi)
ax = fig.add_axes([70.0/w/dpi, 54.0/h/dpi, 1-2*70.0/w/dpi, 1-2*54.0/h/dpi])
ax.loglog(range(len(csizes)), csizes, "r-", clip_on=False);
ax.grid(False)
ax.set_axis_bgcolor("white")
for child in ax.get_children():
if isinstance(child, matplotlib.spines.Spine):
child.set_color('black')
child.set_linewidth(0.5)
ax.tick_params(direction='out', length=4, width=1, colors='k', top=False,
right=False)
ax.tick_params(which="minor", direction='out', length=2, width=0.5,
colors='k', top=False, right=False)
ax.set_xlabel("Clusters ranked by size")
ax.set_ylabel("Cluster sizes")
fig.savefig("Supplementary/cluster-sizes-1.pdf", dpi=200)
def printReport(actual, predicted, score, target_names):
print(classification_report(actual, predicted, target_names=target_names))
fpr, tpr, _ = roc_curve(actual, score)
roc_auc = auc(fpr, tpr)
print('ROC AUC', roc_auc)
print('ROC AUC', roc_auc_score(actual, score))
print('Accuracy', accuracy_score(actual, predicted))
wi,hi, dpi = (4, 4, 100)
fig = plt.figure(figsize=(wi,hi), dpi=dpi)
ax = fig.add_axes([70.0/wi/dpi, 54.0/hi/dpi, 1-2*70.0/wi/dpi, 1-2*54.0/hi/dpi])
ax.plot(fpr, tpr, color='darkorange',
lw=2, label='ROC curve (area = %0.2f)' % roc_auc)
ax.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')
ax.set_xlim([0.0, 1.0])
ax.set_ylim([0.0, 1.05])
ax.set_xlabel('False Positive Rate')
ax.set_ylabel('True Positive Rate')
ax.set_title('Receiver operating characteristic')
ax.legend(loc="lower right")
return ax
def convertScore(mylist):
hs = dict()
for x in mylist:
if (x not in hs):
hs[x] = 1
else:
hs[x] += 1
keys = hs.keys()
values = [0] + list(np.cumsum(hs.values()))
for i in range(len(keys)):
hs[keys[i]] = values[i]
hh = dict()
res = []
for x in mylist:
if (x not in hh):
hh[x] = 0
else:
hh[x] += 1
res += [hh[x] + hs[x]]
return res
def mergeRanks(group, start, exp, weight):
X = np.array([[e[k-start] for e in exp] for k in group])
arr = np.dot(X, np.array(weight))
return arr
def mergeRanks2(group, exp, weight):
X = np.array([[e[k] for e in exp] for k in range(len(group))])
arr = np.dot(X, np.array(weight))
return arr
def getOrder(group, start, exp, weight):
arr = mergeRanks(group, start, exp, weight)
return [group[i] for i in np.argsort(arr)]
def getRanks(gene_groups, h):
expr = []
row_labels = []
ranks = []
for s in gene_groups:
print(len(s), s)
count = 0
avgrank = [0 for i in h.aRange()]
for gn in s:
for id in h.getIDs(gn):
e = h.getExprData(id);
t = h.getThrData(id);
if e[-1] == "":
continue
v = np.array([float(e[i]) for i in h.aRange()])
te = []
for i in h.aRange():
v1 = (float(e[i]) - t[3]) / 3;
if np.std(v) > 0:
v1 = v1 / np.std(v)
avgrank[i-h.start] += v1
te.append(v1)
expr.append(te)
#row_labels.append(h.getSimpleName(id))
row_labels.append(gn)
count += 1
#if count > 100:
# break
ranks.append(avgrank)
return ranks, row_labels, expr
def getRanks2(gene_groups, h):
expr = []
row_labels = []
row_ids = []
row_numhi = []
ranks = []
g_ind = 0
counts = []
for s in gene_groups:
count = 0
avgrank = [0 for i in h.aRange()]
for gn in s:
for id in h.getIDs(gn):
e = h.getExprData(id);
t = h.getThrData(id);
if e[-1] == "":
continue
v = np.array([float(e[i]) if e[i] != "" else 0 for i in h.aRange()])
te = []
sd = np.std(v)
for i in h.aRange():
if (e[i] != ""):
v1 = (float(e[i]) - t[3]) / 3;
if sd > 0:
v1 = v1 / sd
else:
v1 = -t[3]/3/sd
avgrank[i-h.start] += v1
te.append(v1)
expr.append(te)
nm = h.getSimpleName(id)
row_labels.append(nm)
row_ids.append(id)
v1 = [g_ind, sum(v > t[3])]
if g_ind > 3:
v1 = [g_ind, sum(v <= t[3])]
else:
v1 = [g_ind, sum(v > t[3])]
row_numhi.append(v1)
count += 1
#if count > 200:
# break
ranks.append(avgrank)
g_ind += 1
counts += [count]
print(counts)
return ranks, row_labels, row_ids, row_numhi, expr
def getRanks3(gene_groups, h, order):
expr = []
row_labels = []
row_ids = []
row_numhi = []
ranks = []
g_ind = 0
for s in gene_groups:
count = 0
avgrank = [0 for i in order]
for gn in s:
for id in h.getIDs(gn):
e = h.getExprData(id);
if e[-1] == "":
continue
v = np.array([float(e[i]) for i in order])
t = hu.getThrData(v)
te = []
for i in range(len(order)):
v1 = (float(e[order[i]]) - t[3]) / 3;
if np.std(v) > 0:
v1 = v1 / np.std(v)
avgrank[i] += v1
te.append(v1)
expr.append(te)
row_labels.append(h.getSimpleName(id))
row_ids.append(id)
v1 = [g_ind, sum(v > t[3])]
if g_ind > 3:
v1 = [g_ind, sum(v <= t[3])]
else:
v1 = [g_ind, sum(v > t[3])]
row_numhi.append(v1)
count += 1
#if count > 200:
# break
ranks.append(avgrank)
g_ind += 1
return ranks, row_labels, row_ids, row_numhi, expr
def getSName(name):
l1 = re.split(": ", name)
l2 = re.split(" /// ", l1[0])
return l2[0]
def getRanksDf(df_e, df_t):
expr = []
row_labels = []
row_ids = []
row_numhi = []
ranks = []
g_ind = 0
counts = []
for k in range(len(df_e)):
count = 0
order = range(2, df_e[k].shape[1])
avgrank = [0 for i in order]
for j in range(df_e[k].shape[0]):
e = df_e[k].iloc[j,:]
t = df_t[k]['thr2'][j]
if e[-1] == "":
continue
v = np.array([float(e[i]) if e[i] != "" else 0 for i in order])
te = []
sd = np.std(v)
for i in order:
if (e[i] != ""):
v1 = (float(e[i]) - t) / 3;
if sd > 0:
v1 = v1 / sd
else:
v1 = -t/3/sd
avgrank[i-2] += v1
te.append(v1)
expr.append(te)
nm = getSName(e[1])
row_labels.append(nm)
row_ids.append(e[0])
v1 = [g_ind, sum(v > t)]
if g_ind > 3:
v1 = [g_ind, sum(v <= t)]
else:
v1 = [g_ind, sum(v > t)]
row_numhi.append(v1)
count += 1
#if count > 200:
# break
ranks.append(avgrank)
g_ind += 1
counts += [count]
print(counts)
return ranks, row_labels, row_ids, row_numhi, expr
def getNoiseMargin(h, l1, wt1):
ranks = []
g_ind = 0
counts = []
f_ranks = 0
for s in l1:
count = 0
avgrank = 0
for gn in s:
for id in h.getIDs(gn):
e = h.getExprData(id);
t = h.getThrData(id);
if e[-1] == "":
continue
v = np.array([float(e[i]) if e[i] != "" else 0 for i in h.aRange()])
v1 = 0.5/3
std = np.std(v)
if std > 0:
v1 = v1 / std
avgrank += v1 * v1
count += 1
ranks.append(avgrank)
f_ranks += abs(wt1[g_ind]) * avgrank
g_ind += 1
counts += [count]
print(counts)
nm = 0.5/3
if f_ranks > 0:
nm = np.sqrt(f_ranks)
return ranks, nm
def saveList(ofile, l1):
of = open(ofile, "w")
for i in l1:
of.write("\t".join([i]) + "\n")
of.close()
def readList(cfile):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
f_order = []
for line in fp:
line = line.strip();
ll = re.split("[\s]", line);
f_order += [ll[0]]
fp.close();
return f_order
def saveCData(ofile, h, i1, f_ranks):
f_order = dict()
for i in h.aRange():
f_order[i] = ""
for i in range(len(i1)):
f_order[i1[i]] = str(i)
of = open(ofile, "w")
for i in h.aRange():
id1 = h.headers[i]
of.write("\t".join([id1, f_order[i], str(f_ranks[i - h.start])]) + "\n")
of.close()
def saveHeatmapData(ofile, row_labels, row_numhi, row_ids, index, expr):
ind_r = np.array(sorted(range(len(row_labels)), key=lambda x: (row_numhi[x][0], row_numhi[x][1])))
of = open(ofile, "w")
for i in ind_r:
id1 = row_ids[i]
of.write("\t".join([id1, row_labels[i], str(row_numhi[i][0]), str(row_numhi[i][1])] + [str(expr[i][j]) for j in index]) + "\n")
of.close()
def readCData(cfile):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
f_order = []
f_ranks = []
for line in fp:
line = line.strip();
ll = re.split("[\s]", line);
f_order += [ll[1]]
f_ranks += [float(ll[2])]
fp.close();
return f_order, f_ranks
def readHeatmapData(cfile):
if not os.path.isfile(cfile):
print("Can't open file {0} <br>".format(cfile))
exit()
fp = open(cfile, "r")
row_labels, row_numhi, row_ids, expr = [], [], [], []
for line in fp:
line = line.strip();
ll = re.split("\t", line);
row_ids += [ll[0]]
row_labels += [ll[1]]
row_numhi += [ [int(ll[2]), int(ll[3])] ]
expr += [[float(k) for k in ll[4:]]]
fp.close();
return row_labels, row_numhi, row_ids, expr
def barTop(tax, atypes, color_sch1, params):
spaceAnn = 70
widthAnn = 3
tAnn = 1
if 'spaceAnn' in params:
spaceAnn = params['spaceAnn']
if 'widthAnn' in params:
widthAnn = params['widthAnn']
if 'tAnn' in params:
tAnn = params['tAnn']
for i in range(len(atypes)):
tax.add_patch(patches.Rectangle( (i *spaceAnn, 0), widthAnn, 3,
facecolor=color_sch1[i], edgecolor="none", alpha=1.0))
tax.text(i * spaceAnn + widthAnn + tAnn, 1, atypes[i], rotation='horizontal',
ha='left', va='center', fontsize=12)
def plotHeatmap(ofile, data, col_labels, row_labels, params):
genes = []
atypes = []
cval = []
dpi, tl, tw, ts, tsi = (100, 3, 0.25, 0.5, 0)
if 'genes' in params:
genes = params['genes']
if 'atypes' in params:
atypes = params['atypes']
if 'cval' in params:
cval = params['cval']
if 'dpi' in params:
dpi = params['dpi']
if 'tl' in params:
tl = params['tl']
if 'tw' in params:
tw = params['tw']
if 'ts' in params:
ts = params['ts']
if 'tsi' in params:
tsi = params['tsi']
w,h = (12, 12)
dx, dy = (10, 10)
if 'dx' in params:
dx = params['dx']
if 'dy' in params:
dy = params['dy']
if 'w' in params:
w = params['w']
if 'h' in params:
h = params['h']
nAt, nGt = (len(col_labels), len(row_labels))
fig = plt.figure(figsize=(w,h), dpi=dpi)
ax = fig.add_axes([70.0/w/dpi, 54.0/h/dpi, 1-2*70.0/w/dpi, 1-2*54.0/h/dpi])
extent = [0, nAt*dx, 0, nGt*dy]
cvals = [-1, -0.7, -0.4, 0, 0, 0.2, 1]
clrs = ["#210B61","#0B614B","#04B45F", "#D8F781", "#F2F5A9", "red", "#DF0101"]
norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), clrs))
cmap = colors.LinearSegmentedColormap.from_list("BGYR1", tuples)
plt.register_cmap(cmap=cmap)
cvals = [-1, -0.7, -0.4, 0, 0, 0.8, 1]
clrs = ["#210B61","#0B614B","#04B45F", "#D8F781", "#F2F5A9", "red", "#DF0101"]
norm=plt.Normalize(min(cvals),max(cvals))
tuples = list(zip(map(norm,cvals), clrs))
cmap = colors.LinearSegmentedColormap.from_list("BGYR2", tuples)
plt.register_cmap(cmap=cmap)
im = ax.imshow(data, cmap="bwr", interpolation='nearest', vmin=-2.0, vmax=2.0, extent = extent)
ax.tick_params(top=True, bottom=False, labeltop=True, labelbottom=False)
ax.set_xticklabels([])
yticks = []
ylabels = []
if 'rowlabels' in params:
for i in range(len(row_labels)):
g = row_labels[i]
if g in genes:
yticks += [-dy/2 + (len(row_labels) - i) * dy]
ylabels += [ row_labels[i] ]
else:
for g in genes:
if g in row_labels:
i = row_labels.index(g)
yticks += [-dy/2 + (len(row_labels) - i) * dy]
ylabels += [ row_labels[i] ]
si = np.argsort(np.array(yticks))
yiticks = np.array(yticks)[si]
yoticks = np.array(yticks)[si]
ylabels = np.array(ylabels)[si]
sy = 5
if 'sy' in params:
sy = params['sy']
for i in range(1, len(yoticks)):
diff = yoticks[i] - yoticks[i - 1]
if diff < sy*dy:
yoticks[i] = yoticks[i - 1] + sy*dy
for i in range(len(yoticks)):
yoticks[i] = yoticks[i] + tsi
ax.set_yticks(yiticks)
ax.set_yticklabels([])
plt.setp(ax.get_xticklabels(), rotation=-30, ha="right", rotation_mode="anchor")
for edge, spine in ax.spines.items():
spine.set_visible(False)
ax.grid(False)
ax.tick_params(top=False, left=True, bottom=False, right=False,
length=tl, width=tw)
plt.xlim(xmin=0)
trans = blended_transform_factory(ax.transData, ax.transData)
fx, fy = ax.transData.transform((1, 1)) - ax.transData.transform((0, 0))
fx = dpi/fx/72
fy = dpi/fy/72
print(fx, fy)
fx = max(fx, fy)
fy = max(fx, fy)
oo = 2
for i in range(len(yoticks)):
ax.annotate(str(ylabels[i]), xy=(0.0, yoticks[i]),
xycoords=trans,
xytext=(-(2*tl+ts), 0), textcoords='offset points', color="black",
fontsize=8, ha="right")
ax.plot((-(2*tl+ts)*fx, -(tl+ts+oo)*fx, -(tl+oo)*fx, -tl*fx),
(yoticks[i]+4*fy, yoticks[i]+4*fy, yiticks[i], yiticks[i]),
transform=trans,
linestyle='solid', linewidth=tw, color='black', clip_on=False)
oo += 0.5
if (oo > 2):
oo = 0
# Create colorbar
aspect = 20
pad_fraction = 0.5
divider = make_axes_locatable(ax)
width = axes_size.AxesY(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
cax = divider.append_axes("right", size=width, pad=pad)
cbar = plt.colorbar(im, cax=cax)
cbar.ax.set_ylabel("Expression", rotation=-90, va="bottom")
color_sch1 = ["#3B449C", "#B2509E","#EA4824"]
color_sch1 = ["#00CC00", "#EFF51A","#EC008C", "#F7941D", "#808285",
'cyan', 'blue', 'black', 'green', 'red']
if 'acolor' in params:
color_sch1 = params['acolor']
if len(cval) > 0:
width = axes_size.AxesX(ax, aspect=1./aspect)
pad = axes_size.Fraction(pad_fraction, width)
tax = divider.append_axes("top", size=width, pad=pad)
extent = [0, nAt, 0, 5]
tax.axis(extent)
cmap = colors.ListedColormap(color_sch1)
boundaries = range(len(color_sch1) + 1)
norm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)
tax.imshow(cval, interpolation='nearest', cmap=cmap, norm=norm, extent=extent, aspect="auto")
tax.set_xticklabels([])
tax.set_yticklabels([])
tax.tick_params(top=False, left=False, bottom=False, right=False)
if 'tline' in params and params['tline'] == 1:
tax.set_xticks(np.arange(0, nAt, 1))
tax.grid(which='major', alpha=1, linestyle='-', linewidth='1',
color='black')
else:
tax.grid(False)
pad = axes_size.Fraction(0.2, width)
lax = divider.append_axes("top", size=width, pad=pad, frame_on=False)
lax.axison = False
lax.axis(extent)
lax.set_xticklabels([])
lax.set_yticklabels([])
lax.grid(False)
lax.tick_params(top=False, left=False, bottom=False, right=False)
barTop(lax, atypes, color_sch1, params)
fig.savefig(ofile, dpi=dpi)
return ax, divider
def plotTitleBar(cval, atypes, params):
dpi = 100
if 'dpi' in params:
dpi = params['dpi']
w,h = (5, 0.8)
if 'w' in params:
w = params['w']
if 'h' in params:
h = params['h']
color_sch1 = ["#3B449C", "#B2509E","#EA4824"]
color_sch1 = ["#00CC00", "#EFF51A","#EC008C", "#F7941D", "#808285",
'cyan', 'blue', 'black', 'green', 'red']
if 'acolor' in params:
color_sch1 = params['acolor']
if 'cval' in params:
cval = params['cval']
ax = None
if 'ax' in params:
ax = params['ax']
if ax is None:
fig = plt.figure(figsize=(w,h), dpi=dpi)
ax = fig.add_subplot(1, 1, 1)
nAt = len(cval[0])
extent = [0, nAt, 0, 5]
ax.axis(extent)
cmap = colors.ListedColormap(color_sch1)
boundaries = range(len(color_sch1) + 1)
norm = colors.BoundaryNorm(boundaries, cmap.N, clip=True)
ax.imshow(cval, interpolation='nearest', cmap=cmap, \
norm=norm, extent=extent, aspect="auto")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(top=False, left=False, bottom=False, right=False)
ax.set_xticks(np.arange(0, nAt, 1))
ax.grid(which='major', alpha=0.2, linestyle='-', linewidth=0.5,
color='black')
for edge, spine in ax.spines.items():
spine.set_visible(False)
divider = make_axes_locatable(ax)
width = axes_size.AxesX(ax, aspect=1./20)
spaceAnn = 70
widthAnn = 3
tAnn = 1
if 'spaceAnn' in params:
spaceAnn = params['spaceAnn']
if 'widthAnn' in params:
widthAnn = params['widthAnn']
if 'tAnn' in params:
tAnn = params['tAnn']
pad = axes_size.Fraction(0.1, width)
lax = divider.append_axes("top", size="100%", pad="20%", frame_on=False)
lax.axison = False
lax.axis(extent)
lax.set_xticklabels([])
lax.set_yticklabels([])
lax.grid(False)
lax.tick_params(top=False, left=False, bottom=False, right=False)
if 'atypes' in params:
atypes = params['atypes']
barTop(lax, atypes, color_sch1, params)
return ax
def plotDensity(x, atypes, ax = None, color = None):
if color is None:
color = acolor
df = pd.Series(x)
for i in range(len(atypes)):
idx = df[df == i].index
n = len(idx)
l = str(atypes[i]) + "(" + str(n) + ")"
df1 = pd.DataFrame(pd.Series(idx),
columns=[l])
if n <= 1:
continue
if ax is None:
ax = df1.plot.kde(bw_method=1.0, c=color[i], label=l)
else:
ax = df1.plot.kde(bw_method=1.0, ax = ax, c=color[i], label=l)
for i in range(len(atypes)):
idx = df[df == i].index
n = len(idx)
l = str(atypes[i]) + "(" + str(n) + ")"
df1 = pd.DataFrame(pd.Series(idx),
columns=[l])
if n != 1:
continue
df1['y'] = 1
if ax is None:
ax = df1.plot.line(x=l, y='y', c=color[i], label=l)
ax.axvline(x=idx[0], c=color[i])
else:
ax = df1.plot.line(x=l, y='y', ax = ax, c=color[i], label=l)
ax.axvline(x=idx[0], c=color[i])
ax.set_title("Density plot")
ax.set_xlabel("Sample rank")
return ax
def adj_light(color, l=1, s=1):
import matplotlib.colors as mc
import colorsys
try:
c = mc.cnames[color]
except:
c = color
c = colorsys.rgb_to_hls(*mc.to_rgb(c))
return colorsys.hls_to_rgb(c[0], max(0, min(1, l * c[1])),
max(0, min(1, s * c[2])))
def setPlotStyle(params=None):
color_sch1 = acolor
if params is not None and 'acolor' in params:
color_sch1 = params['acolor']
sns.set()
sns.set_style("white")
sns.set_style({'text.color': '.5',
'xtick.color':'.5', 'ytick.color':'.5', 'axes.labelcolor': '.5'})
sns.set_context("notebook")
sns.set_palette([adj_light(c, 1.5, 1) for c in color_sch1])
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)
return m, h
def cAllPvals(lval, atypes):
for i in range(len(lval)):
for j in range(i +1, len(lval)):
if len(lval[i]) <= 0:
continue
if len(lval[j]) <= 0:
continue
#print(lval[i])
#print(lval[j])
t, p = ttest_ind(lval[i],lval[j], equal_var=False)
desc = "%s vs %s %.3g, %.3g" % (atypes[i], atypes[j], t, p)
print(desc)
def plotScores(data, atypes, params):
dpi = 100
if 'dpi' in params:
dpi = params['dpi']
vert = 0
if 'vert' in params:
vert = params['vert']
if vert == 0:
w,h = (2, 0.25 * len(atypes))
else:
w,h = (0.75 * len(atypes), 2)
if 'w' in params:
w = params['w']
if 'h' in params:
h = params['h']
color_sch1 = ["#3B449C", "#B2509E","#EA4824"]
color_sch1 = ["#00CC00", "#EFF51A","#EC008C", "#F7941D", "#808285",
'cyan', 'blue', 'black', 'green', 'red']
if 'acolor' in params:
color_sch1 = params['acolor']
if 'cval' in params: