-
Notifications
You must be signed in to change notification settings - Fork 92
/
path.py
1976 lines (1676 loc) · 72.8 KB
/
path.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
"""BIDS compatible path functionality."""
# Authors: Adam Li <[email protected]>
# Stefan Appelhoff <[email protected]>
#
# License: BSD-3-Clause
import glob
import os
import re
from io import StringIO
import shutil as sh
from copy import deepcopy
from os import path as op
from pathlib import Path
from datetime import datetime
import json
from textwrap import indent
from typing import Optional
import numpy as np
from mne.utils import logger, _validate_type, verbose, _check_fname
from mne_bids.config import (
ALLOWED_PATH_ENTITIES, ALLOWED_FILENAME_EXTENSIONS,
ALLOWED_FILENAME_SUFFIX, ALLOWED_PATH_ENTITIES_SHORT,
ALLOWED_DATATYPES, ALLOWED_DATATYPE_EXTENSIONS,
ALLOWED_SPACES,
reader, ENTITY_VALUE_TYPE)
from mne_bids.utils import (_check_key_val, _check_empty_room_basename,
param_regex, _ensure_tuple, warn)
def _find_empty_room_candidates(bids_path):
"""Get matching empty-room file for an MEG recording."""
# Check whether we have a BIDS root.
bids_root = bids_path.root
if bids_root is None:
raise ValueError('The root of the "bids_path" must be set. '
'Please use `bids_path.update(root="<root>")` '
'to set the root of the BIDS folder to read.')
bids_path = bids_path.copy()
datatype = 'meg' # We're only concerned about MEG data here
bids_fname = bids_path.update(suffix=datatype).fpath
_, ext = _parse_ext(bids_fname)
emptyroom_dir = BIDSPath(root=bids_root, subject='emptyroom').directory
if not emptyroom_dir.exists():
return list()
# Find the empty-room recording sessions.
emptyroom_session_dirs = [x for x in emptyroom_dir.iterdir()
if x.is_dir() and str(x.name).startswith('ses-')]
if not emptyroom_session_dirs: # No session sub-directories found
emptyroom_session_dirs = [emptyroom_dir]
# Now try to discover all recordings inside the session directories.
allowed_extensions = list(reader.keys())
# `.pdf` is just a "virtual" extension for BTi data (which is stored inside
# a dedicated directory that doesn't have an extension)
del allowed_extensions[allowed_extensions.index('.pdf')]
candidate_er_fnames = []
for session_dir in emptyroom_session_dirs:
dir_contents = glob.glob(op.join(session_dir, datatype,
f'sub-emptyroom_*_{datatype}*'))
for item in dir_contents:
item = Path(item)
if ((item.suffix in allowed_extensions) or
(not item.suffix and item.is_dir())): # Hopefully BTi?
candidate_er_fnames.append(item.name)
candidates = list()
for er_fname in candidate_er_fnames:
# get entities from filenamme
er_bids_path = get_bids_path_from_fname(er_fname, check=False)
er_bids_path.subject = 'emptyroom' # er subject entity is different
er_bids_path.root = bids_root
er_bids_path.datatype = 'meg'
candidates.append(er_bids_path)
return candidates
def _find_matched_empty_room(bids_path):
from mne_bids import read_raw_bids # avoid circular import.
candidates = _find_empty_room_candidates(bids_path)
# Walk through recordings, trying to extract the recording date:
# First, from the filename; and if that fails, from `info['meas_date']`.
best_er_bids_path = None
min_delta_t = np.inf
date_tie = False
failed_to_get_er_date_count = 0
bids_path = bids_path.copy().update(datatype='meg')
raw = read_raw_bids(bids_path=bids_path)
if raw.info['meas_date'] is None:
raise ValueError('The provided recording does not have a measurement '
'date set. Cannot get matching empty-room file.')
ref_date = raw.info['meas_date']
del bids_path, raw
for er_bids_path in candidates:
# get entities from filenamme
er_meas_date = None
# Try to extract date from filename.
if er_bids_path.session is not None:
try:
er_meas_date = datetime.strptime(
er_bids_path.session, '%Y%m%d')
except (ValueError, TypeError):
# There is a session in the filename, but it doesn't encode a
# valid date.
pass
if er_meas_date is None: # No luck so far! Check info['meas_date']
_, ext = _parse_ext(er_bids_path.fpath)
extra_params = None
if ext == '.fif':
extra_params = dict(allow_maxshield='yes')
er_raw = read_raw_bids(bids_path=er_bids_path,
extra_params=extra_params)
er_meas_date = er_raw.info['meas_date']
if er_meas_date is None: # There's nothing we can do.
failed_to_get_er_date_count += 1
continue
er_meas_date = er_meas_date.replace(tzinfo=ref_date.tzinfo)
delta_t = er_meas_date - ref_date
if abs(delta_t.total_seconds()) == min_delta_t:
date_tie = True
elif abs(delta_t.total_seconds()) < min_delta_t:
min_delta_t = abs(delta_t.total_seconds())
best_er_bids_path = er_bids_path
date_tie = False
if failed_to_get_er_date_count > 0:
msg = (f'Could not retrieve the empty-room measurement date from '
f'a total of {failed_to_get_er_date_count} recording(s).')
warn(msg)
if date_tie:
msg = ('Found more than one matching empty-room measurement with the '
'same recording date. Selecting the first match.')
warn(msg)
return best_er_bids_path
class BIDSPath(object):
"""A BIDS path object.
BIDS filename prefixes have one or more pieces of metadata in them. They
must follow a particular order, which is followed by this function. This
will generate the *prefix* for a BIDS filename that can be used with many
subsequent files, or you may also give a suffix that will then complete
the file name.
BIDSPath allows dynamic updating of its entities in place, and operates
similar to `pathlib.Path`. In addition, it can query multiple paths
with matching BIDS entities via the ``match`` method.
Note that not all parameters are applicable to each suffix of data. For
example, electrode location TSV files do not need a "task" field.
Parameters
----------
subject : str | None
The subject ID. Corresponds to "sub".
session : str | None
The acquisition session. Corresponds to "ses".
task : str | None
The experimental task. Corresponds to "task".
acquisition: str | None
The acquisition parameters. Corresponds to "acq".
run : int | None
The run number. Corresponds to "run".
processing : str | None
The processing label. Corresponds to "proc".
recording : str | None
The recording name. Corresponds to "rec".
space : str | None
The coordinate space for anatomical and sensor location
files (e.g., ``*_electrodes.tsv``, ``*_markers.mrk``).
Corresponds to "space".
Note that valid values for ``space`` must come from a list
of BIDS keywords as described in the BIDS specification.
split : int | None
The split of the continuous recording file for ``.fif`` data.
Corresponds to "split".
description : str | None
This corresponds to the BIDS entity ``desc``. It is used to provide
additional information for derivative data, e.g., preprocessed data
may be assigned ``description='cleaned'``.
.. versionadded:: 0.11
suffix : str | None
The filename suffix. This is the entity after the
last ``_`` before the extension. E.g., ``'channels'``.
The following filename suffix's are accepted:
'meg', 'markers', 'eeg', 'ieeg', 'T1w',
'participants', 'scans', 'electrodes', 'coordsystem',
'channels', 'events', 'headshape', 'digitizer',
'beh', 'physio', 'stim'
extension : str | None
The extension of the filename. E.g., ``'.json'``.
datatype : str
The BIDS data type, e.g., ``'anat'``, ``'func'``, ``'eeg'``, ``'meg'``,
``'ieeg'``.
root : path-like | None
The root directory of the BIDS dataset.
check : bool
If ``True``, enforces BIDS conformity. Defaults to ``True``.
Attributes
----------
entities : dict
A dictionary of the BIDS entities and their values:
``subject``, ``session``, ``task``, ``acquisition``,
``run``, ``processing``, ``space``, ``recording``,
``split``, ``description``, ``suffix``, and ``extension``.
datatype : str | None
The data type, i.e., one of ``'meg'``, ``'eeg'``, ``'ieeg'``,
``'anat'``.
basename : str
The basename of the file path. Similar to `os.path.basename(fpath)`.
root : pathlib.Path
The root of the BIDS path.
directory : pathlib.Path
The directory path.
fpath : pathlib.Path
The full file path.
check : bool
Whether to enforce BIDS conformity.
Examples
--------
Generate a BIDSPath object and inspect it
>>> bids_path = BIDSPath(subject='test', session='two', task='mytask',
... suffix='ieeg', extension='.edf', datatype='ieeg')
>>> print(bids_path.basename)
sub-test_ses-two_task-mytask_ieeg.edf
>>> bids_path
BIDSPath(
root: None
datatype: ieeg
basename: sub-test_ses-two_task-mytask_ieeg.edf)
Copy and update multiple entities at once
>>> new_bids_path = bids_path.copy().update(subject='test2',
... session='one')
>>> print(new_bids_path.basename)
sub-test2_ses-one_task-mytask_ieeg.edf
Printing a BIDSPath will show a relative path when `root` is not set
>>> print(new_bids_path)
sub-test2/ses-one/ieeg/sub-test2_ses-one_task-mytask_ieeg.edf
Setting `suffix` without an identifiable datatype will make
BIDSPath try to guess the datatype
>>> new_bids_path = new_bids_path.update(suffix='channels',
... extension='.tsv')
>>> print(new_bids_path)
sub-test2/ses-one/ieeg/sub-test2_ses-one_task-mytask_channels.tsv
You can set a new root for the BIDS dataset. Let's see what the
different properties look like for our object:
>>> new_bids_path = new_bids_path.update(root='/bids_dataset')
>>> print(new_bids_path.root.as_posix())
/bids_dataset
>>> print(new_bids_path.basename)
sub-test2_ses-one_task-mytask_channels.tsv
>>> print(new_bids_path)
/bids_dataset/sub-test2/ses-one/ieeg/sub-test2_ses-one_task-mytask_channels.tsv
>>> print(new_bids_path.directory.as_posix())
/bids_dataset/sub-test2/ses-one/ieeg
Notes
-----
BIDS entities are generally separated with a ``"_"`` character, while
entity key/value pairs are separated with a ``"-"`` character.
There are checks performed to make sure that there are no ``'-'``, ``'_'``,
or ``'/'`` characters contained in any entity keys or values.
To represent a filename such as ``dataset_description.json``,
one can set ``check=False``, and pass ``suffix='dataset_description'``
and ``extension='.json'``.
``BIDSPath`` can also be used to represent file and folder names of data
types that are not yet supported through MNE-BIDS, but are recognized by
BIDS. For example, one can set ``datatype`` to ``dwi`` or ``func`` and
pass ``check=False`` to represent diffusion-weighted imaging and
functional MRI paths.
"""
def __init__(self, subject=None, session=None,
task=None, acquisition=None, run=None, processing=None,
recording=None, space=None, split=None, description=None,
root=None, suffix=None, extension=None,
datatype=None, check=True):
if all(ii is None for ii in [subject, session, task,
acquisition, run, processing,
recording, space, description,
root, suffix, extension]):
raise ValueError("At least one parameter must be given.")
self.check = check
self.update(subject=subject, session=session, task=task,
acquisition=acquisition, run=run, processing=processing,
recording=recording, space=space, split=split,
description=description, root=root, datatype=datatype,
suffix=suffix, extension=extension)
@property
def entities(self):
"""Return dictionary of the BIDS entities."""
return {
'subject': self.subject,
'session': self.session,
'task': self.task,
'acquisition': self.acquisition,
'run': self.run,
'processing': self.processing,
'space': self.space,
'recording': self.recording,
'split': self.split,
'description': self.description,
}
@property
def basename(self):
"""Path basename."""
basename = []
for key, val in self.entities.items():
if val is not None and key != 'datatype':
# convert certain keys to shorthand
long_to_short_entity = {
val: key for key, val
in ALLOWED_PATH_ENTITIES_SHORT.items()
}
key = long_to_short_entity[key]
basename.append(f'{key}-{val}')
if self.suffix is not None:
if self.extension is not None:
basename.append(f'{self.suffix}{self.extension}')
else:
basename.append(self.suffix)
basename = '_'.join(basename)
return basename
@property
def directory(self):
"""Get the BIDS parent directory.
If ``subject``, ``session`` and ``datatype`` are set, then they will be
used to construct the directory location. For example, if
``subject='01'``, ``session='02'`` and ``datatype='ieeg'``, then the
directory would be::
<root>/sub-01/ses-02/ieeg
Returns
-------
data_path : pathlib.Path
The path of the BIDS directory.
"""
# Create the data path based on the available entities:
# root, subject, session, and datatype
data_path = '' if self.root is None else self.root
if self.subject is not None:
data_path = op.join(data_path, f'sub-{self.subject}')
if self.session is not None:
data_path = op.join(data_path, f'ses-{self.session}')
# datatype will allow 'meg', 'eeg', 'ieeg', 'anat'
if self.datatype is not None:
data_path = op.join(data_path, self.datatype)
return Path(data_path)
@property
def subject(self) -> Optional[str]:
"""The subject ID."""
return self._subject
@subject.setter
def subject(self, value):
self.update(subject=value)
@property
def session(self) -> Optional[str]:
"""The acquisition session."""
return self._session
@session.setter
def session(self, value):
self.update(session=value)
@property
def task(self) -> Optional[str]:
"""The experimental task."""
return self._task
@task.setter
def task(self, value):
self.update(task=value)
@property
def run(self) -> Optional[str]:
"""The run number."""
return self._run
@run.setter
def run(self, value):
self.update(run=value)
@property
def acquisition(self) -> Optional[str]:
"""The acquisition parameters."""
return self._acquisition
@acquisition.setter
def acquisition(self, value):
self.update(acquisition=value)
@property
def processing(self) -> Optional[str]:
"""The processing label."""
return self._processing
@processing.setter
def processing(self, value):
self.update(processing=value)
@property
def recording(self) -> Optional[str]:
"""The recording name."""
return self._recording
@recording.setter
def recording(self, value):
self.update(recording=value)
@property
def space(self) -> Optional[str]:
"""The coordinate space for an anatomical or sensor position file."""
return self._space
@space.setter
def space(self, value):
self.update(space=value)
@property
def description(self) -> Optional[str]:
"""The description entity."""
return self._description
@description.setter
def description(self, value):
self.update(description=value)
@property
def suffix(self) -> Optional[str]:
"""The filename suffix."""
return self._suffix
@suffix.setter
def suffix(self, value):
self.update(suffix=value)
@property
def root(self) -> Optional[Path]:
"""The root directory of the BIDS dataset."""
return self._root
@root.setter
def root(self, value):
self.update(root=value)
@property
def datatype(self) -> Optional[str]:
"""The BIDS data type, e.g. ``'anat'``, ``'meg'``, ``'eeg'``."""
return self._datatype
@datatype.setter
def datatype(self, value):
self.update(datatype=value)
@property
def split(self) -> Optional[str]:
"""The split of the continuous recording file for ``.fif`` data."""
return self._split
@split.setter
def split(self, value):
self.update(split=value)
@property
def extension(self) -> Optional[str]:
"""The extension of the filename, including a leading period."""
return self._extension
@extension.setter
def extension(self, value):
self.update(extension=value)
def __str__(self):
"""Return the string representation of the path."""
return str(self.fpath.as_posix())
def __repr__(self):
"""Representation in the style of `pathlib.Path`."""
root = self.root.as_posix() if self.root is not None else None
return f'{self.__class__.__name__}(\n' \
f'root: {root}\n' \
f'datatype: {self.datatype}\n' \
f'basename: {self.basename})'
def __fspath__(self):
"""Return the string representation for any fs functions."""
return str(self.fpath)
def __eq__(self, other):
"""Compare str representations."""
return str(self) == str(other)
def __ne__(self, other):
"""Compare str representations."""
return str(self) != str(other)
def copy(self):
"""Copy the instance.
Returns
-------
bidspath : BIDSPath
The copied bidspath.
"""
return deepcopy(self)
def mkdir(self, exist_ok=True):
"""Create the directory structure of the BIDS path.
Parameters
----------
exist_ok : bool
If ``False``, raise an exception if the directory already exists.
Otherwise, do nothing (default).
Returns
-------
self : BIDSPath
The BIDSPath object.
"""
self.directory.mkdir(parents=True, exist_ok=exist_ok)
return self
@property
def fpath(self):
"""Full filepath for this BIDS file.
Getting the file path consists of the entities passed in
and will get the relative (or full if ``root`` is passed)
path.
Returns
-------
bids_fpath : pathlib.Path
Either the relative, or full path to the dataset.
"""
# get the inner-most BIDS directory for this file path
data_path = self.directory
# account for MEG data that are directory-based
# else, all other file paths attempt to match
if self.suffix == 'meg' and self.extension == '.ds':
bids_fpath = op.join(data_path, self.basename)
elif self.suffix == 'meg' and self.extension == '.pdf':
bids_fpath = op.join(data_path,
op.splitext(self.basename)[0])
else:
# if suffix and/or extension is missing, and root is
# not None, then BIDSPath will infer the dataset
# else, return the relative path with the basename
if (self.suffix is None or self.extension is None) and \
self.root is not None:
# get matching BIDSPaths inside the bids root
matching_paths = \
_get_matching_bidspaths_from_filesystem(self)
# FIXME This will break
# FIXME e.g. with FIFF data split across multiple files.
# if extension is not specified and no unique file path
# return filepath of the actual dataset for MEG/EEG/iEEG data
if self.suffix is None or self.suffix in ALLOWED_DATATYPES:
# now only use valid datatype extension
if self.extension is None:
valid_exts = \
sum(ALLOWED_DATATYPE_EXTENSIONS.values(), [])
else:
valid_exts = [self.extension]
matching_paths = [p for p in matching_paths
if _parse_ext(p)[1] in valid_exts]
if (self.split is None and
(not matching_paths or
'_split-' in matching_paths[0])):
# try finding FIF split files (only first one)
this_self = self.copy().update(split='01')
matching_paths = \
_get_matching_bidspaths_from_filesystem(this_self)
# found no matching paths
if not matching_paths:
bids_fpath = op.join(data_path, self.basename)
# if paths still cannot be resolved, then there is an error
elif len(matching_paths) > 1:
matching_paths_str = "\n".join(sorted(matching_paths))
msg = ('Found more than one matching data file for the '
'requested recording. While searching:\n'
f'{indent(repr(self), " ")}\n'
f'Found {len(matching_paths)} paths:\n'
f'{indent(matching_paths_str, " ")}\n'
'Cannot proceed due to the '
'ambiguity. This is likely a problem with your '
'BIDS dataset. Please run the BIDS validator on '
'your data.')
raise RuntimeError(msg)
else:
bids_fpath = matching_paths[0]
else:
bids_fpath = op.join(data_path, self.basename)
bids_fpath = Path(bids_fpath)
return bids_fpath
def update(self, *, check=None, **kwargs):
"""Update inplace BIDS entity key/value pairs in object.
``run`` and ``split`` are auto-converted to have two
digits. For example, if ``run=1``, then it will nbecome ``run='01'``.
Also performs error checks on various entities to
adhere to the BIDS specification. Specifically:
- ``datatype`` should be one of: ``anat``, ``eeg``, ``ieeg``, ``meg``
- ``extension`` should be one of the accepted file
extensions in the file path: ``.con``, ``.sqd``, ``.fif``,
``.pdf``, ``.ds``, ``.vhdr``, ``.edf``, ``.bdf``, ``.set``,
``.edf``, ``.set``, ``.mef``, ``.nwb``
- ``suffix`` should be one of the acceptable file suffixes in: ``meg``,
``markers``, ``eeg``, ``ieeg``, ``T1w``,
``participants``, ``scans``, ``electrodes``, ``channels``,
``coordsystem``, ``events``, ``headshape``, ``digitizer``,
``beh``, ``physio``, ``stim``
- Depending on the modality of the data (EEG, MEG, iEEG),
``space`` should be a valid string according to Appendix VIII
in the BIDS specification.
Parameters
----------
check : None | bool
If a boolean, controls whether to enforce BIDS conformity. This
will set the ``.check`` attribute accordingly. If ``None``, rely on
the existing ``.check`` attribute instead, which is set upon
`mne_bids.BIDSPath` instantiation. Defaults to ``None``.
**kwargs : dict
It can contain updates for valid BIDSPath entities:
'subject', 'session', 'task', 'acquisition', 'processing', 'run',
'recording', 'space', 'suffix', 'split', 'extension',
or updates for 'root' or 'datatype'.
Returns
-------
bidspath : BIDSPath
The updated instance of BIDSPath.
Examples
--------
If one creates a bids basename using
:func:`mne_bids.BIDSPath`:
>>> bids_path = BIDSPath(subject='test', session='two',
... task='mytask', suffix='channels',
... extension='.tsv')
>>> print(bids_path.basename)
sub-test_ses-two_task-mytask_channels.tsv
>>> # Then, one can update this `BIDSPath` object in place
>>> bids_path.update(acquisition='test', suffix='ieeg',
... datatype='ieeg',
... extension='.vhdr', task=None)
BIDSPath(
root: None
datatype: ieeg
basename: sub-test_ses-two_acq-test_ieeg.vhdr)
>>> print(bids_path.basename)
sub-test_ses-two_acq-test_ieeg.vhdr
"""
# Update .check attribute
if check is not None:
self.check = check
for key, val in kwargs.items():
if key == 'root':
_validate_type(val, types=('path-like', None), item_name=key)
continue
if key == 'datatype':
if val is not None and val not in ALLOWED_DATATYPES \
and self.check:
raise ValueError(f'datatype ({val}) is not valid. '
f'Should be one of '
f'{ALLOWED_DATATYPES}')
else:
continue
if key not in ENTITY_VALUE_TYPE:
raise ValueError(f'Key must be one of '
f'{ALLOWED_PATH_ENTITIES}, got {key}')
if ENTITY_VALUE_TYPE[key] == 'label':
_validate_type(val, types=(None, str),
item_name=key)
else:
assert ENTITY_VALUE_TYPE[key] == 'index'
_validate_type(val, types=(int, str, None), item_name=key)
if isinstance(val, str) and not val.isdigit():
raise ValueError(f'{key} is not an index (Got {val})')
elif isinstance(val, int):
kwargs[key] = '{:02}'.format(val)
# ensure extension starts with a '.'
extension = kwargs.get('extension')
if extension is not None and not extension.startswith('.'):
warn(
f'extension should start with a period ".", but got: '
f'"{extension}". Prepending "." to form: ".{extension}". '
f'This will raise an exception starting with MNE-BIDS 0.12.',
category=FutureWarning
)
kwargs['extension'] = f'.{extension}'
# Uncomment in 0.12, and remove above code:
#
# raise ValueError(
# f'Extension must start wie a period ".", but got: '
# f'{extension}'
# )
del extension
# error check entities
old_kwargs = dict()
for key, val in kwargs.items():
# check if there are any characters not allowed
if val is not None and key != 'root':
if key == 'suffix' and not self.check:
# suffix may skip a check if check=False to allow
# things like "dataset_description.json"
pass
else:
_check_key_val(key, val)
# set entity value, ensuring `root` is a Path
if val is not None and key == 'root':
val = Path(val).expanduser()
old_kwargs[key] = \
getattr(self, f'{key}') if hasattr(self, f'_{key}') else None
setattr(self, f'_{key}', val)
# Perform a check of the entities and revert changes if check fails
try:
self._check()
except Exception as e:
old_check = self.check
self.check = False
self.update(**old_kwargs)
self.check = old_check
raise e
return self
def match(self, check=False):
"""Get a list of all matching paths in the root directory.
Performs a recursive search, starting in ``.root`` (if set), based on
`BIDSPath.entities` object. Ignores ``.json`` files.
Parameters
----------
check : bool
If ``True``, only returns paths that conform to BIDS. If ``False``
(default), the ``.check`` attribute of the returned
`mne_bids.BIDSPath` object will be set to ``True`` for paths that
do conform to BIDS, and to ``False`` for those that don't.
Returns
-------
bids_paths : list of mne_bids.BIDSPath
The matching paths.
"""
if self.root is None:
raise RuntimeError('Cannot match basenames if `root` '
'attribute is not set. Please set the'
'BIDS root directory path to `root` via '
'BIDSPath.update().')
# allow searching by datatype
# all other entities are filtered below
if self.datatype is not None:
search_str = f'*/{self.datatype}/*'
else:
search_str = '*.*'
paths = self.root.rglob(search_str)
# Only keep files (not directories), and omit the JSON sidecars.
paths = [p for p in paths
if p.is_file() and p.suffix != '.json']
fnames = _filter_fnames(paths, suffix=self.suffix,
extension=self.extension,
**self.entities)
bids_paths = []
for fname in fnames:
# Form the BIDSPath object.
# To check whether the BIDSPath is conforming to BIDS if
# check=True, we first instantiate without checking and then run
# the check manually, allowing us to be more specific about the
# exception to catch
datatype = _infer_datatype_from_path(fname)
bids_path = get_bids_path_from_fname(fname, check=False)
bids_path.root = self.root
bids_path.datatype = datatype
bids_path.check = True
try:
bids_path._check()
except ValueError:
# path is not BIDS-compatible
if check: # skip!
continue
else:
bids_path.check = False
bids_paths.append(bids_path)
return bids_paths
def _check(self):
"""Deep check or not of the instance."""
self.basename # run basename to check validity of arguments
# perform error check on scans
if (self.suffix == 'scans' and self.extension == '.tsv') \
and _check_non_sub_ses_entity(self):
raise ValueError('scans.tsv file name can only contain '
'subject and session entities. BIDSPath '
f'currently contains {self.entities}.')
# perform deeper check if user has it turned on
if self.check:
if self.subject == 'emptyroom':
_check_empty_room_basename(self)
# ensure extension starts with a '.'
extension = self.extension
if extension is not None:
# check validity of the extension
if extension not in ALLOWED_FILENAME_EXTENSIONS:
raise ValueError(f'Extension {extension} is not '
f'allowed. Use one of these extensions '
f'{ALLOWED_FILENAME_EXTENSIONS}.')
# labels from space entity must come from list (appendix VIII)
space = self.space
if space is not None:
datatype = getattr(self, 'datatype', None)
if datatype is None:
raise ValueError('You must define datatype if you want to '
'use space in your BIDSPath.')
allowed_spaces_for_dtype = ALLOWED_SPACES.get(datatype, None)
if allowed_spaces_for_dtype is None:
raise ValueError(f'space entity is not valid for datatype '
f'{self.datatype}')
elif space not in allowed_spaces_for_dtype:
raise ValueError(f'space ({space}) is not valid for '
f'datatype ({self.datatype}).\n'
f'Should be one of '
f'{allowed_spaces_for_dtype}')
else:
pass
# error check suffix
suffix = self.suffix
if suffix is not None and \
suffix not in ALLOWED_FILENAME_SUFFIX:
raise ValueError(f'Suffix {suffix} is not allowed. '
f'Use one of these suffixes '
f'{ALLOWED_FILENAME_SUFFIX}.')
@verbose
def find_empty_room(self, use_sidecar_only=False, *, verbose=None):
"""Find the corresponding empty-room file of an MEG recording.
This will only work if the ``.root`` attribute of the
:class:`mne_bids.BIDSPath` instance has been set.
Parameters
----------
use_sidecar_only : bool
Whether to only check the ``AssociatedEmptyRoom`` entry in the
sidecar JSON file or not. If ``False``, first look for the entry,
and if unsuccessful, try to find the best-matching empty-room
recording in the dataset based on the measurement date.
%(verbose)s
Returns
-------
BIDSPath | None
The path corresponding to the best-matching empty-room measurement.
Returns ``None`` if none was found.
"""
if self.datatype not in ('meg', None):
raise ValueError('Empty-room data is only supported for MEG '
'datasets')
if self.root is None:
raise ValueError('The root of the "bids_path" must be set. '
'Please use `bids_path.update(root="<root>")` '
'to set the root of the BIDS folder to read.')
# needed to deal with inheritance principle
sidecar_fname = \
self.copy().update(datatype=None).find_matching_sidecar(
extension='.json')
with open(sidecar_fname, 'r', encoding='utf-8') as f:
sidecar_json = json.load(f)
if 'AssociatedEmptyRoom' in sidecar_json:
logger.info('Using "AssociatedEmptyRoom" entry from MEG sidecar '
'file to retrieve empty-room path.')
emptytoom_path = sidecar_json['AssociatedEmptyRoom']
er_bids_path = get_bids_path_from_fname(emptytoom_path)
er_bids_path.root = self.root
er_bids_path.datatype = 'meg'
elif use_sidecar_only:
logger.info(
'The MEG sidecar file does not contain an '
'"AssociatedEmptyRoom" entry. Aborting search for an '
'empty-room recording, as you passed use_sidecar_only=True'
)
return None
else:
logger.info(
'The MEG sidecar file does not contain an '
'"AssociatedEmptyRoom" entry. Will try to find a matching '
'empty-room recording based on the measurement date …'
)
er_bids_path = _find_matched_empty_room(self)
if er_bids_path is not None and not er_bids_path.fpath.exists():
raise FileNotFoundError(
f'Empty-room BIDS path resolved but not found:\n'
f'{er_bids_path}\n'
'Check your BIDS dataset for completeness.')
return er_bids_path
def get_empty_room_candidates(self):
"""Get the list of empty-room candidates for the given file.
Returns
-------
candidates : list of BIDSPath
The candidate files that will be checked if the sidecar does not
contain an "AssociatedEmptyRoom" entry.
Notes
-----
.. versionadded:: 0.12.0
"""
return _find_empty_room_candidates(self)
def find_matching_sidecar(self, suffix=None, extension=None, *,
on_error='raise'):
"""Get the matching sidecar JSON path.
Parameters
----------
suffix : str | None