-
Notifications
You must be signed in to change notification settings - Fork 83
/
test_write.py
4113 lines (3543 loc) · 148 KB
/
test_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
# -*- coding: utf-8 -*-
"""Test the MNE BIDS converter.
For each supported file format, implement a test.
"""
# Authors: Mainak Jas <mainak.jas@telecom-paristech.fr>
# Teon L Brooks <teon.brooks@gmail.com>
# Chris Holdgraf <choldgraf@berkeley.edu>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
# Matt Sanderson <matt.sanderson@mq.edu.au>
#
# License: BSD-3-Clause
import sys
import os
import os.path as op
from glob import glob
from datetime import datetime, timezone, timedelta
import shutil as sh
import json
from pathlib import Path
import codecs
import warnings
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal, assert_array_almost_equal
import mne
from mne.datasets import testing
from mne.utils import check_version
from mne.io import anonymize_info
from mne.io.constants import FIFF
from mne.io.kit.kit import get_kit_info
from mne_bids import (
write_raw_bids,
read_raw_bids,
BIDSPath,
write_anat,
make_dataset_description,
mark_channels,
write_meg_calibration,
write_meg_crosstalk,
get_entities_from_fname,
get_anat_landmarks,
write,
anonymize_dataset,
get_entity_vals,
)
from mne_bids.write import _get_fid_coords
from mne_bids.utils import (
_stamp_to_dt,
_get_anonymization_daysback,
get_anonymization_daysback,
_write_json,
)
from mne_bids.tsv_handler import _from_tsv, _to_tsv
from mne_bids.sidecar_updates import _update_sidecar, update_sidecar_json
from mne_bids.path import _find_matching_sidecar, _parse_ext
from mne_bids.pick import coil_type
from mne_bids.config import REFERENCES, BIDS_COORD_FRAME_DESCRIPTIONS, PYBV_VERSION
base_path = op.join(op.dirname(mne.__file__), "io")
subject_id = "01"
subject_id2 = "02"
session_id = "01"
run = "01"
acq = "01"
run2 = "02"
task = "testing"
_bids_path = BIDSPath(
subject=subject_id, session=session_id, run=run, acquisition=acq, task=task
)
_bids_path_minimal = BIDSPath(subject=subject_id, task=task)
warning_str = dict(
channel_unit_changed="ignore:The unit for chann*.:RuntimeWarning:mne",
meas_date_set_to_none="ignore:.*'meas_date' set to None:RuntimeWarning:" "mne",
nasion_not_found="ignore:.*nasion not found:RuntimeWarning:mne",
unraisable_exception="ignore:.*Exception ignored.*:"
"pytest.PytestUnraisableExceptionWarning",
encountered_data_in="ignore:Encountered data in*.:RuntimeWarning:mne",
edf_warning=r"ignore:^EDF\/EDF\+\/BDF files contain two fields .*"
r":RuntimeWarning:mne",
maxshield="ignore:.*Internal Active Shielding:RuntimeWarning:mne",
edfblocks="ignore:.*EDF format requires equal-length data "
"blocks:RuntimeWarning:mne",
brainvision_unit="ignore:Encountered unsupported "
"non-voltage units*.:UserWarning",
cnt_warning1="ignore:.*Could not parse meas date from the header. "
"Setting to None.",
cnt_warning2="ignore:.*Could not define the number of bytes automatically."
" Defaulting to 2.",
cnt_warning3="ignore:.*Coordinate frame could not be inferred.*",
no_hand="ignore:.*Not setting subject handedness.:RuntimeWarning:mne",
no_montage=r"ignore:Not setting position of.*channel found in "
r"montage.*:RuntimeWarning:mne",
)
def _wrap_read_raw(read_raw):
def fn(fname, *args, **kwargs):
raw = read_raw(fname, *args, **kwargs)
raw.info["line_freq"] = 60
return raw
return fn
_read_raw_fif = _wrap_read_raw(mne.io.read_raw_fif)
_read_raw_ctf = _wrap_read_raw(mne.io.read_raw_ctf)
_read_raw_kit = _wrap_read_raw(mne.io.read_raw_kit)
_read_raw_bti = _wrap_read_raw(mne.io.read_raw_bti)
_read_raw_edf = _wrap_read_raw(mne.io.read_raw_edf)
_read_raw_bdf = _wrap_read_raw(mne.io.read_raw_bdf)
_read_raw_eeglab = _wrap_read_raw(mne.io.read_raw_eeglab)
_read_raw_brainvision = _wrap_read_raw(mne.io.read_raw_brainvision)
_read_raw_persyst = _wrap_read_raw(mne.io.read_raw_persyst)
_read_raw_nihon = _wrap_read_raw(mne.io.read_raw_nihon)
_read_raw_cnt = _wrap_read_raw(mne.io.read_raw_cnt)
_read_raw_snirf = _wrap_read_raw(mne.io.read_raw_snirf)
_read_raw_egi = _wrap_read_raw(mne.io.read_raw_egi)
_read_raw_curry = _wrap_read_raw(mne.io.read_raw_curry)
# parametrized directory, filename and reader for EEG/iEEG data formats
test_eegieeg_data = [
("EDF", "test_reduced.edf", _read_raw_edf),
(
"Persyst",
"sub-pt1_ses-02_task-monitor_acq-ecog_run-01_clip2.lay",
_read_raw_persyst,
), # noqa
("NihonKohden", "MB0400FU.EEG", _read_raw_nihon),
("CNT", "scan41_short.cnt", _read_raw_cnt),
("EGI", "test_egi.mff", _read_raw_egi),
("curry", "test_bdf_stim_channel Curry 8.cdt", _read_raw_curry),
]
test_convert_data = test_eegieeg_data.copy()
test_convert_data.append(("CTF", "testdata_ctf.ds", _read_raw_ctf))
# parametrization for testing conversion of file formats for MEG
test_convertmeg_data = [
("CTF", "FIF", "testdata_ctf.ds", _read_raw_ctf),
("CTF", "auto", "testdata_ctf.ds", _read_raw_ctf),
]
# parametrization for testing converting file formats for EEG/iEEG
test_converteeg_data = [
(
"Persyst",
"BrainVision",
"sub-pt1_ses-02_task-monitor_acq-ecog_run-01_clip2.lay",
_read_raw_persyst,
), # noqa
("NihonKohden", "BrainVision", "MB0400FU.EEG", _read_raw_nihon),
("CNT", "BrainVision", "scan41_short.cnt", _read_raw_cnt),
(
"curry",
"BrainVision",
"test_bdf_stim_channel Curry 8.cdt",
_read_raw_curry,
), # noqa
(
"Persyst",
"EDF",
"sub-pt1_ses-02_task-monitor_acq-ecog_run-01_clip2.lay",
_read_raw_persyst,
), # noqa
("NihonKohden", "EDF", "MB0400FU.EEG", _read_raw_nihon),
("CNT", "EDF", "scan41_short.cnt", _read_raw_cnt),
("curry", "EDF", "test_bdf_stim_channel Curry 8.cdt", _read_raw_curry),
]
data_path = testing.data_path(download=False)
def _test_anonymize(root, raw, bids_path, events_fname=None, event_id=None):
"""Write data to `root` for testing anonymization."""
bids_path = _bids_path.copy().update(root=root)
if raw.info["meas_date"] is not None:
daysback, _ = get_anonymization_daysback(raw)
else:
# just pass back any arbitrary number if no measurement date
daysback = 3300
write_raw_bids(
raw,
bids_path,
events=events_fname,
event_id=event_id,
anonymize=dict(daysback=daysback),
overwrite=False,
)
scans_tsv = BIDSPath(
subject=subject_id,
session=session_id,
suffix="scans",
extension=".tsv",
root=root,
)
data = _from_tsv(scans_tsv)
if data["acq_time"] is not None and data["acq_time"][0] != "n/a":
assert (
datetime.strptime(data["acq_time"][0], "%Y-%m-%dT%H:%M:%S.%fZ").year < 1925
)
return root
@testing.requires_testing_data
def test_write_participants(_bids_validate, tmp_path):
"""Test participants.tsv/.json file writing.
Test that user modifications of the participants
files are kept, and mne-bids correctly writes all
the subject info it can using ``raw.info['subject_info']``.
"""
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
raw = _read_raw_fif(raw_fname)
# add fake participants data
raw.set_meas_date(datetime(year=1994, month=1, day=26, tzinfo=timezone.utc))
raw.info["subject_info"] = {
"his_id": subject_id2,
"birthday": (1993, 1, 26),
"sex": 1,
"hand": 2,
}
bids_path = _bids_path.copy().update(root=tmp_path)
write_raw_bids(raw, bids_path)
# assert age of participant is correct
participants_tsv = tmp_path / "participants.tsv"
data = _from_tsv(participants_tsv)
assert data["age"][data["participant_id"].index("sub-01")] == "1"
# Removing some columns from participants.tsv should not prevent us from
# writing additional participants later on. Before running this test,
# ensure we have at least 2 participants in the dataset already – this is
# a regression test for GH-1104.
bids_path.update(subject="02")
write_raw_bids(raw, bids_path, verbose=False)
data = _from_tsv(participants_tsv)
data.pop("hand")
_to_tsv(data, participants_tsv)
# write in now another subject
bids_path.update(subject="03")
write_raw_bids(raw, bids_path, verbose=False)
data = _from_tsv(participants_tsv)
# hand should have been written properly with now 'n/a' for sub-01 and
# sub-03, but 'L' for sub-03
assert data["hand"][data["participant_id"].index("sub-01")] == "n/a"
assert data["hand"][data["participant_id"].index("sub-02")] == "n/a"
assert data["hand"][data["participant_id"].index("sub-03")] == "L"
# check to make sure participant data is overwritten, but keeps the fields
# if there are extra fields that were user defined
data = _from_tsv(participants_tsv)
participant_idx = data["participant_id"].index(f"sub-{subject_id}")
# create a new test column in participants file tsv
data["subject_test_col1"] = ["n/a"] * len(data["participant_id"])
data["subject_test_col1"][participant_idx] = "S"
data["test_col2"] = ["n/a"] * len(data["participant_id"])
orig_key_order = list(data.keys())
_to_tsv(data, participants_tsv)
# create corresponding json entry
participants_json_fpath = tmp_path / "participants.json"
json_field = {
"Description": "trial-outcome",
"Levels": {"S": "success", "F": "failure"},
}
_update_sidecar(participants_json_fpath, "subject_test_col1", json_field)
# bids root should still be valid because json reflects changes in tsv
_bids_validate(tmp_path)
write_raw_bids(raw, bids_path, overwrite=True)
data = _from_tsv(participants_tsv)
with open(participants_json_fpath, "r", encoding="utf-8") as fin:
participants_json = json.load(fin)
assert "subject_test_col1" in participants_json
assert data["subject_test_col1"][participant_idx] == "S"
# in addition assert the original ordering of the new overwritten file
assert list(data.keys()) == orig_key_order
# if overwrite is False, then nothing should change from the above
with pytest.raises(FileExistsError, match="already exists"):
write_raw_bids(raw, bids_path, overwrite=False)
data = _from_tsv(participants_tsv)
with open(participants_json_fpath, "r", encoding="utf-8") as fin:
participants_json = json.load(fin)
assert "subject_test_col1" in participants_json
assert data["age"][data["participant_id"].index("sub-01")] == "1"
assert data["subject_test_col1"][participant_idx] == "S"
# in addition assert the original ordering of the new overwritten file
assert list(data.keys()) == orig_key_order
# For empty-room data, all fields except participant_id should be 'n/a'
assert raw.info["subject_info"] # Ensure the following test makes sense!
bids_path_er = bids_path.copy().update(
subject="emptyroom",
task="noise",
session=raw.info["meas_date"].strftime("%Y%m%d"),
)
write_raw_bids(raw=raw, bids_path=bids_path_er, verbose=False)
participants_tsv = _from_tsv(participants_tsv)
idx = participants_tsv["participant_id"].index("sub-emptyroom")
assert participants_tsv["hand"][idx] == "n/a"
assert participants_tsv["sex"][idx] == "n/a"
assert participants_tsv["age"][idx] == "n/a"
@testing.requires_testing_data
def test_write_correct_inputs():
"""Test that inputs of write_raw_bids is correct."""
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
raw = _read_raw_fif(raw_fname)
bids_path_str = "sub-01_ses-01_meg.fif"
with pytest.raises(RuntimeError, match='"bids_path" must be a ' "BIDSPath object"):
write_raw_bids(raw, bids_path_str)
bids_path = _bids_path.copy()
assert bids_path.root is None
with pytest.raises(ValueError, match='The root of the "bids_path" must be set'):
write_raw_bids(raw=raw, bids_path=bids_path)
bids_path = _bids_path.copy().update(root="/foo", subject=None)
with pytest.raises(ValueError, match='The subject of the "bids_path" must be set'):
write_raw_bids(raw=raw, bids_path=bids_path)
bids_path = _bids_path.copy().update(root="/foo", task=None)
with pytest.raises(ValueError, match='The task of the "bids_path" must be set'):
write_raw_bids(raw=raw, bids_path=bids_path)
def test_make_dataset_description(tmp_path, monkeypatch):
"""Test making a dataset_description.json."""
make_dataset_description(path=tmp_path, name="tst")
with open(
op.join(tmp_path, "dataset_description.json"), "r", encoding="utf-8"
) as fid:
dataset_description_json = json.load(fid)
assert dataset_description_json["Authors"] == ["[Unspecified]"]
make_dataset_description(
path=tmp_path,
name="tst",
authors="MNE B., MNE P.",
funding="GSOC2019, GSOC2021",
references_and_links="https://doi.org/10.21105/joss.01896",
dataset_type="derivative",
overwrite=False,
verbose=True,
)
with open(
op.join(tmp_path, "dataset_description.json"), "r", encoding="utf-8"
) as fid:
dataset_description_json = json.load(fid)
assert dataset_description_json["Authors"] == ["[Unspecified]"]
make_dataset_description(
path=tmp_path,
name="tst2",
authors="MNE B., MNE P.",
funding="GSOC2019, GSOC2021",
references_and_links="https://doi.org/10.21105/joss.01896",
dataset_type="derivative",
overwrite=True,
verbose=True,
)
with open(
op.join(tmp_path, "dataset_description.json"), "r", encoding="utf-8"
) as fid:
dataset_description_json = json.load(fid)
assert dataset_description_json["Authors"] == ["MNE B.", "MNE P."]
# Check we raise warnings and errors where appropriate
with pytest.raises(
ValueError, match='`dataset_type` must be either "raw" ' 'or "derivative."'
):
make_dataset_description(path=tmp_path, name="tst", dataset_type="src")
with pytest.warns(RuntimeWarning, match="The `doi` field in.*"):
make_dataset_description(
path=tmp_path, name="tst", doi="10.5281/zenodo.3686061"
)
for gen_by in [[1, 2], 12]:
with pytest.raises(ValueError, match="generated_by must be a list.*"):
make_dataset_description(path=tmp_path, name="tst", generated_by=gen_by)
with pytest.raises(ValueError, match='"Name" is a required field.*'):
make_dataset_description(
path=tmp_path, name="tst", generated_by=[{"Version": 2}]
)
gen_by = [{"Name": "bla", "x": 3, "y": 1}]
with pytest.raises(ValueError, match=".*in dict: {'.', '.'}"):
make_dataset_description(path=tmp_path, name="tst", generated_by=gen_by)
for s_ds in [[1, 2], 12]:
with pytest.raises(ValueError, match="source_datasets must be a.*"):
make_dataset_description(path=tmp_path, name="tst", source_datasets=s_ds)
s_ds = [{"URL": "bla", "x": 3, "y": 1}]
with pytest.raises(ValueError, match=".*in dict: {'.', '.'}"):
make_dataset_description(path=tmp_path, name="tst", source_datasets=s_ds)
monkeypatch.setattr(write, "BIDS_VERSION", "old")
with pytest.warns(UserWarning, match="Conflicting BIDSVersion found*"):
make_dataset_description(path=tmp_path, name="tst")
def test_stamp_to_dt():
"""Test conversions of meas_date to datetime objects."""
meas_date = (1346981585, 835782)
meas_datetime = _stamp_to_dt(meas_date)
assert meas_datetime == datetime(2012, 9, 7, 1, 33, 5, 835782, tzinfo=timezone.utc)
meas_date = (1346981585,)
meas_datetime = _stamp_to_dt(meas_date)
assert meas_datetime == datetime(2012, 9, 7, 1, 33, 5, 0, tzinfo=timezone.utc)
@testing.requires_testing_data
def test_get_anonymization_daysback():
"""Test daysback querying for anonymization."""
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
raw = _read_raw_fif(raw_fname)
daysback_min, daysback_max = _get_anonymization_daysback(raw)
# max_val off by 1 on Windows for some reason
assert abs(daysback_min - 28461) < 2 and abs(daysback_max - 36880) < 2
raw2 = raw.copy()
with raw2.info._unlock():
raw2.info["meas_date"] = (np.int32(1158942080), np.int32(720100))
raw3 = raw.copy()
with raw3.info._unlock():
raw3.info["meas_date"] = (np.int32(914992080), np.int32(720100))
daysback_min, daysback_max = get_anonymization_daysback([raw, raw2, raw3])
assert abs(daysback_min - 29850) < 2 and abs(daysback_max - 35446) < 2
raw4 = raw.copy()
with raw4.info._unlock():
raw4.info["meas_date"] = (np.int32(4992080), np.int32(720100))
raw5 = raw.copy()
with raw5.info._unlock():
raw5.info["meas_date"] = None
daysback_min2, daysback_max2 = get_anonymization_daysback([raw, raw2, raw3, raw5])
assert daysback_min2 == daysback_min and daysback_max2 == daysback_max
with pytest.raises(ValueError, match="The dataset spans more time"):
daysback_min, daysback_max = get_anonymization_daysback([raw, raw2, raw4])
def test_create_fif(_bids_validate, tmp_path):
"""Test functionality for very short raw file created from data."""
out_dir = tmp_path / "out"
bids_root = tmp_path / "bids"
out_dir.mkdir()
bids_path = _bids_path.copy().update(root=bids_root)
sfreq, n_points = 1024.0, int(1e6)
info = mne.create_info(["ch1", "ch2", "ch3", "ch4", "ch5"], sfreq, ["seeg"] * 5)
rng = np.random.RandomState(99)
raw = mne.io.RawArray(rng.random((5, n_points)) * 1e-6, info)
raw.info["line_freq"] = 60
raw.save(op.join(out_dir, "test-raw.fif"))
raw = _read_raw_fif(op.join(out_dir, "test-raw.fif"))
write_raw_bids(raw, bids_path, verbose=False, overwrite=True)
_bids_validate(bids_root)
@pytest.mark.parametrize("line_freq", [60, None])
def test_line_freq(line_freq, _bids_validate, tmp_path):
"""Test the power line frequency is written correctly."""
out_dir = tmp_path / "out"
out_dir.mkdir()
bids_root = tmp_path / "bids"
bids_path = _bids_path.copy().update(root=bids_root)
sfreq, n_points = 1024.0, int(1e6)
info = mne.create_info(["ch1", "ch2", "ch3", "ch4", "ch5"], sfreq, ["eeg"] * 5)
rng = np.random.RandomState(99)
raw = mne.io.RawArray(rng.random((5, n_points)) * 1e-6, info)
raw.save(op.join(out_dir, "test-raw.fif"))
raw = _read_raw_fif(op.join(out_dir, "test-raw.fif"))
raw.info["line_freq"] = line_freq
write_raw_bids(raw, bids_path, verbose=False, overwrite=True)
_bids_validate(bids_root)
eeg_json_fpath = (
bids_path.copy().update(suffix="eeg", datatype="eeg", extension=".json").fpath
)
with open(eeg_json_fpath, "r", encoding="utf-8") as fin:
eeg_json = json.load(fin)
if line_freq == 60:
assert eeg_json["PowerLineFrequency"] == line_freq
elif line_freq is None:
assert eeg_json["PowerLineFrequency"] == "n/a"
@testing.requires_testing_data
@pytest.mark.filterwarnings(warning_str["channel_unit_changed"])
@pytest.mark.filterwarnings(warning_str["maxshield"])
def test_fif(_bids_validate, tmp_path):
"""Test functionality of the write_raw_bids conversion for fif."""
pytest.importorskip("pybv", PYBV_VERSION)
bids_root = tmp_path / "bids1"
bids_path = _bids_path.copy().update(root=bids_root, datatype="meg")
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
event_id = {
"Auditory/Left": 1,
"Auditory/Right": 2,
"Visual/Left": 3,
"Visual/Right": 4,
"Smiley": 5,
"Button": 32,
}
events_fname = op.join(
data_path, "MEG", "sample", "sample_audvis_trunc_raw-eve.fif"
)
# Drop unknown events.
events = mne.read_events(events_fname)
events = events[events[:, 2] != 0]
raw = _read_raw_fif(raw_fname)
write_raw_bids(raw, bids_path, events=events, event_id=event_id, overwrite=False)
# Read the file back in to check that the data has come through cleanly.
# Events and bad channel information was read through JSON sidecar files.
with pytest.raises(TypeError, match="unexpected keyword argument 'foo'"):
read_raw_bids(bids_path=bids_path, extra_params=dict(foo="bar"))
raw2 = read_raw_bids(bids_path=bids_path)
assert set(raw.info["bads"]) == set(raw2.info["bads"])
events, _ = mne.events_from_annotations(raw2)
events2 = mne.read_events(events_fname)
events2 = events2[events2[:, 2] != 0]
assert_array_equal(events2[:, 0], events[:, 0])
# check if write_raw_bids works when there is no stim channel
raw.set_channel_types(
{
raw.ch_names[i]: "misc"
for i in mne.pick_types(raw.info, stim=True, meg=False)
}
)
bids_root = tmp_path / "bids2"
bids_path.update(root=bids_root)
with pytest.warns(RuntimeWarning, match="No events found or provided."):
write_raw_bids(raw, bids_path, overwrite=False)
_bids_validate(bids_root)
# try with eeg data only (conversion to bv)
bids_root = tmp_path / "bids3"
bids_root.mkdir()
bids_path.update(root=bids_root)
raw = _read_raw_fif(raw_fname)
raw.load_data()
raw2 = raw.pick_types(meg=False, eeg=True, stim=True, eog=True, ecg=True)
raw2.save(bids_root / "test-raw.fif", overwrite=True)
raw2 = mne.io.Raw(op.join(bids_root, "test-raw.fif"), preload=False)
events = mne.find_events(raw2)
event_id = {
"auditory/left": 1,
"auditory/right": 2,
"visual/left": 3,
"visual/right": 4,
"smiley": 5,
"button": 32,
}
epochs = mne.Epochs(
raw2, events, event_id=event_id, tmin=-0.2, tmax=0.5, preload=True
)
bids_path = bids_path.update(datatype="eeg")
with pytest.warns(
RuntimeWarning, match="Converting data files to BrainVision format"
):
write_raw_bids(
raw2,
bids_path,
events=events,
event_id=event_id,
verbose=True,
overwrite=False,
)
bids_dir = op.join(bids_root, "sub-%s" % subject_id, "ses-%s" % session_id, "eeg")
sidecar_basename = bids_path.copy()
for sidecar in [
"channels.tsv",
"eeg.eeg",
"eeg.json",
"eeg.vhdr",
"eeg.vmrk",
"events.tsv",
]:
suffix, extension = sidecar.split(".")
extension = f".{extension}"
sidecar_basename.update(suffix=suffix, extension=extension)
assert op.isfile(op.join(bids_dir, sidecar_basename.basename))
bids_path.update(root=bids_root, datatype="eeg")
with pytest.warns(RuntimeWarning, match="Not setting position"):
raw2 = read_raw_bids(bids_path=bids_path)
os.remove(op.join(bids_root, "test-raw.fif"))
events2, _ = mne.events_from_annotations(raw2, event_id)
epochs2 = mne.Epochs(
raw2, events2, event_id=event_id, tmin=-0.2, tmax=0.5, preload=True
)
assert_array_almost_equal(raw.get_data(), raw2.get_data())
assert_array_almost_equal(epochs.get_data(), epochs2.get_data(), decimal=4)
_bids_validate(bids_root)
# write the same data but pretend it is empty room data:
raw = _read_raw_fif(raw_fname)
meas_date = raw.info["meas_date"]
if not isinstance(meas_date, datetime):
meas_date = datetime.fromtimestamp(meas_date[0], tz=timezone.utc)
er_date = meas_date.strftime("%Y%m%d")
er_bids_path = BIDSPath(
subject="emptyroom", session=er_date, task="noise", root=bids_root
)
write_raw_bids(raw, er_bids_path, overwrite=False)
assert op.exists(
op.join(
bids_root,
"sub-emptyroom",
"ses-{0}".format(er_date),
"meg",
"sub-emptyroom_ses-{0}_task-noise_meg.json".format(er_date),
)
)
_bids_validate(bids_root)
# test that an incorrect date raises an error.
er_bids_basename_bad = BIDSPath(
subject="emptyroom", session="19000101", task="noise", root=bids_root
)
with pytest.raises(ValueError, match="The date provided"):
write_raw_bids(raw, er_bids_basename_bad, overwrite=False)
# test that the acquisition time was written properly
scans_tsv = BIDSPath(
subject=subject_id,
session=session_id,
suffix="scans",
extension=".tsv",
root=bids_root,
)
data = _from_tsv(scans_tsv)
assert data["acq_time"][0] == meas_date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
# give the raw object some fake participant data (potentially overwriting)
raw = _read_raw_fif(raw_fname)
bids_path_meg = bids_path.copy().update(datatype="meg")
write_raw_bids(raw, bids_path_meg, events=events, event_id=event_id, overwrite=True)
# try and write preloaded data
raw = _read_raw_fif(raw_fname, preload=True)
with pytest.raises(ValueError, match="allow_preload"):
write_raw_bids(
raw,
bids_path_meg,
events=events,
event_id=event_id,
allow_preload=False,
overwrite=False,
)
# test anonymize
raw = _read_raw_fif(raw_fname)
raw.anonymize()
raw_fname2 = tmp_path / "tmp_anon" / "sample_audvis_raw.fif"
raw_fname2.parent.mkdir()
raw.save(raw_fname2)
# add some readme text
readme = op.join(bids_root, "README")
with open(readme, "w", encoding="utf-8-sig") as fid:
fid.write("Welcome to my dataset\n")
bids_path2 = bids_path_meg.copy().update(subject=subject_id2)
raw = _read_raw_fif(raw_fname2)
bids_output_path = write_raw_bids(
raw, bids_path2, events=events, event_id=event_id, overwrite=False
)
# check that the overwrite parameters work correctly for the participant
# data
# change the gender but don't force overwrite.
raw = _read_raw_fif(raw_fname)
raw.info["subject_info"] = {
"his_id": subject_id2,
"birthday": (1994, 1, 26),
"sex": 2,
"hand": 1,
}
with pytest.raises(FileExistsError, match="already exists"): # noqa: F821
write_raw_bids(
raw, bids_path2, events=events, event_id=event_id, overwrite=False
)
# assert README has references in it
with open(readme, "r", encoding="utf-8-sig") as fid:
text = fid.read()
assert "Welcome to my dataset\n" in text
assert REFERENCES["mne-bids"] in text
assert REFERENCES["meg"] in text
assert REFERENCES["eeg"] not in text
assert REFERENCES["ieeg"] not in text
# now force the overwrite
write_raw_bids(raw, bids_path2, events=events, event_id=event_id, overwrite=True)
with open(readme, "r", encoding="utf-8-sig") as fid:
text = fid.read()
assert "Welcome to my dataset\n" in text
assert REFERENCES["mne-bids"] in text
assert REFERENCES["meg"] in text
with pytest.raises(ValueError, match="raw_file must be"):
write_raw_bids("blah", bids_path)
_bids_validate(bids_root)
assert op.exists(op.join(bids_root, "participants.tsv"))
# asserting that single fif files do not include the split key
files = glob(
op.join(
bids_output_path, "sub-" + subject_id2, "ses-" + subject_id2, "meg", "*.fif"
)
)
ii = 0
for ii, FILE in enumerate(files):
assert "split" not in FILE
assert ii < 1
# check that split files have split key
raw = _read_raw_fif(raw_fname)
raw_fname3 = tmp_path / "test-split-key" / "sample_audvis_raw.fif"
raw_fname3.parent.mkdir()
raw.save(
raw_fname3,
buffer_size_sec=1.0,
split_size="10MB",
split_naming="neuromag",
overwrite=True,
)
raw = _read_raw_fif(raw_fname3)
subject_id3 = "03"
bids_path3 = bids_path.copy().update(subject=subject_id3)
bids_output_path = write_raw_bids(raw, bids_path3, overwrite=False)
files = glob(
op.join(
bids_output_path, "sub-" + subject_id3, "ses-" + subject_id3, "meg", "*.fif"
)
)
for FILE in files:
assert "split" in FILE
# test whether extra points in raw.info['dig'] are correctly used
# to set DigitizedHeadShape in the JSON sidecar
# unchanged sample data includes extra points
meg_json_path = Path(
_find_matching_sidecar(
bids_path=bids_path.copy().update(root=bids_root, datatype="meg"),
suffix="meg",
extension=".json",
)
)
meg_json = json.loads(meg_json_path.read_text(encoding="utf-8"))
assert meg_json["DigitizedHeadPoints"] is True
# drop extra points from raw.info['dig'] and write again
raw_no_extra_points = _read_raw_fif(raw_fname)
new_dig = []
for dig_point in raw_no_extra_points.info["dig"]:
if dig_point["kind"] != FIFF.FIFFV_POINT_EXTRA:
new_dig.append(dig_point)
with raw_no_extra_points.info._unlock():
raw_no_extra_points.info["dig"] = new_dig
write_raw_bids(
raw_no_extra_points, bids_path, events=events, event_id=event_id, overwrite=True
)
meg_json_path = Path(
_find_matching_sidecar(
bids_path=bids_path.copy().update(root=bids_root, datatype="meg"),
suffix="meg",
extension=".json",
)
)
meg_json = json.loads(meg_json_path.read_text(encoding="utf-8"))
assert meg_json["DigitizedHeadPoints"] is False
assert "SoftwareFilters" in meg_json
software_filters = meg_json["SoftwareFilters"]
assert "SpatialCompensation" in software_filters
assert "GradientOrder" in software_filters["SpatialCompensation"]
assert (
software_filters["SpatialCompensation"]["GradientOrder"]
== raw.compensation_grade
)
@pytest.mark.parametrize("format", ("fif_no_chpi", "fif", "ctf", "kit"))
@pytest.mark.filterwarnings(warning_str["maxshield"])
@testing.requires_testing_data
def test_chpi(_bids_validate, tmp_path, format):
"""Test writing of cHPI information."""
if format == "fif_no_chpi":
fif_raw_fname = op.join(
data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif"
)
raw = _read_raw_fif(fif_raw_fname)
elif format == "fif":
fif_raw_fname = op.join(data_path, "SSS", "test_move_anon_raw.fif")
raw = _read_raw_fif(fif_raw_fname, allow_maxshield="yes")
elif format == "ctf":
ctf_raw_fname = op.join(data_path, "CTF", "testdata_ctf.ds")
raw = _read_raw_ctf(ctf_raw_fname)
elif format == "kit":
kit_data_path = op.join(base_path, "kit", "tests", "data")
kit_raw_fname = op.join(kit_data_path, "test.sqd")
kit_hpi_fname = op.join(kit_data_path, "test_mrk.sqd")
kit_electrode_fname = op.join(kit_data_path, "test.elp")
kit_headshape_fname = op.join(kit_data_path, "test.hsp")
raw = _read_raw_kit(
kit_raw_fname,
mrk=kit_hpi_fname,
elp=kit_electrode_fname,
hsp=kit_headshape_fname,
)
bids_root = tmp_path / "bids"
bids_path = _bids_path.copy().update(root=bids_root, datatype="meg")
write_raw_bids(raw, bids_path)
_bids_validate(bids_path.root)
meg_json = bids_path.copy().update(suffix="meg", extension=".json")
meg_json_data = json.loads(meg_json.fpath.read_text(encoding="utf-8"))
if format in ["fif_no_chpi", "fif"]:
if format == "fif_no_chpi":
assert meg_json_data["ContinuousHeadLocalization"] is False
assert meg_json_data["HeadCoilFrequency"] == []
elif format == "fif":
assert meg_json_data["ContinuousHeadLocalization"] is True
assert_array_almost_equal(
meg_json_data["HeadCoilFrequency"], [83.0, 143.0, 203.0, 263.0, 323.0]
)
elif format == "kit":
# no cHPI info is contained in the sample data
assert meg_json_data["ContinuousHeadLocalization"] is False
assert meg_json_data["HeadCoilFrequency"] == []
elif format == "ctf":
assert meg_json_data["ContinuousHeadLocalization"] is True
assert meg_json_data["HeadCoilFrequency"] == []
@pytest.mark.filterwarnings(warning_str["channel_unit_changed"])
@testing.requires_testing_data
def test_fif_dtype(_bids_validate, tmp_path):
"""Test functionality of the write_raw_bids conversion for fif."""
bids_path = _bids_path.copy().update(root=tmp_path, datatype="meg")
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
desired_fmt = "int"
raw = _read_raw_fif(raw_fname)
# Fiddle with raw.orig_format -- this should never be done in "real-life",
# but we do it here to test whether write_raw_bids() will actually stick
# to the format that's specified in that attribute.
assert raw.orig_format != desired_fmt # We're actually changing something
raw.orig_format = desired_fmt
write_raw_bids(raw, bids_path, overwrite=False)
raw = read_raw_bids(bids_path)
assert raw.orig_format == desired_fmt
@testing.requires_testing_data
def test_fif_anonymize(_bids_validate, tmp_path):
"""Test write_raw_bids() with anonymization fif."""
bids_root = tmp_path / "bids1"
bids_path = _bids_path.copy().update(root=bids_root)
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
event_id = {
"Auditory/Left": 1,
"Auditory/Right": 2,
"Visual/Left": 3,
"Visual/Right": 4,
"Smiley": 5,
"Button": 32,
}
events_fname = op.join(
data_path, "MEG", "sample", "sample_audvis_trunc_raw-eve.fif"
)
# Drop unknown events.
events = mne.read_events(events_fname)
events = events[events[:, 2] != 0]
# test keyword mne-bids anonymize
raw = _read_raw_fif(raw_fname)
with pytest.raises(ValueError, match="`daysback` argument required"):
write_raw_bids(
raw,
bids_path,
events=events,
event_id=event_id,
anonymize=dict(),
overwrite=True,
)
bids_root = tmp_path / "bids2"
bids_path.update(root=bids_root)
raw = _read_raw_fif(raw_fname)
with pytest.warns(RuntimeWarning, match="daysback` is too small"):
write_raw_bids(
raw,
bids_path,
events=events,
event_id=event_id,
anonymize=dict(daysback=400),
overwrite=False,
)
bids_root = tmp_path / "bids3"
bids_path.update(root=bids_root)
raw = _read_raw_fif(raw_fname)
with pytest.raises(ValueError, match="`daysback` exceeds maximum value"):
write_raw_bids(
raw,
bids_path,
events=events,
event_id=event_id,
anonymize=dict(daysback=40000),
overwrite=False,
)
bids_root = tmp_path / "bids4"
bids_path.update(root=bids_root)
raw = _read_raw_fif(raw_fname)
write_raw_bids(
raw,
bids_path,
events=events,
event_id=event_id,
anonymize=dict(daysback=30000, keep_his=True),
overwrite=False,
)
scans_tsv = BIDSPath(
subject=subject_id,
session=session_id,
suffix="scans",
extension=".tsv",
root=bids_root,
)
data = _from_tsv(scans_tsv)
# anonymize using MNE manually
anonymized_info = anonymize_info(info=raw.info, daysback=30000, keep_his=True)
anon_date = anonymized_info["meas_date"].strftime("%Y-%m-%dT%H:%M:%S.%fZ")
assert data["acq_time"][0] == anon_date
_bids_validate(bids_root)
@pytest.mark.filterwarnings(warning_str["channel_unit_changed"])
@testing.requires_testing_data
def test_fif_ias(tmp_path):
"""Test writing FIF files with internal active shielding."""
raw_fname = op.join(data_path, "MEG", "sample", "sample_audvis_trunc_raw.fif")
raw = _read_raw_fif(raw_fname)
raw.set_channel_types({raw.ch_names[0]: "ias"})
this_path = BIDSPath(subject="sample", task="task", root=tmp_path)
write_raw_bids(raw, this_path)
raw = read_raw_bids(this_path)
assert raw.info["chs"][0]["kind"] == FIFF.FIFFV_IAS_CH