bids.py 6.84 KB
Newer Older
Paul McCarthy's avatar
Paul McCarthy committed
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
#
# bids.py - Simple BIDS metadata reader.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides a few functions for working with BIDS data sets.

.. autosummary::
   :nosignatures:

12
   BIDSFile
Paul McCarthy's avatar
Paul McCarthy committed
13
14
15
16
17
   isBIDSDir
   inBIDSDir
   isBIDSFile
   loadMetadata

18
19
20
All of the other functions in this module should not be considered part of the
public API.

21
.. see:: https://bids-specification.readthedocs.io/en/stable/
Paul McCarthy's avatar
Paul McCarthy committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

.. note::  The `pybids <https://bids-standard.github.io/pybids/>`_ library is
           a more suitable choice if you are after a more robust and featured
           interface for working with BIDS datasets.
"""


import os.path   as op
import itertools as it
import              re
import              glob
import              json

import fsl.utils.memoize as memoize
import fsl.utils.path    as fslpath


class BIDSFile(object):
40
41
    """The ``BIDSFile`` class parses and stores the entities and suffix
    contained in a BIDS file. See the :func:`parseFilename` function.
Paul McCarthy's avatar
Paul McCarthy committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

    The :meth:`match` method can be used to compare two ``BIDSFile`` instances.

    The following attributes are available on a ``BIDSFile`` instance:

     - ``filename``: Absolute path to the file
     - ``entities``: Dict of ``key : value`` pairs, the entities that are
       present in the file name (e.g. ``{'sub' : '01}``)
     - ``suffix``: File suffix (e.g. ``T1w``, ``bold``, etc.)
    """


    def __init__(self, filename):
        """Create a ``BIDSFile``. """
        entities, suffix = parseFilename(filename)
        self.filename    = op.abspath(filename)
        self.entities    = entities
        self.suffix      = suffix


62
63
64
65
66
67
68
69
70
71
72
    def __str__(self):
        """Return a strimg representation of this ``BIDSFile``. """
        return 'BIDSFile({})'.format(self.filename)


    def __repr__(self):
        """Return a strimg representation of this ``BIDSFile``. """
        return str(self)


    def match(self, other, suffix=True):
Paul McCarthy's avatar
Paul McCarthy committed
73
74
        """Compare this ``BIDSFile`` to ``other``.

75
76
77
78
79
80
81
82
        :arg other:  ``BIDSFile`` to compare

        :arg suffix: Defaults to ``True``. If ``False``, the comparison
                     is made solely on the entity values.

        :returns:    ``True`` if ``self.suffix == other.suffix`` (unless
                     ``suffix`` is ``False``) and if all of the entities in
                     ``other`` are present in ``self``, ``False`` otherwise.
Paul McCarthy's avatar
Paul McCarthy committed
83
84
        """

85
        suffix   = (not suffix) or (self.suffix == other.suffix)
Paul McCarthy's avatar
Paul McCarthy committed
86
87
88
        entities = True

        for key, value in other.entities.items():
89
            entities = entities and (self.entities.get(key, None) == value)
Paul McCarthy's avatar
Paul McCarthy committed
90
91
92
93
94

        return suffix and entities


def parseFilename(filename):
95
96
97
    """Parses a BIDS-like file name, returning the entities and suffix encoded
    in the name. See the :func:`isBIDSFile` function for an explanation of
    what is considered to be a valid BIDS file name.
98
99
100

    .. note:: This function assumes that no period (``.``) characters occur in
              the body of a BIDS filename.
Paul McCarthy's avatar
Paul McCarthy committed
101
102

    :returns: A tuple containing:
103
104
               - A dict containing the entities
               - The suffix
Paul McCarthy's avatar
Paul McCarthy committed
105
106
    """

107
108
109
110
    if not isBIDSFile(filename, strict=False):
        raise ValueError('Does not look like a BIDS '
                         'file: {}'.format(filename))

Paul McCarthy's avatar
Paul McCarthy committed
111
112
113
    suffix   = None
    entities = []
    filename = op.basename(filename)
114
    filename = fslpath.removeExt(filename, firstDot=True)
Paul McCarthy's avatar
Paul McCarthy committed
115
116
117
118
119
    parts    = filename.split('_')

    for part in parts[:-1]:
        entities.append(part.split('-'))

120
    suffix   = parts[-1]
Paul McCarthy's avatar
Paul McCarthy committed
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
    entities = dict(entities)

    return entities, suffix


def isBIDSDir(dirname):
    """Returns ``True`` if ``dirname`` is the root directory of a BIDS dataset.
    """
    return op.exists(op.join(dirname, 'dataset_description.json'))


def inBIDSDir(filename):
    """Returns ``True`` if ``filename`` looks like it is within a BIDS dataset
    directory, ``False`` otherwise.
    """

    dirname = op.abspath(op.dirname(filename))
    inBIDS  = False

    while True:

        if isBIDSDir(dirname):
            inBIDS = True
            break

        prevdir = dirname
        dirname = op.dirname(dirname)

        # at filesystem root
        if prevdir == dirname:
            break

    return inBIDS


156
def isBIDSFile(filename, strict=True):
Paul McCarthy's avatar
Paul McCarthy committed
157
    """Returns ``True`` if ``filename`` looks like a BIDS image or JSON file.
158

159
160
161
162
163
164
165
166
167
    A BIDS file name must consist of one or more "entities" (alpha-numeric
    ``name-value`` pairs), a "suffix", all separated by underscores, and a
    regular file extension. For example, the following file::

        sub-01_ses-01_task-stim_bold.nii.gz

    has suffix ``bold``, entities ``sub=01``, ``ses=01`` and ``task=stim``, and
    extension ``.nii.gz``.

168
169
170
    :arg filename: Name of file to check
    :arg strict:   If ``True`` (the default), the file must be within a BIDS
                   dataset directory, as defined by :func:`inBIDSDir`.
Paul McCarthy's avatar
Paul McCarthy committed
171
172
    """

173
    name    = op.basename(filename)
174
    pattern = r'([a-z0-9]+-[a-z0-9]+_)+([a-z0-9])+\.(.+)'
175
    flags   = re.ASCII | re.IGNORECASE
176
    match   = re.fullmatch(pattern, name, flags) is not None
Paul McCarthy's avatar
Paul McCarthy committed
177

178
    return ((not strict) or inBIDSDir(filename)) and match
Paul McCarthy's avatar
Paul McCarthy committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195


@memoize.memoize
def loadMetadataFile(filename):
    """Load ``filename`` (assumed to be JSON), returning its contents. """
    with open(filename, 'rt') as f:
        return json.load(f)


def loadMetadata(filename):
    """Load all of the metadata associated with ``filename``.

    :arg filename: Path to a data file in a BIDS dataset.
    :returns:      A dict containing all of the metadata associated with
                   ``filename``
    """

196
    filename  = op.abspath(filename)
Paul McCarthy's avatar
Paul McCarthy committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    bfile     = BIDSFile(filename)
    dirname   = op.dirname(filename)
    prevdir   = filename
    metafiles = []
    metadata  = {}

    # Walk up the directory tree until
    # we hit the BIDS dataset root, or
    # the filesystem root
    while True:

        # Gather all json files in this
        # directory with matching entities
        # and suffix, sorted alphabetically
211
212
213
        # and reversed, so that earlier
        # ones take precedence
        files = reversed(sorted(glob.glob(op.join(dirname, '*.json'))))
Paul McCarthy's avatar
Paul McCarthy committed
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
        files = [BIDSFile(f) for f in files if isBIDSFile(f)]
        files = [f.filename  for f in files if bfile.match(f)]

        # build a list of all files
        metafiles.append(files)

        # move to the next dir up
        prevdir = dirname
        dirname = op.dirname(dirname)

        # stop when we hit the dataset or filesystem root
        if isBIDSDir(prevdir) or dirname == prevdir:
            break

    # Load in each json file, from
    # shallowest to deepest, so entries
    # in deeper files take precedence
    # over shallower ones.
    for f in it.chain(*reversed(metafiles)):

        # assuming here that every file contains a dict
        metadata.update(loadMetadataFile(f))

    return metadata