gifti.py 9.93 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
#
# gifti.py - GIFTI file support.
#
# Author: Paul McCarthy  <pauldmccarthy@gmail.com>
#         Michiel Cottar <michiel.cottaar@ndcn.ox.ac.uk>
#
"""This class provides classes and functions for working with GIFTI files.

The GIFTI file format specification can be found at
http://www.nitrc.org/projects/gifti/

Support is currently very basic - only the following classes/functions
are available:

  .. autosummary::
     :nosignatures:

19
20
21
     GiftiMesh
     loadGiftiMesh
     loadGiftiVertexData
22
     relatedFiles
23
24
25
"""


26
import            glob
27
import os.path as op
28
import            deprecation
29

30
import numpy   as np
31
32
import nibabel as nib

33
34
35
import fsl.utils.path     as fslpath
import fsl.data.constants as constants
import fsl.data.mesh      as fslmesh
36
37


38
39
40
41
42
43
44
45
46
47
48
49

ALLOWED_EXTENSIONS = ['.surf.gii']
"""List of file extensions that a file containing Gifti surface data
is expected to have.
"""


EXTENSION_DESCRIPTIONS = ['GIFTI surface file']
"""A description for each of the :data:`ALLOWED_EXTENSIONS`. """


class GiftiMesh(fslmesh.Mesh):
50
51
52
    """Class which represents a GIFTI surface image. This is essentially
    just a 3D model made of triangles.

53
54
55
    For each GIFTI surface file that is loaded, the
    ``nibabel.gifti.GiftiImage`` instance is stored in the :class:`.Meta`
    store, with the absolute path to the surface file as the key.
56
57
58
    """


59
    def __init__(self, infile, fixWinding=False, loadAll=False):
60
        """Load the given GIFTI file using ``nibabel``, and extracts surface
Paul McCarthy's avatar
Paul McCarthy committed
61
        data using the  :func:`loadGiftiSurface` function.
62

63
64
65
66
67
68
69
70
        :arg infile:     A GIFTI surface file (``*.surf.gii``).

        :arg fixWinding: Passed through to the :meth:`addVertices` method
                         for the first vertex set.

        :arg loadAll:    If ``True``, the ``infile`` directory is scanned
                         for other surface files which are then loaded
                         as additional vertex sets.
71
72
73

        .. todo:: Allow loading from a ``.topo.gii`` and ``.coord.gii`` file?
                  Maybe.
74
75
        """

76
77
78
        name   = fslpath.removeExt(op.basename(infile), ALLOWED_EXTENSIONS)
        infile = op.abspath(infile)

79
        surfimg, vertices, indices = loadGiftiSurface(infile)
80

81
82
83
84
        fslmesh.Mesh.__init__(self,
                              indices,
                              name=name,
                              dataSource=infile)
85

86
87
        self.addVertices(vertices, infile, fixWinding=fixWinding)
        self.setMeta(infile, surfimg)
88

89
90
91
92
        # Find and load all other
        # surfaces in the same directory
        # as the specfiied one.
        if loadAll:
93

94
95
            nvertices = vertices.shape[0]
            surfFiles = relatedFiles(infile, 'surf')
96

97
98
99
100
101
102
103
104
105
106
107
108
            for sfile in surfFiles:

                surfimg, vertices, _ = loadGiftiSurface(sfile)

                if vertices.shape[0] != nvertices:
                    continue

                self.addVertices(vertices, sfile, select=False)
                self.setMeta(    sfile, surfimg)


    def loadVertexData(self, infile, key=None):
109
110
111
        """Overrides the :meth:`.TriangleMesh.loadVertexData` method.

        Attempts to load data associated with each vertex of this
112
113
        ``GiftiSurface`` from the given ``dataSource``, which may be
        a GIFTI file or a plain text file which contains vertex data.
114
115
        """

116
        infile = op.abspath(infile)
117

118
119
        if key is None:
            key = infile
120

121
122
123
124
        if infile.endswith('.gii'):
            vdata = loadGiftiVertexData(infile)[1]
            self.addVertexData(key, vdata)
            return vdata
125

126
127
        else:
            return fslmesh.Mesh.loadVertexData(self, infile, key)
128
129


130
def loadGiftiMesh(filename):
131
132
133
134
135
136
137
138
139
140
    """Extracts surface data from the given ``nibabel.gifti.GiftiImage``.

    The image is expected to contain the following``<DataArray>`` elements:

      - one comprising ``NIFTI_INTENT_POINTSET`` data (the surface vertices)
      - one comprising ``NIFTI_INTENT_TRIANGLE`` data (vertex indices
        defining the triangles).

    A ``ValueError`` will be raised if this is not the case.

141
    :arg filename: Name of a GIFTI file containing surface data.
142
143
144

    :returns:     A tuple containing these values:

145
146
                   - The loaded ``nibabel.gifti.GiftiImage`` instance

147
                   - A ``(N, 3)`` array containing ``N`` vertices.
148

149
150
                   - A ``(M, 3))`` array containing the vertex indices for
                     ``M`` triangles.
151
152
    """

153
    gimg = nib.load(filename)
154

155
156
157
158
159
160
161
    pointsetCode = constants.NIFTI_INTENT_POINTSET
    triangleCode = constants.NIFTI_INTENT_TRIANGLE

    pointsets = [d for d in gimg.darrays if d.intent == pointsetCode]
    triangles = [d for d in gimg.darrays if d.intent == triangleCode]

    if len(gimg.darrays) != 2:
162
163
164
        raise ValueError('{}: GIFTI surface files must contain '
                         'exactly one pointset array and one '
                         'triangle array'.format(filename))
165

166
    if len(pointsets) != 1:
