-
Notifications
You must be signed in to change notification settings - Fork 91
/
write.py
3142 lines (2735 loc) · 116 KB
/
write.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
"""Make BIDS compatible directory structures and infer meta data from MNE."""
# Authors: The MNE-BIDS developers
# SPDX-License-Identifier: BSD-3-Clause
import json
import os
import os.path as op
import re
import shutil
import sys
import warnings
from collections import OrderedDict, defaultdict
from datetime import datetime, timedelta, timezone
from pathlib import Path
import mne
import mne.preprocessing
import numpy as np
from mne import Epochs, channel_type
from mne.channels.channels import _get_meg_system, _unit2human
from mne.chpi import get_chpi_info
from mne.io import BaseRaw, read_fiducials
from mne.io.constants import FIFF
from mne.io.pick import _picks_to_idx
from mne.transforms import _get_trans, apply_trans, rotation, translation
from mne.utils import (
Bunch,
ProgressBar,
_validate_type,
check_version,
get_subjects_dir,
logger,
verbose,
)
from scipy import linalg
from mne_bids import (
BIDSPath,
get_anonymization_daysback,
get_bids_path_from_fname,
read_raw_bids,
)
from mne_bids.config import (
ALLOWED_DATATYPE_EXTENSIONS,
ALLOWED_INPUT_EXTENSIONS,
ANONYMIZED_JSON_KEY_WHITELIST,
BIDS_STANDARD_TEMPLATE_COORDINATE_SYSTEMS,
BIDS_VERSION,
CONVERT_FORMATS,
EXT_TO_UNIT_MAP,
IGNORED_CHANNELS,
MANUFACTURERS,
ORIENTATION,
PYBV_VERSION,
REFERENCES,
UNITS_MNE_TO_BIDS_MAP,
_map_options,
reader,
)
from mne_bids.copyfiles import (
copyfile_brainvision,
copyfile_bti,
copyfile_ctf,
copyfile_edf,
copyfile_eeglab,
copyfile_kit,
)
from mne_bids.dig import _write_coordsystem_json, _write_dig_bids
from mne_bids.path import _mkdir_p, _parse_ext, _path_to_str
from mne_bids.pick import coil_type
from mne_bids.read import _find_matching_sidecar, _read_events
from mne_bids.sidecar_updates import update_sidecar_json
from mne_bids.tsv_handler import _combine_rows, _contains_row, _drop, _from_tsv
from mne_bids.utils import (
_age_on_date,
_check_anonymize,
_get_ch_type_mapping,
_handle_datatype,
_import_nibabel,
_infer_eeg_placement_scheme,
_stamp_to_dt,
_write_json,
_write_text,
_write_tsv,
warn,
)
_FIFF_SPLIT_SIZE = "2GB" # MNE-Python default; can be altered during debugging
def _is_numeric(n):
return isinstance(n, (np.integer, np.floating, int, float))
def _channels_tsv(raw, fname, overwrite=False):
"""Create a channels.tsv file and save it.
Parameters
----------
raw : mne.io.Raw
The data as MNE-Python Raw object.
fname : str | mne_bids.BIDSPath
Filename to save the channels.tsv to.
overwrite : bool
Whether to overwrite the existing file.
Defaults to False.
"""
# Get channel type mappings between BIDS and MNE nomenclatures
map_chs = _get_ch_type_mapping(fro="mne", to="bids")
# Prepare the descriptions for each channel type
map_desc = defaultdict(lambda: "Other type of channel")
map_desc.update(
meggradaxial="Axial Gradiometer",
megrefgradaxial="Axial Gradiometer Reference",
meggradplanar="Planar Gradiometer",
megmag="Magnetometer",
megrefmag="Magnetometer Reference",
stim="Trigger",
eeg="ElectroEncephaloGram",
ecog="Electrocorticography",
seeg="StereoEEG",
ecg="ElectroCardioGram",
eog="ElectroOculoGram",
emg="ElectroMyoGram",
misc="Miscellaneous",
bio="Biological",
ias="Internal Active Shielding",
dbs="Deep Brain Stimulation",
fnirs_cw_amplitude="Near Infrared Spectroscopy (continuous wave)",
resp="Respiration",
gsr="Galvanic skin response (electrodermal activity, EDA)",
temperature="Temperature",
)
get_specific = ("mag", "ref_meg", "grad")
# get the manufacturer from the file in the Raw object
_, ext = _parse_ext(raw.filenames[0])
manufacturer = MANUFACTURERS.get(ext, "")
ignored_channels = IGNORED_CHANNELS.get(manufacturer, list())
status, ch_type, description = list(), list(), list()
for idx, ch in enumerate(raw.info["ch_names"]):
status.append("bad" if ch in raw.info["bads"] else "good")
_channel_type = channel_type(raw.info, idx)
if _channel_type in get_specific:
_channel_type = coil_type(raw.info, idx, _channel_type)
ch_type.append(map_chs[_channel_type])
description.append(map_desc[_channel_type])
low_cutoff, high_cutoff = (raw.info["highpass"], raw.info["lowpass"])
if raw._orig_units:
units = [raw._orig_units.get(ch, "n/a") for ch in raw.ch_names]
else:
units = [_unit2human.get(ch_i["unit"], "n/a") for ch_i in raw.info["chs"]]
units = [u if u not in ["NA"] else "n/a" for u in units]
# Translate from MNE to BIDS unit naming
for idx, mne_unit in enumerate(units):
if mne_unit in UNITS_MNE_TO_BIDS_MAP:
bids_unit = UNITS_MNE_TO_BIDS_MAP[mne_unit]
units[idx] = bids_unit
n_channels = raw.info["nchan"]
sfreq = raw.info["sfreq"]
# default to 'n/a' for status description
# XXX: improve with API to modify the description
status_description = ["n/a"] * len(status)
ch_data = OrderedDict(
[
("name", raw.info["ch_names"]),
("type", ch_type),
("units", units),
("low_cutoff", np.full((n_channels), low_cutoff)),
("high_cutoff", np.full((n_channels), high_cutoff)),
("description", description),
("sampling_frequency", np.full((n_channels), sfreq)),
("status", status),
("status_description", status_description),
]
)
ch_data = _drop(ch_data, ignored_channels, "name")
if "fnirs_cw_amplitude" in raw:
ch_data["wavelength_nominal"] = [
raw.info["chs"][i]["loc"][9] for i in range(len(raw.ch_names))
]
picks = _picks_to_idx(raw.info, "fnirs", exclude=[], allow_empty=True)
sources = np.empty(picks.shape, dtype="<U20")
detectors = np.empty(picks.shape, dtype="<U20")
for ii in picks:
# NIRS channel names take a specific form in MNE-Python.
# The channel names always reflect the source and detector
# pair, followed by the wavelength frequency.
# The following code extracts the source and detector
# numbers from the channel name.
ch1_name_info = re.match(
r"S(\d+)_D(\d+) (\d+)", raw.info["chs"][ii]["ch_name"]
)
sources[ii] = "S" + str(ch1_name_info.groups()[0])
detectors[ii] = "D" + str(ch1_name_info.groups()[1])
ch_data["source"] = sources
ch_data["detector"] = detectors
ch_data.move_to_end("wavelength_nominal", last=False)
ch_data.move_to_end("detector", last=False)
ch_data.move_to_end("source", last=False)
ch_data.move_to_end("type", last=False)
ch_data.move_to_end("name", last=False)
_write_tsv(fname, ch_data, overwrite)
_cardinal_ident_mapping = {
FIFF.FIFFV_POINT_NASION: "nasion",
FIFF.FIFFV_POINT_LPA: "lpa",
FIFF.FIFFV_POINT_RPA: "rpa",
}
def _get_fid_coords(dig_points, raise_error=True):
"""Get the fiducial coordinates from a DigMontage.
Parameters
----------
dig_points : array-like of DigPoint
The digitization points of the fiducial coordinates.
raise_error : bool
Whether to raise an error if the coordinates are missing or
incorrectly formatted
Returns
-------
fid_coords : mne.utils.Bunch
The coordinates stored by fiducial name.
coord_frame : int
The integer key corresponding to the coordinate frame of the montage.
"""
fid_coords = Bunch(nasion=None, lpa=None, rpa=None)
fid_coord_frames = dict()
for d in dig_points:
if d["kind"] == FIFF.FIFFV_POINT_CARDINAL:
key = _cardinal_ident_mapping[d["ident"]]
fid_coords[key] = d["r"]
fid_coord_frames[key] = d["coord_frame"]
if len(fid_coord_frames) > 0 and raise_error:
if set(fid_coord_frames.keys()) != set(["nasion", "lpa", "rpa"]):
raise ValueError(
f"Some fiducial points are missing, got {fid_coords.keys()}"
)
if len(set(fid_coord_frames.values())) > 1:
raise ValueError(
"All fiducial points must be in the same coordinate system, "
f"got {len(fid_coord_frames)})"
)
coord_frame = fid_coord_frames.popitem()[1] if fid_coord_frames else None
return fid_coords, coord_frame
def _events_tsv(events, durations, raw, fname, trial_type, overwrite=False):
"""Create an events.tsv file and save it.
This function will write the mandatory 'onset', and 'duration' columns as
well as the optional 'value' and 'sample'. The 'value'
corresponds to the marker value as found in the TRIG channel of the
recording. In addition, the 'trial_type' field can be written.
Parameters
----------
events : np.ndarray, shape = (n_events, 3)
The first column contains the event time in samples and the third
column contains the event id. The second column is ignored for now but
typically contains the value of the trigger channel either immediately
before the event or immediately after.
durations : np.ndarray, shape (n_events,)
The event durations in seconds.
raw : mne.io.Raw
The data as MNE-Python Raw object.
fname : str | mne_bids.BIDSPath
Filename to save the events.tsv to.
trial_type : dict | None
Dictionary mapping a brief description key to an event id (value). For
example {'Go': 1, 'No Go': 2}.
overwrite : bool
Whether to overwrite the existing file.
Defaults to False.
"""
# Start by filling all data that we know into an ordered dictionary
first_samp = raw.first_samp
sfreq = raw.info["sfreq"]
events = events.copy()
events[:, 0] -= first_samp
# Onset column needs to be specified in seconds
data = OrderedDict(
[
("onset", events[:, 0] / sfreq),
("duration", durations),
("trial_type", None),
("value", events[:, 2]),
("sample", events[:, 0]),
]
)
# Now check if trial_type is specified or should be removed
if trial_type:
trial_type_map = {v: k for k, v in trial_type.items()}
data["trial_type"] = [trial_type_map.get(i, "n/a") for i in events[:, 2]]
else:
del data["trial_type"]
_write_tsv(fname, data, overwrite)
def _events_json(fname, overwrite=False):
"""Create participants.json for non-default columns in accompanying TSV.
Parameters
----------
fname : str | mne_bids.BIDSPath
Output filename.
overwrite : bool
Whether to overwrite the output file if it exists.
"""
new_data = {
"onset": {
"Description": (
"Onset (in seconds) of the event from the beginning of the first data"
"point. Negative onsets account for events before the first stored "
"data point."
),
"Units": "s",
},
"duration": {
"Description": (
"Duration of the event in seconds from onset. "
"Must be zero, positive, or 'n/a' if unavailable. "
"A zero value indicates an impulse event. "
),
"Units": "s",
},
"sample": {
"Description": (
"The event onset time in number of sampling points."
"First sample is 0."
),
},
"value": {
"Description": (
"The event code (also known as trigger code or event ID) "
"associated with the event."
)
},
"trial_type": {"Description": "The type, category, or name of the event."},
}
# make sure to append any JSON fields added by the user
fname = Path(fname)
if fname.exists():
orig_data = json.loads(
fname.read_text(encoding="utf-8"), object_pairs_hook=OrderedDict
)
new_data = {**orig_data, **new_data}
_write_json(fname, new_data, overwrite)
def _readme(datatype, fname, overwrite=False):
"""Create a README file and save it.
This will write a README file containing an MNE-BIDS citation.
If a README already exists, the behavior depends on the
`overwrite` parameter, as described below.
Parameters
----------
datatype : string
The type of data contained in the raw file ('meg', 'eeg', 'ieeg')
fname : str | mne_bids.BIDSPath
Filename to save the README to.
overwrite : bool
Whether to overwrite the existing file (defaults to False).
If overwrite is True, create a new README containing an
MNE-BIDS citation. If overwrite is False, append an
MNE-BIDS citation to the existing README, unless it
already contains that citation.
"""
if os.path.isfile(fname) and not overwrite:
with open(fname, encoding="utf-8-sig") as fid:
orig_data = fid.read()
mne_bids_ref = REFERENCES["mne-bids"] in orig_data
datatype_ref = REFERENCES[datatype] in orig_data
if mne_bids_ref and datatype_ref:
return
text = "{}References\n----------\n{}{}".format(
orig_data + "\n\n",
"" if mne_bids_ref else REFERENCES["mne-bids"] + "\n\n",
"" if datatype_ref else REFERENCES[datatype] + "\n",
)
else:
text = "References\n----------\n{}{}".format(
REFERENCES["mne-bids"] + "\n\n", REFERENCES[datatype] + "\n"
)
_write_text(fname, text, overwrite=True)
def _participants_tsv(raw, subject_id, fname, overwrite=False):
"""Create a participants.tsv file and save it.
This will append any new participant data to the current list if it
exists. Otherwise a new file will be created with the provided information.
Parameters
----------
raw : mne.io.Raw
The data as MNE-Python Raw object.
subject_id : str
The subject name in BIDS compatible format ('01', '02', etc.)
fname : str | mne_bids.BIDSPath
Filename to save the participants.tsv to.
overwrite : bool
Whether to overwrite the existing file.
Defaults to False.
If there is already data for the given `subject_id` and overwrite is
False, an error will be raised.
"""
subject_age = "n/a"
sex = "n/a"
hand = "n/a"
weight = "n/a"
height = "n/a"
subject_info = raw.info.get("subject_info", None)
if subject_id != "emptyroom" and subject_info is not None:
# add sex
sex = _map_options(
what="sex", key=subject_info.get("sex", 0), fro="mne", to="bids"
)
# add handedness
hand = _map_options(
what="hand", key=subject_info.get("hand", 0), fro="mne", to="bids"
)
# determine the age of the participant
age = subject_info.get("birthday", None)
meas_date = raw.info.get("meas_date", None)
if isinstance(meas_date, (tuple, list, np.ndarray)):
meas_date = meas_date[0]
if meas_date is not None and age is not None:
bday = datetime(age[0], age[1], age[2], tzinfo=timezone.utc)
if isinstance(meas_date, datetime):
meas_datetime = meas_date
else:
meas_datetime = datetime.fromtimestamp(meas_date, tz=timezone.utc)
subject_age = _age_on_date(bday, meas_datetime)
else:
subject_age = "n/a"
# add weight and height
weight = subject_info.get("weight", "n/a")
height = subject_info.get("height", "n/a")
subject_id = "sub-" + subject_id
data = OrderedDict(participant_id=[subject_id])
data.update(
{
"age": [subject_age],
"sex": [sex],
"hand": [hand],
"weight": [weight],
"height": [height],
}
)
if os.path.exists(fname):
orig_data = _from_tsv(fname)
# whether the new data exists identically in the previous data
exact_included = _contains_row(
data=orig_data,
row_data={
"participant_id": subject_id,
"age": subject_age,
"sex": sex,
"hand": hand,
"weight": weight,
"height": height,
},
)
# whether the subject id is in the previous data
sid_included = subject_id in orig_data["participant_id"]
# if the subject data provided is different to the currently existing
# data and overwrite is not True raise an error
if (sid_included and not exact_included) and not overwrite:
raise FileExistsError(
f'"{subject_id}" already exists in '
f"the participant list. Please set "
f"overwrite to True."
)
# Append any columns the original data did not have, and fill them with
# n/a's.
for key in data.keys():
if key in orig_data:
continue
orig_data[key] = ["n/a"] * len(orig_data["participant_id"])
# Append any additional columns that original data had.
# Keep the original order of the data by looping over
# the original OrderedDict keys
for key in orig_data.keys():
if key in data:
continue
# add original value for any user-appended columns
# that were not handled by mne-bids
p_id = data["participant_id"][0]
if p_id in orig_data["participant_id"]:
row_idx = orig_data["participant_id"].index(p_id)
data[key] = [orig_data[key][row_idx]]
# otherwise add the new data as new row
data = _combine_rows(orig_data, data, "participant_id")
# overwrite is forced to True as all issues with overwrite == False have
# been handled by this point
_write_tsv(fname, data, True)
def _participants_json(fname, overwrite=False):
"""Create participants.json for non-default columns in accompanying TSV.
Parameters
----------
fname : str | mne_bids.BIDSPath
Output filename.
overwrite : bool
Defaults to False.
Whether to overwrite the existing data in the file.
If there is already data for the given `fname` and overwrite is False,
an error will be raised.
"""
new_data = {
"participant_id": {"Description": "Unique participant identifier"},
"age": {
"Description": "Age of the participant at time of testing",
"Units": "years",
},
"sex": {
"Description": "Biological sex of the participant",
"Levels": {"F": "female", "M": "male"},
},
"hand": {
"Description": "Handedness of the participant",
"Levels": {"R": "right", "L": "left", "A": "ambidextrous"},
},
"weight": {"Description": "Body weight of the participant", "Units": "kg"},
"height": {"Description": "Body height of the participant", "Units": "m"},
}
# make sure to append any JSON fields added by the user
# Note: mne-bids will overwrite age, sex and hand fields
# if `overwrite` is True
fname = Path(fname)
if fname.exists():
orig_data = json.loads(
fname.read_text(encoding="utf-8"), object_pairs_hook=OrderedDict
)
new_data = {**orig_data, **new_data}
_write_json(fname, new_data, overwrite)
def _scans_tsv(raw, raw_fname, fname, keep_source, overwrite=False):
"""Create a scans.tsv file and save it.
Parameters
----------
raw : mne.io.Raw
The data as MNE-Python Raw object.
raw_fname : str | mne_bids.BIDSPath
Relative path to the raw data file.
fname : str
Filename to save the scans.tsv to.
keep_source : bool
Wehter to store``raw.filenames`` in the ``source`` column.
overwrite : bool
Defaults to False.
Whether to overwrite the existing data in the file.
If there is already data for the given `fname` and overwrite is False,
an error will be raised.
"""
# get measurement date in UTC from the data info
meas_date = raw.info["meas_date"]
if meas_date is None:
acq_time = "n/a"
elif isinstance(meas_date, datetime):
acq_time = meas_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
# for fif files check whether raw file is likely to be split
raw_fnames = [raw_fname]
if raw_fname.endswith(".fif"):
# check whether fif files were split when saved
# use the files in the target directory what should be written
# to scans.tsv
datatype, basename = raw_fname.split(os.sep)
raw_dir = op.join(op.dirname(fname), datatype)
raw_files = [f for f in os.listdir(raw_dir) if f.endswith(".fif")]
if basename not in raw_files:
raw_fnames = []
split_base = basename.replace("_meg.fif", "_split-{}")
for raw_f in raw_files:
if len(raw_f.split("_split-")) == 2:
if split_base.format(raw_f.split("_split-")[1]) == raw_f:
raw_fnames.append(op.join(datatype, raw_f))
raw_fnames.sort()
data = OrderedDict(
[
(
"filename",
["{:s}".format(raw_f.replace(os.sep, "/")) for raw_f in raw_fnames],
),
("acq_time", [acq_time] * len(raw_fnames)),
]
)
# add source filename if desired
if keep_source:
data["source"] = [Path(src_fname).name for src_fname in raw.filenames]
# write out a sidecar JSON if not exists
sidecar_json_path = Path(fname).with_suffix(".json")
sidecar_json_path = get_bids_path_from_fname(sidecar_json_path)
sidecar_json = {"source": {"Description": "Original source filename."}}
if sidecar_json_path.fpath.exists():
update_sidecar_json(sidecar_json_path, sidecar_json)
else:
_write_json(sidecar_json_path, sidecar_json)
if os.path.exists(fname):
orig_data = _from_tsv(fname)
# if the file name is already in the file raise an error
if raw_fname in orig_data["filename"] and not overwrite:
raise FileExistsError(
f'"{raw_fname}" already exists in '
f"the scans list. Please set "
f"overwrite to True."
)
for key in data.keys():
if key in orig_data:
continue
# add 'n/a' if any missing columns
orig_data[key] = ["n/a"] * len(next(iter(data.values())))
# otherwise add the new data
data = _combine_rows(orig_data, data, "filename")
# overwrite is forced to True as all issues with overwrite == False have
# been handled by this point
_write_tsv(fname, data, True)
def _load_image(image, name="image"):
nib = _import_nibabel()
if type(image) not in nib.all_image_classes:
try:
image = _path_to_str(image)
except ValueError:
# image -> str conversion in the try block was successful,
# so load the file from the specified location. We do this
# here to keep the try block as short as possible.
raise ValueError(
f"`{name}` must be a path to an MRI data "
"file or a nibabel image object, but it "
f'is of type "{type(image)}"'
)
else:
image = nib.load(image)
image = nib.Nifti1Image(image.dataobj, image.affine)
# XYZT_UNITS = NIFT_UNITS_MM (10 in binary or 2 in decimal)
# seems to be the default for Nifti files
# https://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/xyzt_units.html
if image.header["xyzt_units"] == 0:
image.header["xyzt_units"] = np.array(10, dtype="uint8")
return image
def _meg_landmarks_to_mri_landmarks(meg_landmarks, trans):
"""Convert landmarks from head space to MRI space.
Parameters
----------
meg_landmarks : np.ndarray, shape (3, 3)
The meg landmark data: rows LPA, NAS, RPA, columns x, y, z.
trans : mne.transforms.Transform
The transformation matrix from head coordinates to MRI coordinates.
Returns
-------
mri_landmarks : np.ndarray, shape (3, 3)
The mri RAS landmark data converted to from m to mm.
"""
# Transform MEG landmarks into MRI space, adjust units by * 1e3
return apply_trans(trans, meg_landmarks, move=True) * 1e3
def _mri_landmarks_to_mri_voxels(mri_landmarks, t1_mgh):
"""Convert landmarks from MRI surface RAS space to MRI voxel space.
Parameters
----------
mri_landmarks : np.ndarray, shape (3, 3)
The MRI RAS landmark data: rows LPA, NAS, RPA, columns x, y, z.
t1_mgh : nib.MGHImage
The image data in MGH format.
Returns
-------
vox_landmarks : np.ndarray, shape (3, 3)
The MRI voxel-space landmark data.
"""
# Get landmarks in voxel space, using the T1 data
vox2ras_tkr_t = t1_mgh.header.get_vox2ras_tkr()
ras_tkr2vox_t = linalg.inv(vox2ras_tkr_t)
vox_landmarks = apply_trans(ras_tkr2vox_t, mri_landmarks)
return vox_landmarks
def _mri_voxels_to_mri_scanner_ras(mri_landmarks, img_mgh):
"""Convert landmarks from MRI voxel space to MRI scanner RAS space.
Parameters
----------
mri_landmarks : np.ndarray, shape (3, 3)
The MRI RAS landmark data: rows LPA, NAS, RPA, columns x, y, z.
img_mgh : nib.MGHImage
The image data in MGH format.
Returns
-------
ras_landmarks : np.ndarray, shape (3, 3)
The MRI scanner RAS landmark data.
"""
# Get landmarks in voxel space, using the T1 data
vox2ras = img_mgh.header.get_vox2ras()
ras_landmarks = apply_trans(vox2ras, mri_landmarks) # in scanner RAS
return ras_landmarks
def _mri_scanner_ras_to_mri_voxels(ras_landmarks, img_mgh):
"""Convert landmarks from MRI scanner RAS space to MRI to MRI voxel space.
Parameters
----------
ras_landmarks : np.ndarray, shape (3, 3)
The MRI RAS landmark data: rows LPA, NAS, RPA, columns x, y, z.
img_mgh : nib.MGHImage
The image data in MGH format.
Returns
-------
vox_landmarks : np.ndarray, shape (3, 3)
The MRI voxel-space landmark data.
"""
# Get landmarks in voxel space, using the T1 data
vox2ras = img_mgh.header.get_vox2ras()
ras2vox = linalg.inv(vox2ras)
vox_landmarks = apply_trans(ras2vox, ras_landmarks) # in vox
return vox_landmarks
def _sidecar_json(
raw, task, manufacturer, fname, datatype, emptyroom_fname=None, overwrite=False
):
"""Create a sidecar json file depending on the suffix and save it.
The sidecar json file provides meta data about the data
of a certain datatype.
Parameters
----------
raw : mne.io.Raw
The data as MNE-Python Raw object.
task : str
Name of the task the data is based on.
manufacturer : str
Manufacturer of the acquisition system. For MEG also used to define the
coordinate system for the MEG sensors.
fname : str | mne_bids.BIDSPath
Filename to save the sidecar json to.
datatype : str
Type of the data as in ALLOWED_ELECTROPHYSIO_DATATYPE.
emptyroom_fname : str | mne_bids.BIDSPath
For MEG recordings, the path to an empty-room data file to be
associated with ``raw``. Only supported for MEG.
overwrite : bool
Whether to overwrite the existing file.
Defaults to False.
"""
sfreq = raw.info["sfreq"]
try:
powerlinefrequency = raw.info["line_freq"]
powerlinefrequency = "n/a" if powerlinefrequency is None else powerlinefrequency
except KeyError:
raise ValueError(
"PowerLineFrequency parameter is required in the sidecar files. "
"Please specify it in info['line_freq'] before saving to BIDS, "
"e.g. by running: "
" raw.info['line_freq'] = 60"
"in your script, or by passing: "
" --line_freq 60 "
"in the command line for a 60 Hz line frequency. If the frequency "
"is unknown, set it to None"
)
if isinstance(raw, BaseRaw):
rec_type = "continuous"
elif isinstance(raw, Epochs):
rec_type = "epoched"
else:
rec_type = "n/a"
# determine whether any channels have to be ignored:
n_ignored = len(
[
ch_name
for ch_name in IGNORED_CHANNELS.get(manufacturer, list())
if ch_name in raw.ch_names
]
)
# all ignored channels are trigger channels at the moment...
n_megchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_MEG_CH])
n_megrefchan = len(
[ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_REF_MEG_CH]
)
n_eegchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_EEG_CH])
n_ecogchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_ECOG_CH])
n_seegchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_SEEG_CH])
n_eogchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_EOG_CH])
n_ecgchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_ECG_CH])
n_emgchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_EMG_CH])
n_miscchan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_MISC_CH])
n_stimchan = (
len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_STIM_CH])
- n_ignored
)
n_dbschan = len([ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_DBS_CH])
nirs_channels = [ch for ch in raw.info["chs"] if ch["kind"] == FIFF.FIFFV_FNIRS_CH]
n_nirscwchan = len(nirs_channels)
n_nirscwsrc = len(
np.unique([ch["ch_name"].split(" ")[0].split("_")[0] for ch in nirs_channels])
)
n_nirscwdet = len(
np.unique([ch["ch_name"].split(" ")[0].split("_")[1] for ch in nirs_channels])
)
# Set DigitizedLandmarks to True if any of LPA, RPA, NAS are found
# Set DigitizedHeadPoints to True if any "Extra" points are found
# (DigitizedHeadPoints done for Neuromag MEG files only)
digitized_head_points = False
digitized_landmark = False
if datatype == "meg" and raw.info["dig"] is not None:
for dig_point in raw.info["dig"]:
if dig_point["kind"] in [
FIFF.FIFFV_POINT_NASION,
FIFF.FIFFV_POINT_RPA,
FIFF.FIFFV_POINT_LPA,
]:
digitized_landmark = True
elif dig_point["kind"] == FIFF.FIFFV_POINT_EXTRA and str(
raw.filenames[0]
).endswith(".fif"):
digitized_head_points = True
software_filters = {
"SpatialCompensation": {"GradientOrder": raw.compensation_grade}
}
# Compile cHPI information, if any.
system, _ = _get_meg_system(raw.info)
chpi = None
hpi_freqs = []
if datatype == "meg":
# We need to handle different data formats differently
if system == "CTF_275":
try:
mne.chpi.extract_chpi_locs_ctf(raw)
chpi = True
except RuntimeError:
chpi = False
logger.info("Could not find cHPI information in raw data.")
elif system == "KIT":
try:
mne.chpi.extract_chpi_locs_kit(raw)
chpi = True
except (RuntimeError, ValueError):
chpi = False
logger.info("Could not find cHPI information in raw data.")
elif system in ["122m", "306m"]:
n_active_hpi = mne.chpi.get_active_chpi(raw, on_missing="ignore")
chpi = bool(n_active_hpi.sum() > 0)
if chpi:
hpi_freqs, _, _ = get_chpi_info(info=raw.info, on_missing="ignore")
hpi_freqs = list(hpi_freqs)
# Define datatype-specific JSON dictionaries
ch_info_json_common = [
("TaskName", task),
("Manufacturer", manufacturer),
("PowerLineFrequency", powerlinefrequency),
("SamplingFrequency", sfreq),
("SoftwareFilters", "n/a"),
("RecordingDuration", raw.times[-1]),
("RecordingType", rec_type),
]
ch_info_json_meg = [
("DewarPosition", "n/a"),
("DigitizedLandmarks", digitized_landmark),
("DigitizedHeadPoints", digitized_head_points),
("MEGChannelCount", n_megchan),
("MEGREFChannelCount", n_megrefchan),
("SoftwareFilters", software_filters),
]
if chpi is not None:
ch_info_json_meg.append(("ContinuousHeadLocalization", chpi))
ch_info_json_meg.append(("HeadCoilFrequency", hpi_freqs))
if emptyroom_fname is not None:
ch_info_json_meg.append(("AssociatedEmptyRoom", str(emptyroom_fname)))
ch_info_json_eeg = [
("EEGReference", "n/a"),
("EEGGround", "n/a"),
("EEGPlacementScheme", _infer_eeg_placement_scheme(raw)),
("Manufacturer", manufacturer),
]
ch_info_json_ieeg = [
("iEEGReference", "n/a"),
("ECOGChannelCount", n_ecogchan),
("SEEGChannelCount", n_seegchan + n_dbschan),
]
ch_info_json_nirs = [("Manufacturer", manufacturer)]
ch_info_ch_counts = [
("EEGChannelCount", n_eegchan),
("EOGChannelCount", n_eogchan),
("ECGChannelCount", n_ecgchan),
("EMGChannelCount", n_emgchan),
("MiscChannelCount", n_miscchan),
("TriggerChannelCount", n_stimchan),
]
ch_info_ch_counts_nirs = [
("NIRSChannelCount", n_nirscwchan),
("NIRSSourceOptodeCount", n_nirscwsrc),
("NIRSDetectorOptodeCount", n_nirscwdet),
]
# Stitch together the complete JSON dictionary
ch_info_json = ch_info_json_common
if datatype == "meg":
append_datatype_json = ch_info_json_meg
elif datatype == "eeg":
append_datatype_json = ch_info_json_eeg
elif datatype == "ieeg":
append_datatype_json = ch_info_json_ieeg
elif datatype == "nirs":
append_datatype_json = ch_info_json_nirs
ch_info_ch_counts.extend(ch_info_ch_counts_nirs)
ch_info_json += append_datatype_json
ch_info_json += ch_info_ch_counts
ch_info_json = OrderedDict(ch_info_json)