Skip to content

Commit adde085

Browse files
committed
ENH: Add CoordinateImage slicing by parcel name
1 parent 6d8e9d5 commit adde085

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

nibabel/coordimage.py

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import numpy as np
2+
13
import nibabel as nib
24
from nibabel.fileslice import fill_slicer
35
import nibabel.pointset as ps
@@ -16,6 +18,26 @@ def __init__(self, data, coordaxis, header=None):
1618
self.coordaxis = coordaxis
1719
self.header = header
1820

21+
@property
22+
def shape(self):
23+
return self.data.shape
24+
25+
def __getitem__(self, slicer):
26+
if isinstance(slicer, str):
27+
slicer = self.coordaxis.get_indices(slicer)
28+
elif isinstance(slicer, list):
29+
slicer = np.hstack([self.coordaxis.get_indices(sub) for sub in slicer])
30+
31+
if isinstance(slicer, range):
32+
slicer = slice(slicer.start, slicer.stop, slicer.step)
33+
34+
data = self.data
35+
if not isinstance(slicer, slice):
36+
data = np.asanyarray(data)
37+
return self.__class__(data[slicer],
38+
self.coordaxis[slicer],
39+
header=self.header.copy())
40+
1941
@classmethod
2042
def from_image(klass, img):
2143
coordaxis = CoordinateAxis.from_header(img.header)
@@ -53,7 +75,7 @@ def __getitem__(self, slicer):
5375
Return a sub-sampled CoordinateAxis containing structures
5476
matching the indices provided.
5577
"""
56-
if slicer is Ellipsis or slicer == slice(None):
78+
if slicer is Ellipsis or isinstance(slicer, slice) and slicer == slice(None):
5779
return self
5880
elif isinstance(slicer, slice):
5981
slicer = fill_slicer(slicer, len(self))

nibabel/tests/test_coordimage.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,11 @@ def test_Cifti2Image_as_CoordImage():
6868
assert len(subaxis) == len(caxis) - 200
6969
assert len(subaxis.parcels) == len(caxis.parcels)
7070

71-
caxis.get_indices("CIFTI_STRUCTURE_CORTEX_LEFT")
71+
lh_img = cimg["CIFTI_STRUCTURE_CORTEX_LEFT"]
72+
assert len(lh_img.coordaxis.parcels) == 1
73+
assert lh_img.shape == (29696, 1)
74+
75+
# # Not working yet.
76+
# cortex_img = cimg[["CIFTI_STRUCTURE_CORTEX_LEFT", "CIFTI_STRUCTURE_CORTEX_RIGHT"]]
77+
# assert len(cortex_img.coordaxis.parcels) == 2
78+
# assert cortex_img.shape == (59412, 1)

0 commit comments

Comments
 (0)