-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvisualizations.py
1676 lines (1444 loc) · 58.2 KB
/
visualizations.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
import os
import hashlib
# third party, numpy and matplotlib
import numpy as np
import nibabel as nib
from matplotlib import cm, colors
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.gridspec as gridspec
# brainnets
from brainnets import settings, aux, dataio
from brainnets import netgen, communities
from brainnets import fname_conventions as fnc
# verkko
from verkko.plots import alluvial
from verkko.plots import colorhelp
from verkko.permtests import measures
from verkko.permtests import ptests
from verkko.permtests import corrections
def viz_data_on_brain_using_slices(
in_data_nii_fname="",
T=1E-300,
slices="xyz",
bg_nii_fname="/usr/share/fsl/data/standard/MNI152_T1_2mm_brain.nii.gz",
colormap=None,
slice_step=1,
cmap_lims=None):
"""
Plotting the indata on top of the MNI template brain.
Parameters
----------
in_data_nii_fname : str
path to the .nii image which will be visualized
T : float
All values with abs(val) < T are not shown.
slices : str
string of all of the slice directions, e.g. ("yz") for y and z slices
bg_nii_fname : str
which background image to use
colormap: matplotlib colormap
Colormap to use, if None, a suitable colormap for
visualizing positiv and negative t-values is used.
cmap_lims : tuple (or list)
cmap_lims[0] and cmap_lims[1] correspond to the the minimum
and maximum values of the colorbar
"""
in_data = nib.load(in_data_nii_fname)
in_vol = in_data.get_data()
bg_data = nib.load(bg_nii_fname)
bg_vol = bg_data.get_data()
in_data_min = np.min(in_vol)
in_data_max = np.max(in_vol)
in_data_abs_max = np.maximum(np.abs(in_data_min), in_data_max)
using_default_colormap = False
if colormap is None:
using_default_colormap = True
lowcut = (0.5 - T / in_data_abs_max * 0.5)
highcut = (0.5 + T / in_data_abs_max * 0.5)
# colormap combination of builtin winter & autumn colormaps
cdict = {
'blue': ((0.0, 1.0, 1.0),
(lowcut, 0.5, 0.7),
(highcut, 0.7, 0.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 0.0, 0.0),
(lowcut, 1.0, 0.7),
(highcut, 0.7, 0.0),
(1.0, 1.0, 1.0)),
'red': ((0.0, 0.0, 0.0),
(lowcut, 0.0, 0.7),
(highcut, 0.7, 1.0),
(1.0, 1.0, 1.0)),
'alpha': ((0.0, 0.0, 0.0),
(lowcut, 0.0, 0.0),
(highcut, 0.0, 1.0),
(1.0, 1.0, 0.0))
}
colormap = LinearSegmentedColormap('custom', cdict, N=1024)
step_size = slice_step * 3
slice_ranges = {'x': range(16, 78, step_size), # 84,step_size),
'y': range(12, 95, step_size),
'z': range(8, 76, step_size)
}
slicedir2dim = {'x': 0, 'y': 1, 'z': 2}
in_vol = np.array(in_vol)
if cmap_lims is not None:
vmin = cmap_lims[0]
vmax = cmap_lims[1]
else:
vmax = in_data_abs_max
vmin = -in_data_abs_max
for slice_dir in slices:
slice_range = slice_ranges[slice_dir]
n_slices = len(slice_range)
in_vol_view = in_vol.swapaxes(0, slicedir2dim[slice_dir])
bg_vol_view = bg_vol.swapaxes(0, slicedir2dim[slice_dir])
nrows = n_slices / 7 + bool(n_slices % 7)
ncols = n_slices / nrows + bool(n_slices % nrows) + 1
gs = gridspec.GridSpec(nrows, ncols)
fig = plt.figure(figsize=(15, 6))
# 12, step=3
for j, i in enumerate(slice_range): # 0,len(in_vol[0])):#,10):
# print j%(ncols-1), j/(ncols-1)
ax = fig.add_subplot(gs[j / (ncols - 1), j % (ncols - 1)])
# axes have been swapped accordingly before
Z = in_vol_view[i, :, :]
if slice_dir in "yz":
bg = bg_vol_view[i, :, :]
else:
bg = bg_vol_view[-i, :, :]
cond = (-T < Z) & (Z < T)
Z_mask = np.ma.masked_where(cond, Z)
# else:
# cond = (Z < 0)
# Z_mask= np.ma.masked_where(cond, Z)
if slice_dir in "x":
ax.imshow(
bg.T, cmap="gray", origin="lower", interpolation="nearest")
im = ax.imshow(Z_mask.T, cmap=colormap, origin="lower",
interpolation='nearest', alpha=1.0,
vmax=vmax, vmin=vmin)
if slice_dir in "y":
ax.imshow(
bg.T[:, ::-1], cmap="gray", origin="lower",
interpolation="nearest")
im = ax.imshow(Z_mask.T, cmap=colormap, origin="lower",
interpolation='nearest', alpha=1.0,
vmax=vmax, vmin=vmin)
if slice_dir == "z":
ax.imshow(
bg[:, ::-1], cmap="gray", origin="lower",
interpolation="nearest")
im = ax.imshow(Z_mask, cmap=colormap, origin="lower",
interpolation="nearest", vmax=vmax, vmin=vmin)
# add left/right texts
if slice_dir == 'x':
if j == 0:
ax.text(0.1, 0.5, 'L', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,
color="w", weight="bold")
if j == len(slice_range) - 1:
ax.text(0.9, 0.5, 'R', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,
color="w", weight="bold")
if slice_dir in 'yz':
ax.text(0.1, 0.9, 'L', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,
color="0.5", weight="bold")
ax.text(0.9, 0.9, 'R', horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,
color="0.5", weight="bold")
dim = slicedir2dim[slice_dir]
slice_coords = np.zeros(3, dtype=np.int16)
slice_coords[dim] = i
mni_coords = aux.space2MNI(slice_coords)[dim]
ax.text(0.97, 0.1, str(mni_coords), horizontalalignment='right',
verticalalignment='center', transform=ax.transAxes,
color="0.5", weight="bold")
ax.set_xticks([])
ax.set_yticks([])
# colorbar axes
cax = fig.add_axes([0.9, 0.1125, 0.02, 0.775])
cbar = plt.colorbar(im, cax=cax)
if not using_default_colormap:
maxZ = np.nanmax(in_vol_view)
print maxZ
if maxZ - int(maxZ) < 1e-6:
print maxZ
if maxZ < 16:
ticks = np.arange(1, maxZ + 2)
cbar.set_ticks(ticks)
plt.tight_layout(w_pad=0.2)
return fig
def viz_nodewise_vals_using_slices(
node_val_array, node_info_fname, blacklist_fname,
vals_blacklist_filtered=False,
default_value=0, slicedirs="xyz", cmap=None,
cmap_lims=None, T=1e-300, slice_step=1):
"""
Plots the node values (node_val_array) using different brain slices.
Parameters
----------
node_val_array : numpy array
1D numpy array containing the values for each node,
by default the values should not be blacklist filtered
vals_blacklist_filtered : bool
True if node_val_array is blacklist filtered
blacklist_fname : str
path to the ".mat" file containing the node blacklist
node_info_fname : str
name of the ".mat" file containing the node information
default_value : node_val_array.dtype
default value for non-blacklisted nodes
cmap : a matplotlib colormap
colormap to be used in the visualization
cmap_lims : tuple of floats
the min and max of the colormap range
T : float
threshold value used in the visualization
(to omit exactly zero values, the code needs improvement)
slice_step : int
how many 2mm slices are between images
Returns
-------
fig : matplotlib figure, or None
if everything goes ok, returns matplotlib figure, otherwise None
"""
if vals_blacklist_filtered:
ok_nodes = dataio.get_ok_nodes(blacklist_fname)
node_val_array = dataio.expand_1D_node_vals_to_non_blacklisted_array(
node_val_array, ok_nodes, default_value=default_value)
pid_str = str(os.getpid())
nii_fname = "/tmp/" + pid_str + ".nii"
success = dataio.out_put_node_prop_to_nii(
node_val_array,
"/tmp/" + pid_str + ".nii",
node_info_fname,
blacklist_fname)
if not success:
# outputting node_prop_to_nii did not succeed
return None
fig = viz_data_on_brain_using_slices(
nii_fname, slices=slicedirs,
colormap=cmap, cmap_lims=cmap_lims, T=T, slice_step=slice_step)
os.remove(nii_fname)
return fig
def viz_node_props_for_ind(fname, prop_tag, cfg, savefig=True):
"""
Visualizes node properties for one subject.
Parameters
----------
fname : str
the original mat file containing the correlation matrix
prop_tag : str
the tag of the property
cfg : dict
brainnets config dictionary
Returns
-------
fig : a matplotlib.Figure
the figure with the brain properties plotted on the brain
"""
data = dataio.load_pickle(fnc.get_ind_fname(fname, cfg, "node_props"))
node_val_array = data[prop_tag]
fig = viz_nodewise_vals_using_slices(
node_val_array, cfg['node_info_fname'],
cfg['blacklist_fname'], default_value=0
)
if savefig:
basename = (fnc.extract_basename(fname) + "_" + str(prop_tag) + "_"
+ str(cfg["density"]))
fig.savefig(cfg['outdata_dir'] + basename + ".pdf", format="pdf")
return fig
def viz_com_stru_for_ind(fname, cfg, i=0, savefig=True, comdet_tag=None):
"""
Visualizes the community structure for one subject.
Parameters
----------
fname : str
the original mat file containing the correlation matrix
cfg : dict
brainnets config dictionary
i : int
which com structure to plot if multiple communities have been computed
savefig : bool, optional
whether to save the fig or not
comdet_tag : str, optional
community detection tag
Returns
-------
fig : matplotlib.Figure
the figure with the brain properties plotted on the brain
"""
if comdet_tag is None:
comdet_tag = settings.louvain_cluster_tag
data = dataio.load_pickle(
fnc.get_ind_fname(fname, cfg, comdet_tag)
)
com = data[comdet_tag][i]
ok_nodes = dataio.get_ok_nodes(cfg['blacklist_fname'])
com = com[ok_nodes]
fig = viz_com_structure_using_slices(
com, cfg, slicedirs="x",
mask_large_cluster_w_gray=True
)
if savefig:
basename = (fnc.extract_basename(fname) + "_" +
str(comdet_tag) + "_" +
str(cfg["density"]) + "_" + str(i))
fig.savefig(cfg['outdata_dir'] + basename + ".pdf", format="pdf")
return fig
def viz_com_structure_from_file(com_fname, cfg, module_colors=None, **kwargs):
"""
A convenience function for
Parameters
----------
com_fname : str
path to the filename which is going to be visualized
cfg : dict
brainnets config dict
kwargs : optional, see :py:func:`viz_com_structure_using_slices`
"""
com = dataio.load(com_fname)[settings.louvain_cluster_tag]
ok_nodes = dataio.get_ok_nodes(cfg['blacklist_fname'])
com = com[ok_nodes]
return viz_com_structure_using_slices(com, cfg, module_colors=module_colors, **kwargs)
def viz_com_structure_using_slices(filtered_comstructure, cfg, module_colors=None, slicedirs="x",
mask_large_cluster_w_gray=False):
"""
Vizualizes a given unfiltered community structure in brain slices.
Parameters
----------
filtered_comstructure : list / numpy array
membership list, contains values only for the ok_nodes
cfg : dict
brainnets confic dict
slicedirs : str
e.g. "yz" means that slices whose tangent is aligned with "y" and
"z" axes are shown
mask_large_cluster_with_gray : bool
whether to mask one big cluster (>=0.5*N) with gray
Returns
-------
fig : matplotlib figure
See also
--------
viz_com_structure_from_file : give a filename to a com structure
instead of a filtered_comstructure
"""
filtered_comstructure = np.array(filtered_comstructure, dtype=np.int32)
sorted_clu_labels = np.setdiff1d(
filtered_comstructure, [settings.undef_clu_label])
newComStructure = np.zeros(filtered_comstructure.shape)
for i, label in enumerate(sorted_clu_labels):
indices = (filtered_comstructure == label)
newComStructure[indices] = i
n_colors = len(sorted_clu_labels)
if module_colors is None:
cols = get_module_colors(np.sort(np.unique(sorted_clu_labels)))
else:
cols = module_colors
# newComStructure = communities.make_zero_indexed_clustering(
# filtered_comstructure)
# mask some cluster with gray?:
if mask_large_cluster_w_gray:
tmpComStructure = newComStructure[
newComStructure != settings.undef_clu_label]
clusizes = communities.get_module_sizes(np.array(tmpComStructure))
if mask_large_cluster_w_gray:
mask_large_cluster_with_gray(cols, clusizes)
listed_color_map = colors.ListedColormap(cols, N=len(cols))
listed_color_map.set_bad(color="k", alpha=0.0)
fig = viz_nodewise_vals_using_slices(
newComStructure + 1, cfg['node_info_fname'], cfg['blacklist_fname'],
slicedirs=slicedirs, vals_blacklist_filtered=True, default_value=0,
cmap=listed_color_map,
cmap_lims=[0.5, n_colors + 0.5])
return fig
# PLOTTING THE BRAIN NODE PROPERTIES USING BRAIN SLICES
def _get_matched_renumbered_communities_for_viz(
clus_1,
clus_2,
undef_clu_label=settings.undef_clu_label):
"""
Computes new matched and renumbered (starging from zero)
communities.
Parameters
----------
clus_1 : np.array
membership list, with non-ok nodes marked with
:py:attr:`settings.undef_clu_label
clus_2 : np.array
membership list, with non-ok nodes marked with
:py:attr:`settings.undef_clu_label
Returns
-------
filtered_clus_1 : np.array
filtered_clus_2 : np.array
n_clu_1 : int
number of clusters in the first partition
n_clu_2 : int
number of clusters in the second partition
"""
clus_1 = np.array(clus_1, dtype=np.int32)
clus_2 = np.array(clus_2, dtype=np.int32)
ok_nodesMovie = (clus_1 != undef_clu_label)
ok_nodesRest = (clus_1 != undef_clu_label)
assert (ok_nodesMovie == ok_nodesRest).all()
ok_nodes = ok_nodesMovie
filtered_clus_1 = clus_1[clus_1 != undef_clu_label] + 1
filtered_clus_2 = clus_2[clus_2 != undef_clu_label] + 1
n_clu_1 = len(np.unique(filtered_clus_1))
n_clu_2 = len(np.unique(filtered_clus_2))
filtered_clus_1, filtered_clus_2 = \
communities.match_clusters_greedy(filtered_clus_1,
filtered_clus_2
)
all_clu_nums = np.union1d(filtered_clus_1, filtered_clus_2)
# this could maybe be simplified
filtered_clus = [filtered_clus_1, filtered_clus_2]
for i in range(len(filtered_clus)):
clustering = filtered_clus[i]
new_clu = np.ones(len(clustering), dtype=np.int64) * -1000
for j, clu_num in enumerate(all_clu_nums):
clunum_indices = (clustering == clu_num)
new_clu[clunum_indices] = j
# expands only if ok_nodes is not all
filtered_clus[i] = dataio.expand_1D_node_vals_to_non_blacklisted_array(
new_clu, ok_nodes, default_value=undef_clu_label)
filtered_clus_1 = filtered_clus[0]
filtered_clus_2 = filtered_clus[1]
return filtered_clus_1, filtered_clus_2, n_clu_1, n_clu_2
def plot_alluvial_diagram(consensus_clu_movie,
consensus_clu_rest,
node_info_fname,
blacklist_fname,
ribbon_label_size_lim=15,
stab_mask_1=None,
stab_mask_2=None,
mask_large_cluster_w_gray=True,
mod_colors1=None,
mod_colors2=None):
"""
Plots the alluvial diagram between two community structures
(com_struct_fname_1 & com_struct_fname_2), see what is expected from
the files in the code below.
Parameters
----------
com_struct_fname_1 : str
a .pkl file containing the first non-blacklisted community structure
com_struct_fname_2 : str
a .pkl file containing the second non-blacklisted community structure
node_info_fname : str
path to the node info fname (.mat)
blacklist_fname :
path to the blacklist
ribbon_label_size_lim : int
how many labels of some type ("label") is required for adding a label
stab_mask_1 : array of bools
a (non-blacklisted) cluster mask for the stable nodes in
com_struct_fname_1. If i is stable, then stab_mask_1[i] = True (?)
stab_mask_2 : array of bools
a (non-blacklisted) cluster mask for the stable nodes in
com_struct_fname_1. If i is stable, then stab_mask_1[i] = True (?)
mask_large_cluster_with_gray : bool
if cluster's size is more than half of the total number of nodes
then it's color is forced to be grey
Returns
-------
fig : the matplotlib figure
"""
if stab_mask_1 is not None and stab_mask_2 is not None:
plot_stabilities = True
else:
plot_stabilities = False
ok_nodes = dataio.get_ok_nodes(blacklist_fname)
try:
rois = dataio.load_mat(node_info_fname, squeeze_me=True)["rois"]
okRois = rois[ok_nodes]
# okRoiAalLabels = okRois['better_label']
okRoiAalLabels = okRois['abbr']
except:
# if something goes wrong with the above, set labels to ""
okRoiAalLabels = np.array([""] * sum(ok_nodes))
if mask_large_cluster_with_gray:
max_val = np.max([consensus_clu_movie, consensus_clu_rest])
for conclu in [consensus_clu_movie, consensus_clu_rest]:
clu_labels = np.setdiff1d(conclu, [settings.undef_clu_label])
for i, item in enumerate(clu_labels):
mod_nodes = (item == conclu)
if np.sum(mod_nodes) > 0.5 * len(mod_nodes) \
and item != max_val:
conclu[mod_nodes] = max_val + 1
consensus_clu_movie = consensus_clu_movie[ok_nodes]
consensus_clu_rest = consensus_clu_rest[ok_nodes]
n_clu_1 = len(np.unique(consensus_clu_movie))
n_clu_2 = len(np.unique(consensus_clu_rest))
if plot_stabilities:
stab_mask_1 = stab_mask_1[ok_nodes]
stab_mask_2 = stab_mask_2[ok_nodes]
stableRibbonSizes1 = np.zeros((n_clu_1, n_clu_2))
stableRibbonSizes2 = np.zeros((n_clu_1, n_clu_2))
else:
stab_mask_1 = None
stab_mask_2 = None
stableRibbonSizes1 = None
stableRibbonSizes2 = None
if mod_colors1 is None or mod_colors2 is None:
mod_colors1 = get_module_colors(
np.sort(np.unique(consensus_clu_movie)))
mod_colors2 = get_module_colors(np.sort(np.unique(consensus_clu_rest)))
# compute modulesizes & ribbon_size_mat
moduleSizes1 = np.zeros(n_clu_1)
moduleSizes2 = np.zeros(n_clu_2)
np.zeros((n_clu_1, n_clu_2))
ribbon_label_mat = np.zeros((n_clu_1, n_clu_2), dtype=object)
ribbon_size_mat = np.zeros((n_clu_1, n_clu_2), dtype=float)
clu_labels = np.setdiff1d(consensus_clu_movie, [settings.undef_clu_label])
for i, item in enumerate(clu_labels):
moduleNodes1 = (item == consensus_clu_movie)
moduleSizes1[i] = np.sum(item == consensus_clu_movie)
for j, jtem in enumerate(np.sort(np.unique(consensus_clu_rest))):
moduleNodes2 = (jtem == consensus_clu_rest)
moduleSizes2[j] = np.sum(moduleNodes2)
commonNodes = moduleNodes2 * moduleNodes1
nCommonNodes = np.sum(moduleNodes2 * moduleNodes1)
ribbon_size_mat[i, j] = nCommonNodes
if plot_stabilities:
stableRibbonSizes1[i, j] = np.sum(commonNodes * stab_mask_1)
stableRibbonSizes2[i, j] = np.sum(commonNodes * stab_mask_2)
# obtain ribbon labels here
ribbonLabelString = ""
uniques, indices = np.unique(
okRoiAalLabels[commonNodes], return_inverse=True)
counts = [np.sum(indices == k) for k in range(0, len(uniques))]
ordering_big_to_small = np.argsort(counts)[::-1]
counter = 0
for index in ordering_big_to_small:
unique = uniques[index]
count = counts[index]
if unique:
if count > ribbon_label_size_lim:
if counter < 3:
ribbonLabelString += unique + ", "
counter += 1
else:
ribbonLabelString += unique + "\n "
counter = 0
ribbonLabelString = ribbonLabelString[:-2]
ribbon_label_mat[i, j] = ribbonLabelString
# return
assert len(moduleSizes1) == len(mod_colors1)
assert len(moduleSizes2) == len(mod_colors2)
if mask_large_cluster_with_gray:
mask_large_cluster_with_gray(mod_colors1, moduleSizes1)
mask_large_cluster_with_gray(mod_colors2, moduleSizes2)
fig = plt.figure(figsize=(10, 12))
ax = fig.add_axes((0.05, 0.05, 0.90, 0.90)) # (111)
alluvial.plot_alluvial(
ax,
ribbon_size_mat,
ribbon_label_mat,
mod_colors1,
mod_colors2,
ribbon_bglim=30,
stable_ribbon_sizes_1=stableRibbonSizes1,
stable_ribbon_sizes_2=stableRibbonSizes2,
horizontal_pad_lr=0.0,
vertical_pad_btw_modules=0.02,
module_width=0.15
)
return fig
def mask_large_cluster_with_gray(mod_colors, mod_sizes):
if len(mod_colors[0]) == 4:
grey = (0.65, 0.65, 0.65, 1)
else:
grey = (0.65, 0.65, 0.65)
mod_colors[mod_sizes > 0.5 * np.sum(mod_sizes)] = grey
def get_module_colors(sorted_clu_labels, n_cols=None):
# indexing starts from zero
if n_cols is None:
n_cols = np.max(sorted_clu_labels) + 1
cols = colorhelp.get_distinct_colors(n_cols)
scls = np.array([int(scl) for scl in sorted_clu_labels])
colors = cols[scls]
assert len(colors) == len(sorted_clu_labels)
return colors
def add_colorbar(ax, vmin=0, vmax=1,
colormap="jet",
orientation="vertical",
cmapLabel="",
norm=None,
p_val_tick_vals=None,
p_val_tick_labels=None):
"""
Add a colorbar to the axis.
"""
if norm is None:
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
cb = mpl.colorbar.ColorbarBase(
ax, cmap=colormap, norm=norm, orientation='vertical')
cb.set_label(cmapLabel, rotation=90)
if p_val_tick_vals:
cb.set_ticks(p_val_tick_vals)
cb.set_ticklabels(p_val_tick_labels)
def cluster_diff_plot_with_matrices(
clustering, adj_mats, nodeColors, n1, paired_study, nIt=1e5,
normcoords=None, suptitle="clusterplot", vmin=None, vmax=None,
xlabel=None, invert_cmap=True,
titles=None):
# clustering = clustering[clustering!=settings.undef_clu_label]
# clustering = communities.makeZeroIndexedClustering(clustering)
movie_avg_adj_mat = np.average(adj_mats[:n1], axis=0)
rest_avg_adj_mat = np.average(adj_mats[n1:], axis=0)
abs_diff_mat = np.abs(movie_avg_adj_mat - rest_avg_adj_mat)
t_val_diff_mat = measures.paired_t_value(
np.array(adj_mats), len(adj_mats) / 2)
fig = plt.figure(figsize=(12, 4))
from matplotlib import gridspec
gs = gridspec.GridSpec(1, 4, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None,
width_ratios=[1, 1, 1, 0.15])
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[0, 2])
if invert_cmap:
cmap = cm.get_cmap("RdBu")
else:
cmap = cm.get_cmap('RdBu_r')
# cols[len(cols) / 2] = (0.9, 0.9, 0.9, 1.0)
# n_colors = 11 # pretty number a hack
# tmp_colors = colormap(np.linspace(0, 1, n_colors))
# colormap = mpl.colors.ListedColormap(tmp_colors)
adj_mats = np.array(adj_mats)
p_vals, mean_diffs = ptests.mean_difference_permtest(
adj_mats, n1, len(adj_mats) - n1, paired_study, nIt)
print p_vals
p_vals_vec = p_vals[np.triu_indices_from(p_vals)]
p_t, sig = corrections.fdr_bh(
0.05, p_vals_vec, return_significant=True)
if p_t < 0.001 or p_t > 0.005:
p_val_limits = [0, 0.001, 0.05, 1, 1.95, 2 - 0.001, 2]
# p_val_limits = [0, 0.001, 0.005, 0.01, 1.0, 1.99, 1.995, 1.999, 2]
ticks = [str(i)
for i in [0, 0.001, 0.05, 1, 0.05, 0.001, 0]]
else:
p_val_limits = [0, 0.001, p_t, 0.05, 1, 1.95, 2 - p_t, 2 - 0.001, 2]
# p_val_limits = [0, 0.001, 0.005, 0.01, 1.0, 1.99, 1.995, 1.999, 2]
ticks = [str(i)
for i in [0, 0.001, str(p_t)[:6] + " FDR $<$ 0.05", 0.05, 1, 0.05, str(p_t)[:6] + " FDR $<$ 0.05", 0.001, 0]]
assert len(p_val_limits) == len(ticks)
# [0, 0.001, 0.005, 0.01, 1.0, 0.01, 0.005, 0.001, 0]]
print p_vals_vec
print np.sum(p_vals_vec <= p_t)
print p_t
print p_vals < p_t
# debug
assert (mean_diffs == movie_avg_adj_mat - rest_avg_adj_mat).all()
# one_sided_p_vals = p_vals / 2.0
col_p_vals = 2 - ((1 + np.sign(mean_diffs)) - np.sign(mean_diffs) * p_vals)
cols = cmap(np.array(np.linspace(0, 1, len(p_val_limits) - 1)))
colormap, norm = colors.from_levels_and_colors(
p_val_limits, cols, extend=u'neither')
colorMatrix = colormap(norm(col_p_vals))
max_ax12 = np.maximum(
np.max(movie_avg_adj_mat), np.max(rest_avg_adj_mat)) * 1.2
# weights = [1000, 3000, 10000, 30000, 50000]
# manually inserted for the paper
weights = [500, 1500, 5000, 15000, 50000]
if max_ax12 < 5000 or max_ax12 > 100000:
weights = [max_ax12 / 100.0, max_ax12 / 10., max_ax12]
_hinton(ax1, movie_avg_adj_mat,
clusterColors=nodeColors, xlabel=xlabel, max_weight=max_ax12, scale_weights=weights)
_hinton(ax2, rest_avg_adj_mat,
clusterColors=nodeColors, xlabel=xlabel, max_weight=max_ax12, scale_weights=weights)
# xlim = ax1.get_xlim()
# bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
# width, height = bbox.width, bbox.height
# max_esize = width / (xlim[1] - xlim[0])
# ax_ascale = plt.subplot(gs[1, 0:2])
# square_scale(ax_ascale, weights, max_width_in_inches=max_esize)
# ax_dscale = plt.subplot(gs[1, 2])
# exit()
max_diff = np.max(abs_diff_mat)
wscale_diff = [100, 300, 1000, 3000, 10000]
if max_diff < 3000 or max_diff > 100000:
wscale_diff = [max_diff/100.0, max_diff/10., max_diff]
_hinton(ax3, abs_diff_mat, clusterColors=nodeColors,
colorMatrix=colorMatrix, xlabel=xlabel,
scale_weights=wscale_diff,
scale_box_color='white',
max_weight=max_diff) # max_diff)
ax_cb = fig.add_axes([0.84, 0.3, 0.03, 0.47])
add_colorbar(ax_cb, vmin=0, vmax=1, colormap=colormap,
orientation="vertical",
cmapLabel='p-value',
norm=norm,
p_val_tick_vals=p_val_limits,
p_val_tick_labels=ticks)
if titles:
if invert_cmap:
ax1.set_title(titles[0], color=cols[-2])
ax2.set_title(titles[1], color=cols[1])
else:
ax1.set_title(titles[0], color=cols[1])
ax2.set_title(titles[1], color=cols[-2])
ax3.set_title(titles[2])
ax_cb.text(
0.5, -0.05, r'\noindent \begin{center} More links \\in ' + titles[0].lower() + "\end{center}", va='top', ha='center', )
ax_cb.text(
0.5, 1.05, r'\noindent \begin{center} More links \\in ' + titles[1].lower() + "\end{center}", va='bottom', ha='center')
fig.suptitle(suptitle)
return fig
def corr_mat_diff_plot(
corr_mats,
mod_colors,
n1, nIt,
paired_study,
normcoords=None,
suptitle="clusterplot",
vmin=None, vmax=None,
xlabel=None, invert_cmap=True, titles=None):
avg_adj_mat_1 = np.average(corr_mats[:n1], axis=0)
avg_adj_mat_2 = np.average(corr_mats[n1:], axis=0)
abs_diff_mat = np.abs(avg_adj_mat_1 - avg_adj_mat_2)
fig = plt.figure(figsize=(12, 4))
from matplotlib import gridspec
gs = gridspec.GridSpec(1, 4, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None,
width_ratios=[1, 1, 1, 0.15])
ax1 = plt.subplot(gs[0, 0])
ax2 = plt.subplot(gs[0, 1])
ax3 = plt.subplot(gs[0, 2])
if invert_cmap:
cmap = cm.get_cmap("RdBu")
else:
cmap = cm.get_cmap('RdBu_r')
# cols[len(cols) / 2] = (0.9, 0.9, 0.9, 1.0)
# n_colors = 11 # pretty number a hack
# tmp_colors = colormap(np.linspace(0, 1, n_colors))
# colormap = mpl.colors.ListedColormap(tmp_colors)
adj_mats = np.array(corr_mats)
p_vals, mean_diffs = ptests.mean_difference_permtest(
np.arctanh(adj_mats), n1, len(adj_mats) - n1, paired_study, nIt)
p_vals_vec = p_vals[np.triu_indices_from(p_vals)]
p_t, sig = corrections.fdr_bh(
0.05, p_vals_vec, return_significant=True)
p_val_limits = [0, 0.001, p_t, 0.05, 1, 1.95, 2 - p_t, 2 - 0.001, 2]
# p_val_limits = [0, 0.001, 0.005, 0.01, 1.0, 1.99, 1.995, 1.999, 2]
ticks = [str(i)
for i in [0, 0.001, str(p_t)[:6] + " FDR $<$ 0.05", 0.05, 1, 0.05, str(p_t)[:6] + " FDR $<$ 0.05", 0.001, 0]]
assert len(p_val_limits) == len(ticks)
# [0, 0.001, 0.005, 0.01, 1.0, 0.01, 0.005, 0.001, 0]]
print p_vals_vec
print np.sum(p_vals_vec <= p_t)
print p_t
print p_vals < p_t
# debug###############
# assert (mean_diffs == avg_adj_mat_1 - avg_adj_mat_2).all()
# one_sided_p_vals = p_vals / 2.0
col_p_vals = 2 - ((1 + np.sign(mean_diffs)) - np.sign(mean_diffs) * p_vals)
cols = cmap(np.array(np.linspace(0, 1, len(p_val_limits) - 1)))
colormap, norm = colors.from_levels_and_colors(
p_val_limits, cols, extend=u'neither')
color_mat = colormap(norm(col_p_vals))
max_ax12 = np.maximum(
np.max(avg_adj_mat_1), np.max(avg_adj_mat_2)) * 1.2
# weights = [1000, 3000, 10000, 30000, 50000]
corr_cmap = cm.get_cmap('RdBu_r')
max_avg_corr = np.maximum(np.max(avg_adj_mat_1), np.max(avg_adj_mat_2))
_hinton(ax1, np.ones(avg_adj_mat_1.shape),
clusterColors=mod_colors, xlabel=xlabel,
colorMatrix=corr_cmap((avg_adj_mat_1)/max_avg_corr),
max_weight=max_ax12
)
_hinton(ax2, np.ones(avg_adj_mat_2.shape),
clusterColors=mod_colors, xlabel=xlabel,
colorMatrix=corr_cmap((avg_adj_mat_2)/max_avg_corr),
max_weight=max_ax12
)
if invert_cmap:
ax1.set_title(titles[0], color=cols[-2])
ax2.set_title(titles[1], color=cols[1])
else:
ax1.set_title(titles[0], color=cols[1])
ax2.set_title(titles[1], color=cols[-2])
_hinton(ax3, np.ones(abs_diff_mat.shape),
clusterColors=mod_colors,
colorMatrix=color_mat,
xlabel=xlabel,
scale_box_color='white')
ax3.set_title(titles[2])
ax_cb = fig.add_axes([0.84, 0.3, 0.03, 0.47])
add_colorbar(ax_cb, vmin=0, vmax=1, colormap=colormap,
orientation="vertical",
cmapLabel='p-value',
norm=norm,
p_val_tick_vals=p_val_limits,
p_val_tick_labels=ticks)
if titles:
ax_cb.text(
0.5, -0.05, r'\noindent \begin{center} More correlated \\in ' + titles[0].lower() + "\end{center}", va='top', ha='center', )
ax_cb.text(
0.5, 1.05, r'\noindent \begin{center} More correlated \\in ' + titles[1].lower() + "\end{center}", va='bottom', ha='center')
fig.suptitle(suptitle)
return fig
def _hinton(ax, sizeMatrix, clusterColors=None, colorMatrix=None,
xlabel=True, max_weight=None, bg_color=None, box_color=None,
scale_weights=None, scale_box_color=None):
"""Draw Hinton diagram for visualizing a weight matrix.
Parameters
----------
ax : matplotlib axes to plot the hinton diagram to
sizeMatrix : 2d numpy matrix of shape (n,n)
describes the areas of the squares in the hinton diagram
clusterColors : list-like
list of colors for each cluster
colorMatrix : 2d numpy array of shape (n,n)
each element should correspond to a matplotlib color
xlabel : str
what to use for labeling for x and y axis
max_weight : float
the maximum "size of a block"
bg_color: matplotlib color
'gray'
box_color: float between 0.0 and 1.0
shades of grey at the moment
Returns
-------
None
"""
ax = ax if ax is not None else plt.gca()
if bg_color is None:
bg_color = 'white'
if box_color is None:
box_color = 0.0
if max_weight is None:
max_weight = np.max(sizeMatrix) * 1.1
if colorMatrix is None:
x, y = sizeMatrix.shape
colorMatrix = np.ones((x, y, 3)) * box_color
sizeMatrix = sizeMatrix[::-1, ::-1]
colorMatrix = colorMatrix[::-1, ::-1]
if clusterColors is not None:
clusterColors = clusterColors[::-1]
ax.patch.set_facecolor(bg_color)
ax.set_aspect('equal', 'box')
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for (i, j), w in np.ndenumerate(sizeMatrix):
color = colorMatrix[i, j]
side_length = np.sqrt(w / float(max_weight))
# print i, j, w, side_length
rect = plt.Rectangle(
[i - side_length / 2, j - side_length /
2], side_length, side_length,
facecolor=color, edgecolor=color)
ax.add_patch(rect)
if clusterColors is not None:
for i, color in enumerate(clusterColors):
rect = plt.Rectangle(
[i - 1. / 2., - 3 / 2.], 1, 1, facecolor=color,
edgecolor=color)
ax.add_patch(rect)
rect = plt.Rectangle(
[- 3. / 2., i - 1 / 2.], 1, 1, facecolor=color,
edgecolor=color)
ax.add_patch(rect)