-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_plotstuff.py
More file actions
executable file
·1704 lines (1487 loc) · 57.1 KB
/
_plotstuff.py
File metadata and controls
executable file
·1704 lines (1487 loc) · 57.1 KB
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
try:
from mayavi import mlab
except (ModuleNotFoundError, ImportError):
print("Package mayavi not installed!")
try:
from surfer import Brain
except (ModuleNotFoundError, ImportError):
print("Package pysurfer not installed!")
print("Install it or don't run plot_toSurface()")
import json
from copy import deepcopy
from glob import glob
from os import makedirs, path, remove
from pathlib import Path
import h5py
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import nibabel as nib
import numpy as np
from matplotlib import colors, patches
from matplotlib.widgets import Button, Slider
from nilearn.surface import vol_to_surf
from PIL import Image
try:
import neuropythy as ny
except:
print("neuropythy not installed, samsrf data not available")
def _resolve_fs_subject_dir(
fs_dir: Path | str, sub: str, sess: str | None = None
) -> Path:
"""
Resolve FreeSurfer subject directory, checking for new layout if old doesn't exist.
Parameters
----------
fs_dir : Path | str
Base FreeSurfer directory
sub : str
Subject ID
sess : str | None, optional
Session ID for new layout fallback
Returns
-------
Path
Resolved subject directory path
"""
fs_dir = Path(fs_dir)
old_path = fs_dir / f"{sub}"
if old_path.exists():
return f"{sub}", str(old_path)
# Try new layout with session if available
if sess:
new_path = fs_dir / f"{sub}_{sess}"
if new_path.exists():
return f"{sub}_{sess}", str(new_path)
# Try to find any session directory for this subject
pattern = fs_dir / f"{sub}_ses-*"
matches = sorted(pattern.parent.glob(pattern.name))
if matches:
return f"{sub}_{sess}", str(matches[0])
# Return old path as default (will fail later if doesn't exist)
return f"{sub}", str(old_path)
class label:
"""
Mini class that defines a label, needed to plot borders
"""
def __init__(self, ar, at, he, allAreaFiles, left_hemi):
self.name = ar
self.hemi = he[0].lower()[0] + "h"
if not "sourcedata/freesurfer" in allAreaFiles[0]:
vJsonName = [
j
for j in allAreaFiles
if f"hemi-{he[0].upper()}_" in path.basename(j)
and f"desc-{ar}-" in path.basename(j)
and at in path.basename(j)
][0]
with open(vJsonName, "r") as fl:
maskinfo = json.load(fl)
if "roiIndOrig" in maskinfo.keys():
self.vertices = np.array(maskinfo["roiIndOrig"])
else:
key = [a for a in maskinfo.keys() if a.startswith("roiIndFs")][0]
self.vertices = np.array(maskinfo[key])
else:
f = [j for j in allAreaFiles if f"/{he[0].lower()}h."][0]
maskinfo = nib.load(f).get_fdata().squeeze()
mdl = ny.vision.retinotopy_model("benson17", "lh")
areaLabels = dict(mdl.area_id_to_name)
areaLabels = {areaLabels[k]: k for k in areaLabels}
labels = areaLabels[ar]
self.vertices = np.where(maskinfo == labels)
if he.upper() == "R":
self.vertices -= left_hemi
# ----------------------------------------------------------------------------#
def _createmask(self, shape, otherRratio=None):
"""
Create a circular boolean mask of a given size.
Args:
shape (tuple): Shape of the mask (height, width).
otherRratio (float, optional): Ratio for the mask radius. If None, uses full size.
Returns:
np.ndarray: Boolean mask array of the specified shape.
"""
x0, y0 = shape[0] // 2, shape[1] // 2
n = shape[0]
if otherRratio is not None:
r = shape[0] / 2 * otherRratio + 1
else:
r = shape[0] // 2 + 1
y, x = np.ogrid[-x0 : n - x0, -y0 : n - y0]
return x * x + y * y <= r * r
def _draw_grid(ax, maxEcc):
"""
Draw a polar grid on the given matplotlib axis for coverage map visualization.
Args:
ax (matplotlib.axes.Axes): The axis to draw the grid on.
maxEcc (float): Maximum eccentricity for the grid.
"""
# draw grid
maxEcc13 = maxEcc / 3
maxEcc23 = maxEcc / 3 * 2
si = np.sin(np.pi / 4) * maxEcc
co = np.cos(np.pi / 4) * maxEcc
for e in [maxEcc13, maxEcc23, maxEcc]:
ax.add_patch(plt.Circle((0, 0), e, color="grey", fill=False, linewidth=0.8))
ax.plot((-1 * maxEcc, maxEcc), (0, 0), color="grey", linewidth=0.8)
ax.plot((0, 0), (-1 * maxEcc, maxEcc), color="grey", linewidth=0.8)
ax.plot((-co, co), (-si, si), color="grey", linewidth=0.8)
ax.plot((-co, co), (si, -si), color="grey", linewidth=0.8)
ax.tick_params(axis="x", which="both", bottom=False, top=False, labelbottom=False)
ax.yaxis.set_ticks(
[np.round(maxEcc13, 1), np.round(maxEcc23, 1), np.round(maxEcc, 1)]
)
ax.tick_params(axis="y", direction="in", pad=-ax.get_window_extent().height * 0.48)
plt.setp(ax.yaxis.get_majorticklabels(), va="bottom")
ax.tick_params(axis="both", which="both", length=0)
ax.set_frame_on(False)
ax.set_box_aspect(1)
def _calcCovMap(self, maxEcc, method="max", force=False, background="black"):
"""
Calculate the pRF coverage map and save it as a .npy file.
Args:
maxEcc (float): Maximum eccentricity for the coverage map.
method (str, optional): Method to calculate the coverage map ('max', 'mean', 'sumClip'). Defaults to 'max'.
force (bool, optional): If True, overwrite existing file. Defaults to False.
background (str, optional): Background color for the map ('black' or 'white'). Defaults to 'black'.
Returns:
np.ndarray: The calculated coverage map.
"""
# create the filename
if self._dataFrom == "mrVista":
VEstr = (
f"_VarExp-{int(self._isVarExpMasked*100)}"
if self._isVarExpMasked and self.doVarExpMsk
else ""
)
Bstr = (
f"_betaThresh-{self._isBetaMasked}"
if self._isBetaMasked and self.doBetaMsk
else ""
)
Sstr = "_MPspace" if self._orientation == "MP" else ""
Estr = (
f"_maxEcc-{self._isEccMasked}"
if self._isEccMasked and self.doEccMsk
else ""
)
Mstr = (
f"-manualMask{self._isManualMasked}"
if self._isManualMasked and self.doManualMsk
else ""
)
methodStr = f"_{method}"
savePathB = path.join(
self._baseP,
self._study,
"plots",
"cover",
"data",
self.subject,
self.session,
)
savePathF = f"{self.subject}_{self.session}_{self._analysis}{VEstr}{Estr}{Bstr}{Mstr}{Sstr}{methodStr}.npy"
elif self._dataFrom in ["docker", "samsrf", "hdf5"]:
VEstr = (
f"-VarExp{int(self._isVarExpMasked*100)}"
if self._isVarExpMasked and self.doVarExpMsk
else ""
)
Bstr = (
f"-betaThresh{self._isBetaMasked}"
if self._isBetaMasked and self.doBetaMsk
else ""
)
Sistr = (
f"-sigmaThresh{self._isSigMasked}"
if self._isSigMasked and self.doSigMsk
else ""
)
Mstr = (
f"-manualMask{self._isManualMasked}"
if self._isManualMasked and self.doManualMsk
else ""
)
Sstr = "-MPspace" if self._orientation == "MP" else ""
Estr = (
f"_maxEcc{self._isEccMasked}" if self._isEccMasked and self.doEccMsk else ""
)
hemiStr = f"_hemi-{self._hemis.upper()}" if self._hemis != "" else ""
methodStr = f"-{method}"
areaStr = "multipleAreas" if len(self._area) > 10 else "".join(self._area)
savePathB = path.join(
self._derivatives_path,
"prfresult",
self._prfanalyze_method,
self._prfanaAn,
"covMapData",
self.subject,
self.session,
)
savePathF = f"{self.subject}_{self.session}_{self._task}_{self._run}{hemiStr}_desc-{areaStr}{VEstr}{Estr}{Bstr}{Mstr}{Sistr}{Sstr}{methodStr}_covmapData.npy"
savePath = path.join(savePathB, savePathF)
def gaussian(x, mu, sig):
return np.exp(-np.power((x - mu) / sig, 2.0) / 2)
if path.isfile(savePath) and not force:
self.covMap = np.load(savePath, allow_pickle=True)
return self.covMap
else:
if not path.isdir(savePathB):
makedirs(savePathB)
xx = np.linspace(-1 * maxEcc, maxEcc, max(int(maxEcc * 30), 300) + 1)
covMap = np.zeros((len(xx), len(xx)))
jj = 0
for i in range(len(self.x)):
kern1dx = gaussian(xx, self.x[i], self.s[i])
kern1dy = gaussian(xx, self.y[i], self.s[i])
kern2d = np.outer(kern1dx, kern1dy)
if np.max(kern2d) > 0:
jj += 1
if method == "max":
covMap = np.max((covMap, kern2d), 0)
elif method == "mean" or method == "sumClip":
covMap = np.sum((covMap, kern2d), 0)
if method == "mean":
covMap /= jj
msk = self._createmask(covMap.shape)
if background == "black":
covMap[~msk] = 0
else:
covMap[~msk] = np.nan
self.covMap = covMap.T
np.save(savePath, self.covMap, allow_pickle=True)
return self.covMap
def _get_covMap_savePath(self, method="max", cmapMin=0, output_format="svg"):
if self._dataFrom == "mrVista":
VEstr = (
f"_VarExp-{int(self._isVarExpMasked*100)}"
if self._isVarExpMasked and self.doVarExpMsk
else ""
)
Bstr = (
f"_betaThresh-{self._isBetaMasked}"
if self._isBetaMasked and self.doBetaMsk
else ""
)
Sstr = "_MPspace" if self._orientation == "MP" else ""
Estr = (
f"_maxEcc-{self._isEccMasked}"
if self._isEccMasked and self.doEccMsk
else ""
)
Mstr = (
f"-manualMask{self._isManualMasked}"
if self._isManualMasked and self.doManualMsk
else ""
)
CBstr = f"_colBar-{cmapMin}".replace(".", "") if cmapMin != 0 else ""
methodStr = f"_{method}"
savePathB = path.join(
self._baseP,
self._study,
"plots",
"cover",
self.subject,
self.session,
)
savePathF = f"{self.subject}_{self.session}_{self._analysis}{CBstr}{VEstr}{Estr}{Bstr}{Mstr}{Sstr}{methodStr}.{output_format}"
elif self._dataFrom in ["docker", "samsrf", "hdf5"]:
VEstr = (
f"-VarExp{int(self._isVarExpMasked*100)}"
if self._isVarExpMasked and self.doVarExpMsk
else ""
)
Bstr = (
f"-betaThresh{self._isBetaMasked}"
if self._isBetaMasked and self.doBetaMsk
else ""
)
Sistr = (
f"-sigmaThresh{self._isSigMasked}"
if self._isSigMasked and self.doSigMsk
else ""
)
Mstr = (
f"-manualMask{self._isManualMasked}"
if self._isManualMasked and self.doManualMsk
else ""
)
Sstr = "-MPspace" if self._orientation == "MP" else ""
Estr = (
f"_maxEcc{self._isEccMasked}" if self._isEccMasked and self.doEccMsk else ""
)
CBstr = f"-colBar{cmapMin}".replace(".", "") if cmapMin != 0 else ""
hemiStr = f"_hemi-{self._hemis.upper()}" if self._hemis != "" else ""
methodStr = f"-{method}"
areaStr = "multipleAreas" if len(self._area) > 10 else "".join(self._area)
savePathB = path.join(
self._derivatives_path,
"prfresult",
self._prfanalyze_method,
self._prfanaAn,
"covMap",
self.subject,
self.session,
)
savePathF = f"{self.subject}_{self.session}_{self._task}_{self._run}{hemiStr}_desc-{areaStr}{VEstr}{Estr}{Bstr}{Mstr}{Sistr}{Sstr}{methodStr}{CBstr}_covmap.{output_format}"
# create folder if not exist
if not path.isdir(savePathB):
makedirs(savePathB)
return path.join(savePathB, savePathF)
# ----------------------------------------------------------------------------#
def plot_covMap(
self,
method="max",
cmapMin=0,
cmapMax=None,
title=None,
show=True,
save=False,
force=False,
maxEcc=None,
do_scatter=True,
output_format="svg",
plot_colorbar=True,
background="white",
):
"""
Plot the pRF coverage map and optionally save it.
Args:
method (str, optional): Method to calculate the coverage map ('max', 'mean', 'sumClip'). Defaults to 'max'.
cmapMin (float, optional): Minimum value for the colormap (0-1). Defaults to 0.
cmapMax (float, optional): Maximum value for the colormap. If None, set automatically. Defaults to None.
title (str, optional): Title for the plot. Defaults to None.
show (bool, optional): Whether to display the plot interactively. Defaults to True.
save (bool, optional): Whether to save the plot to disk. Defaults to False.
force (bool, optional): If True, overwrite existing files. Defaults to False.
maxEcc (float, optional): Maximum eccentricity for the plot axes. If None, uses self.maxEcc. Defaults to None.
do_scatter (bool, optional): Whether to overlay scatter plot of pRF centers. Defaults to True.
output_format (str, optional): File format for saving (e.g., 'svg', 'pdf'). Defaults to 'svg'.
plot_colorbar (bool, optional): Whether to display a colorbar. Defaults to True.
background (str, optional): Background color for the plot. Defaults to 'white'.
Returns:
matplotlib.figure.Figure or str: Figure handle if not saving, otherwise the path to the saved file.
Raises:
ValueError: If method is not recognized or colormap limits are invalid.
"""
if not show:
plt.ioff()
# do maxEcc
maxEcc = maxEcc if maxEcc else self.maxEcc
# create the filename
savePath = self._get_covMap_savePath(method, cmapMin, output_format)
# warning if the chosen method is not possible
if not path.isfile(savePath) or show or force:
methods = ["max", "mean", "sumClip"]
if method not in methods:
raise ValueError(
f'Chosen method "{method}" is not available. Choose from {methods}.'
)
# calculate the coverage map
self._calcCovMap(maxEcc, method, force=force, background=background)
# set method-specific stuff
if method == "max":
vmax = 1
elif method == "mean":
vmax = self.covMap.max()
elif method == "sumClip":
vmax = 1
# adapt the colorbar for the passed cmapMax and cmapMin
if cmapMin > 1 or cmapMin < 0:
raise ValueError("Choose a cmap min between 0 and 1.")
else:
vmin = cmapMin
if cmapMax is not None:
if cmapMax < vmin:
raise ValueError("Choose a cmapMax bigger than cmapMin.")
vmax = cmapMax
fig = plt.figure(constrained_layout=True, facecolor="white")
ax = plt.gca()
im = ax.imshow(
self.covMap,
cmap="hot",
extent=(-1 * maxEcc, maxEcc, -1 * maxEcc, maxEcc),
origin="lower",
vmin=vmin,
vmax=vmax,
)
if do_scatter:
ax.scatter(
self.x[self.r < maxEcc], self.y[self.r < maxEcc], s=0.3, c="grey"
)
ax.set_xlim((-1 * maxEcc, maxEcc))
ax.set_ylim((-1 * maxEcc, maxEcc))
ax.set_aspect("equal", "box")
if plot_colorbar:
fig.colorbar(im, location="right", ax=ax)
# draw grid
_draw_grid(ax, maxEcc)
if title is not None:
ax.set_title(title, pad=16, fontsize=16)
if save and not path.isfile(savePath):
fig.savefig(savePath, bbox_inches="tight")
print(f"new Coverage Map saved to {savePath}")
# plt.close('all')
if not show:
# plt.ion()
pass
if save:
return savePath
else:
return fig
# ----------------------------------------------------------------------------#
def _get_surfaceSavePath(self, param, hemi, surface="cortex", plain=False):
"""
Define the path and filename to save the cortex plot.
Args:
param (str): The parameter to plot.
hemi (str): The hemisphere ('L', 'R', or 'both').
surface (str, optional): Surface type (e.g., 'cortex', 'inflated'). Defaults to 'cortex'.
plain (bool, optional): If True, use a simplified filename. Defaults to False.
Returns:
tuple: (savePathB, savePathF) where savePathB is the directory and savePathF is the filename (without extension).
"""
VEstr = (
f"-VarExp{int(self._isVarExpMasked*100)}"
if self._isVarExpMasked and self.doVarExpMsk
else ""
)
Bstr = (
f"-betaThresh{self._isBetaMasked}"
if self._isBetaMasked and self.doBetaMsk
else ""
)
Mstr = (
f"-manualMask{self._isManualMasked}"
if self._isManualMasked and self.doManualMsk
else ""
)
if isinstance(param, str):
Pstr = f"-{param}"
else:
Pstr = "-manualParam"
if self._dataFrom == "mrVista":
savePathB = path.join(
self._baseP,
self._study,
"plots",
"cortex",
self.subject,
self.session,
)
else:
savePathB = path.join(
self._derivatives_path,
"prfresult",
self._prfanalyze_method,
self._prfanaAn,
"cortex",
self.subject,
self.session,
)
ending = surface
areaStr = "multipleAreas" if len(self._area) > 10 else "".join(self._area)
if not plain:
savePathF = f"{self.subject}_{self.session}_{self._task}_{self._run}_hemi-{hemi[0].upper()}_desc-{areaStr}{VEstr}{Bstr}{Mstr}{Pstr}_{ending}"
else:
savePathF = f"{self.subject}_{self.session}_{self._task}_{self._run}_hemi-{hemi[0].upper()}_desc{Pstr}_{ending}"
if not path.isdir(savePathB):
makedirs(savePathB)
return savePathB, savePathF
def _make_gif(self, frameFolder, outFilename):
"""
Create a GIF from a sequence of PNG frames in a folder.
Args:
frameFolder (str): Folder containing the frames and output GIF.
outFilename (str): Output GIF filename (with extension).
"""
# Read the images
frames = [Image.open(image) for image in sorted(glob(f"{frameFolder}/frame*.png"))]
# Create the gif
frame_one = frames[0]
frame_one.save(
path.join(frameFolder, outFilename),
format="GIF",
append_images=frames,
save_all=True,
duration=500,
loop=0,
)
print(f"new Cortex Map saved to {outFilename}")
# Delete the png-s
[remove(image) for image in glob(f"{frameFolder}/frame*.png")]
def _prepare_mrVista_for_surface_plot(self):
pass
# ----------------------------------------------------------------------------#
def plot_toSurface(
self,
param="ecc",
hemi="left",
save=False,
forceNewPosition=False,
force=False,
surface="inflated",
showBordersAtlas=None,
showBordersArea=None,
interactive=True,
create_gif=False,
headless=False,
maxEcc=None,
plot_colorbar=True,
background="black",
output_format="pdf",
pmax=None,
pmin=None,
):
"""
Plot a parameter (eccentricity, polar angle, sigma, or variance explained) to the cortical surface.
Args:
param (str or np.ndarray, optional): Parameter to plot ('ecc', 'pol', 'sig', 'var') or array. Defaults to 'ecc'.
hemi (str, optional): Hemisphere to plot ('L', 'R', or 'both'). Defaults to 'left'.
fmriprepAna (str, optional): fMRIPrep analysis number. Defaults to '01'.
save (bool, optional): Whether to save the screenshot. Defaults to False.
forceNewPosition (bool, optional): Force manual positioning. Defaults to False.
force (bool, optional): Overwrite existing files. Defaults to False.
surface (str, optional): Surface type (e.g., 'inflated', 'sphere'). Defaults to 'inflated'.
showBordersAtlas (list or str, optional): Atlases to show area borders from. Defaults to None.
showBordersArea (list or str, optional): Areas to show borders for. Defaults to None.
interactive (bool, optional): Enable interactive mode. Defaults to True.
create_gif (bool, optional): Create a GIF instead of a static image. Defaults to False.
headless (bool, optional): Suppress pop-ups. Defaults to False.
maxEcc (float, optional): Maximum eccentricity for plotting. Defaults to None.
plot_colorbar (bool, optional): Show colorbar. Defaults to True.
background (str, optional): Background color. Defaults to 'black'.
output_format (str, optional): Output file format. Defaults to 'pdf'.
pmax (float, optional): Maximum value for color scaling. Defaults to None.
pmin (float, optional): Minimum value for color scaling. Defaults to None.
Raises:
RuntimeError: If plotting is not supported for the data type or space.
ValueError: If the parameter is not recognized.
"""
maxEcc = maxEcc if maxEcc else self.maxEcc
if headless:
mlab.options.offscreen = True
# mlab.init_notebook('x3d', 800, 800)
else:
mlab.options.offscreen = False
if surface == "sphere":
create_gif = False
# turn of other functionality when creating gif
if create_gif:
manualPosition = False
save = False
interactive = True
else:
manualPosition = True if not surface == "sphere" else False
if self._dataFrom in ["docker", "samsrf", "hdf5"]:
if self.analysisSpace == "volume":
raise RuntimeError(
"plot_toSurface is not yet supported for volumetric data!"
)
need_to_convert = True
fsP = path.join(
self._derivatives_path,
"fmriprep",
f"analysis-{self.fmriprep_analysis}",
"sourcedata",
"freesurfer",
)
# define the subject as fsaverage
if self.analysisSpace == "fsaverage":
plot_subject = "fsaverage"
else:
plot_subject = self.subject
need_to_convert = False
positioning_subject = plot_subject
elif self._dataFrom == "mrVista":
fsP = path.join(
self._baseP,
self._study,
"subjects",
self.subject,
self.session,
"segmentation",
)
plot_subject = "freesurfer"
need_to_convert = True
positioning_subject = self.subject
# if self._dataFrom == "mrVista":
# raise RuntimeError("plot_toSurface is not supported for non-docker data!")
# elif self._dataFrom in ["docker", "samsrf", "hdf5"]:
if hemi == "both":
hemis = ["L", "R"]
else:
hemis = [hemi]
for hemi in hemis:
hemi_full = "left" if hemi[0].upper() == "L" else "right"
if save:
if self._dataFrom == "mrVista":
plot_out_p = path.join(
self._baseP,
self._study,
"plots",
"volumeResults",
self.subject,
self.session,
self._analysis,
)
n = f"{self.subject}_{self.session}_{self._analysis}_hemi-{hemi_full[0].upper()}_desc-{param}_{surface}"
else:
plot_out_p, n = self._get_surfaceSavePath(param, hemi, surface)
if (
path.isfile(path.join(plot_out_p, n + f".{output_format}"))
and not force
):
return
makedirs(plot_out_p, exist_ok=True)
if create_gif:
plot_out_p, n = self._get_surfaceSavePath(param, hemi)
if path.isfile(path.join(plot_out_p, n + ".gif")) and not force:
return
makedirs(plot_out_p, exist_ok=True)
(
a,
p,
) = _resolve_fs_subject_dir(fsP, plot_subject, self.session)
pialP = path.join(
p,
"surf",
f"{hemi[0].lower()}h.pial",
)
if not path.isfile(pialP):
pialP = path.join(
p,
"surf",
f"{hemi[0].lower()}h.pial.T1",
)
if not path.isfile(pialP):
raise RuntimeError(f"Pial surface not found, {pialP}!")
pial = nib.freesurfer.read_geometry(pialP)
nVertices = len(pial[0])
# create mask dependent on used hemisphere
if need_to_convert:
# now we need to convert the volume data to the surface
# first get the 3D versions of the data
data_in_3d = self.save_results(
params=[param + "0", "mask"], save=False, force=True
)
fs_pial = path.join(
p,
"surf",
f"{hemi[0].lower()}h.pial",
)
fs_white = path.join(
p,
"surf",
f"{hemi[0].lower()}h.white",
)
else:
if not hasattr(self, "_roiWhichHemi"):
raise RuntimeError(
"Please mask for visual area with instance.maskROI()!"
)
hemiM = self._roiWhichHemi == hemi[0].upper()
roiIndOrigHemi = self._roiIndOrig[hemiM]
roiIndBoldHemi = self._roiIndBold[hemiM]
# write data array to plot
plotData = np.ones(nVertices) * np.nan
# depending on used parameter set the plot data, colormap und ranges
if isinstance(param, str):
if param == "ecc":
if need_to_convert:
plotData = vol_to_surf(
data_in_3d["r0"],
surf_mesh=fs_pial,
inner_mesh=fs_white,
mask_img=data_in_3d["mask"] if "mask" in data_in_3d else None,
)
else:
plotData[roiIndOrigHemi] = self.r0[roiIndBoldHemi]
cmap = "rainbow_r"
datMin, datMax = 0, maxEcc
elif param == "pol":
if need_to_convert:
plotData = vol_to_surf(
data_in_3d["phi0"],
surf_mesh=fs_pial,
inner_mesh=fs_white,
mask_img=data_in_3d["mask"] if "mask" in data_in_3d else None,
)
else:
plotData[roiIndOrigHemi] = self.phi0[roiIndBoldHemi]
cmap = colors.LinearSegmentedColormap.from_list(
"", ["yellow", (0, 0, 1), (0, 1, 0), (1, 0, 0), "yellow"]
)
datMin, datMax = 0, 2 * np.pi
elif param == "sig":
if need_to_convert:
plotData = vol_to_surf(
data_in_3d["s0"],
surf_mesh=fs_pial,
inner_mesh=fs_white,
mask_img=data_in_3d["mask"] if "mask" in data_in_3d else None,
)
else:
plotData[roiIndOrigHemi] = self.s0[roiIndBoldHemi]
cmap = "rainbow_r"
datMin, datMax = 0, 4
elif param == "var":
if need_to_convert:
plotData = vol_to_surf(
data_in_3d["varexp0"],
surf_mesh=fs_pial,
inner_mesh=fs_white,
mask_img=data_in_3d["mask"] if "mask" in data_in_3d else None,
)
else:
plotData[roiIndOrigHemi] = self.varexp0[roiIndBoldHemi]
cmap = "hot"
datMin, datMax = 0, 1
elif isinstance(param, (np.ndarray, np.generic)):
plotData[roiIndOrigHemi] = param[roiIndBoldHemi]
cmap = "hot"
datMin, datMax = (
param[roiIndBoldHemi].min(),
param[roiIndBoldHemi].max(),
)
else:
raise ValueError(
'Parameter string must be in ["ecc", "pol", "sig", "var"] or a np.array of the same size with values!'
)
# manually set plot max and min
if pmax is not None:
datMax = pmax
if pmin is not None:
datMin = pmin
# set everything outside mask (ROI, VarExp, ...) to nan
if not self._dataFrom == "mrVista":
plotData = deepcopy(plotData)
if isinstance(param, str):
if not param == "var":
plotData[roiIndOrigHemi[~self.mask[roiIndBoldHemi]]] = np.nan
else:
plotData[roiIndOrigHemi[~self.mask[roiIndBoldHemi]]] = np.nan
# plot the brain
brain = Brain(
a,
f"{hemi[0].lower()}h",
surface,
subjects_dir=fsP,
background=background,
)
# plot the data
brain.add_data(
np.float16(plotData),
colormap=cmap,
min=datMin,
max=datMax,
smoothing_steps="nearest",
remove_existing=True,
colorbar=plot_colorbar,
)
# set nan to transparent
brain.data["surfaces"][0].module_manager.scalar_lut_manager.lut.nan_color = (
0,
0,
0,
0,
)
brain.data["surfaces"][0].update_pipeline()
# print borders (freesurfer)
if showBordersArea is not None and showBordersAtlas is not None:
if showBordersAtlas == "all":
ats = self._atlas
elif isinstance(showBordersAtlas, list):
ats = showBordersAtlas
elif isinstance(showBordersAtlas, str):
ats = [showBordersAtlas]
elif showBordersAtlas is True:
ats = ["benson"]
if isinstance(showBordersArea, list):
ars = showBordersArea
else:
ars = self._area
for at in ats:
for ar in ars:
try:
if self._dataFrom == "samsrf":
aaf = self._area_files_p
left_hemi = self._vertices_left_hemi
else:
aaf = self._allAreaFiles
left_hemi = None
brain.add_label(
label(ar, at, hemi, aaf, left_hemi),
borders=True,
color="black",
alpha=0.7,
)
except:
pass
# save the positioning for left and right once per subject
if manualPosition:
if self._dataFrom == "mrVista":
posSavePath = path.join(
self._baseP,
self._study,
"plots",
"volumeResults",
"positioning",
positioning_subject,
)
else:
posSavePath = path.join(
self._derivatives_path,
"prfresult",
"positioning",
positioning_subject,
)
if not path.isdir(posSavePath):
makedirs(posSavePath)
areaStr = "multipleAreas" if len(self._area) > 10 else "".join(self._area)
posSaveFile = (
f"{positioning_subject}_hemi-{hemi[0].upper()}_desc-{areaStr}_cortex.h5"
)
posPath = path.join(posSavePath, posSaveFile)
posPath_npy = path.join(posSavePath, posSaveFile.replace(".h5", ".npy"))
if (
not (path.isfile(posPath) or path.isfile(posPath_npy))
or forceNewPosition
):
if hemi[0].upper() == "L":
brain.show_view(
{
"azimuth": -57.5,
"elevation": 106,
"distance": 300,
"focalpoint": np.array([-43, -23, -8]),
},
roll=-130,
)
elif hemi[0].upper() == "R":