167
168
        raise ValueError('{}: GIFTI surface files must contain '
                         'exactly one pointset array'.format(filename))
169

170
    if len(triangles) != 1:
171
172
        raise ValueError('{}: GIFTI surface files must contain '
                         'exactly one triangle array'.format(filename))
173
174
175
176
177
178
179
180
181
182
183
184
185

    vertices = pointsets[0].data
    indices  = triangles[0].data

    return gimg, vertices, indices


def loadGiftiVertexData(filename):
    """Loads vertex data from the given GIFTI file.

    It is assumed that the given file does not contain any
    ``NIFTI_INTENT_POINTSET`` or ``NIFTI_INTENT_TRIANGLE`` data arrays, and
    which contains either:
186

187
188
189
190
191
192
193
      - One ``(M, N)`` data array containing ``N`` data points for ``M``
        vertices

      - One or more ``(M, 1)`` data arrays each containing a single data point
        for ``M`` vertices, and all with the same intent code

    Returns a tuple containing:
194

195
      - The loaded ``nibabel.gifti.GiftiImage`` object
196

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
      - A ``(M, N)`` numpy array containing ``N`` data points for ``M``
        vertices
    """

    gimg = nib.load(filename)

    intents = set([d.intent for d in gimg.darrays])

    if len(intents) != 1:
        raise ValueError('{} contains multiple (or no) intents'
                         ': {}'.format(filename, intents))

    intent = intents.pop()

    if intent in (constants.NIFTI_INTENT_POINTSET,
                  constants.NIFTI_INTENT_TRIANGLE):
213

214
215
216
217
218
219
220
        raise ValueError('{} contains surface data'.format(filename))

    # Just a single array - return it as-is.
    # n.b. Storing (M, N) data in a single
    # DataArray goes against the GIFTI spec,
    # but hey, it happens.
    if len(gimg.darrays) == 1:
221
222
        vdata = gimg.darrays[0].data
        return gimg, vdata.reshape(vdata.shape[0], -1)
223
224
225
226
227
228
229
230

    # Otherwise extract and concatenate
    # multiple 1-dimensional arrays
    vdata = [d.data for d in gimg.darrays]

    if any([len(d.shape) != 1 for d in vdata]):
        raise ValueError('{} contains one or more non-vector '
                         'darrays'.format(filename))
231

232
233
234
235
    vdata = np.vstack(vdata).T
    vdata = vdata.reshape(vdata.shape[0], -1)

    return gimg, vdata
236
237


238
def relatedFiles(fname, ftype=None):
239
240
241
    """Given a GIFTI file, returns a list of other GIFTI files in the same
    directory which appear to be related with the given one.  Files which
    share the same prefix are assumed to be related to the given file.
242
243
244
245
246

    :arg fname: Name of the file to search for related files for

    :arg ftype: If provided, only files with a name ``'*.[ftype].gii'`` are
                searched for.
247
248
    """

Paul McCarthy's avatar
Paul McCarthy committed
249
250
251
    # We want to return all files in the same
    # directory which have the following name:

252
    #
Paul McCarthy's avatar
Paul McCarthy committed
253
254
255
256
257
258
259
260
    # [prefix].*.[type].gii
    #
    #   where
    #     - prefix is the file prefix, and which
    #       may include periods.
    #
    #     - we don't care about the middle
    #
261
    #     - type is func, shape, label, time, or `ftype`
Paul McCarthy's avatar
Paul McCarthy committed
262
263
264
265
266
267
268
269
270
271
272

    # We determine the unique prefix of the
    # given file, and back-up to the most
    # recent period. Then search for other
    # files which have that same (non-unique)
    # prefix.
    prefix  = fslpath.uniquePrefix(fname)
    lastdot = prefix.rfind('.')
    prefix  = prefix[:lastdot]

    if lastdot == -1:
273
        return []
Paul McCarthy's avatar
Paul McCarthy committed
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
    if ftype is None:
        ftypes = ['func', 'shape', 'label', 'time']
    else:
        ftypes = [ftype]

    related = []

    for ftype in ftypes:
        related += list(glob.glob('{}*.{}.gii'.format(prefix, ftype)))

    return [r for r in related if r != fname]


class GiftiSurface(fslmesh.TriangleMesh):
    """Deprecated - use GiftiMesh instead. """


    @deprecation.deprecated(deprecated_in='1.6.0',
                            removed_in='2.0.0',
                            details='Use GiftiMesh instead')
    def __init__(self, infile, fixWinding=False):
        """Deprecated - use GiftiMesh instead. """
        surfimg, vertices, indices = loadGiftiSurface(infile)

        fslmesh.TriangleMesh.__init__(self, vertices, indices, fixWinding)
Paul McCarthy's avatar
Paul McCarthy committed
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
        name   = fslpath.removeExt(op.basename(infile), ALLOWED_EXTENSIONS)
        infile = op.abspath(infile)

        self._Mesh__name       = name
        self._Mesh__dataSource = infile
        self.surfImg           = surfimg


    @deprecation.deprecated(deprecated_in='1.6.0',
                            removed_in='2.0.0',
                            details='Use GiftiMesh instead')
    def loadVertexData(self, dataSource, vertexData=None):
        """Deprecated - use GiftiMesh instead. """

        if vertexData is None:
            if dataSource.endswith('.gii'):
                vertexData = loadGiftiVertexData(dataSource)[1]
            else:
                vertexData = None

        return fslmesh.TriangleMesh.loadVertexData(
            self, dataSource, vertexData)


@deprecation.deprecated(deprecated_in='1.6.0',
                        removed_in='2.0.0',
                        details='Use loadGiftiMesh instead')
def loadGiftiSurface(filename):
    """Deprecated - use loadGiftiMesh instead."""
    return loadGiftiMesh(filename)