-
Notifications
You must be signed in to change notification settings - Fork 2
/
draw.py
executable file
·3127 lines (2516 loc) · 117 KB
/
draw.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
"""
draw class for glbase
this is a static class containing various generic methods for drawing etc.
**TODO**
There's a change in direction here. Instead of draw containing lots of generic draw functions
instead its more like a set of wrappers around common ways to do matplotlib stuff.
Drawing inside genelists is fine, as long as it follows this paradigm:
fig = self.draw.getfigure(**kargs)
ax = ...
etc ...
self.draw.do_common_args(fig, **kargs)
filename = fig.savefigure(fig, filename)
It would probably be an improvement if the class part was removed.
Instead a series of methods, exposed by draw.method() at the module level would be better.
This makes them more like helpers for matplotlib than a full fledged object.
This could be easily refactored by changing lines like::
class genelist:
... init
self.draw = draw()
to
self.draw = draw
For now, until I refactor the code to remove lines like that.
Also I want to rename this file gldraw to remove name clashes.
Then it can go::
gldraw.heatmap()
gldraw.scatter()
"""
import sys, os, copy, random, numpy, math, statistics
from collections.abc import Iterable
from numpy import array, arange, mean, max, min, std, float32
from scipy.cluster.hierarchy import distance, linkage, dendrogram
from scipy.spatial.distance import pdist # not in scipy.cluster.hierarchy.distance as you might expect :(
from numpy import polyfit, polyval
from scipy.stats import linregress
import scipy.stats
import numpy as np
import matplotlib
import matplotlib.pyplot as plot
import matplotlib.cm as cm
from cycler import cycler # colours
from matplotlib.colors import ColorConverter, rgb2hex, ListedColormap
import matplotlib.colors as matplotlib_colors
import matplotlib.mlab as mlab
from matplotlib.patches import Ellipse, Circle
import matplotlib.lines as mlines
import matplotlib.gridspec as gridspec
from .adjustText import adjust_text
from . import config, cmaps, utils
from .errors import AssertionError
# This helps AI recognise the text as text:
matplotlib.rcParams['pdf.fonttype']=42
# this is a work around in the implementation of
# scipy.cluster.hierarchy. It does some heavy
# recursion and even with relatively small samples quickly eats the
# available stack.
# I may need to implement this myself later.
# This can deal with ~23,000 x 14 at least.
# No idea on the upper limit.
sys.setrecursionlimit(5000) # 5x larger recursion.
# define static class here.
class draw:
def __init__(self, bad_arg=None, **kargs):
"""please deprecate me"""
pass
def bracket_data(self,
data,
min:int,
max:int):
"""
brackets the data between min and max (ie. bounds the data with no scaling)
This should be a helper?
"""
ran = max - min
newd = copy.deepcopy(data)
for x, row in enumerate(data):
for y, value in enumerate(row):
if value < min:
newd[x][y] = min
elif value > max:
newd[x][y] = max
return(newd)
def heatmap(self,
filename:str = None,
cluster_mode:str = "euclidean",
row_cluster:bool = True,
col_cluster:bool = True,
vmin = 0,
vmax = None,
colour_map=cm.RdBu_r,
col_norm:bool = False,
row_norm:bool = False,
heat_wid = 0.25,
heat_hei = 0.85,
highlights = None,
digitize:bool = False,
border:bool = False,
draw_numbers:bool = False,
draw_numbers_threshold = -9e14,
draw_numbers_fmt = '{:.1f}',
draw_numbers_font_size = 6,
grid:bool = False,
row_color_threshold:bool = None,
col_names:bool = None,
row_colbar:bool = None,
col_colbar:bool = None,
optimal_ordering:bool = True,
dpi:int = 300,
_draw_supplied_cell_labels = False,
**kargs):
"""
my own version of heatmap.
This will draw a dendrogram ... etc...
See the inplace variants as to how to use.
row_names is very important as it describes the order of the data.
cluster_mode = pdist method. = ["euclidean"] ??????!
**Arguments**
data (Required)
the data to use. Should be a 2D array for the heatmap.
filename (Required)
The filename to save the heatmap to.
col_norm (Optional, default=False)
normalise each column of data between 0 .. max => 0.0 .. 1.0
row_norm (Optional, default=False)
similar to the defauly output of heatmap.2 in R, rows are normalised 0 .. 1
row_tree (Optional, default=False)
provide your own tree for drawing. Should be a Scipy tree. row_labels and the data
will be rearranged based on the tree, so don't rearrnge the data yourself.
i.e. the data should be unclustered. Use tree() to get a suitable tree for loading here
col_tree (Optional, default=False)
provide your own tree for ordering the data by. See row_tree for details.
This one is applied to the columns.
row_font_size or yticklabel_fontsize (Optional, default=guess suitable size)
the size of the row labels (in points). If set this will also override the hiding of
labels if there are too many elements.
col_font_size or xticklabel_fontsize (Optional, default=6)
the size of the column labels (in points)
heat_wid (Optional, default=0.25)
The width of the heatmap panel. The image goes from 0..1 and the left most
side of the heatmap begins at 0.3 (making the heatmap span from 0.3 -> 0.55).
You can expand or shrink this value depending wether you want it a bit larger
or smaller.
heat_hei (Optional, default=0.85)
The height of the heatmap. Heatmap runs from 0.1 to heat_hei, with a maximum of 0.9 (i.e. a total of 1.0)
value is a fraction of the entire figure size.
colbar_label (Optional, default=None)
the label to place beneath the colour scale bar
highlights (Optional, default=None)
sometimes the row_labels will be suppressed as there is too many labels on the plot.
But you still want to highlight a few specific genes/rows on the plot.
Send a list to highlights that matches entries in the row_names.
digitize (Optional, default=False)
change the colourmap (either supplied in cmap or the default) into a 'discretized' version
that has large blocks of colours, defined by the number you send to discretize.
Note that disctretize only colorises the comlourmap and the data is still clustered on the underlying numeric data.
You probably want to use expression.digitize() for that.
imshow (Optional, default=False)
optional ability to use images for the heatmap. Currently experimental it is
not always supported in the vector output files.
draw_numbers (Optional, default=False)
draw the values of the heatmaps in each cell see also draw_numbers_threshold
draw_numbers_threshold (Optional, default=-9e14)
draw the values in the cell if > draw_numbers_threshold
draw_numbers_fmt (Optional, default= '{:.1f}')
string formatting for the displayed values
draw_numbers_font_size (Optional, default=6)
the font size for the numbers in each cell
_draw_supplied_cell_labels (Optional, default=False)
semi-undocumented function to draw text in each cell.
Please provide a 2D list, with the same dimensions as the heatmap, and this text
will be drawn in each cell. Useful for tings like drawing a heatmap of expression
and then overlaying p-values on top of all significant cells.
col_colbar (Optional, default=None)
add a colourbar for the samples names. This is designed for when you have too many
conditions, and just want to show the different samples as colours
Should be a list of colours in the same order as the condition names
row_colbar (Optional, default=None)
add a colourbar for the samples names. This is designed for when you have too many
conditions, and just want to show the different samples as colours
Should be a list of colours in the same order as the row names.
Note that unclustered data goes from the bottom to the top!
optimal_ordering (Optional, default=True)
See https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.dendrogram.html
**Returns**
The actual filename used to save the image.
"""
assert filename, "heatmap() - no specified filename"
# preprocess data
if isinstance(kargs["data"], dict):
# The data key should be a serialised Dict, I need to make an array.
data = array([kargs["data"][key] for key in col_names]).T
# If the lists are not square then this makes a numpy array of lists.
# Then it will fail below with a strange error.
# Let's check to make sure its square:
ls = [len(kargs["data"][key]) for key in col_names]
if not all(x == ls[0] for x in ls):
raise Exception("Heatmap data not Square")
else:
# the default is a numpy like array object which can be passed right through.
data = array(kargs["data"], dtype=float32)
if col_colbar:
assert len(col_colbar) == data.shape[1], "col_colbar not the same length as data.shape[1]"
if row_colbar:
assert len(row_colbar) == data.shape[0], "row_colbar not the same length as data.shape[0]"
if col_norm:
for col in range(data.shape[1]):
data[:,col] /= float(data[:,col].max())
if row_norm:
for row in range(data.shape[0]):
mi = min(data[row,:])
ma = max(data[row,:])
data[row,:] = (data[row,:]-mi) / (ma-mi)
if "square" in kargs and kargs["square"]:
# make the heatmap square, for e.g. comparison plots
left_side_tree = [0.15, 0.15, 0.10, 0.75]
top_side_tree = [0.25, 0.90, 0.55, 0.08]
heatmap_location = [0.25, 0.15, 0.55, 0.75]
loc_col_colbar = [] # not supported?
else:
# positions of the items in the plot:
# heat_hei needs to be adjusted. as 0.1 is the bottom edge. User wants the bottom
# edge to move up rather than the top edge to move down.
if row_cluster:
mmheat_hei = 0.93 - heat_hei # this is also the maximal value (heamap edge is against the bottom)
left_side_tree = [0.01, mmheat_hei, 0.186, heat_hei]
top_side_tree = [0.198, 0.932, heat_wid, 0.044]
heatmap_location = [0.198, mmheat_hei, heat_wid, heat_hei]
if col_colbar: # Slice a little out of the tree
top_side_tree = [0.198, 0.946, heat_wid, 0.040]
loc_col_colbar = [0.198, mmheat_hei+heat_hei+0.002, heat_wid, 0.012]
if row_colbar: # Slice a little out of the tree
left_side_tree = [0.01, mmheat_hei, 0.186-0.018, heat_hei]
loc_row_colbar = [0.198-0.016, mmheat_hei, 0.014, heat_hei]
else:
# If no row cluster take advantage of the extra width available, but shift down to accomodate the scalebar
mmheat_hei = 0.89 - heat_hei # this is also the maximal value (heamap edge is against the bottom)
#top_side_tree = [0.03, 0.852, heat_wid, 0.044]
top_side_tree = [0.03, 0.891, heat_wid, 0.020]
heatmap_location = [0.03, mmheat_hei, heat_wid, heat_hei]
loc_row_colbar = [0.03-0.016, mmheat_hei, 0.014, heat_hei] # No need to cut the tree, just squeeze i into the left edge
if col_colbar:
top_side_tree = [0.03, 0.906, heat_wid, 0.025] # squeeze up the colbar
loc_col_colbar = [0.03, 0.892, heat_wid, 0.012] #
scalebar_location = [0.01, 0.98, 0.14, 0.015]
# set size of the row text depending upon the number of items:
row_font_size = 0
if "row_font_size" in kargs:
row_font_size = kargs["row_font_size"]
elif "yticklabel_fontsize" in kargs:
row_font_size = kargs["yticklabel_fontsize"]
else:
if "row_names" in kargs and kargs["row_names"]:
if len(kargs["row_names"]) <= 100:
row_font_size = 6
elif len(kargs["row_names"]) <= 150:
row_font_size = 4
elif len(kargs["row_names"]) <= 200:
row_font_size = 3
elif len(kargs["row_names"]) <= 300:
row_font_size = 2
else:
if not highlights: # if highlights, don't kill kargs["row_names"] and don't print warning.
config.log.warning("heatmap has too many row labels to be visible. Suppressing row_labels")
kargs["row_names"] = None
row_font_size = 1
else:
row_font_size = 0
if highlights:
highlights = list(set(highlights)) # Make it unique, because sometimes duplicates get through and it erroneously reports failure.
found = [False for i in highlights]
if row_font_size == 0:
row_font_size = 5 # IF the above sets to zero, reset to a reasonable value.
if "row_font_size" in kargs: # but override ir row_font_size is being used.
row_font_size = kargs["row_font_size"] # override size if highlights == True
# I suppose this means you could do row_font_size = 0 if you wanted.
# blank out anything not in row_names:
new_row_names = []
for item in kargs["row_names"]:
if item in highlights:
new_row_names.append(item)
index = highlights.index(item)
found[index] = True
else:
new_row_names.append("")
kargs["row_names"] = new_row_names
for i, e in enumerate(found): # check all highlights found:
if not e:
config.log.warning("highlight: '%s' not found" % highlights[i])
col_font_size = 6
if "col_font_size" in kargs:
col_font_size = kargs["col_font_size"]
elif "xticklabel_fontsize" in kargs:
col_font_size = kargs["xticklabel_fontsize"]
if "bracket" in kargs: # done here so clustering is performed on bracketed data
data = self.bracket_data(data, kargs["bracket"][0], kargs["bracket"][1])
vmin = kargs["bracket"][0]
vmax = kargs["bracket"][1]
if not vmax:
"""
I must guess the vmax value. I will do this by working out the
mean then determining a symmetric colour distribution
"""
try:
me = statistics.mean(data)
except (AttributeError, TypeError):
me = data.mean()
ma = abs(me - max(data))
mi = abs(min(data) + me)
if ma > mi:
vmin = me - ma
vmax = me + ma
else:
vmin = me - mi
vmax = me + mi
if "row_cluster" in kargs:
row_cluster = kargs["row_cluster"]
if "col_cluster" in kargs:
col_cluster = kargs["col_cluster"]
if not "colbar_label" in kargs:
kargs["colbar_label"] = ""
if "cmap" in kargs:
colour_map = kargs["cmap"]
if digitize:
colour_map = cmaps.discretize(colour_map, digitize)
# a few grace and sanity checks here;
if len(data) <= 1: row_cluster = False # clustering with a single point?
if len(data[0]) <= 1: col_cluster = False # ditto.
if not "aspect" in kargs:
kargs["aspect"] = "long"
fig = self.getfigure(**kargs)
row_order = False
if row_cluster:
# ---------------- Left side plot (tree) -------------------
ax1 = fig.add_subplot(141)
# from scipy;
# generate the dendrogram
if "row_tree" in kargs:
assert "dendrogram" in kargs["row_tree"], "row_tree appears to be improperly formed ('dendrogram' is missing)"
Z = kargs["row_tree"]["linkage"]
else:
Y = pdist(data, metric=cluster_mode)
Z = linkage(Y, method='complete', metric=cluster_mode, optimal_ordering=optimal_ordering)
if row_color_threshold:
row_color_threshold = row_color_threshold*((Y.max()-Y.min())+Y.min()) # Convert to local threshold.
a = dendrogram(Z, orientation='left', color_threshold=row_color_threshold, ax=ax1)
ax1.axvline(row_color_threshold, color="grey", ls=":")
else:
a = dendrogram(Z, orientation='left', ax=ax1)
ax1.set_position(left_side_tree)
ax1.set_frame_on(False)
ax1.set_xticklabels("")
ax1.set_yticklabels("")
ax1.set_ylabel("")
# clear the ticks.
ax1.tick_params(top=False, bottom=False, left=False, right=False)
# Use the tree to reorder the data.
row_order = [int(v) for v in a['ivl']]
# resort the data by order;
if "row_names" in kargs and kargs["row_names"]: # make it possible to cluster without names
newd = []
new_row_names = []
for index in row_order:
newd.append(data[index])
new_row_names.append(kargs["row_names"][index])
data = array(newd)
kargs["row_names"] = new_row_names
else: # no row_names, I still want to cluster
newd = []
for index in row_order:
newd.append(data[index])
data = array(newd)
if row_colbar:
row_colbar = [row_colbar[index] for index in row_order]
col_order = False
if col_cluster:
# ---------------- top side plot (tree) --------------------
transposed_data = data.T
ax2 = fig.add_subplot(142)
ax2.set_frame_on(False)
ax2.set_position(top_side_tree)
if "col_tree" in kargs and kargs["col_tree"]:
assert "dendrogram" in kargs["col_tree"], "col_tree appears to be improperly formed ('dendrogram' is missing)"
#if kargs["col_names"] and kargs["col_names"]:
# assert len(kargs["col_tree"]["Z"]) == len(kargs["col_names"]), "tree is not the same size as the column labels"
Z = kargs["col_tree"]["linkage"]
else:
Y = pdist(transposed_data, metric=cluster_mode)
Z = linkage(Y, method='complete', metric=cluster_mode, optimal_ordering=optimal_ordering)
a = dendrogram(Z, orientation='top', ax=ax2)
ax2.tick_params(top=False, bottom=False, left=False, right=False)
ax2.set_xticklabels("")
ax2.set_yticklabels("")
col_order = [int(v) for v in a["ivl"]]
# resort the data by order;
if col_names: # make it possible to cluster without names
newd = []
new_col_names = []
for index in col_order:
newd.append(transposed_data[index])
new_col_names.append(col_names[index])
data = array(newd).T # transpose back orientation
col_names = new_col_names
if col_colbar:
col_colbar = [col_colbar[index] for index in col_order]
# ---------------- Second plot (heatmap) -----------------------
ax3 = fig.add_subplot(143)
if 'imshow' in kargs and kargs['imshow']:
ax3.set_position(heatmap_location) # must be done early for imshow
hm = ax3.imshow(data, cmap=colour_map, vmin=vmin, vmax=vmax, aspect="auto",
origin='lower', extent=[0, data.shape[1], 0, data.shape[0]],
interpolation=config.get_interpolation_mode(filename)) # Yes, it really is nearest. Otherwise it will go to something like bilinear
else:
edgecolors = 'none'
if grid:
edgecolors = 'black'
hm = ax3.pcolormesh(data, cmap=colour_map, vmin=vmin, vmax=vmax, antialiased=False, edgecolors=edgecolors, lw=0.4)
if col_colbar:
new_colbar = []
for c in col_colbar:
if '#' in c:
new_colbar.append([utils.hex_to_rgb(c)]) # needs to be tupled?
else: # must be a named color:
new_colbar.append([matplotlib_colors.to_rgb(c)])
col_colbar = numpy.array(new_colbar)#.transpose(1,0,2)
ax4 = fig.add_axes(loc_col_colbar)
if 'imshow' in kargs and kargs['imshow']:
col_colbar = numpy.array(new_colbar).transpose(1,0,2)
ax4.imshow(col_colbar, aspect="auto",
origin='lower', extent=[0, len(col_colbar), 0, 1],
interpolation=config.get_interpolation_mode(filename))
else:
col_colbar = numpy.array(new_colbar)
# unpack the oddly contained data:
col_colbar = [tuple(i[0]) for i in col_colbar]
cols = list(set(col_colbar))
lcmap = ListedColormap(cols)
col_colbar_as_col_indeces = [cols.index(i) for i in col_colbar]
ax4.pcolormesh(numpy.array([col_colbar_as_col_indeces,]), cmap=lcmap,
vmin=min(col_colbar_as_col_indeces), vmax=max(col_colbar_as_col_indeces),
antialiased=False, edgecolors=edgecolors, lw=0.4)
ax4.set_frame_on(False)
ax4.tick_params(top=False, bottom=False, left=False, right=False)
ax4.set_xticklabels("")
ax4.set_yticklabels("")
if row_colbar:
new_colbar = []
for c in row_colbar:
if '#' in c:
new_colbar.append([utils.hex_to_rgb(c)]) # needs to be tupled?
else: # must be a named color:
new_colbar.append([matplotlib_colors.to_rgb(c)])
row_colbar = numpy.array(new_colbar)
ax4 = fig.add_axes(loc_row_colbar)
if 'imshow' in kargs and kargs['imshow']:
ax4.imshow(row_colbar, aspect="auto",
origin='lower', extent=[0, len(row_colbar), 0, 1],
interpolation=config.get_interpolation_mode(filename))
else:
# unpack the oddly contained data:
row_colbar = [tuple(i[0]) for i in row_colbar]
cols = list(set(row_colbar))
lcmap = ListedColormap(cols)
row_colbar_as_col_indeces = [cols.index(i) for i in row_colbar]
ax4.pcolormesh(numpy.array([row_colbar_as_col_indeces,]).T, cmap=lcmap,
vmin=min(row_colbar_as_col_indeces), vmax=max(row_colbar_as_col_indeces),
antialiased=False, edgecolors=edgecolors, lw=0.4)
ax4.set_frame_on(False)
ax4.tick_params(top=False, bottom=False, left=False, right=False)
ax4.set_xticklabels("")
ax4.set_yticklabels("")
if draw_numbers:
for x in range(data.shape[0]):
for y in range(data.shape[1]):
if data[x, y] >= draw_numbers_threshold:
if '%' in draw_numbers_fmt:
ax3.text(y+0.5, x+0.5, draw_numbers_fmt, size=draw_numbers_font_size,
ha='center', va='center')
else:
ax3.text(y+0.5, x+0.5, draw_numbers_fmt.format(data[x, y]), size=draw_numbers_font_size,
ha='center', va='center')
if _draw_supplied_cell_labels:
assert len(_draw_supplied_cell_labels) == data.shape[0], '_draw_supplied_cell_labels X does not equal shape[1]'
assert len(_draw_supplied_cell_labels[0]) == data.shape[1], '_draw_supplied_cell_labels Y does not equal shape[0]'
# This hack will go wrong if col_cluster or row_cluster is True
# So fix the ordering:
x_order = row_order if row_order else range(data.shape[0])
y_order = col_order if col_order else range(data.shape[1])
print(x_order, y_order)
for xp, x in zip(range(data.shape[0]), x_order):
for yp, y in zip(range(data.shape[1]), y_order):
val = _draw_supplied_cell_labels[x][y]
if draw_numbers_threshold and val < draw_numbers_threshold:
ax3.text(yp+0.5, xp+0.5, draw_numbers_fmt.format(val), size=draw_numbers_font_size,
ha='center', va='center')
ax3.set_frame_on(border)
ax3.set_position(heatmap_location)
if col_names:
ax3.set_xticks(arange(len(col_names))+0.5)
ax3.set_xticklabels(col_names, rotation="vertical")
ax3.set_xlim([0, len(col_names)])
if "square" in kargs and kargs["square"]:
ax3.set_xticklabels(col_names, rotation="vertical")
else:
ax3.set_xlim([0,data.shape[1]])
if "row_names" in kargs and kargs["row_names"]:
ax3.set_yticks(arange(len(kargs["row_names"]))+0.5)
ax3.set_ylim([0, len(kargs["row_names"])])
ax3.set_yticklabels(kargs["row_names"])
else:
ax3.set_ylim([0,data.shape[0]])
ax3.set_yticklabels("")
ax3.yaxis.tick_right()
ax3.tick_params(top=False, bottom=False, left=False, right=False)
[t.set_fontsize(row_font_size) for t in ax3.get_yticklabels()] # generally has to go last.
[t.set_fontsize(col_font_size) for t in ax3.get_xticklabels()]
# Make it possible to blank with x/yticklabels
if "xticklabels" in kargs:
ax3.set_xticklabels(kargs["xticklabels"])
if "yticklabels" in kargs:
ax3.set_yticklabels(kargs["yticklabels"])
ax0 = fig.add_subplot(144)
ax0.set_position(scalebar_location)
ax0.set_frame_on(False)
cb = fig.colorbar(hm, orientation="horizontal", cax=ax0)
cb.set_label(kargs["colbar_label"], fontsize=6)
cb.ax.tick_params(labelsize=4)
return {
"real_filename": self.savefigure(fig, filename, dpi=dpi),
"reordered_cols": col_names,
"reordered_rows": kargs["row_names"],
"reordered_data": data
}
def heatmap2(self, filename=None, cluster_mode="euclidean", row_cluster=True, col_cluster=True,
vmin=0, vmax=None, colour_map=cm.plasma, col_norm=False, row_norm=False, heat_wid=0.25,
imshow=False,
**kargs):
"""
**Purpose**
This version of heatmap is a simplified heatmap. It does not accept colnames, row_names
and it outputs the heatmap better centred and expanded to fill the available space
it does not draw a tree and (unlike normal heatmap) draws a black border
around. Also, the scale-bar is optional, and by default is switched off.
It is ideal for drawing sequence tag pileup heatmaps. For that is what it was originally made for
(see track.heatmap())
**Arguments**
data (Required)
the data to use. Should be a 2D array for the heatmap.
filename (Required)
The filename to save the heatmap to.
col_norm (Optional, default=False)
normalise each column of data between 0 .. max => 0.0 .. 1.0
row_norm (Optional, default=False)
similar to the defauly output of heatmap.2 in R, rows are normalised 0 .. 1
colbar_label (Optional, default="expression")
the label to place beneath the colour scale bar
colour_map (Optional, default=afmhot)
a matplotlib cmap for colour
imshow (Optional, default=False)
optional ability to use images for the heatmap. Currently experimental it is
not always supported in the vector output files.
**Returns**
The actual filename used to save the image.
"""
assert filename, "heatmap() - no specified filename"
data = array(kargs["data"], dtype=float32) # heatmap2 can only accept a numpy array
if col_norm:
for col in range(data.shape[1]):
data[:,col] /= float(data[:,col].max())
if row_norm:
for row in range(data.shape[0]):
mi = min(data[row,:])
ma = max(data[row,:])
data[row,:] = (data[row,:]-mi) / (ma-mi)
# positions of the items in the plot:
heatmap_location = [0.05, 0.01, 0.90, 0.90]
scalebar_location = [0.05, 0.97, 0.90, 0.02]
if "bracket" in kargs: # done here so clustering is performed on bracketed data
data = self.bracket_data(data, kargs["bracket"][0], kargs["bracket"][1])
vmin = kargs["bracket"][0]
vmax = kargs["bracket"][1]
else:
vmin = data.min()
vmax = data.max()
if not "colbar_label" in kargs:
kargs["colbar_label"] = "density"
if "cmap" in kargs: colour_map = kargs["cmap"]
# a few grace and sanity checks here;
if len(data) <= 1: row_cluster = False # clustering with a single point?
if len(data[0]) <= 1: col_cluster = False # ditto.
if "size" not in kargs:
kargs["size"] = (3,6)
fig = self.getfigure(**kargs)
# ---------------- (heatmap) -----------------------
ax3 = fig.add_subplot(111)
if imshow:
ax3.set_position(heatmap_location) # must be done early for imshow
hm = ax3.imshow(data, cmap=colour_map, vmin=vmin, vmax=vmax, aspect="auto",
origin='lower', extent=[0, data.shape[1], 0, data.shape[0]],
interpolation=config.get_interpolation_mode(filename))
else:
hm = ax3.pcolormesh(data, cmap=colour_map, vmin=vmin, vmax=vmax, antialiased=False)
#ax3.set_frame_on(True)
ax3.set_position(heatmap_location)
ax3.set_xlim([0,data.shape[1]])
ax3.set_ylim([0,data.shape[0]])
ax3.set_yticklabels("")
ax3.yaxis.tick_right()
ax3.tick_params(top=False, bottom=False, left=False, right=False)
[t.set_fontsize(1) for t in ax3.get_yticklabels()] # generally has to go last.
[t.set_fontsize(1) for t in ax3.get_xticklabels()]
ax0 = fig.add_subplot(144)
ax0.set_position(scalebar_location)
ax0.set_frame_on(False)
cb = fig.colorbar(hm, orientation="horizontal", cax=ax0, cmap=colour_map)
cb.set_label(kargs["colbar_label"])
[label.set_fontsize(5) for label in ax0.get_xticklabels()]
return(self.savefigure(fig, filename))
def _heatmap_and_plot(self,
peak_data=None,
match_key=None,
arraydata=None,
peakdata=None,
random_backgrounds=None,
bin=None,
draw_frames=False,
plot_bracket=None,
imshow=False,
**kargs):
"""
Required:
filename
the filename to save the png to.
array_data
the data, usually serialisedArrayDataDict
peak_data
locations of the TF binding sites.
match_key
the key to match between the array and the peaklist.
draw_frames (Optional, default=False)
draw a frame around each of the elements in the figure.
imshow (Optional, default=False)
heatmaps are drawn using imshow, not individual squares
window
the size of the moving average window (defaults to 10% of the list)
If you specify a number it is the number of elements in the list
and not a percentage.
use_tag_score (defaults to False)
use the key set by "use_tag_score" to determine the plot intesity for
the peakdata. By default if the array and the peaklist
match then it simply uses the
"""
# ----------------------defaults:
vmin = 0.0
vmax = 1.0
# ----------------------modify defaults:
if "window" in kargs: moving_window = kargs["window"]
if "match_key" in kargs: match_key = kargs["match_key"]
if "bracket" in kargs:
vmin = kargs["bracket"][0]
vmax = kargs["bracket"][1]
if "cmap" in kargs:
cmap = kargs["cmap"]
else:
cmap = cm.RdBu_r
# Positions of the items in the figure:
left_heatmap = [0.10, 0.05, 0.20, 0.85]
scale_bar = [0.10, 0.97, 0.30, 0.02]
binding_map = [0.32, 0.05, 0.08, 0.85]
freq_plot = [0.42, 0.05, 0.4, 0.85]
# Now do the plots:
fig = self.getfigure(**kargs)
# heatmap ------------------------------------------------------
ax0 = fig.add_subplot(141) # colour bar goes in here.
ax0.set_frame_on(draw_frames)
ax0.set_position(scale_bar)
ax0.tick_params(left=False, right=False)
ax1 = fig.add_subplot(142)
plot_data = arraydata.T
if imshow:
ax1.set_position(left_heatmap)
#hm = ax1.imshow(plot_data, cmap=cmap, vmin=vmin, vmax=vmax,
# interpolation=config.get_interpolation_mode(kargs["filename"]))
hm = ax1.imshow(
plot_data,
cmap=cmap,
vmin=vmin,
vmax=vmax,
aspect="auto",
origin='lower',
extent=[0, plot_data.shape[1], 0, plot_data.shape[0]],
interpolation=config.get_interpolation_mode(kargs["filename"])
)
else:
hm = ax1.pcolormesh(plot_data, cmap=cmap, vmin=vmin, vmax=vmax, antialiased=False)
ax1.set_frame_on(draw_frames)
ax1.set_position(left_heatmap)
if "col_names" in kargs and kargs["col_names"]:
ax1.set_xticks(arange(len(kargs["col_names"]))+0.5)
ax1.set_xticklabels(kargs["col_names"])
ax1.set_xlim([0, len(kargs["col_names"])])
else:
ax1.set_xlim([0,plot_data.shape[1]])
ax1.set_xticklabels("")
# Don't draw labels on the rows. Makes no sense in this plot;
ax1.set_ylim([0,plot_data.shape[0]])
ax1.set_yticklabels("")
ax1.yaxis.tick_left()
ax1.tick_params(top=False, bottom=False, left=False, right=False)
[t.set_fontsize(6) for t in ax1.get_yticklabels()] # generally has to go last.
[t.set_fontsize(6) for t in ax1.get_xticklabels()]
fig.colorbar(hm, cax=ax0, orientation="horizontal")
for label in ax0.get_xticklabels():
label.set_fontsize(6)
# binding map --------------------------------------------------
ax2 = fig.add_subplot(143)
a = array(bin) # reshape the bin array
a.shape = 1,len(bin)
if imshow:
ax2.set_position(binding_map)
hm = ax2.imshow(
a.T,
cmap=cm.binary,
aspect="auto",
origin='lower',
extent=[0, a.T.shape[1], 0, a.T.shape[0]],
interpolation=config.get_interpolation_mode(kargs["filename"])
)
else:
hm = ax2.pcolormesh(a.T, cmap=cm.binary, antialiased=True)
ax2.set_frame_on(draw_frames)
ax2.set_position(binding_map)
ax2.set_yticks(arange(len(kargs["row_names"]))+0.5)
ax2.set_yticklabels("")
ax2.set_xticklabels("")
ax2.set_xlim([0,1])
ax2.set_ylim([0,len(kargs["row_names"])])
ax2.yaxis.tick_left()
ax2.tick_params(top=False, bottom=False, left=False, right=False)
# linegraph -----------------------------------------------------
ax3 = fig.add_subplot(144)
if random_backgrounds:
ms = []
ss = []
for b in random_backgrounds:
ax3.plot(b, arange(len(peakdata)), lw=0.5, c='lightgrey', alpha=0.5)
ms.append(statistics.mean(b))
ss.append(statistics.stdev(b))
m = statistics.mean(ms)
s = statistics.mean(ss)
ax3.axvline(x=m, color='grey', linestyle=":", linewidth=1)
ax3.axvline(x=(m+s), color='r', linestyle=":", linewidth=0.5)
ax3.axvline(x=(m-s), color='r', linestyle=":", linewidth=0.5)
ax3.plot(peakdata, arange(len(peakdata))) # doesn't use the movingAverage generated x, scale it across the entire graph.
ax3.set_frame_on(draw_frames)
ax3.set_position(freq_plot)
ax3.set_yticklabels("")
ax3.set_ylim([0, len(peakdata)])
pad = s*2
ax3.set_xlim([min(peakdata)-pad, (max(peakdata))+pad])
ax3.tick_params(left=False, right=False)
[item.set_markeredgewidth(0.2) for item in ax3.xaxis.get_ticklines()]
[t.set_fontsize(6) for t in ax3.get_xticklabels()]
if plot_bracket:
ax3.set_xlim(plot_bracket)
return self.savefigure(fig, kargs["filename"], dpi=600)
def multi_heatmap(self,
list_of_data=None,
filename=None,
groups=None,
titles=None,
vmin=0, vmax=None,
colour_map=cm.YlOrRd,
col_norm=False,
row_norm=False,
heat_wid=0.25,
frames=True,
imshow=False,
size=None,
dpi:int = 80,
**kargs):
"""
**Purpose**
Draw a multi-heatmap figure, i.e. containing multiple heatmaps. And also supports a
last column indicating the different groups the blocks belong to.
**Arguments**
list_of_data (Required)
Should be a list of 2D arrays ALL OF THE SAME SIZE! and all must be numpy arrays.
groups (Optional)
A list indicating which group each row belongs to.
filename (Required)
The filename to save the heatmap to.
colbar_label (Optional, default="expression")
the label to place beneath the colour scale bar
size (Optional, default=None)
override the guessed figure size with your own dimensions.
**Returns**
The actual filename used to save the image.
"""
assert filename, "heatmap() - no specified filename"
# work out a suitable size for the figure.
num_heatmaps = len(list_of_data)
if size: