/
atlas.py
1597 lines (1282 loc) · 54.7 KB
/
atlas.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: atlas datasets
"""
import os
import warnings
import xml.etree.ElementTree
from tempfile import mkdtemp
import json
import shutil
import nibabel as nb
import numpy as np
from numpy.lib import recfunctions
import re
from sklearn.utils import Bunch
from .utils import _get_dataset_dir, _fetch_files, _get_dataset_descr
from .._utils import check_niimg, fill_doc
from ..image import new_img_like, get_data, reorder_img
_TALAIRACH_LEVELS = ['hemisphere', 'lobe', 'gyrus', 'tissue', 'ba']
@fill_doc
def fetch_atlas_difumo(dimension=64, resolution_mm=2, data_dir=None, resume=True, verbose=1):
"""Fetch DiFuMo brain atlas
Dictionaries of Functional Modes, or “DiFuMo”, can serve as atlases to extract
functional signals with different dimensionalities (64, 128, 256, 512, and 1024).
These modes are optimized to represent well raw BOLD timeseries,
over a with range of experimental conditions.
See :footcite:`DADI2020117126`.
.. versionadded:: 0.7.1
Notes
-----
Direct download links from OSF:
- 64: https://osf.io/pqu9r/download
- 128: https://osf.io/wjvd5/download
- 256: https://osf.io/3vrct/download
- 512: https://osf.io/9b76y/download
- 1024: https://osf.io/34792/download
Parameters
----------
dimension : int, optional
Number of dimensions in the dictionary. Valid resolutions
available are {64, 128, 256, 512, 1024}.
Default=64.
resolution_mm : int, optional
The resolution in mm of the atlas to fetch. Valid options
available are {2, 3}. Default=2mm.
%(data_dir)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, the interest attributes are :
- 'maps': str, 4D path to nifti file containing regions definition.
- 'labels': Numpy recarray containing the labels of the regions.
- 'description': str, general description of the dataset.
References
----------
.. footbibliography::
"""
dic = {64: 'pqu9r',
128: 'wjvd5',
256: '3vrct',
512: '9b76y',
1024: '34792',
}
valid_dimensions = [64, 128, 256, 512, 1024]
valid_resolution_mm = [2, 3]
if dimension not in valid_dimensions:
raise ValueError("Requested dimension={} is not available. Valid "
"options: {}".format(dimension, valid_dimensions))
if resolution_mm not in valid_resolution_mm:
raise ValueError("Requested resolution_mm={} is not available. Valid "
"options: {}".format(resolution_mm,
valid_resolution_mm))
url = 'https://osf.io/{}/download'.format(dic[dimension])
opts = {'uncompress': True}
csv_file = os.path.join('{0}', 'labels_{0}_dictionary.csv')
if resolution_mm != 3:
nifti_file = os.path.join('{0}', '2mm', 'maps.nii.gz')
else:
nifti_file = os.path.join('{0}', '3mm', 'maps.nii.gz')
files = [(csv_file.format(dimension), url, opts),
(nifti_file.format(dimension), url, opts)]
dataset_name = 'difumo_atlases'
data_dir = _get_dataset_dir(dataset_name=dataset_name, data_dir=data_dir,
verbose=verbose)
# Download the zip file, first
files_ = _fetch_files(data_dir, files, verbose=verbose)
labels = np.recfromcsv(files_[0])
# README
readme_files = [('README.md', 'https://osf.io/4k9bf/download',
{'move': 'README.md'})]
if not os.path.exists(os.path.join(data_dir, 'README.md')):
_fetch_files(data_dir, readme_files, verbose=verbose)
fdescr = _get_dataset_descr(dataset_name)
params = dict(description=fdescr, maps=files_[1], labels=labels)
return Bunch(**params)
@fill_doc
def fetch_atlas_craddock_2012(data_dir=None, url=None, resume=True, verbose=1):
"""Download and return file names for the Craddock 2012 parcellation
The provided images are in MNI152 space.
See :footcite:`CreativeCommons` for the licence.
See :footcite:`craddock2012whole` and :footcite:`nitrcClusterROI`
for more information on this parcellation.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, keys are:
scorr_mean, tcorr_mean,
scorr_2level, tcorr_2level,
random
References
----------
.. footbibliography::
"""
if url is None:
url = "ftp://www.nitrc.org/home/groups/cluster_roi/htdocs" \
"/Parcellations/craddock_2011_parcellations.tar.gz"
opts = {'uncompress': True}
dataset_name = "craddock_2012"
keys = ("scorr_mean", "tcorr_mean",
"scorr_2level", "tcorr_2level",
"random")
filenames = [
("scorr05_mean_all.nii.gz", url, opts),
("tcorr05_mean_all.nii.gz", url, opts),
("scorr05_2level_all.nii.gz", url, opts),
("tcorr05_2level_all.nii.gz", url, opts),
("random_all.nii.gz", url, opts)
]
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
sub_files = _fetch_files(data_dir, filenames, resume=resume,
verbose=verbose)
fdescr = _get_dataset_descr(dataset_name)
params = dict([('description', fdescr)] + list(zip(keys, sub_files)))
return Bunch(**params)
@fill_doc
def fetch_atlas_destrieux_2009(lateralized=True, data_dir=None, url=None,
resume=True, verbose=1):
"""Download and load the Destrieux cortical atlas (dated 2009)
see :footcite:`Fischl2004Automatically`,
and :footcite:`Destrieux2009sulcal`.
Parameters
----------
lateralized : boolean, optional
If True, returns an atlas with distinct regions for right and left
hemispheres. Default=True.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, contains:
- Cortical ROIs, lateralized or not (maps)
- Labels of the ROIs (labels)
References
----------
.. footbibliography::
"""
if url is None:
url = "https://www.nitrc.org/frs/download.php/11942/"
url += "destrieux2009.tgz"
opts = {'uncompress': True}
lat = '_lateralized' if lateralized else ''
files = [
('destrieux2009_rois_labels' + lat + '.csv', url, opts),
('destrieux2009_rois' + lat + '.nii.gz', url, opts),
('destrieux2009.rst', url, opts)
]
dataset_name = 'destrieux_2009'
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
files_ = _fetch_files(data_dir, files, resume=resume,
verbose=verbose)
params = dict(maps=files_[1], labels=np.recfromcsv(files_[0]))
with open(files_[2], 'r') as rst_file:
params['description'] = rst_file.read()
return Bunch(**params)
@fill_doc
def fetch_atlas_harvard_oxford(atlas_name, data_dir=None,
symmetric_split=False,
resume=True, verbose=1):
"""Load Harvard-Oxford parcellations from FSL.
This function downloads Harvard Oxford atlas packaged from FSL 5.0
and stores atlases in NILEARN_DATA folder in home directory.
This function can also load Harvard Oxford atlas from your local directory
specified by your FSL installed path given in `data_dir` argument.
See documentation for details.
Parameters
----------
atlas_name : string
Name of atlas to load. Can be:
cort-maxprob-thr0-1mm, cort-maxprob-thr0-2mm,
cort-maxprob-thr25-1mm, cort-maxprob-thr25-2mm,
cort-maxprob-thr50-1mm, cort-maxprob-thr50-2mm,
cort-prob-1mm, cort-prob-2mm,
cortl-maxprob-thr0-1mm, cortl-maxprob-thr0-2mm,
cortl-maxprob-thr25-1mm, cortl-maxprob-thr25-2mm,
cortl-maxprob-thr50-1mm, cortl-maxprob-thr50-2mm,
cortl-prob-1mm, cortl-prob-2mm,
sub-maxprob-thr0-1mm, sub-maxprob-thr0-2mm,
sub-maxprob-thr25-1mm, sub-maxprob-thr25-2mm,
sub-maxprob-thr50-1mm, sub-maxprob-thr50-2mm,
sub-prob-1mm, sub-prob-2mm
data_dir : string, optional
Path of data directory where data will be stored. Optionally,
it can also be a FSL installation directory (which is dependent
on your installation).
Example, if FSL is installed in /usr/share/fsl/ then
specifying as '/usr/share/' can get you Harvard Oxford atlas
from your installed directory. Since we mimic same root directory
as FSL to load it easily from your installation.
symmetric_split : bool, optional
If True, lateralized atlases of cort or sub with maxprob will be
returned. For subcortical types (sub-maxprob), we split every
symmetric region in left and right parts. Effectively doubles the
number of regions.
.. note::
Not implemented for full probabilistic atlas (*-prob-* atlases).
Default=False.
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, keys are:
- "maps": nibabel.Nifti1Image, 4D maps if a probabilistic atlas is
requested and 3D labels if a maximum probabilistic atlas was
requested.
- "labels": string list, labels of the regions in the atlas.
See also
--------
nilearn.datasets.fetch_atlas_juelich
"""
atlases = ["cort-maxprob-thr0-1mm", "cort-maxprob-thr0-2mm",
"cort-maxprob-thr25-1mm", "cort-maxprob-thr25-2mm",
"cort-maxprob-thr50-1mm", "cort-maxprob-thr50-2mm",
"cort-prob-1mm", "cort-prob-2mm",
"cortl-maxprob-thr0-1mm", "cortl-maxprob-thr0-2mm",
"cortl-maxprob-thr25-1mm", "cortl-maxprob-thr25-2mm",
"cortl-maxprob-thr50-1mm", "cortl-maxprob-thr50-2mm",
"cortl-prob-1mm", "cortl-prob-2mm",
"sub-maxprob-thr0-1mm", "sub-maxprob-thr0-2mm",
"sub-maxprob-thr25-1mm", "sub-maxprob-thr25-2mm",
"sub-maxprob-thr50-1mm", "sub-maxprob-thr50-2mm",
"sub-prob-1mm", "sub-prob-2mm"]
if atlas_name not in atlases:
raise ValueError("Invalid atlas name: {0}. Please choose "
"an atlas among:\n{1}".
format(atlas_name, '\n'.join(atlases)))
is_probabilistic = "-prob-" in atlas_name
if is_probabilistic and symmetric_split:
raise ValueError("Region splitting not supported for probabilistic "
"atlases")
atlas_img, names, is_lateralized = _get_atlas_data_and_labels(
"HarvardOxford",
atlas_name,
symmetric_split=symmetric_split,
data_dir=data_dir,
resume=resume,
verbose=verbose)
atlas_niimg = check_niimg(atlas_img)
if not symmetric_split or is_lateralized:
return Bunch(filename=atlas_img, maps=atlas_niimg, labels=names)
new_atlas_data, new_names = _compute_symmetric_split("HarvardOxford",
atlas_niimg,
names)
new_atlas_niimg = new_img_like(atlas_niimg,
new_atlas_data,
atlas_niimg.affine)
return Bunch(filename=atlas_img, maps=new_atlas_niimg, labels=new_names)
def fetch_atlas_juelich(atlas_name, data_dir=None,
symmetric_split=False,
resume=True, verbose=1):
"""Load Juelich parcellations from FSL.
This function downloads Juelich atlas packaged from FSL 5.0
and stores atlases in NILEARN_DATA folder in home directory.
This function can also load Juelich atlas from your local directory
specified by your FSL installed path given in `data_dir` argument.
See documentation for details.
.. versionadded:: 0.8.1
Parameters
----------
atlas_name : string
Name of atlas to load. Can be:
maxprob-thr0-1mm, maxprob-thr0-2mm,
maxprob-thr25-1mm, maxprob-thr25-2mm,
maxprob-thr50-1mm, maxprob-thr50-2mm,
prob-1mm, prob-2mm
data_dir : string, optional
Path of data directory where data will be stored. Optionally,
it can also be a FSL installation directory (which is dependent
on your installation).
Example, if FSL is installed in /usr/share/fsl/ then
specifying as '/usr/share/' can get you Juelich atlas
from your installed directory. Since we mimic same root directory
as FSL to load it easily from your installation.
symmetric_split : bool, optional
If True, lateralized atlases of cort or sub with maxprob will be
returned. For subcortical types (sub-maxprob), we split every
symmetric region in left and right parts. Effectively doubles the
number of regions.
NOTE Not implemented for full probabilistic atlas (*-prob-* atlases).
Default=False.
resume : bool, optional
Whether to resumed download of a partly-downloaded file.
Default=True.
verbose : int, optional
Verbosity level (0 means no message). Default=1.
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, keys are:
- "maps": nibabel.Nifti1Image, 4D maps if a probabilistic atlas is
requested and 3D labels if a maximum probabilistic atlas was
requested.
- "labels": string list, labels of the regions in the atlas.
See also
--------
nilearn.datasets.fetch_atlas_harvard_oxford
"""
atlases = ["maxprob-thr0-1mm", "maxprob-thr0-2mm",
"maxprob-thr25-1mm", "maxprob-thr25-2mm",
"maxprob-thr50-1mm", "maxprob-thr50-2mm",
"prob-1mm", "prob-2mm"]
if atlas_name not in atlases:
raise ValueError("Invalid atlas name: {0}. Please choose "
"an atlas among:\n{1}".
format(atlas_name, '\n'.join(atlases)))
is_probabilistic = atlas_name.startswith("prob-")
if is_probabilistic and symmetric_split:
raise ValueError("Region splitting not supported for probabilistic "
"atlases")
atlas_img, names, _ = _get_atlas_data_and_labels("Juelich",
atlas_name,
data_dir=data_dir,
resume=resume,
verbose=verbose)
atlas_niimg = check_niimg(atlas_img)
atlas_data = get_data(atlas_niimg)
if is_probabilistic:
new_atlas_data, new_names = _merge_probabilistic_maps_juelich(
atlas_data, names)
elif symmetric_split:
new_atlas_data, new_names = _compute_symmetric_split("Juelich",
atlas_niimg,
names)
else:
new_atlas_data, new_names = _merge_labels_juelich(atlas_data, names)
new_atlas_niimg = new_img_like(atlas_niimg,
new_atlas_data,
atlas_niimg.affine)
return Bunch(filename=atlas_img, maps=new_atlas_niimg,
labels=list(new_names))
def _get_atlas_data_and_labels(atlas_source, atlas_name, symmetric_split=False,
data_dir=None, resume=True, verbose=1):
"""Helper function for both fetch_atlas_juelich and fetch_atlas_harvard_oxford.
This function downloads the atlas image and labels.
"""
if atlas_source == "Juelich":
url = 'https://www.nitrc.org/frs/download.php/12096/Juelich.tgz'
elif atlas_source == "HarvardOxford":
url = 'http://www.nitrc.org/frs/download.php/9902/HarvardOxford.tgz'
else:
raise ValueError("Atlas source {} is not valid.".format(
atlas_source))
# For practical reasons, we mimic the FSL data directory here.
data_dir = _get_dataset_dir('fsl', data_dir=data_dir,
verbose=verbose)
opts = {'uncompress': True}
root = os.path.join('data', 'atlases')
if atlas_source == 'HarvardOxford':
if symmetric_split:
atlas_name = atlas_name.replace("cort-max", "cortl-max")
if atlas_name.startswith("sub-"):
label_file = 'HarvardOxford-Subcortical.xml'
is_lateralized = False
elif atlas_name.startswith("cortl"):
label_file = 'HarvardOxford-Cortical-Lateralized.xml'
is_lateralized = True
else:
label_file = 'HarvardOxford-Cortical.xml'
is_lateralized = False
else:
label_file = "Juelich.xml"
is_lateralized = False
label_file = os.path.join(root, label_file)
atlas_file = os.path.join(root, atlas_source,
'{}-{}.nii.gz'.format(atlas_source,
atlas_name))
atlas_img, label_file = _fetch_files(
data_dir,
[(atlas_file, url, opts),
(label_file, url, opts)],
resume=resume, verbose=verbose)
# Reorder image to have positive affine diagonal
atlas_img = reorder_img(atlas_img)
names = {}
from xml.etree import ElementTree
names[0] = 'Background'
for n, label in enumerate(
ElementTree.parse(label_file).findall('.//label')):
new_idx = int(label.get('index')) + 1
if new_idx in names:
raise ValueError(
f"Duplicate index {new_idx} for labels "
f"'{names[new_idx]}', and '{label.text}'")
names[new_idx] = label.text
# The label indices should range from 0 to nlabel + 1
assert list(names.keys()) == list(range(n + 2))
names = [item[1] for item in sorted(names.items())]
return atlas_img, names, is_lateralized
def _merge_probabilistic_maps_juelich(atlas_data, names):
"""Helper function for fetch_atlas_juelich.
This function handles probabilistic juelich atlases
when symmetric_split=False. In this situation, we need
to merge labels and maps corresponding to left and right
regions.
"""
new_names = np.unique([re.sub(r" (L|R)$", "", name) for name in names])
new_name_to_idx = {k: v - 1 for v, k in enumerate(new_names)}
new_atlas_data = np.zeros((*atlas_data.shape[:3],
len(new_names) - 1))
for i, name in enumerate(names):
if name != "Background":
new_name = re.sub(r" (L|R)$", "", name)
new_atlas_data[..., new_name_to_idx[new_name]] += (
atlas_data[..., i - 1])
return new_atlas_data, new_names
def _merge_labels_juelich(atlas_data, names):
"""Helper function for fetch_atlas_juelich.
This function handles 3D atlases when symmetric_split=False.
In this case, we need to merge the labels corresponding to
left and right regions.
"""
new_names = np.unique([re.sub(r" (L|R)$", "", name) for name in names])
new_names_dict = {k: v for v, k in enumerate(new_names)}
new_atlas_data = atlas_data.copy()
for label, name in enumerate(names):
new_name = re.sub(r" (L|R)$", "", name)
new_atlas_data[atlas_data == label] = new_names_dict[new_name]
return new_atlas_data, new_names
def _compute_symmetric_split(source, atlas_niimg, names):
"""Helper function for both fetch_atlas_juelich and
fetch_atlas_harvard_oxford.
This function handles 3D atlases when symmetric_split=True.
"""
# The atlas_niimg should have been passed to
# reorder_img such that the affine's diagonal
# should be positive. This is important to
# correctly split left and right hemispheres.
assert atlas_niimg.affine[0, 0] > 0
atlas_data = get_data(atlas_niimg)
labels = np.unique(atlas_data)
# Build a mask of both halves of the brain
middle_ind = (atlas_data.shape[0]) // 2
# Split every zone crossing the median plane into two parts.
left_atlas = atlas_data.copy()
left_atlas[middle_ind:] = 0
right_atlas = atlas_data.copy()
right_atlas[:middle_ind] = 0
if source == "Juelich":
for idx, name in enumerate(names):
if name.endswith('L'):
names[idx] = re.sub(r" L$", "", name)
names[idx] = "Left " + name
if name.endswith('R'):
names[idx] = re.sub(r" R$", "", name)
names[idx] = "Right " + name
new_label = 0
new_atlas = atlas_data.copy()
# Assumes that the background label is zero.
new_names = [names[0]]
for label, name in zip(labels[1:], names[1:]):
new_label += 1
left_elements = (left_atlas == label).sum()
right_elements = (right_atlas == label).sum()
n_elements = float(left_elements + right_elements)
if (left_elements / n_elements < 0.05
or right_elements / n_elements < 0.05):
new_atlas[atlas_data == label] = new_label
new_names.append(name)
continue
new_atlas[left_atlas == label] = new_label
new_names.append('Left ' + name)
new_label += 1
new_atlas[right_atlas == label] = new_label
new_names.append('Right ' + name)
return new_atlas, new_names
@fill_doc
def fetch_atlas_msdl(data_dir=None, url=None, resume=True, verbose=1):
"""Download and load the MSDL brain atlas.
It can be downloaded at :footcite:`atlas_msdl`, and cited
using :footcite:`Varoquaux2011multisubject`.
See also :footcite:`VAROQUAUX2013405` for more information.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, the interest attributes are :
- 'maps': str, path to nifti file containing regions definition.
- 'labels': string list containing the labels of the regions.
- 'region_coords': tuple list (x, y, z) containing coordinates
of each region in MNI space.
- 'networks': string list containing names of the networks.
- 'description': description about the atlas.
References
----------
.. footbibliography::
"""
url = 'https://team.inria.fr/parietal/files/2015/01/MSDL_rois.zip'
opts = {'uncompress': True}
dataset_name = "msdl_atlas"
files = [(os.path.join('MSDL_rois', 'msdl_rois_labels.csv'), url, opts),
(os.path.join('MSDL_rois', 'msdl_rois.nii'), url, opts)]
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
files = _fetch_files(data_dir, files, resume=resume, verbose=verbose)
csv_data = np.recfromcsv(files[0])
labels = [name.strip() for name in csv_data['name'].tolist()]
labels = [label.decode("utf-8") for label in labels]
with warnings.catch_warnings():
warnings.filterwarnings('ignore', module='numpy',
category=FutureWarning)
region_coords = csv_data[['x', 'y', 'z']].tolist()
net_names = [net_name.strip() for net_name in csv_data['net_name'].tolist()]
fdescr = _get_dataset_descr(dataset_name)
return Bunch(maps=files[1], labels=labels, region_coords=region_coords,
networks=net_names, description=fdescr)
def fetch_coords_power_2011():
"""Download and load the Power et al. brain atlas composed of 264 ROIs
See :footcite:`Power2011Functional`.
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, contains:
- "rois": coordinates of 264 ROIs in MNI space
References
----------
.. footbibliography::
"""
dataset_name = 'power_2011'
fdescr = _get_dataset_descr(dataset_name)
package_directory = os.path.dirname(os.path.abspath(__file__))
csv = os.path.join(package_directory, "data", "power_2011.csv")
params = dict(rois=np.recfromcsv(csv), description=fdescr)
return Bunch(**params)
@fill_doc
def fetch_atlas_smith_2009(data_dir=None, mirror='origin', url=None,
resume=True, verbose=1):
"""Download and load the Smith ICA and BrainMap atlas (dated 2009).
See :footcite:`Smith200913040` and :footcite:`Laird2011behavioral`.
Parameters
----------
%(data_dir)s
mirror : string, optional
By default, the dataset is downloaded from the original website of the
atlas. Specifying "nitrc" will force download from a mirror, with
potentially higher bandwidth. Default='origin'.
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, contains:
- 20-dimensional ICA, Resting-FMRI components:
- all 20 components (rsn20)
- 10 well-matched maps from these, as shown in PNAS paper (rsn10)
- 20-dimensional ICA, BrainMap components:
- all 20 components (bm20)
- 10 well-matched maps from these, as shown in PNAS paper (bm10)
- 70-dimensional ICA, Resting-FMRI components (rsn70)
- 70-dimensional ICA, BrainMap components (bm70)
References
----------
.. footbibliography::
Notes
-----
For more information about this dataset's structure:
http://www.fmrib.ox.ac.uk/datasets/brainmap+rsns/
"""
if url is None:
if mirror == 'origin':
url = "http://www.fmrib.ox.ac.uk/datasets/brainmap+rsns/"
elif mirror == 'nitrc':
url = [
'https://www.nitrc.org/frs/download.php/7730/',
'https://www.nitrc.org/frs/download.php/7729/',
'https://www.nitrc.org/frs/download.php/7731/',
'https://www.nitrc.org/frs/download.php/7726/',
'https://www.nitrc.org/frs/download.php/7728/',
'https://www.nitrc.org/frs/download.php/7727/',
]
else:
raise ValueError('Unknown mirror "%s". Mirror must be "origin" '
'or "nitrc"' % str(mirror))
files = [
'rsn20.nii.gz',
'PNAS_Smith09_rsn10.nii.gz',
'rsn70.nii.gz',
'bm20.nii.gz',
'PNAS_Smith09_bm10.nii.gz',
'bm70.nii.gz'
]
if isinstance(url, str):
url = [url] * len(files)
files = [(f, u + f, {}) for f, u in zip(files, url)]
dataset_name = 'smith_2009'
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
files_ = _fetch_files(data_dir, files, resume=resume,
verbose=verbose)
fdescr = _get_dataset_descr(dataset_name)
keys = ['rsn20', 'rsn10', 'rsn70', 'bm20', 'bm10', 'bm70']
params = dict(zip(keys, files_))
params['description'] = fdescr
return Bunch(**params)
@fill_doc
def fetch_atlas_yeo_2011(data_dir=None, url=None, resume=True, verbose=1):
"""Download and return file names for the Yeo 2011 parcellation.
The provided images are in MNI152 space.
For more information on this dataset's structure,
see :footcite:`CorticalParcellation_Yeo2011`,
and :footcite:`Yeo2011organization`.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, keys are:
- "thin_7", "thick_7": 7-region parcellations,
fitted to resp. thin and thick template cortex segmentations.
- "thin_17", "thick_17": 17-region parcellations.
- "colors_7", "colors_17": colormaps (text files) for 7- and 17-region
parcellation respectively.
- "anat": anatomy image.
References
----------
.. footbibliography::
Notes
-----
Licence: unknown.
"""
if url is None:
url = ('ftp://surfer.nmr.mgh.harvard.edu/pub/data/'
'Yeo_JNeurophysiol11_MNI152.zip')
opts = {'uncompress': True}
dataset_name = "yeo_2011"
keys = ("thin_7", "thick_7",
"thin_17", "thick_17",
"colors_7", "colors_17", "anat")
basenames = (
"Yeo2011_7Networks_MNI152_FreeSurferConformed1mm.nii.gz",
"Yeo2011_7Networks_MNI152_FreeSurferConformed1mm_LiberalMask.nii.gz",
"Yeo2011_17Networks_MNI152_FreeSurferConformed1mm.nii.gz",
"Yeo2011_17Networks_MNI152_FreeSurferConformed1mm_LiberalMask.nii.gz",
"Yeo2011_7Networks_ColorLUT.txt",
"Yeo2011_17Networks_ColorLUT.txt",
"FSL_MNI152_FreeSurferConformed_1mm.nii.gz")
filenames = [(os.path.join("Yeo_JNeurophysiol11_MNI152", f), url, opts)
for f in basenames]
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
sub_files = _fetch_files(data_dir, filenames, resume=resume,
verbose=verbose)
fdescr = _get_dataset_descr(dataset_name)
params = dict([('description', fdescr)] + list(zip(keys, sub_files)))
return Bunch(**params)
@fill_doc
def fetch_atlas_aal(version='SPM12', data_dir=None, url=None, resume=True,
verbose=1):
"""Downloads and returns the AAL template for SPM 12.
This atlas is the result of an automated anatomical parcellation of the
spatially normalized single-subject high-resolution T1 volume provided by
the Montreal Neurological Institute (MNI) (D. L. Collins et al., 1998,
Trans. Med. Imag. 17, 463-468, PubMed).
For more information on this dataset's structure,
see :footcite:`AAL_atlas`,
and :footcite:`TZOURIOMAZOYER2002273`.
Parameters
----------
version : string {'SPM12', 'SPM5', 'SPM8'}, optional
The version of the AAL atlas. Must be SPM5, SPM8 or SPM12.
Default='SPM12'.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, keys are:
- "maps": str. path to nifti file containing regions.
- "labels": list of the names of the regions
References
----------
.. footbibliography::
Notes
-----
Licence: unknown.
"""
versions = ['SPM5', 'SPM8', 'SPM12']
if version not in versions:
raise ValueError('The version of AAL requested "%s" does not exist.'
'Please choose one among %s.' %
(version, str(versions)))
if url is None:
baseurl = "http://www.gin.cnrs.fr/AAL_files/aal_for_%s.tar.gz"
url = baseurl % version
opts = {'uncompress': True}
dataset_name = "aal_" + version
# keys and basenames would need to be handled for each spm_version
# for now spm_version 12 is hardcoded.
basenames = ("AAL.nii", "AAL.xml")
filenames = [(os.path.join('aal', 'atlas', f), url, opts)
for f in basenames]
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,
verbose=verbose)
atlas_img, labels_file = _fetch_files(data_dir, filenames, resume=resume,
verbose=verbose)
fdescr = _get_dataset_descr(dataset_name)
# We return the labels contained in the xml file as a dictionary
xml_tree = xml.etree.ElementTree.parse(labels_file)
root = xml_tree.getroot()
labels = []
indices = []
for label in root.iter('label'):
indices.append(label.find('index').text)
labels.append(label.find('name').text)
params = {'description': fdescr, 'maps': atlas_img,
'labels': labels, 'indices': indices}
return Bunch(**params)
@fill_doc
def fetch_atlas_basc_multiscale_2015(version='sym', data_dir=None, url=None,
resume=True, verbose=1):
"""Downloads and loads multiscale functional brain parcellations
This atlas includes group brain parcellations generated from
resting-state functional magnetic resonance images from about
200 young healthy subjects.
Multiple scales (number of networks) are available, among
7, 12, 20, 36, 64, 122, 197, 325, 444. The brain parcellations
have been generated using a method called bootstrap analysis of
stable clusters called as BASC :footcite:`BELLEC20101126`,
and the scales have been selected using a data-driven method
called MSTEPS :footcite:`Bellec2013Mining`.
Note that two versions of the template are available, 'sym' or 'asym'.
The 'asym' type contains brain images that have been registered in the
asymmetric version of the MNI brain template (reflecting that the brain
is asymmetric), while the 'sym' type contains images registered in the
symmetric version of the MNI template. The symmetric template has been
forced to be symmetric anatomically, and is therefore ideally suited to
study homotopic functional connections in fMRI: finding homotopic regions
simply consists of flipping the x-axis of the template.
.. versionadded:: 0.2.3
Parameters
----------
version : str {'sym', 'asym'}, optional
Available versions are 'sym' or 'asym'. By default all scales of
brain parcellations of version 'sym' will be returned.
Default='sym'.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : sklearn.datasets.base.Bunch
Dictionary-like object, Keys are:
- "scale007", "scale012", "scale020", "scale036", "scale064",
"scale122", "scale197", "scale325", "scale444": str, path
to Nifti file of various scales of brain parcellations.
- "description": details about the data release.
References
----------
.. footbibliography::
Notes
-----
For more information on this dataset's structure, see
https://figshare.com/articles/basc/1285615
"""
versions = ['sym', 'asym']
if version not in versions:
raise ValueError('The version of Brain parcellations requested "%s" '
'does not exist. Please choose one among them %s.' %
(version, str(versions)))
keys = ['scale007', 'scale012', 'scale020', 'scale036', 'scale064',
'scale122', 'scale197', 'scale325', 'scale444']
if version == 'sym':
url = "https://ndownloader.figshare.com/files/1861819"
elif version == 'asym':
url = "https://ndownloader.figshare.com/files/1861820"
opts = {'uncompress': True}
dataset_name = "basc_multiscale_2015"
data_dir = _get_dataset_dir(dataset_name, data_dir=data_dir,