/
atlas.py
2186 lines (1827 loc) · 72.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 json
import os
import re
import shutil
import warnings
import xml.etree.ElementTree
from pathlib import Path
from tempfile import mkdtemp
import nibabel as nb
import numpy as np
import pandas as pd
from sklearn.utils import Bunch
from .._utils import check_niimg, fill_doc
from ..image import get_data, new_img_like, reorder_img
from ._utils import fetch_files, get_dataset_descr, get_dataset_dir
_TALAIRACH_LEVELS = ["hemisphere", "lobe", "gyrus", "tissue", "ba"]
_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_atlas_difumo(
dimension=64,
resolution_mm=2,
data_dir=None,
resume=True,
verbose=1,
legacy_format=True,
):
"""Fetch DiFuMo brain atlas.
Dictionaries of Functional Modes, or “DiFuMo”, can serve as
:term:`probabilistic atlases<Probabilistic atlas>` to extract
functional signals with different dimensionalities (64, 128,
256, 512, and 1024).
These modes are optimized to represent well raw :term:`BOLD` timeseries,
over a with range of experimental conditions.
See :footcite:t:`Dadi2020`.
.. 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 : :obj:`int`, default=64
Number of dimensions in the dictionary. Valid resolutions
available are {64, 128, 256, 512, 1024}.
resolution_mm : :obj:`int`, default=2mm
The resolution in mm of the atlas to fetch. Valid options
available are {2, 3}.
%(data_dir)s
%(resume)s
%(verbose)s
%(legacy_format)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, the interest attributes are :
- 'maps': :obj:`str`, path to 4D nifti file containing regions
definition. The shape of the image is
``(104, 123, 104, dimension)`` where ``dimension`` is the
requested dimension of the atlas.
- 'labels': :class:`numpy.recarray` containing the labels of
the regions. The length of the label array corresponds to the
number of dimensions requested. ``data.labels[i]`` is the label
corresponding to volume ``i`` in the 'maps' image.
If ``legacy_format`` is set to ``False``, this is a
:class:`pandas.DataFrame`.
- 'description': :obj:`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(
f"Requested dimension={dimension} is not available. "
f"Valid options: {valid_dimensions}"
)
if resolution_mm not in valid_resolution_mm:
raise ValueError(
"Requested resolution_mm={resolution_mm} is not available. "
"Valid options: {valid_resolution_mm}"
)
url = f"https://osf.io/{dic[dimension]}/download"
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 = pd.read_csv(files_[0])
labels = labels.rename(columns={c: c.lower() for c in labels.columns})
if legacy_format:
warnings.warn(_LEGACY_FORMAT_MSG, DeprecationWarning)
labels = labels.to_records(index=False)
# 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)
return Bunch(description=fdescr, maps=files_[1], labels=labels)
@fill_doc
def fetch_atlas_craddock_2012(
data_dir=None,
url=None,
resume=True,
verbose=1,
homogeneity=None,
grp_mean=True,
):
"""Download and return file names \
for the Craddock 2012 :term:`parcellation`.
This function returns a :term:`probabilistic atlas<Probabilistic atlas>`.
The provided images are in MNI152 space. All images are 4D with
shapes equal to ``(47, 56, 46, 43)``.
See :footcite:t:`CreativeCommons` for the licence.
See :footcite:t:`Craddock2012` and :footcite:t:`nitrcClusterROI`
for more information on this :term:`parcellation`.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
homogeneity: :obj:`str`, optional
The choice of the homogeneity ('spatial' or 'temporal' or 'random')
grp_mean: :obj:`bool`, default=True
The choice of the :term:`parcellation` (with group_mean or without)
Default=True.
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, keys are:
- 'scorr_mean': obj:`str`, path to nifti file containing the
group-mean :term:`parcellation`
when emphasizing spatial homogeneity.
- 'tcorr_mean': obj:`str`, path to nifti file containing the
group-mean parcellation when emphasizing temporal homogeneity.
- 'scorr_2level': obj:`str`, path to nifti file containing the
:term:`parcellation` obtained
when emphasizing spatial homogeneity.
- 'tcorr_2level': obj:`str`, path to nifti file containing the
:term:`parcellation` obtained
when emphasizing temporal homogeneity.
- 'random': obj:`str`, path to nifti file containing the
:term:`parcellation` obtained with random clustering.
- 'description': :obj:`str`, general description of the dataset.
Warns
-----
DeprecationWarning
If an homogeneity input is provided, the current behavior
(returning multiple maps) is deprecated.
Starting in version 0.13, one map will be returned in a 'maps' dict key
depending on the homogeneity and grp_mean value.
References
----------
.. footbibliography::
"""
if url is None:
url = (
"https://cluster_roi.projects.nitrc.org"
"/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)
if homogeneity:
if homogeneity in ["spatial", "temporal"]:
if grp_mean:
filename = [
(homogeneity[0] + "corr05_mean_all.nii.gz", url, opts)
]
else:
filename = [
(homogeneity[0] + "corr05_2level_all.nii.gz", url, opts)
]
else:
filename = [("random_all.nii.gz", url, opts)]
data = fetch_files(data_dir, filename, resume=resume, verbose=verbose)
params = dict(maps=data[0], description=fdescr)
else:
params = dict([("description", fdescr)] + list(zip(keys, sub_files)))
warnings.warn(
category=DeprecationWarning,
message="In release 0.13, this fetcher will return a dictionary "
"with one map accessed through a 'maps' key. Please use the new "
"parameters homogeneity and grp_mean.",
)
return Bunch(**params)
@fill_doc
def fetch_atlas_destrieux_2009(
lateralized=True,
data_dir=None,
url=None,
resume=True,
verbose=1,
legacy_format=True,
):
"""Download and load the Destrieux cortical \
:term:`deterministic atlas<Deterministic atlas>` (dated 2009).
See :footcite:t:`Fischl2004`,
and :footcite:t:`Destrieux2009`.
.. note::
Some labels from the list of labels might not be present in the
atlas image, in which case the integer values in the image might
not be consecutive.
Parameters
----------
lateralized : :obj:`bool`, default=True
If True, returns an atlas with distinct regions for right and left
hemispheres.
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
%(legacy_format)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, contains:
- 'maps': :obj:`str`, path to nifti file containing the
:class:`~nibabel.nifti1.Nifti1Image` defining the cortical
ROIs, lateralized or not. The image has shape ``(76, 93, 76)``,
and contains integer values which can be interpreted as the
indices in the list of labels.
- 'labels': :class:`numpy.recarray`, rec array containing the
names of the ROIs.
If ``legacy_format`` is set to ``False``, this is a
:class:`pandas.DataFrame`.
- 'description': :obj:`str`, description of the atlas.
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 = [
(f"destrieux2009_rois_labels{lat}.csv", url, opts),
(f"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=pd.read_csv(files_[0], index_col=0))
if legacy_format:
warnings.warn(_LEGACY_FORMAT_MSG, DeprecationWarning)
params["labels"] = params["labels"].to_records()
params["description"] = Path(files_[2]).read_text()
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.
.. note::
For atlases 'cort-prob-1mm', 'cort-prob-2mm', 'cortl-prob-1mm',
'cortl-prob-2mm', 'sub-prob-1mm', and 'sub-prob-2mm', the function
returns a :term:`Probabilistic atlas`, and the
:class:`~nibabel.nifti1.Nifti1Image` returned is 4D, with shape
``(182, 218, 182, 48)``.
For :term:`deterministic atlases<Deterministic atlas>`, the
:class:`~nibabel.nifti1.Nifti1Image` returned is 3D, with
shape ``(182, 218, 182)`` and 48 regions (+ background).
Parameters
----------
atlas_name : :obj:`str`
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)s
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 the Harvard Oxford atlas
from your installed directory. Since we mimic the same root directory
as FSL to load it easily from your installation.
symmetric_split : :obj:`bool`, default=False
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 :term:`Probabilistic atlas` (*-prob-* atlases).
%(resume)s
%(verbose)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, keys are:
- 'maps': :obj:`str`, path to nifti file containing the
atlas :class:`~nibabel.nifti1.Nifti1Image`. It is a 4D image
if a :term:`Probabilistic atlas` is requested, and a 3D image
if a :term:`maximum probability atlas<Deterministic atlas>` is
requested. In the latter case, the image contains integer
values which can be interpreted as the indices in the list
of labels.
.. note::
For some atlases, it can be the case that some regions
are empty. In this case, no :term:`voxels<voxel>` in the
map are assigned to these regions. So the number of
unique values in the map can be strictly smaller than the
number of region names in ``labels``.
- 'labels': :obj:`list` of :obj:`str`, list of labels for the
regions in the atlas.
- 'filename': Same as 'maps', kept for backward
compatibility only.
- 'description': :obj:`str`, description of 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:
atlases = "\n".join(atlases)
raise ValueError(
f"Invalid atlas name: {atlas_name}. "
f"Please choose an atlas among:\n{atlases}"
)
is_probabilistic = "-prob-" in atlas_name
if is_probabilistic and symmetric_split:
raise ValueError(
"Region splitting not supported for probabilistic atlases"
)
(
atlas_img,
atlas_filename,
names,
is_lateralized,
) = _get_atlas_data_and_labels(
"HarvardOxford",
atlas_name,
symmetric_split=symmetric_split,
data_dir=data_dir,
resume=resume,
verbose=verbose,
)
fdescr = get_dataset_descr("harvard_oxford")
atlas_niimg = check_niimg(atlas_img)
if not symmetric_split or is_lateralized:
return Bunch(
filename=atlas_filename,
maps=atlas_niimg,
labels=names,
description=fdescr,
)
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_filename,
maps=new_atlas_niimg,
labels=new_names,
description=fdescr,
)
@fill_doc
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
.. note::
For atlases 'prob-1mm', and 'prob-2mm', the function returns a
:term:`Probabilistic atlas`, and the
:class:`~nibabel.nifti1.Nifti1Image` returned is 4D, with shape
``(182, 218, 182, 62)``.
For :term:`deterministic atlases<Deterministic atlas>`, the
:class:`~nibabel.nifti1.Nifti1Image` returned is 3D, with shape
``(182, 218, 182)`` and 62 regions (+ background).
Parameters
----------
atlas_name : :obj:`str`
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)s
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 : :obj:`bool`, default=False
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 :term:`Probabilistic atlas`
(``*-prob-*`` atlases).
%(resume)s
%(verbose)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, keys are:
- 'maps': :class:`~nibabel.nifti1.Nifti1Image`. It is a 4D image
if a :term:`Probabilistic atlas` is requested, and a 3D image
if a :term:`maximum probability atlas<Deterministic atlas>` is
requested. In the latter case, the image contains integer
values which can be interpreted as the indices in the list
of labels.
.. note::
For some atlases, it can be the case that some regions
are empty. In this case, no :term:`voxels<voxel>` in the
map are assigned to these regions. So the number of
unique values in the map can be strictly smaller than the
number of region names in ``labels``.
- 'labels': :obj:`list` of :obj:`str`, list of labels for the
regions in the atlas.
- 'filename': Same as 'maps', kept for backward
compatibility only.
- 'description': :obj:`str`, description of 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:
atlases = "\n".join(atlases)
raise ValueError(
f"Invalid atlas name: {atlas_name}. "
f"Please choose an atlas among:\n{atlases}"
)
is_probabilistic = atlas_name.startswith("prob-")
if is_probabilistic and symmetric_split:
raise ValueError(
"Region splitting not supported for probabilistic atlases"
)
atlas_img, atlas_filename, 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
)
fdescr = get_dataset_descr("juelich")
return Bunch(
filename=atlas_filename,
maps=new_atlas_niimg,
labels=list(new_names),
description=fdescr,
)
def _get_atlas_data_and_labels(
atlas_source,
atlas_name,
symmetric_split=False,
data_dir=None,
resume=True,
verbose=1,
):
"""Implement fetching logic common to \
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 = "https://www.nitrc.org/frs/download.php/9902/HarvardOxford.tgz"
else:
raise ValueError(f"Atlas source {atlas_source} is not valid.")
# 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, f"{atlas_source}-{atlas_name}.nii.gz"
)
atlas_file, 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_file)
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}'"
)
# fix typos in Harvard Oxford labels
if atlas_source == "HarvardOxford":
label.text = label.text.replace("Ventrical", "Ventricle")
label.text = label.text.replace("Operculum", "Opercular")
names[new_idx] = label.text.strip()
# 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, atlas_file, names, is_lateralized
def _merge_probabilistic_maps_juelich(atlas_data, names):
"""Handle probabilistic juelich atlases when symmetric_split=False.
Helper function for fetch_atlas_juelich.
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):
"""Handle 3D atlases when symmetric_split=False.
Helper function for fetch_atlas_juelich.
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):
"""Handle 3D atlases when symmetric_split=True.
Helper function for both fetch_atlas_juelich and
fetch_atlas_harvard_oxford.
"""
# 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] = f"Left {name}"
if name.endswith("R"):
names[idx] = re.sub(r" R$", "", name)
names[idx] = f"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(f"Left {name}")
new_label += 1
new_atlas[right_atlas == label] = new_label
new_names.append(f"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 :term:`Probabilistic atlas`.
It can be downloaded at :footcite:t:`atlas_msdl`, and cited
using :footcite:t:`Varoquaux2011`.
See also :footcite:t:`Varoquaux2013` for more information.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, the interest attributes are :
- 'maps': :obj:`str`, path to nifti file containing the
:term:`Probabilistic atlas` image (shape is equal to
``(40, 48, 35, 39)``).
- 'labels': :obj:`list` of :obj:`str`, list containing the labels
of the regions. There are 39 labels such that ``data.labels[i]``
corresponds to map ``i``.
- 'region_coords': :obj:`list` of length-3 :obj:`tuple`,
``data.region_coords[i]`` contains the coordinates ``(x, y, z)``
of region ``i`` in :term:`MNI` space.
- 'networks': :obj:`list` of :obj:`str`, list containing the names
of the networks. There are 39 network names such that
``data.networks[i]`` is the network name of region ``i``.
- 'description': :obj:`str`, description of 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 = pd.read_csv(files[0])
labels = [name.strip() for name in csv_data["name"].tolist()]
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", module="numpy", category=FutureWarning
)
region_coords = csv_data[["x", "y", "z"]].values.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,
)
@fill_doc
def fetch_coords_power_2011(legacy_format=True):
"""Download and load the Power et al. brain atlas composed of 264 ROIs.
See :footcite:t:`Power2011`.
Parameters
----------
%(legacy_format)s
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, contains:
- 'rois': :class:`numpy.recarray`, rec array containing the
coordinates of 264 ROIs in :term:`MNI` space.
If ``legacy_format`` is set to ``False``, this is a
:class:`pandas.DataFrame`.
- 'description': :obj:`str`, description of the atlas.
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=pd.read_csv(csv), description=fdescr)
params["rois"] = params["rois"].rename(
columns={c: c.lower() for c in params["rois"].columns}
)
if legacy_format:
warnings.warn(_LEGACY_FORMAT_MSG, DeprecationWarning)
params["rois"] = params["rois"].to_records(index=False)
return Bunch(**params)
@fill_doc
def fetch_atlas_smith_2009(
data_dir=None,
url=None,
resume=True,
verbose=1,
mirror="origin",
dimension=None,
resting=True,
):
"""Download and load the Smith :term:`ICA` and BrainMap \
:term:`Probabilistic atlas` (2009).
See :footcite:t:`Smith2009b` and :footcite:t:`Laird2011`.
Parameters
----------
%(data_dir)s
%(url)s
%(resume)s
%(verbose)s
mirror : :obj:`str`, default='origin'
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.
dimension: :obj:`int`, optional
Number of dimensions in the dictionary. Valid resolutions
available are {10, 20, 70}.
resting : :obj:`bool`, default=True
Either to fetch the resting-:term:`fMRI` or BrainMap components
Returns
-------
data : :class:`sklearn.utils.Bunch`
Dictionary-like object, contains:
- 'rsn20': :obj:`str`, path to nifti file containing the
20-dimensional :term:`ICA`, resting-:term:`fMRI` components.
The shape of the image is ``(91, 109, 91, 20)``.