/
func.py
3166 lines (2715 loc) · 98.7 KB
/
func.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
"""Downloading NeuroImaging datasets: \
functional datasets (task + resting-state)."""
import fnmatch
import glob
import json
import numbers
import os
import re
import warnings
from io import BytesIO
from pathlib import Path
import nibabel
import nibabel as nib
import numpy as np
import pandas as pd
from scipy.io import loadmat
try:
from scipy.io.matlab import MatReadError
except ImportError: # SciPy < 1.8
from scipy.io.matlab.miobase import MatReadError
from sklearn.utils import Bunch
from nilearn.image import get_data
from .._utils import check_niimg, fill_doc
from .._utils.numpy_conversions import csv_to_array
from ._utils import (
fetch_files,
fetch_single_file,
filter_columns,
get_dataset_descr,
get_dataset_dir,
read_md5_sum_file,
tree,
uncompress_file,
)
_LEGACY_FORMAT_MSG = (
"`legacy_format` will default to `False` in release 0.11. "
"Dataset fetchers will then return pandas dataframes by default "
"instead of recarrays."
)
@fill_doc
def fetch_haxby(
data_dir=None,
subjects=(2,),
fetch_stimuli=False,
url=None,
resume=True,
verbose=1,
):
"""Download and loads complete haxby dataset.
See :footcite:t:`Haxby2001`.
Parameters
----------
%(data_dir)s
subjects : list or int, default=(2,)
Either a list of subjects or the number of subjects to load,
from 1 to 6.
By default, 2nd subject will be loaded.
Empty list returns no subject data.
fetch_stimuli : boolean, default=False
Indicate if stimuli images must be downloaded.
They will be presented as a dictionary of categories.
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, the interest attributes are :
- 'anat': :obj:`list` of :obj:`str`. Paths to anatomic images.
- 'func': :obj:`list` of :obj:`str`.
Paths to nifti file with :term:`BOLD` data.
- 'session_target': :obj:`list` of :obj:`str`.
Paths to text file containing run and target data.
- 'mask': :obj:`str`. Path to fullbrain mask file.
- 'mask_vt': :obj:`list` of :obj:`str`.
Paths to nifti ventral temporal mask file.
- 'mask_face': :obj:`list` of :obj:`str`.
Paths to nifti with face-reponsive brain regions.
- 'mask_face_little': :obj:`list` of :obj:`str`.
Spatially more constrained version of the above.
- 'mask_house': :obj:`list` of :obj:`str`.
Paths to nifti with house-reponsive brain regions.
- 'mask_house_little': :obj:`list` of :obj:`str`.
Spatially more constrained version of the above.
References
----------
.. footbibliography::
Notes
-----
PyMVPA provides a tutorial making use of this dataset:
http://www.pymvpa.org/tutorial.html
More information about its structure:
http://dev.pymvpa.org/datadb/haxby2001.html
See `additional information
<https://www.science.org/doi/10.1126/science.1063736>`
Run 8 in subject 5 does not contain any task labels.
The anatomical image for subject 6 is unavailable.
"""
if isinstance(subjects, numbers.Number) and subjects > 6:
subjects = 6
if subjects is not None and isinstance(subjects, (list, tuple)):
for sub_id in subjects:
if sub_id not in [1, 2, 3, 4, 5, 6]:
raise ValueError(
f"You provided invalid subject id {sub_id} in a "
"list. Subjects must be selected in "
"[1, 2, 3, 4, 5, 6]"
)
dataset_name = "haxby2001"
data_dir = get_dataset_dir(
dataset_name, data_dir=data_dir, verbose=verbose
)
# Get the mask
url_mask = "https://www.nitrc.org/frs/download.php/7868/mask.nii.gz"
mask = fetch_files(
data_dir, [("mask.nii.gz", url_mask, {})], verbose=verbose
)[0]
# Dataset files
if url is None:
url = "http://data.pymvpa.org/datasets/haxby2001/"
md5sums = fetch_files(
data_dir, [("MD5SUMS", url + "MD5SUMS", {})], verbose=verbose
)[0]
md5sums = read_md5_sum_file(md5sums)
# definition of dataset files
sub_files = [
"bold.nii.gz",
"labels.txt",
"mask4_vt.nii.gz",
"mask8b_face_vt.nii.gz",
"mask8b_house_vt.nii.gz",
"mask8_face_vt.nii.gz",
"mask8_house_vt.nii.gz",
"anat.nii.gz",
]
n_files = len(sub_files)
if subjects is None:
subjects = []
if isinstance(subjects, numbers.Number):
subject_mask = np.arange(1, subjects + 1)
else:
subject_mask = np.array(subjects)
files = [
(
os.path.join(f"subj{int(i)}", sub_file),
url + f"subj{int(i)}-2010.01.14.tar.gz",
{
"uncompress": True,
"md5sum": md5sums.get(f"subj{int(i)}-2010.01.14.tar.gz", None),
},
)
for i in subject_mask
for sub_file in sub_files
if sub_file != "anat.nii.gz" or i != 6
]
files = fetch_files(data_dir, files, resume=resume, verbose=verbose)
if (isinstance(subjects, numbers.Number) and subjects == 6) or np.any(
subject_mask == 6
):
files.append(None) # None value because subject 6 has no anat
kwargs = {}
if fetch_stimuli:
stimuli_files = [
(
os.path.join("stimuli", "README"),
url + "stimuli-2010.01.14.tar.gz",
{"uncompress": True},
)
]
readme = fetch_files(
data_dir, stimuli_files, resume=resume, verbose=verbose
)[0]
kwargs["stimuli"] = tree(
os.path.dirname(readme), pattern="*.jpg", dictionary=True
)
fdescr = get_dataset_descr(dataset_name)
# return the data
return Bunch(
anat=files[7::n_files],
func=files[0::n_files],
session_target=files[1::n_files],
mask_vt=files[2::n_files],
mask_face=files[3::n_files],
mask_house=files[4::n_files],
mask_face_little=files[5::n_files],
mask_house_little=files[6::n_files],
mask=mask,
description=fdescr,
**kwargs,
)
def adhd_ids():
"""Return subject ids for the ADHD dataset."""
return [
"0010042",
"0010064",
"0010128",
"0021019",
"0023008",
"0023012",
"0027011",
"0027018",
"0027034",
"0027037",
"1019436",
"1206380",
"1418396",
"1517058",
"1552181",
"1562298",
"1679142",
"2014113",
"2497695",
"2950754",
"3007585",
"3154996",
"3205761",
"3520880",
"3624598",
"3699991",
"3884955",
"3902469",
"3994098",
"4016887",
"4046678",
"4134561",
"4164316",
"4275075",
"6115230",
"7774305",
"8409791",
"8697774",
"9744150",
"9750701",
]
@fill_doc
def fetch_adhd(n_subjects=30, data_dir=None, url=None, resume=True, verbose=1):
"""Download and load the ADHD :term:`resting-state` dataset.
See :footcite:t:`ADHDdataset`.
Parameters
----------
n_subjects : int, default=30
The number of subjects to load from maximum of 40 subjects.
By default, 30 subjects will be loaded. If None is given,
all 40 subjects will be loaded.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, the interest attributes are :
- 'func': Paths to functional :term:`resting-state` images
- 'phenotypic': Explanations of preprocessing steps
- 'confounds': CSV files containing the nuisance variables
References
----------
.. footbibliography::
"""
if url is None:
url = "https://www.nitrc.org/frs/download.php/"
# Preliminary checks and declarations
dataset_name = "adhd"
data_dir = get_dataset_dir(
dataset_name, data_dir=data_dir, verbose=verbose
)
ids = adhd_ids()
nitrc_ids = range(7782, 7822)
max_subjects = len(ids)
if n_subjects is None:
n_subjects = max_subjects
if n_subjects > max_subjects:
warnings.warn(f"Warning: there are only {max_subjects} subjects")
n_subjects = max_subjects
ids = ids[:n_subjects]
nitrc_ids = nitrc_ids[:n_subjects]
opts = dict(uncompress=True)
# Dataset description
fdescr = get_dataset_descr(dataset_name)
# First, get the metadata
phenotypic = (
"ADHD200_40subs_motion_parameters_and_phenotypics.csv",
url + "7781/adhd40_metadata.tgz",
opts,
)
phenotypic = fetch_files(
data_dir, [phenotypic], resume=resume, verbose=verbose
)[0]
# Load the csv file
phenotypic = np.genfromtxt(
phenotypic, names=True, delimiter=",", dtype=None, encoding=None
)
# Keep phenotypic information for selected subjects
int_ids = np.asarray(ids, dtype=int)
phenotypic = phenotypic[
[np.where(phenotypic["Subject"] == i)[0][0] for i in int_ids]
]
# Download dataset files
archives = [
url + f"{int(ni)}/adhd40_{ii}.tgz" for ni, ii in zip(nitrc_ids, ids)
]
functionals = [
f"data/{i}/{i}_rest_tshift_RPI_voreg_mni.nii.gz" for i in ids
]
confounds = [f"data/{i}/{i}_regressors.csv" for i in ids]
functionals = fetch_files(
data_dir,
zip(functionals, archives, (opts,) * n_subjects),
resume=resume,
verbose=verbose,
)
confounds = fetch_files(
data_dir,
zip(confounds, archives, (opts,) * n_subjects),
resume=resume,
verbose=verbose,
)
return Bunch(
func=functionals,
confounds=confounds,
phenotypic=phenotypic,
description=fdescr,
)
def miyawaki2008_file_mask():
"""Return file listing for the miyawaki 2008 dataset."""
return [
"mask.nii.gz",
"LHlag0to1.nii.gz",
"LHlag10to11.nii.gz",
"LHlag1to2.nii.gz",
"LHlag2to3.nii.gz",
"LHlag3to4.nii.gz",
"LHlag4to5.nii.gz",
"LHlag5to6.nii.gz",
"LHlag6to7.nii.gz",
"LHlag7to8.nii.gz",
"LHlag8to9.nii.gz",
"LHlag9to10.nii.gz",
"LHV1d.nii.gz",
"LHV1v.nii.gz",
"LHV2d.nii.gz",
"LHV2v.nii.gz",
"LHV3A.nii.gz",
"LHV3.nii.gz",
"LHV4v.nii.gz",
"LHVP.nii.gz",
"RHlag0to1.nii.gz",
"RHlag10to11.nii.gz",
"RHlag1to2.nii.gz",
"RHlag2to3.nii.gz",
"RHlag3to4.nii.gz",
"RHlag4to5.nii.gz",
"RHlag5to6.nii.gz",
"RHlag6to7.nii.gz",
"RHlag7to8.nii.gz",
"RHlag8to9.nii.gz",
"RHlag9to10.nii.gz",
"RHV1d.nii.gz",
"RHV1v.nii.gz",
"RHV2d.nii.gz",
"RHV2v.nii.gz",
"RHV3A.nii.gz",
"RHV3.nii.gz",
"RHV4v.nii.gz",
"RHVP.nii.gz",
]
@fill_doc
def fetch_miyawaki2008(data_dir=None, url=None, resume=True, verbose=1):
"""Download and loads Miyawaki et al. 2008 dataset (153MB).
See :footcite:t:`Miyawaki2008`.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
- 'func': :obj:`list` of :obj:`str`
Paths to nifti file with :term:`BOLD` data
- 'label': :obj:`list` of :obj:`str`
Paths to text file containing run and target data
- 'mask': :obj:`str`
Path to nifti mask file to define target volume in visual
cortex
- 'background': :obj:`str`
Path to nifti file containing a background image usable as a
background image for miyawaki images.
References
----------
.. footbibliography::
Notes
-----
This dataset is available on the `brainliner website
<http://brainliner.jp/data/brainliner-admin/Reconstruct>`_
See `additional information
<http://www.cns.atr.jp/dni/en/downloads/
fmri-data-set-for-visual-image-reconstruction/>`_
"""
url = (
"https://www.nitrc.org/frs/download.php"
"/8486/miyawaki2008.tgz?i_agree=1&download_now=1"
)
opts = {"uncompress": True}
# Dataset files
# Functional MRI:
# * 20 random scans (usually used for training)
# * 12 figure scans (usually used for testing)
func_figure = [
(os.path.join("func", f"data_figure_run{int(i):02}.nii.gz"), url, opts)
for i in range(1, 13)
]
func_random = [
(os.path.join("func", f"data_random_run{int(i):02}.nii.gz"), url, opts)
for i in range(1, 21)
]
# Labels, 10x10 patches, stimuli shown to the subject:
# * 20 random labels
# * 12 figure labels (letters and shapes)
label_filename = "data_%s_run%02d_label.csv"
label_figure = [
(os.path.join("label", label_filename % ("figure", i)), url, opts)
for i in range(1, 13)
]
label_random = [
(os.path.join("label", label_filename % ("random", i)), url, opts)
for i in range(1, 21)
]
# Masks
file_mask = [
(os.path.join("mask", m), url, opts) for m in miyawaki2008_file_mask()
]
file_names = (
func_figure + func_random + label_figure + label_random + file_mask
)
dataset_name = "miyawaki2008"
data_dir = get_dataset_dir(
dataset_name, data_dir=data_dir, verbose=verbose
)
files = fetch_files(data_dir, file_names, resume=resume, verbose=verbose)
# Fetch the background image
bg_img = fetch_files(
data_dir, [("bg.nii.gz", url, opts)], resume=resume, verbose=verbose
)[0]
fdescr = get_dataset_descr(dataset_name)
# Return the data
return Bunch(
func=files[:32],
label=files[32:64],
mask=files[64],
mask_roi=files[65:],
background=bg_img,
description=fdescr,
)
@fill_doc
def fetch_localizer_contrasts(
contrasts,
n_subjects=None,
get_tmaps=False,
get_masks=False,
get_anats=False,
data_dir=None,
url=None,
resume=True,
verbose=1,
legacy_format=True,
):
"""Download and load Brainomics/Localizer dataset (94 subjects).
"The Functional Localizer is a simple and fast acquisition
procedure based on a 5-minute functional magnetic resonance
imaging (fMRI) sequence that can be run as easily and as
systematically as an anatomical scan. This protocol captures the
cerebral bases of auditory and visual perception, motor actions,
reading, language comprehension and mental calculation at an
individual level. Individual functional maps are reliable and
quite precise. The procedure is described in more detail on the
Functional Localizer page."
(see https://osf.io/vhtf6/)
You may cite :footcite:t:`Papadopoulos-Orfanos2017`
when using this dataset.
Scientific results obtained using this dataset are described
in :footcite:t:`Pinel2007`.
Parameters
----------
contrasts : :obj:`list` of :obj:`str`
The contrasts to be fetched (for all 94 subjects available).
Allowed values are::
- "checkerboard"
- "horizontal checkerboard"
- "vertical checkerboard"
- "horizontal vs vertical checkerboard"
- "vertical vs horizontal checkerboard"
- "sentence listening"
- "sentence reading"
- "sentence listening and reading"
- "sentence reading vs checkerboard"
- "calculation (auditory cue)"
- "calculation (visual cue)"
- "calculation (auditory and visual cue)"
- "calculation (auditory cue) vs sentence listening"
- "calculation (visual cue) vs sentence reading"
- "calculation vs sentences"
- "calculation (auditory cue) and sentence listening"
- "calculation (visual cue) and sentence reading"
- "calculation and sentence listening/reading"
- "calculation (auditory cue) and sentence listening vs "
- "calculation (visual cue) and sentence reading"
- "calculation (visual cue) and sentence reading vs checkerboard"
- "calculation and sentence listening/reading vs button press"
- "left button press (auditory cue)"
- "left button press (visual cue)"
- "left button press"
- "left vs right button press"
- "right button press (auditory cue)"
- "right button press (visual cue)"
- "right button press"
- "right vs left button press"
- "button press (auditory cue) vs sentence listening"
- "button press (visual cue) vs sentence reading"
- "button press vs calculation and sentence listening/reading"
or equivalently on can use the original names::
- "checkerboard"
- "horizontal checkerboard"
- "vertical checkerboard"
- "horizontal vs vertical checkerboard"
- "vertical vs horizontal checkerboard"
- "auditory sentences"
- "visual sentences"
- "auditory&visual sentences"
- "visual sentences vs checkerboard"
- "auditory calculation"
- "visual calculation"
- "auditory&visual calculation"
- "auditory calculation vs auditory sentences"
- "visual calculation vs sentences"
- "auditory&visual calculation vs sentences"
- "auditory processing"
- "visual processing"
- "visual processing vs auditory processing"
- "auditory processing vs visual processing"
- "visual processing vs checkerboard"
- "cognitive processing vs motor"
- "left auditory click"
- "left visual click"
- "left auditory&visual click"
- "left auditory & visual click vs right auditory&visual click"
- "right auditory click"
- "right visual click"
- "right auditory&visual click"
- "right auditory & visual click vs left auditory&visual click"
- "auditory click vs auditory sentences"
- "visual click vs visual sentences"
- "auditory&visual motor vs cognitive processing"
n_subjects : int or list, optional
The number or list of subjects to load. If None is given,
all 94 subjects are used.
get_tmaps : boolean, default=False
Whether t maps should be fetched or not.
get_masks : boolean, default=False
Whether individual masks should be fetched or not.
get_anats : boolean, default=False
Whether individual structural images should be fetched or not.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
%(legacy_format)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
- 'cmaps': :obj:`list` of :obj:`str`
Paths to nifti contrast maps
- 'tmaps' :obj:`list` of :obj:`str` (if 'get_tmaps' set to True)
Paths to nifti t maps
- 'masks': :obj:`list` of :obj:`str`
Paths to nifti files corresponding to the subjects individual masks
- 'anats': :obj:`str`
Path to nifti files corresponding to the subjects structural images
References
----------
.. footbibliography::
See Also
--------
nilearn.datasets.fetch_localizer_calculation_task
nilearn.datasets.fetch_localizer_button_task
"""
if isinstance(contrasts, str):
raise ValueError(
"Contrasts should be a list of strings, but "
f'a single string was given: "{contrasts}"'
)
if n_subjects is None:
n_subjects = 94 # 94 subjects available
if isinstance(n_subjects, numbers.Number) and (
(n_subjects > 94) or (n_subjects < 1)
):
warnings.warn(
"Wrong value for 'n_subjects' (%d). The maximum "
"value will be used instead ('n_subjects=94')"
)
n_subjects = 94 # 94 subjects available
# we allow the user to use alternatives to Brainomics contrast names
contrast_name_wrapper = {
# Checkerboard
"checkerboard": "checkerboard",
"horizontal checkerboard": "horizontal checkerboard",
"vertical checkerboard": "vertical checkerboard",
"horizontal vs vertical checkerboard": "horizontal vs vertical checkerboard", # noqa 501
"vertical vs horizontal checkerboard": "vertical vs horizontal checkerboard", # noqa 501
# Sentences
"sentence listening": "auditory sentences",
"sentence reading": "visual sentences",
"sentence listening and reading": "auditory&visual sentences",
"sentence reading vs checkerboard": "visual sentences vs checkerboard",
# Calculation
"calculation (auditory cue)": "auditory calculation",
"calculation (visual cue)": "visual calculation",
"calculation (auditory and visual cue)": "auditory&visual calculation", # noqa 501
"calculation (auditory cue) vs sentence listening": "auditory calculation vs auditory sentences", # noqa 501
"calculation (visual cue) vs sentence reading": "visual calculation vs sentences", # noqa 501
"calculation vs sentences": "auditory&visual calculation vs sentences", # noqa 501
# Calculation + Sentences
"calculation (auditory cue) and sentence listening": "auditory processing", # noqa 501
"calculation (visual cue) and sentence reading": "visual processing",
"calculation (visual cue) and sentence reading vs "
"calculation (auditory cue) and sentence listening": "visual processing vs auditory processing", # noqa 501
"calculation (auditory cue) and sentence listening vs "
"calculation (visual cue) and sentence reading": "auditory processing vs visual processing", # noqa 501
"calculation (visual cue) and sentence reading vs checkerboard": "visual processing vs checkerboard", # noqa 501
"calculation and sentence listening/reading vs button press": "cognitive processing vs motor", # noqa 501
# Button press
"left button press (auditory cue)": "left auditory click",
"left button press (visual cue)": "left visual click",
"left button press": "left auditory&visual click",
"left vs right button press": "left auditory & visual click vs "
+ "right auditory&visual click",
"right button press (auditory cue)": "right auditory click",
"right button press (visual cue)": "right visual click",
"right button press": "right auditory & visual click",
"right vs left button press": "right auditory & visual click "
+ "vs left auditory&visual click",
"button press (auditory cue) vs sentence listening": "auditory click vs auditory sentences", # noqa 501
"button press (visual cue) vs sentence reading": "visual click vs visual sentences", # noqa 501
"button press vs calculation and sentence listening/reading": "auditory&visual motor vs cognitive processing", # noqa 501
}
allowed_contrasts = list(contrast_name_wrapper.values())
# convert contrast names
contrasts_wrapped = []
# get a unique ID for each contrast. It is used to give a unique name to
# each download file and avoid name collisions.
contrasts_indices = []
for contrast in contrasts:
if contrast in allowed_contrasts:
contrasts_wrapped.append(contrast.title().replace(" ", ""))
contrasts_indices.append(allowed_contrasts.index(contrast))
elif contrast in contrast_name_wrapper:
name = contrast_name_wrapper[contrast]
contrasts_wrapped.append(name.title().replace(" ", ""))
contrasts_indices.append(allowed_contrasts.index(name))
else:
raise ValueError(f"Contrast '{contrast}' is not available")
# Get the dataset OSF index
dataset_name = "brainomics_localizer"
index_url = "https://osf.io/hwbm2/download"
data_dir = get_dataset_dir(
dataset_name, data_dir=data_dir, verbose=verbose
)
index_file = fetch_single_file(index_url, data_dir, verbose=verbose)
with open(index_file) as of:
index = json.load(of)
# Build data URLs that will be fetched
files = {}
# Download from the relevant OSF project, using hashes generated
# from the OSF API. Note the trailing slash. For more info, see:
# https://gist.github.com/emdupre/3cb4d564511d495ea6bf89c6a577da74
root_url = "https://osf.io/download/{0}/"
if isinstance(n_subjects, numbers.Number):
subject_mask = np.arange(1, n_subjects + 1)
else:
subject_mask = np.array(n_subjects)
subject_ids = [f"S{int(s):02}" for s in subject_mask]
data_types = ["cmaps"]
if get_tmaps:
data_types.append("tmaps")
filenames = []
def _is_valid_path(path, index, verbose):
if path not in index:
if verbose > 0:
print(f"Skipping path '{path}'...")
return False
return True
for subject_id in subject_ids:
for data_type in data_types:
for _, contrast in enumerate(contrasts_wrapped):
name_aux = str.replace(
str.join("_", [data_type, contrast]), " ", "_"
)
file_path = os.path.join(
"brainomics_data", subject_id, f"{name_aux}.nii.gz"
)
path = "/".join(
[
"/localizer",
"derivatives",
"spm_1st_level",
f"sub-{subject_id}",
(
f"sub-{subject_id}_task-localizer"
f"_acq-{contrast}_{data_type}.nii.gz"
),
]
)
if _is_valid_path(path, index, verbose=verbose):
file_url = root_url.format(index[path][1:])
opts = {"move": file_path}
filenames.append((file_path, file_url, opts))
files.setdefault(data_type, []).append(file_path)
# Fetch masks if asked by user
if get_masks:
for subject_id in subject_ids:
file_path = os.path.join(
"brainomics_data", subject_id, "boolean_mask_mask.nii.gz"
)
path = "/".join(
[
"/localizer",
"derivatives",
"spm_1st_level",
f"sub-{subject_id}",
f"sub-{subject_id}_mask.nii.gz",
]
)
if _is_valid_path(path, index, verbose=verbose):
file_url = root_url.format(index[path][1:])
opts = {"move": file_path}
filenames.append((file_path, file_url, opts))
files.setdefault("masks", []).append(file_path)
# Fetch anats if asked by user
if get_anats:
for subject_id in subject_ids:
file_path = os.path.join(
"brainomics_data",
subject_id,
"normalized_T1_anat_defaced.nii.gz",
)
path = "/".join(
[
"/localizer",
"derivatives",
"spm_preprocessing",
f"sub-{subject_id}",
f"sub-{subject_id}_T1w.nii.gz",
]
)
if _is_valid_path(path, index, verbose=verbose):
file_url = root_url.format(index[path][1:])
opts = {"move": file_path}
filenames.append((file_path, file_url, opts))
files.setdefault("anats", []).append(file_path)
# Fetch subject characteristics
participants_file = os.path.join("brainomics_data", "participants.tsv")
path = "/localizer/participants.tsv"
if _is_valid_path(path, index, verbose=verbose):
file_url = root_url.format(index[path][1:])
opts = {"move": participants_file}
filenames.append((participants_file, file_url, opts))
# Fetch behavioural
behavioural_file = os.path.join(
"brainomics_data", "phenotype", "behavioural.tsv"
)
path = "/localizer/phenotype/behavioural.tsv"
if _is_valid_path(path, index, verbose=verbose):
file_url = root_url.format(index[path][1:])
opts = {"move": behavioural_file}
filenames.append((behavioural_file, file_url, opts))
# Actual data fetching
fdescr = get_dataset_descr(dataset_name)
fetch_files(data_dir, filenames, verbose=verbose)
for key, value in files.items():
files[key] = [os.path.join(data_dir, val) for val in value]
# Load covariates file
participants_file = os.path.join(data_dir, participants_file)
csv_data = pd.read_csv(participants_file, delimiter="\t")
behavioural_file = os.path.join(data_dir, behavioural_file)
csv_data2 = pd.read_csv(behavioural_file, delimiter="\t")
csv_data = csv_data.merge(csv_data2)
subject_names = csv_data["participant_id"].tolist()
subjects_indices = []
for name in subject_ids:
if name not in subject_names:
continue
subjects_indices.append(subject_names.index(name))
csv_data = csv_data.iloc[subjects_indices]
if legacy_format:
warnings.warn(_LEGACY_FORMAT_MSG, DeprecationWarning)
csv_data = csv_data.to_records(index=False)
return Bunch(ext_vars=csv_data, description=fdescr, **files)
@fill_doc
def fetch_localizer_calculation_task(
n_subjects=1, data_dir=None, url=None, verbose=1, legacy_format=True
):
"""Fetch calculation task contrast maps from the localizer.
Parameters
----------
n_subjects : :obj:`int`, default=1
The number of subjects to load. If None is given,
all 94 subjects are used.
%(data_dir)s
%(url)s
%(verbose)s
%(legacy_format)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
'cmaps': string list, giving paths to nifti contrast maps
Notes
-----
This function is only a caller for the fetch_localizer_contrasts in order
to simplify examples reading and understanding.
The 'calculation (auditory and visual cue)' contrast is used.
See Also
--------
nilearn.datasets.fetch_localizer_button_task
nilearn.datasets.fetch_localizer_contrasts
"""
data = fetch_localizer_contrasts(
["calculation (auditory and visual cue)"],
n_subjects=n_subjects,
get_tmaps=False,
get_masks=False,
get_anats=False,
data_dir=data_dir,
url=url,
resume=True,
verbose=verbose,
legacy_format=legacy_format,
)
return data
@fill_doc
def fetch_localizer_button_task(
data_dir=None, url=None, verbose=1, legacy_format=True
):
"""Fetch left vs right button press :term:`contrast` maps \
from the localizer.
Parameters
----------
%(data_dir)s
%(url)s
%(verbose)s
%(legacy_format)s
Returns
-------
data : Bunch
Dictionary-like object, the interest attributes are :
- 'cmaps': string list, giving paths to nifti :term:`contrast` maps
- 'tmap': string, giving paths to nifti :term:`contrast` maps
- 'anat': string, giving paths to normalized anatomical image
Notes
-----
This function is only a caller for the fetch_localizer_contrasts in order
to simplify examples reading and understanding.
The 'left vs right button press' contrast is used.
See Also
--------
nilearn.datasets.fetch_localizer_calculation_task
nilearn.datasets.fetch_localizer_contrasts
"""
data = fetch_localizer_contrasts(
["left vs right button press"],
n_subjects=[2],
get_tmaps=True,