-
Notifications
You must be signed in to change notification settings - Fork 87
/
write.py
2604 lines (2246 loc) · 104 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: Mainak Jas <[email protected]>
# Alexandre Gramfort <[email protected]>
# Teon Brooks <[email protected]>
# Chris Holdgraf <[email protected]>
# Stefan Appelhoff <[email protected]>
# Matt Sanderson <[email protected]>
#
# License: BSD-3-Clause
from typing import List
import json
import sys
import os
import os.path as op
from pathlib import Path
from datetime import datetime, timezone, timedelta
import shutil
from collections import defaultdict, OrderedDict
from pkg_resources import parse_version
import numpy as np
from scipy import linalg
import mne
from mne.transforms import (_get_trans, apply_trans, rotation, translation)
from mne import Epochs
from mne.io.constants import FIFF
from mne.io.pick import channel_type
from mne.io import BaseRaw, read_fiducials
from mne.channels.channels import _unit2human
from mne.utils import (check_version, has_nibabel, logger, warn, Bunch,
_validate_type, get_subjects_dir, verbose,
deprecated, ProgressBar)
import mne.preprocessing
from mne_bids.pick import coil_type
from mne_bids.dig import _write_dig_bids, _write_coordsystem_json
from mne_bids.utils import (_write_json, _write_tsv, _write_text,
_age_on_date, _infer_eeg_placement_scheme,
_get_ch_type_mapping, _check_anonymize,
_stamp_to_dt, _handle_datatype)
from mne_bids import (BIDSPath, read_raw_bids, get_anonymization_daysback,
get_bids_path_from_fname)
from mne_bids.path import _parse_ext, _mkdir_p, _path_to_str
from mne_bids.copyfiles import (copyfile_brainvision, copyfile_eeglab,
copyfile_ctf, copyfile_bti, copyfile_kit,
copyfile_edf)
from mne_bids.tsv_handler import (_from_tsv, _drop, _contains_row,
_combine_rows)
from mne_bids.read import _find_matching_sidecar, _read_events
from mne_bids.sidecar_updates import update_sidecar_json
from mne_bids.config import (ORIENTATION, UNITS, MANUFACTURERS,
IGNORED_CHANNELS, ALLOWED_DATATYPE_EXTENSIONS,
BIDS_VERSION, REFERENCES, _map_options, reader,
ALLOWED_INPUT_EXTENSIONS, CONVERT_FORMATS,
ANONYMIZED_JSON_KEY_WHITELIST)
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')
get_specific = ('mag', 'ref_meg', 'grad')
# get the manufacturer from the file in the Raw object
_, ext = _parse_ext(raw.filenames[0])
manufacturer = MANUFACTURERS[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]
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')
_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, raise_error=True):
"""Get the fiducial coordinates from a DigMontage.
Parameters
----------
dig : mne.channels.DigMontage
The dig montage with 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:
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 _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, 'r', 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_id = 'sub-' + subject_id
data = OrderedDict(participant_id=[subject_id])
subject_age = "n/a"
sex = "n/a"
hand = 'n/a'
subject_info = raw.info.get('subject_info', None)
if 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"
data.update({'age': [subject_age], 'sex': [sex], 'hand': [hand]})
if os.path.exists(fname):
orig_data = _from_tsv(fname)
# whether the new data exists identically in the previous data
exact_included = _contains_row(orig_data,
{'participant_id': subject_id,
'age': subject_age,
'sex': sex,
'hand': hand})
# 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 ' # noqa: E501 F821
f'the participant list. Please set '
f'overwrite to True.')
# Append any columns the original data did not have
# that mne-bids is trying to write. This handles
# the edge case where users write participants data for
# a subset of `hand`, `age` and `sex`.
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())))
# Append any additional columns that original data had.
# Keep the original order of the data by looping over
# the original OrderedDict keys
col_name = 'participant_id'
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[col_name][0]
if p_id in orig_data[col_name]:
row_idx = orig_data[col_name].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
Filename to save the scans.tsv to.
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.
"""
cols = OrderedDict()
cols['participant_id'] = {'Description': 'Unique participant identifier'}
cols['age'] = {'Description': 'Age of the participant at time of testing',
'Units': 'years'}
cols['sex'] = {'Description': 'Biological sex of the participant',
'Levels': {'F': 'female', 'M': 'male'}}
cols['hand'] = {'Description': 'Handedness of the participant',
'Levels': {'R': 'right', 'L': 'left', 'A': 'ambidextrous'}}
# 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
if op.exists(fname):
with open(fname, 'r', encoding='utf-8-sig') as fin:
orig_cols = json.load(fin, object_pairs_hook=OrderedDict)
for key, val in orig_cols.items():
if key not in cols:
cols[key] = val
_write_json(fname, cols, overwrite)
def _scans_tsv(raw, raw_fname, fname, 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.
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'
# The "Z" indicates UTC time
elif isinstance(meas_date, (tuple, list, np.ndarray)): # pragma: no cover
# for MNE < v0.20
acq_time = _stamp_to_dt(meas_date).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
elif isinstance(meas_date, datetime):
# for MNE >= v0.20
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))])
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.')
# 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'):
if not has_nibabel(): # pragma: no cover
raise ImportError('This function requires nibabel.')
import nibabel as nib
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('`{}` must be a path to an MRI data '
'file or a nibabel image object, but it '
'is of type "{}"'.format(name, 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 = t1_mgh.header.get_vox2ras_tkr()
ras2vox_tkr = linalg.inv(vox2ras_tkr)
vox_landmarks = apply_trans(ras2vox_tkr, mri_landmarks) # in vox
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])
# 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 \
raw.filenames[0].endswith('.fif'):
digitized_head_points = True
software_filters = {
'SpatialCompensation': {
'GradientOrder': raw.compensation_grade
}
}
# Compile cHPI information, if any.
from mne.io.ctf import RawCTF
from mne.io.kit.kit import RawKIT
chpi = False
hpi_freqs = np.array([])
if (datatype == 'meg' and
parse_version(mne.__version__) > parse_version('0.23')):
# We need to handle different data formats differently
if isinstance(raw, RawCTF):
try:
mne.chpi.extract_chpi_locs_ctf(raw)
chpi = True
except RuntimeError:
logger.info('Could not find cHPI information in raw data.')
elif isinstance(raw, RawKIT):
try:
mne.chpi.extract_chpi_locs_kit(raw)
chpi = True
except (RuntimeError, ValueError):
logger.info('Could not find cHPI information in raw data.')
else:
hpi_freqs, _, _ = mne.chpi.get_chpi_info(info=raw.info,
on_missing='ignore')
if hpi_freqs.size > 0:
chpi = True
elif datatype == 'meg':
logger.info('Cannot check for & write continuous head localization '
'information: requires MNE-Python >= 0.24')
chpi = None
# 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', list(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_ch_counts = [
('EEGChannelCount', n_eegchan),
('EOGChannelCount', n_eogchan),
('ECGChannelCount', n_ecgchan),
('EMGChannelCount', n_emgchan),
('MiscChannelCount', n_miscchan),
('TriggerChannelCount', n_stimchan)]
# 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
ch_info_json += append_datatype_json
ch_info_json += ch_info_ch_counts
ch_info_json = OrderedDict(ch_info_json)
_write_json(fname, ch_info_json, overwrite)
return fname
def _deface(image, landmarks, deface):
if not has_nibabel(): # pragma: no cover
raise ImportError('This function requires nibabel.')
import nibabel as nib
inset, theta = (5, 15.)
if isinstance(deface, dict):
if 'inset' in deface:
inset = deface['inset']
if 'theta' in deface:
theta = deface['theta']
if not _is_numeric(inset):
raise ValueError('inset must be numeric (float, int). '
'Got %s' % type(inset))
if not _is_numeric(theta):
raise ValueError('theta must be numeric (float, int). '
'Got %s' % type(theta))
if inset < 0:
raise ValueError('inset should be positive, '
'Got %s' % inset)
if not 0 <= theta < 90:
raise ValueError('theta should be between 0 and 90 '
'degrees. Got %s' % theta)
# get image data, make a copy
image_data = image.get_fdata().copy()
# make indices to move around so that the image doesn't have to
idxs = np.meshgrid(np.arange(image_data.shape[0]),
np.arange(image_data.shape[1]),
np.arange(image_data.shape[2]),
indexing='ij')
idxs = np.array(idxs) # (3, *image_data.shape)
idxs = np.transpose(idxs, [1, 2, 3, 0]) # (*image_data.shape, 3)
idxs = idxs.reshape(-1, 3) # (n_voxels, 3)
# convert to RAS by applying affine
idxs = nib.affines.apply_affine(image.affine, idxs)
# now comes the actual defacing
# 1. move center of voxels to (nasion - inset)
# 2. rotate the head by theta from vertical
x, y, z = nib.affines.apply_affine(image.affine, landmarks)[1]
idxs = apply_trans(translation(x=-x, y=-y + inset, z=-z), idxs)
idxs = apply_trans(rotation(x=-np.pi / 2 + np.deg2rad(theta)), idxs)
idxs = idxs.reshape(image_data.shape + (3,))
mask = (idxs[..., 2] < 0) # z < middle
image_data[mask] = 0.
# smooth decided against for potential lack of anonymizaton
# https://gist.github.com/alexrockhill/15043928b716a432db3a84a050b241ae
image = nib.Nifti1Image(image_data, image.affine, image.header)
return image
def _write_raw_fif(raw, bids_fname):
"""Save out the raw file in FIF.
Parameters
----------
raw : mne.io.Raw
Raw file to save out.
bids_fname : str | mne_bids.BIDSPath
The name of the BIDS-specified file where the raw object
should be saved.
"""
raw.save(bids_fname, fmt=raw.orig_format, split_naming='bids',
overwrite=True)
def _write_raw_brainvision(raw, bids_fname, events, overwrite):
"""Save out the raw file in BrainVision format.
Parameters
----------
raw : mne.io.Raw
Raw file to save out.
bids_fname : str
The name of the BIDS-specified file where the raw object
should be saved.
events : ndarray
The events as MNE-Python format ndaray.
overwrite : bool
Whether or not to overwrite existing files.
"""
if not check_version('pybv', '0.6'): # pragma: no cover
raise ImportError('pybv >=0.6 is required for converting '
'file to BrainVision format')
from pybv import write_brainvision
# Subtract raw.first_samp because brainvision marks events starting from
# the first available data point and ignores the raw.first_samp
if events is not None:
events[:, 0] -= raw.first_samp
events = events[:, [0, 2]] # reorder for pybv required order
meas_date = raw.info['meas_date']
if meas_date is not None:
meas_date = _stamp_to_dt(meas_date)
# pybv needs to know the units of the data for appropriate scaling
# get voltage units as micro-volts and all other units "as is"
unit = []
for chs in raw.info['chs']:
if chs['unit'] == FIFF.FIFF_UNIT_V:
unit.append('µV')
else:
unit.append(_unit2human.get(chs['unit'], 'n/a'))
unit = [u if u not in ['NA'] else 'n/a' for u in unit]
# We enforce conversion to float32 format
# XXX: pybv can also write to int16, to do that, we need to get
# original units of data prior to conversion, and add an optimization
# function to pybv that maximizes the resolution parameter while
# ensuring that int16 can represent the data in original units.
if raw.orig_format != 'single':
warn(f'Encountered data in "{raw.orig_format}" format. '
f'Converting to float32.', RuntimeWarning)
# Writing to float32 µV with 0.1 resolution are the pybv defaults,
# which guarantees accurate roundtrip for values >= 1e-7 µV
fmt = 'binary_float32'
resolution = 1e-1
write_brainvision(data=raw.get_data(),
sfreq=raw.info['sfreq'],
ch_names=raw.ch_names,
ref_ch_names=None,
fname_base=op.splitext(op.basename(bids_fname))[0],
folder_out=op.dirname(bids_fname),
overwrite=overwrite,
events=events,
resolution=resolution,
unit=unit,
fmt=fmt,
meas_date=meas_date)
def _write_raw_edf(raw, bids_fname):
"""Store data as EDF.
Parameters
----------
raw : mne.io.Raw
Raw data to save.
bids_fname : str
The output filename.
"""
assert str(bids_fname).endswith('.edf')
raw.export(bids_fname)
@verbose
def make_dataset_description(path, name, data_license=None,
authors=None, acknowledgements=None,
how_to_acknowledge=None, funding=None,
references_and_links=None, doi=None,
dataset_type='raw',
overwrite=False, verbose=None):
"""Create json for a dataset description.
BIDS datasets may have one or more fields, this function allows you to
specify which you wish to include in the description. See the BIDS
documentation for information about what each field means.
Parameters
----------
path : str
A path to a folder where the description will be created.
name : str
The name of this BIDS dataset.
data_license : str | None
The license under which this dataset is published.
authors : list | str | None
List of individuals who contributed to the creation/curation of the
dataset. Must be a list of str or a single comma separated str
like ['a', 'b', 'c'].
acknowledgements : list | str | None
Either a str acknowledging individuals who contributed to the
creation/curation of this dataset OR a list of the individuals'
names as str.
how_to_acknowledge : list | str | None
Either a str describing how to acknowledge this dataset OR a list of
publications that should be cited.
funding : list | str | None
List of sources of funding (e.g., grant numbers). Must be a list of
str or a single comma separated str like ['a', 'b', 'c'].
references_and_links : list | str | None
List of references to publication that contain information on the
dataset, or links. Must be a list of str or a single comma
separated str like ['a', 'b', 'c'].
doi : str | None
The DOI for the dataset.
dataset_type : str
Must be either "raw" or "derivative". Defaults to "raw".
overwrite : bool
Whether to overwrite existing files or data in files.
Defaults to False.
If overwrite is True, provided fields will overwrite previous data.
If overwrite is False, no existing data will be overwritten or