-
Notifications
You must be signed in to change notification settings - Fork 15
/
plots.py
1178 lines (1023 loc) · 34.7 KB
/
plots.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
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Plotting tools shared across MRIQC and ASLPREP."""
import numpy as np
import nibabel as nb
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import gridspec as mgs
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap, Normalize
from matplotlib.colorbar import ColorbarBase
from nilearn.plotting import plot_img
from nilearn.signal import clean
from nilearn._utils import check_niimg_4d
from nilearn._utils.niimg import _safe_get_data
import seaborn as sns
DINA4_LANDSCAPE = (11.69, 8.27)
class fMRIPlot:
"""Generates the fMRI Summary Plot."""
__slots__ = (
"timeseries",
"segments",
"tr",
"confounds",
"spikes",
"nskip",
"sort_carpet",
"paired_carpet",
)
def __init__(
self,
timeseries,
segments,
confounds=None,
confounds_file=None,
tr=None,
usecols=None,
units=None,
vlines=None,
spikes_files=None,
nskip=0,
sort_carpet=True,
paired_carpet=False,
):
self.timeseries = timeseries
self.segments = segments
self.tr = tr
self.nskip = nskip
self.sort_carpet = sort_carpet
self.paired_carpet = paired_carpet
if units is None:
units = {}
if vlines is None:
vlines = {}
self.confounds = {}
if confounds is None and confounds_file:
confounds = pd.read_csv(confounds_file, sep=r"[\t\s]+", usecols=usecols, index_col=False)
if confounds is not None:
for name in confounds.columns:
self.confounds[name] = {
"values": confounds[[name]].values.squeeze().tolist(),
"units": units.get(name),
"cutoff": vlines.get(name),
}
self.spikes = []
if spikes_files:
for sp_file in spikes_files:
self.spikes.append((np.loadtxt(sp_file), None, False))
def plot(self, figure=None):
"""Main plotter"""
import seaborn as sns
sns.set_style("whitegrid")
sns.set_context("paper", font_scale=0.8)
if figure is None:
figure = plt.gcf()
nconfounds = len(self.confounds)
nspikes = len(self.spikes)
nrows = 1 + nconfounds + nspikes
# Create grid
grid = mgs.GridSpec(
nrows, 1, wspace=0.0, hspace=0.05, height_ratios=[1] * (nrows - 1) + [5]
)
grid_id = 0
for tsz, name, iszs in self.spikes:
spikesplot(tsz, title=name, outer_gs=grid[grid_id], tr=self.tr, zscored=iszs)
grid_id += 1
if self.confounds:
from seaborn import color_palette
palette = color_palette("husl", nconfounds)
for i, (name, kwargs) in enumerate(self.confounds.items()):
tseries = kwargs.pop("values")
confoundplot(tseries, grid[grid_id], tr=self.tr, color=palette[i], name=name, **kwargs)
grid_id += 1
plot_carpet(
self.timeseries,
segments=self.segments,
subplot=grid[-1],
tr=self.tr,
sort_rows=self.sort_carpet,
drop_trs=self.nskip,
cmap="paired" if self.paired_carpet else None,
)
return figure
def plot_carpet(
func,
atlaslabels=None,
detrend=True,
nskip=0,
size=(950, 800),
subplot=None,
title=None,
output_file=None,
legend=False,
tr=None,
lut=None,
):
"""
Plot an image representation of voxel intensities across time also know
as the "carpet plot" or "Power plot". See Jonathan Power Neuroimage
2017 Jul 1; 154:150-158.
Parameters
----------
func : string
Path to NIfTI or CIFTI ASL image
atlaslabels: ndarray, optional
A 3D array of integer labels from an atlas, resampled into ``img`` space.
Required if ``func`` is a NIfTI image.
detrend : boolean, optional
Detrend and standardize the data prior to plotting.
nskip : int, optional
Number of volumes at the beginning of the scan marked as nonsteady state.
Not used.
size : tuple, optional
Size of figure.
subplot : matplotlib Subplot, optional
Subplot to plot figure on.
title : string, optional
The title displayed on the figure.
output_file : string, or None, optional
The name of an image file to export the plot to. Valid extensions
are .png, .pdf, .svg. If output_file is not None, the plot
is saved to a file, and the display is closed.
legend : bool
Whether to render the average functional series with ``atlaslabels`` as
overlay.
tr : float , optional
Specify the TR, if specified it uses this value. If left as None,
# of frames is plotted instead of time.
lut : ndarray, optional
Look up table for segmentations
"""
epinii = None
segnii = None
nslices = None
img = nb.load(func)
if isinstance(img, nb.Cifti2Image):
assert (
img.nifti_header.get_intent()[0] == "ConnDenseSeries"
), "Not a dense timeseries"
data = img.get_fdata().T
matrix = img.header.matrix
struct_map = {
"LEFT_CORTEX": 1,
"RIGHT_CORTEX": 2,
"SUBCORTICAL": 3,
"CEREBELLUM": 4,
}
seg = np.zeros((data.shape[0],), dtype="uint32")
for bm in matrix.get_index_map(1).brain_models:
if "CORTEX" in bm.brain_structure:
lidx = (1, 2)["RIGHT" in bm.brain_structure]
elif "CEREBELLUM" in bm.brain_structure:
lidx = 4
else:
lidx = 3
index_final = bm.index_offset + bm.index_count
seg[bm.index_offset:index_final] = lidx
assert len(seg[seg < 1]) == 0, "Unassigned labels"
# Decimate data
data, seg = _decimate_data(data, seg, size)
# preserve as much continuity as possible
order = seg.argsort(kind="stable")
cmap = ListedColormap([cm.get_cmap("Paired").colors[i] for i in (1, 0, 7, 3)])
assert len(cmap.colors) == len(
struct_map
), "Mismatch between expected # of structures and colors"
# ensure no legend for CIFTI
legend = False
else: # Volumetric NIfTI
img_nii = check_niimg_4d(img, dtype="auto",)
func_data = _safe_get_data(img_nii, ensure_finite=True)
ntsteps = func_data.shape[-1]
data = func_data[atlaslabels > 0].reshape(-1, ntsteps)
oseg = atlaslabels[atlaslabels > 0].reshape(-1)
# Map segmentation
if lut is None:
lut = np.zeros((256,), dtype="int")
lut[1:11] = 1
lut[255] = 2
lut[30:99] = 3
lut[100:201] = 4
# Apply lookup table
seg = lut[oseg.astype(int)]
# Decimate data
data, seg = _decimate_data(data, seg, size)
# Order following segmentation labels
order = np.argsort(seg)[::-1]
# Set colormap
cmap = ListedColormap(cm.get_cmap("tab10").colors[:4][::-1])
if legend:
epiavg = func_data.mean(3)
epinii = nb.Nifti1Image(epiavg, img_nii.affine, img_nii.header)
segnii = nb.Nifti1Image(
lut[atlaslabels.astype(int)], epinii.affine, epinii.header
)
segnii.set_data_dtype("uint8")
nslices = epiavg.shape[-1]
return _carpet(
data,
seg,
order,
cmap,
epinii=epinii,
segnii=segnii,
nslices=nslices,
tr=tr,
subplot=subplot,
title=title,
output_file=output_file,
)
def _carpet(
data,
seg,
order,
cmap,
tr=None,
detrend=True,
subplot=None,
legend=False,
title=None,
output_file=None,
epinii=None,
segnii=None,
nslices=None,
):
"""Common carpetplot building code for volumetric / CIFTI plots"""
notr = False
if tr is None:
notr = True
tr = 1.0
# Detrend data
v = (None, None)
if detrend:
data = clean(data.T, t_r=tr).T
v = (-2, 2)
# If subplot is not defined
if subplot is None:
subplot = mgs.GridSpec(1, 1)[0]
# Define nested GridSpec
wratios = [1, 100, 20]
gs = mgs.GridSpecFromSubplotSpec(
1,
2 + int(legend),
subplot_spec=subplot,
width_ratios=wratios[: 2 + int(legend)],
wspace=0.0,
)
# Segmentation colorbar
ax0 = plt.subplot(gs[0])
ax0.set_yticks([])
ax0.set_xticks([])
ax0.imshow(seg[order, np.newaxis], interpolation="none", aspect="auto", cmap=cmap)
ax0.grid(False)
ax0.spines["left"].set_visible(False)
ax0.spines["bottom"].set_color("none")
ax0.spines["bottom"].set_visible(False)
# Carpet plot
ax1 = plt.subplot(gs[1])
ax1.imshow(
data[order],
interpolation="nearest",
aspect="auto",
cmap="gray",
vmin=v[0],
vmax=v[1],
)
ax1.grid(False)
ax1.set_yticks([])
ax1.set_yticklabels([])
# Set 10 frame markers in X axis
interval = max((int(data.shape[-1] + 1) // 10, int(data.shape[-1] + 1) // 5, 1))
xticks = list(range(0, data.shape[-1])[::interval])
ax1.set_xticks(xticks)
ax1.set_xlabel("time (frame #)" if notr else "time (s)")
labels = tr * (np.array(xticks))
ax1.set_xticklabels(["%.02f" % t for t in labels.tolist()], fontsize=5)
# Remove and redefine spines
for side in ["top", "right"]:
# Toggle the spine objects
ax0.spines[side].set_color("none")
ax0.spines[side].set_visible(False)
ax1.spines[side].set_color("none")
ax1.spines[side].set_visible(False)
ax1.yaxis.set_ticks_position("left")
ax1.xaxis.set_ticks_position("bottom")
ax1.spines["bottom"].set_visible(False)
ax1.spines["left"].set_color("none")
ax1.spines["left"].set_visible(False)
ax2 = None
if legend:
gslegend = mgs.GridSpecFromSubplotSpec(
5, 1, subplot_spec=gs[2], wspace=0.0, hspace=0.0
)
coords = np.linspace(int(0.10 * nslices), int(0.95 * nslices), 5).astype(
np.uint8
)
for i, c in enumerate(coords.tolist()):
ax2 = plt.subplot(gslegend[i])
plot_img(
segnii,
bg_img=epinii,
axes=ax2,
display_mode="z",
annotate=False,
cut_coords=[c],
threshold=0.1,
cmap=cmap,
interpolation="nearest",
)
if output_file is not None:
figure = plt.gcf()
figure.savefig(output_file, bbox_inches="tight")
plt.close(figure)
figure = None
return output_file
return (ax0, ax1, ax2), gs
def spikesplot(
ts_z,
outer_gs=None,
tr=None,
zscored=True,
spike_thresh=6.0,
title="Spike plot",
ax=None,
cmap="viridis",
hide_x=True,
nskip=0,
):
"""
A spikes plot. Thanks to Bob Dogherty (this docstring needs be improved with proper ack)
"""
if ax is None:
ax = plt.gca()
if outer_gs is not None:
gs = mgs.GridSpecFromSubplotSpec(
1, 2, subplot_spec=outer_gs, width_ratios=[1, 100], wspace=0.0
)
ax = plt.subplot(gs[1])
# Define TR and number of frames
if tr is None:
tr = 1.0
# Load timeseries, zscored slice-wise
nslices = ts_z.shape[0]
ntsteps = ts_z.shape[1]
# Load a colormap
my_cmap = cm.get_cmap(cmap)
norm = Normalize(vmin=0, vmax=float(nslices - 1))
colors = [my_cmap(norm(sl)) for sl in range(nslices)]
stem = len(np.unique(ts_z).tolist()) == 2
# Plot one line per axial slice timeseries
for sl in range(nslices):
if not stem:
ax.plot(ts_z[sl, :], color=colors[sl], lw=0.5)
else:
markerline, stemlines, baseline = ax.stem(ts_z[sl, :])
plt.setp(markerline, "markerfacecolor", colors[sl])
plt.setp(baseline, "color", colors[sl], "linewidth", 1)
plt.setp(stemlines, "color", colors[sl], "linewidth", 1)
# Handle X, Y axes
ax.grid(False)
# Handle X axis
last = ntsteps - 1
ax.set_xlim(0, last)
xticks = list(range(0, last)[::20]) + [last] if not hide_x else []
ax.set_xticks(xticks)
if not hide_x:
if tr is None:
ax.set_xlabel("time (frame #)")
else:
ax.set_xlabel("time (s)")
ax.set_xticklabels(["%.02f" % t for t in (tr * np.array(xticks)).tolist()])
# Handle Y axis
ylabel = "slice-wise noise average on background"
if zscored:
ylabel += " (z-scored)"
zs_max = np.abs(ts_z).max()
ax.set_ylim(
(
-(np.abs(ts_z[:, nskip:]).max()) * 1.05,
(np.abs(ts_z[:, nskip:]).max()) * 1.05,
)
)
ytick_vals = np.arange(0.0, zs_max, float(np.floor(zs_max / 2.0)))
yticks = (
list(reversed((-1.0 * ytick_vals[ytick_vals > 0]).tolist()))
+ ytick_vals.tolist()
)
# TODO plot min/max or mark spikes
# yticks.insert(0, ts_z.min())
# yticks += [ts_z.max()]
for val in ytick_vals:
ax.plot((0, ntsteps - 1), (-val, -val), "k:", alpha=0.2)
ax.plot((0, ntsteps - 1), (val, val), "k:", alpha=0.2)
# Plot spike threshold
if zs_max < spike_thresh:
ax.plot((0, ntsteps - 1), (-spike_thresh, -spike_thresh), "k:")
ax.plot((0, ntsteps - 1), (spike_thresh, spike_thresh), "k:")
else:
yticks = [
ts_z[:, nskip:].min(),
np.median(ts_z[:, nskip:]),
ts_z[:, nskip:].max(),
]
ax.set_ylim(
0, max(yticks[-1] * 1.05, (yticks[-1] - yticks[0]) * 2.0 + yticks[-1])
)
# ax.set_ylim(ts_z[:, nskip:].min() * 0.95,
# ts_z[:, nskip:].max() * 1.05)
ax.annotate(
ylabel,
xy=(0.0, 0.7),
xycoords="axes fraction",
xytext=(0, 0),
textcoords="offset points",
va="center",
ha="left",
color="gray",
size=4,
bbox={
"boxstyle": "round",
"fc": "w",
"ec": "none",
"color": "none",
"lw": 0,
"alpha": 0.8,
},
)
ax.set_yticks([])
ax.set_yticklabels([])
# if yticks:
# # ax.set_yticks(yticks)
# # ax.set_yticklabels(['%.02f' % y for y in yticks])
# # Plot maximum and minimum horizontal lines
# ax.plot((0, ntsteps - 1), (yticks[0], yticks[0]), 'k:')
# ax.plot((0, ntsteps - 1), (yticks[-1], yticks[-1]), 'k:')
for side in ["top", "right"]:
ax.spines[side].set_color("none")
ax.spines[side].set_visible(False)
if not hide_x:
ax.spines["bottom"].set_position(("outward", 10))
ax.xaxis.set_ticks_position("bottom")
else:
ax.spines["bottom"].set_color("none")
ax.spines["bottom"].set_visible(False)
# ax.spines["left"].set_position(('outward', 30))
# ax.yaxis.set_ticks_position('left')
ax.spines["left"].set_visible(False)
ax.spines["left"].set_color(None)
# labels = [label for label in ax.yaxis.get_ticklabels()]
if title:
ax.set_title(title)
return ax
def spikesplot_cb(position, cmap="viridis", fig=None):
# Add colorbar
if fig is None:
fig = plt.gcf()
cax = fig.add_axes(position)
cb = ColorbarBase(
cax,
cmap=cm.get_cmap(cmap),
spacing="proportional",
orientation="horizontal",
drawedges=False,
)
cb.set_ticks([0, 0.5, 1.0])
cb.set_ticklabels(["Inferior", "(axial slice)", "Superior"])
cb.outline.set_linewidth(0)
cb.ax.xaxis.set_tick_params(width=0)
return cax
def confoundplot(
tseries,
gs_ts,
gs_dist=None,
name=None,
units=None,
tr=None,
hide_x=True,
color="b",
nskip=0,
cutoff=None,
ylims=None,
):
# Define TR and number of frames
notr = False
if tr is None:
notr = True
tr = 1.0
ntsteps = len(tseries)
tseries = np.array(tseries)
# Define nested GridSpec
gs = mgs.GridSpecFromSubplotSpec(
1, 2, subplot_spec=gs_ts, width_ratios=[1, 100], wspace=0.0
)
ax_ts = plt.subplot(gs[1])
ax_ts.grid(False)
# Set 10 frame markers in X axis
interval = max((ntsteps // 10, ntsteps // 5, 1))
xticks = list(range(0, ntsteps)[::interval])
ax_ts.set_xticks(xticks)
if not hide_x:
if notr:
ax_ts.set_xlabel("time (frame #)")
else:
ax_ts.set_xlabel("time (s)")
labels = tr * np.array(xticks)
ax_ts.set_xticklabels(["%.02f" % t for t in labels.tolist()])
else:
ax_ts.set_xticklabels([])
if name is not None:
if units is not None:
name += " [%s]" % units
ax_ts.annotate(
name,
xy=(0.0, 0.7),
xytext=(0, 0),
xycoords="axes fraction",
textcoords="offset points",
va="center",
ha="left",
color=color,
size=8,
bbox={
"boxstyle": "round",
"fc": "w",
"ec": "none",
"color": "none",
"lw": 0,
"alpha": 0.8,
},
)
for side in ["top", "right"]:
ax_ts.spines[side].set_color("none")
ax_ts.spines[side].set_visible(False)
if not hide_x:
ax_ts.spines["bottom"].set_position(("outward", 20))
ax_ts.xaxis.set_ticks_position("bottom")
else:
ax_ts.spines["bottom"].set_color("none")
ax_ts.spines["bottom"].set_visible(False)
# ax_ts.spines["left"].set_position(('outward', 30))
ax_ts.spines["left"].set_color("none")
ax_ts.spines["left"].set_visible(False)
# ax_ts.yaxis.set_ticks_position('left')
ax_ts.set_yticks([])
ax_ts.set_yticklabels([])
nonnan = tseries[~np.isnan(tseries)]
if nonnan.size > 0:
# Calculate Y limits
valrange = nonnan.max() - nonnan.min()
def_ylims = [nonnan.min() - 0.1 * valrange, nonnan.max() + 0.1 * valrange]
if ylims is not None:
if ylims[0] is not None:
def_ylims[0] = min([def_ylims[0], ylims[0]])
if ylims[1] is not None:
def_ylims[1] = max([def_ylims[1], ylims[1]])
# Add space for plot title and mean/SD annotation
def_ylims[0] -= 0.1 * (def_ylims[1] - def_ylims[0])
ax_ts.set_ylim(def_ylims)
# Annotate stats
maxv = nonnan.max()
mean = nonnan.mean()
stdv = nonnan.std()
p95 = np.percentile(nonnan, 95.0)
else:
maxv = 0
mean = 0
stdv = 0
p95 = 0
stats_label = (
r"max: {max:.3f}{units} $\bullet$ mean: {mean:.3f}{units} "
r"$\bullet$ $\sigma$: {sigma:.3f}"
).format(max=maxv, mean=mean, units=units or "", sigma=stdv)
ax_ts.annotate(
stats_label,
xy=(0.98, 0.7),
xycoords="axes fraction",
xytext=(0, 0),
textcoords="offset points",
va="center",
ha="right",
color=color,
size=4,
bbox={
"boxstyle": "round",
"fc": "w",
"ec": "none",
"color": "none",
"lw": 0,
"alpha": 0.8,
},
)
# Annotate percentile 95
ax_ts.plot((0, ntsteps - 1), [p95] * 2, linewidth=0.1, color="lightgray")
ax_ts.annotate(
"%.2f" % p95,
xy=(0, p95),
xytext=(-1, 0),
textcoords="offset points",
va="center",
ha="right",
color="lightgray",
size=3,
)
if cutoff is None:
cutoff = []
for i, thr in enumerate(cutoff):
ax_ts.plot((0, ntsteps - 1), [thr] * 2, linewidth=0.2, color="dimgray")
ax_ts.annotate(
"%.2f" % thr,
xy=(0, thr),
xytext=(-1, 0),
textcoords="offset points",
va="center",
ha="right",
color="dimgray",
size=3,
)
ax_ts.plot(tseries, color=color, linewidth=0.8)
ax_ts.set_xlim((0, ntsteps - 1))
if gs_dist is not None:
ax_dist = plt.subplot(gs_dist)
sns.displot(tseries, vertical=True, ax=ax_dist)
ax_dist.set_xlabel("Timesteps")
ax_dist.set_ylim(ax_ts.get_ylim())
ax_dist.set_yticklabels([])
return [ax_ts, ax_dist], gs
return ax_ts, gs
def confoundplotx(tseries, gs_ts, gs_dist=None, name=None,
units=None, tr=None, hide_x=True, color='b', nskip=0,
cutoff=None, ylims=None):
# Define TR and number of frames
notr = False
if tr is None:
notr = True
tr = 1.
ntsteps = len(tseries)
tseries = np.array(tseries)
# Define nested GridSpec
gs = mgs.GridSpecFromSubplotSpec(1, 2, subplot_spec=gs_ts,
width_ratios=[1, 100], wspace=0.0)
ax_ts = plt.subplot(gs[1])
ax_ts.grid(False)
# Set 10 frame markers in X axis
interval = max((ntsteps // 10, ntsteps // 5, 1))
xticks = list(range(0, ntsteps)[::interval])
ax_ts.set_xticks(xticks)
if not hide_x:
if notr:
ax_ts.set_xlabel('time (frame #)')
else:
ax_ts.set_xlabel('time (s)')
labels = tr * np.array(xticks)
ax_ts.set_xticklabels(['%.02f' % t for t in labels.tolist()])
else:
ax_ts.set_xticklabels([])
if name is not None:
if units is not None:
name += ' [%s]' % units
ax_ts.annotate(
name, xy=(0.0, 0.7), xytext=(0, 0), xycoords='axes fraction',
textcoords='offset points', va='center', ha='left',
color=color, size=8,
bbox={'boxstyle': 'round', 'fc': 'w', 'ec': 'none',
'color': 'none', 'lw': 0, 'alpha': 0.8})
for side in ["top", "right"]:
ax_ts.spines[side].set_color('none')
ax_ts.spines[side].set_visible(False)
if not hide_x:
ax_ts.spines["bottom"].set_position(('outward', 20))
ax_ts.xaxis.set_ticks_position('bottom')
else:
ax_ts.spines["bottom"].set_color('none')
ax_ts.spines["bottom"].set_visible(False)
# ax_ts.spines["left"].set_position(('outward', 30))
ax_ts.spines["left"].set_color('none')
ax_ts.spines["left"].set_visible(False)
# ax_ts.yaxis.set_ticks_position('left')
ax_ts.set_yticks([])
ax_ts.set_yticklabels([])
nonnan = tseries[~np.isnan(tseries)]
if nonnan.size > 0:
# Calculate Y limits
valrange = (nonnan.max() - nonnan.min())
def_ylims = [nonnan.min() - 0.1 * valrange, nonnan.max() + 0.1 * valrange]
if ylims is not None:
if ylims[0] is not None:
def_ylims[0] = min([def_ylims[0], ylims[0]])
if ylims[1] is not None:
def_ylims[1] = max([def_ylims[1], ylims[1]])
# Add space for plot title and mean/SD annotation
def_ylims[0] -= 0.1 * (def_ylims[1] - def_ylims[0])
ax_ts.set_ylim(def_ylims)
# Annotate stats
maxv = nonnan.max()
mean = nonnan.mean()
stdv = nonnan.std()
p95 = np.percentile(nonnan, 95.0)
else:
maxv = 0
mean = 0
stdv = 0
p95 = 0
stats_label = (r'max: {max:.3f}{units} $\bullet$ mean: {mean:.3f}{units} '
r'$\bullet$ $\sigma$: {sigma:.3f}').format(
max=maxv, mean=mean, units=units or '', sigma=stdv)
ax_ts.annotate(
stats_label, xy=(0.98, 0.7), xycoords='axes fraction',
xytext=(0, 0), textcoords='offset points',
va='center', ha='right', color=color, size=4,
bbox={'boxstyle': 'round', 'fc': 'w', 'ec': 'none', 'color': 'none',
'lw': 0, 'alpha': 0.8}
)
# Annotate percentile 95
ax_ts.plot((0, ntsteps - 1), [p95] * 2, linewidth=.1, color='lightgray')
ax_ts.annotate(
'%.2f' % p95, xy=(0, p95), xytext=(-1, 0),
textcoords='offset points', va='center', ha='right',
color='lightgray', size=3)
if cutoff is None:
cutoff = []
for i, thr in enumerate(cutoff):
ax_ts.plot((0, ntsteps - 1), [thr] * 2,
linewidth=.2, color='dimgray')
ax_ts.annotate(
'%.2f' % thr, xy=(0, thr), xytext=(-1, 0),
textcoords='offset points', va='center', ha='right',
color='dimgray', size=3)
# ax_ts.plot(tseries, color=color, linewidth=.8)
# ax_ts.set_xlim((0, ntsteps - 1))
ax_ts.step(range(0, ntsteps), tseries, color=color)
ax_ts.set_xlim((0, ntsteps - 1))
if gs_dist is not None:
ax_dist = plt.subplot(gs_dist)
sns.displot(tseries, vertical=True, ax=ax_dist)
ax_dist.set_xlabel('Timesteps')
ax_dist.set_ylim(ax_ts.get_ylim())
ax_dist.set_yticklabels([])
return [ax_ts, ax_dist], gs
return ax_ts, gs
def compcor_variance_plot(
metadata_files,
metadata_sources=None,
output_file=None,
varexp_thresh=(0.5, 0.7, 0.9),
fig=None,
):
"""
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anatomical and temporal
CompCor decompositions), then all metadata files can be provided in
the list. However, each metadata file should have a corresponding
entry in `metadata_sources`.
metadata_sources: list or None
List of source names (e.g., ['aCompCor']) for decompositions. This
list should be of the same length as `metadata_files`.
output_file: str or None
Path where the output figure should be saved. If this is not defined,
then the plotting axes will be returned instead of the saved figure
path.
varexp_thresh: tuple
Set of variance thresholds to include in the plot (default 0.5, 0.7,
0.9).
fig: figure or None
Existing figure on which to plot.
Returns
-------
ax: axes
Plotting axes. Returned only if the `output_file` parameter is None.
output_file: str
The file where the figure is saved.
"""
metadata = {}
if metadata_sources is None:
if len(metadata_files) == 1:
metadata_sources = ["CompCor"]
else:
metadata_sources = [
"Decomposition {:d}".format(i) for i in range(len(metadata_files))
]
for file, source in zip(metadata_files, metadata_sources):
metadata[source] = pd.read_csv(str(file), sep=r"\s+")
metadata[source]["source"] = source
metadata = pd.concat(list(metadata.values()))
bbox_txt = {
"boxstyle": "round",
"fc": "white",
"ec": "none",
"color": "none",
"linewidth": 0,
"alpha": 0.8,
}
decompositions = []
data_sources = list(metadata.groupby(["source", "mask"]).groups.keys())
for source, mask in data_sources:
if not np.isnan(
metadata.loc[(metadata["source"] == source) & (metadata["mask"] == mask)][
"singular_value"
].values[0]
):
decompositions.append((source, mask))
if fig is not None:
ax = [
fig.add_subplot(1, len(decompositions), i + 1)
for i in range(len(decompositions))
]
elif len(decompositions) > 1:
fig, ax = plt.subplots(
1, len(decompositions), figsize=(5 * len(decompositions), 5)
)
else:
ax = [plt.axes()]
for m, (source, mask) in enumerate(decompositions):
components = metadata[
(metadata["mask"] == mask) & (metadata["source"] == source)
]
if len([m for s, m in decompositions if s == source]) > 1:
title_mask = " ({} mask)".format(mask)
else:
title_mask = ""
fig_title = "{}{}".format(source, title_mask)
ax[m].plot(
np.arange(components.shape[0] + 1),
[0] + list(100 * components["cumulative_variance_explained"]),
color="purple",
linewidth=2.5,
)
ax[m].grid(False)
ax[m].set_xlabel("number of components in model")
ax[m].set_ylabel("cumulative variance explained (%)")
ax[m].set_title(fig_title)
varexp = {}
for i, thr in enumerate(varexp_thresh):
varexp[thr] = (
np.atleast_1d(
np.searchsorted(components["cumulative_variance_explained"], thr)
)
+ 1
)
ax[m].axhline(y=100 * thr, color="lightgrey", linewidth=0.25)
ax[m].axvline(
x=varexp[thr], color="C{}".format(i), linewidth=2, linestyle=":"
)
ax[m].text(