/
meas_info.py
3766 lines (3361 loc) · 129 KB
/
meas_info.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
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Matti Hämäläinen <msh@nmr.mgh.harvard.edu>
# Teon Brooks <teon.brooks@gmail.com>
# Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import contextlib
import datetime
import operator
import string
from collections import Counter, OrderedDict, defaultdict
from collections.abc import Mapping
from copy import deepcopy
from io import BytesIO
from textwrap import shorten
import numpy as np
from ..defaults import _handle_default
from ..html_templates import _get_html_template
from ..utils import (
_check_fname,
_check_on_missing,
_check_option,
_dt_to_stamp,
_is_numeric,
_on_missing,
_pl,
_stamp_to_dt,
_validate_type,
check_fname,
fill_doc,
logger,
object_diff,
repr_html,
verbose,
warn,
)
from ._digitization import (
DigPoint,
_dig_kind_ints,
_dig_kind_proper,
_dig_kind_rev,
_format_dig_points,
_get_data_as_dict_from_dig,
_read_dig_fif,
write_dig,
)
from .compensator import get_current_comp
from .constants import FIFF, _ch_unit_mul_named, _coord_frame_named
from .ctf_comp import _read_ctf_comp, write_ctf_comp
from .open import fiff_open
from .pick import (
_DATA_CH_TYPES_SPLIT,
_contains_ch_type,
_picks_to_idx,
channel_type,
get_channel_type_constants,
pick_types,
)
from .proc_history import _read_proc_history, _write_proc_history
from .proj import (
Projection,
_normalize_proj,
_proj_equal,
_read_proj,
_uniquify_projs,
_write_proj,
)
from .tag import (
_ch_coord_dict,
_float_item,
_int_item,
_rename_list,
_update_ch_info_named,
find_tag,
read_tag,
)
from .tree import dir_tree_find
from .write import (
DATE_NONE,
_safe_name_list,
end_block,
start_and_end_file,
start_block,
write_ch_info,
write_coord_trans,
write_dig_points,
write_float,
write_float_matrix,
write_id,
write_int,
write_julian,
write_name_list_sanitized,
write_string,
)
b = bytes # alias
_SCALAR_CH_KEYS = (
"scanno",
"logno",
"kind",
"range",
"cal",
"coil_type",
"unit",
"unit_mul",
"coord_frame",
)
_ALL_CH_KEYS_SET = set(_SCALAR_CH_KEYS + ("loc", "ch_name"))
# XXX we need to require these except when doing simplify_info
_MIN_CH_KEYS_SET = set(("kind", "cal", "unit", "loc", "ch_name"))
def _get_valid_units():
"""Get valid units according to the International System of Units (SI).
The International System of Units (SI, :footcite:`WikipediaSI`) is the
default system for describing units in the Brain Imaging Data Structure
(BIDS). For more information, see the BIDS specification
:footcite:`BIDSdocs` and the appendix "Units" therein.
References
----------
.. footbibliography::
"""
valid_prefix_names = [
"yocto",
"zepto",
"atto",
"femto",
"pico",
"nano",
"micro",
"milli",
"centi",
"deci",
"deca",
"hecto",
"kilo",
"mega",
"giga",
"tera",
"peta",
"exa",
"zetta",
"yotta",
]
valid_prefix_symbols = [
"y",
"z",
"a",
"f",
"p",
"n",
"µ",
"m",
"c",
"d",
"da",
"h",
"k",
"M",
"G",
"T",
"P",
"E",
"Z",
"Y",
]
valid_unit_names = [
"metre",
"kilogram",
"second",
"ampere",
"kelvin",
"mole",
"candela",
"radian",
"steradian",
"hertz",
"newton",
"pascal",
"joule",
"watt",
"coulomb",
"volt",
"farad",
"ohm",
"siemens",
"weber",
"tesla",
"henry",
"degree Celsius",
"lumen",
"lux",
"becquerel",
"gray",
"sievert",
"katal",
]
valid_unit_symbols = [
"m",
"kg",
"s",
"A",
"K",
"mol",
"cd",
"rad",
"sr",
"Hz",
"N",
"Pa",
"J",
"W",
"C",
"V",
"F",
"Ω",
"S",
"Wb",
"T",
"H",
"°C",
"lm",
"lx",
"Bq",
"Gy",
"Sv",
"kat",
]
# Valid units are all possible combinations of either prefix name or prefix
# symbol together with either unit name or unit symbol. E.g., nV for
# nanovolt
valid_units = []
valid_units += [
"".join([prefix, unit])
for prefix in valid_prefix_names
for unit in valid_unit_names
]
valid_units += [
"".join([prefix, unit])
for prefix in valid_prefix_names
for unit in valid_unit_symbols
]
valid_units += [
"".join([prefix, unit])
for prefix in valid_prefix_symbols
for unit in valid_unit_names
]
valid_units += [
"".join([prefix, unit])
for prefix in valid_prefix_symbols
for unit in valid_unit_symbols
]
# units are also valid without a prefix
valid_units += valid_unit_names
valid_units += valid_unit_symbols
# we also accept "n/a" as a unit, which is the default missing value in
# BIDS
valid_units += ["n/a"]
return tuple(valid_units)
@verbose
def _unique_channel_names(ch_names, max_length=None, verbose=None):
"""Ensure unique channel names."""
suffixes = tuple(string.ascii_lowercase)
if max_length is not None:
ch_names[:] = [name[:max_length] for name in ch_names]
unique_ids = np.unique(ch_names, return_index=True)[1]
if len(unique_ids) != len(ch_names):
dups = {ch_names[x] for x in np.setdiff1d(range(len(ch_names)), unique_ids)}
warn(
"Channel names are not unique, found duplicates for: "
"%s. Applying running numbers for duplicates." % dups
)
for ch_stem in dups:
overlaps = np.where(np.array(ch_names) == ch_stem)[0]
# We need an extra character since we append '-'.
# np.ceil(...) is the maximum number of appended digits.
if max_length is not None:
n_keep = max_length - 1 - int(np.ceil(np.log10(len(overlaps))))
else:
n_keep = np.inf
n_keep = min(len(ch_stem), n_keep)
ch_stem = ch_stem[:n_keep]
for idx, ch_idx in enumerate(overlaps):
# try idx first, then loop through lower case chars
for suffix in (idx,) + suffixes:
ch_name = ch_stem + "-%s" % suffix
if ch_name not in ch_names:
break
if ch_name not in ch_names:
ch_names[ch_idx] = ch_name
else:
raise ValueError(
"Adding a single alphanumeric for a "
"duplicate resulted in another "
"duplicate name %s" % ch_name
)
return ch_names
class MontageMixin:
"""Mixin for Montage getting and setting."""
@fill_doc
def get_montage(self):
"""Get a DigMontage from instance.
Returns
-------
%(montage)s
"""
from ..channels.montage import make_dig_montage
from ..transforms import _frame_to_str
info = self if isinstance(self, Info) else self.info
if info["dig"] is None:
return None
# obtain coord_frame, and landmark coords
# (nasion, lpa, rpa, hsp, hpi) from DigPoints
montage_bunch = _get_data_as_dict_from_dig(info["dig"])
coord_frame = _frame_to_str.get(montage_bunch.coord_frame)
# get the channel names and chs data structure
ch_names, chs = info["ch_names"], info["chs"]
picks = pick_types(
info,
meg=False,
eeg=True,
seeg=True,
ecog=True,
dbs=True,
fnirs=True,
exclude=[],
)
# channel positions from dig do not match ch_names one to one,
# so use loc[:3] instead
ch_pos = {ch_names[ii]: chs[ii]["loc"][:3] for ii in picks}
# fNIRS uses multiple channels for the same sensors, we use
# a private function to format these for dig montage.
fnirs_picks = pick_types(info, fnirs=True, exclude=[])
if len(ch_pos) == len(fnirs_picks):
ch_pos = _get_fnirs_ch_pos(info)
elif len(fnirs_picks) > 0:
raise ValueError(
"MNE does not support getting the montage "
"for a mix of fNIRS and other data types. "
"Please raise a GitHub issue if you "
"require this feature."
)
# create montage
montage = make_dig_montage(
ch_pos=ch_pos,
coord_frame=coord_frame,
nasion=montage_bunch.nasion,
lpa=montage_bunch.lpa,
rpa=montage_bunch.rpa,
hsp=montage_bunch.hsp,
hpi=montage_bunch.hpi,
)
return montage
@verbose
def set_montage(
self,
montage,
match_case=True,
match_alias=False,
on_missing="raise",
verbose=None,
):
"""Set %(montage_types)s channel positions and digitization points.
Parameters
----------
%(montage)s
%(match_case)s
%(match_alias)s
%(on_missing_montage)s
%(verbose)s
Returns
-------
inst : instance of Raw | Epochs | Evoked
The instance, modified in-place.
See Also
--------
mne.channels.make_standard_montage
mne.channels.make_dig_montage
mne.channels.read_custom_montage
Notes
-----
.. warning::
Only %(montage_types)s channels can have their positions set using
a montage. Other channel types (e.g., MEG channels) should have
their positions defined properly using their data reading
functions.
.. warning::
Applying a montage will only set locations of channels that exist
at the time it is applied. This means when
:ref:`re-referencing <tut-set-eeg-ref>`
make sure to apply the montage only after calling
:func:`mne.add_reference_channels`
"""
# How to set up a montage to old named fif file (walk through example)
# https://gist.github.com/massich/f6a9f4799f1fbeb8f5e8f8bc7b07d3df
from ..channels.montage import _set_montage
info = self if isinstance(self, Info) else self.info
_set_montage(info, montage, match_case, match_alias, on_missing)
return self
channel_type_constants = get_channel_type_constants(include_defaults=True)
_human2fiff = {
k: v.get("kind", FIFF.FIFFV_COIL_NONE) for k, v in channel_type_constants.items()
}
_human2unit = {
k: v.get("unit", FIFF.FIFF_UNIT_NONE) for k, v in channel_type_constants.items()
}
_unit2human = {
FIFF.FIFF_UNIT_V: "V",
FIFF.FIFF_UNIT_T: "T",
FIFF.FIFF_UNIT_T_M: "T/m",
FIFF.FIFF_UNIT_MOL: "M",
FIFF.FIFF_UNIT_NONE: "NA",
FIFF.FIFF_UNIT_CEL: "C",
FIFF.FIFF_UNIT_S: "S",
FIFF.FIFF_UNIT_PX: "px",
}
def _check_set(ch, projs, ch_type):
"""Ensure type change is compatible with projectors."""
new_kind = _human2fiff[ch_type]
if ch["kind"] != new_kind:
for proj in projs:
if ch["ch_name"] in proj["data"]["col_names"]:
raise RuntimeError(
"Cannot change channel type for channel %s "
'in projector "%s"' % (ch["ch_name"], proj["desc"])
)
ch["kind"] = new_kind
class SetChannelsMixin(MontageMixin):
"""Mixin class for Raw, Evoked, Epochs."""
def _get_channel_positions(self, picks=None):
"""Get channel locations from info.
Parameters
----------
picks : str | list | slice | None
None gets good data indices.
Notes
-----
.. versionadded:: 0.9.0
"""
info = self if isinstance(self, Info) else self.info
picks = _picks_to_idx(info, picks)
chs = info["chs"]
pos = np.array([chs[k]["loc"][:3] for k in picks])
n_zero = np.sum(np.sum(np.abs(pos), axis=1) == 0)
if n_zero > 1: # XXX some systems have origin (0, 0, 0)
raise ValueError(
"Could not extract channel positions for " "{} channels".format(n_zero)
)
return pos
def _set_channel_positions(self, pos, names):
"""Update channel locations in info.
Parameters
----------
pos : array-like | np.ndarray, shape (n_points, 3)
The channel positions to be set.
names : list of str
The names of the channels to be set.
Notes
-----
.. versionadded:: 0.9.0
"""
info = self if isinstance(self, Info) else self.info
if len(pos) != len(names):
raise ValueError(
"Number of channel positions not equal to " "the number of names given."
)
pos = np.asarray(pos, dtype=np.float64)
if pos.shape[-1] != 3 or pos.ndim != 2:
msg = "Channel positions must have the shape (n_points, 3) " "not %s." % (
pos.shape,
)
raise ValueError(msg)
for name, p in zip(names, pos):
if name in self.ch_names:
idx = self.ch_names.index(name)
info["chs"][idx]["loc"][:3] = p
else:
msg = "%s was not found in the info. Cannot be updated." % name
raise ValueError(msg)
@verbose
def set_channel_types(self, mapping, *, on_unit_change="warn", verbose=None):
"""Specify the sensor types of channels.
Parameters
----------
mapping : dict
A dictionary mapping channel names to sensor types, e.g.,
``{'EEG061': 'eog'}``.
on_unit_change : ``'raise'`` | ``'warn'`` | ``'ignore'``
What to do if the measurement unit of a channel is changed
automatically to match the new sensor type.
.. versionadded:: 1.4
%(verbose)s
Returns
-------
inst : instance of Raw | Epochs | Evoked
The instance (modified in place).
.. versionchanged:: 0.20
Return the instance.
Notes
-----
The following sensor types are accepted:
ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, dbs, stim, syst,
ecog, hbo, hbr, fnirs_cw_amplitude, fnirs_fd_ac_amplitude,
fnirs_fd_phase, fnirs_od, eyetrack_pos, eyetrack_pupil,
temperature, gsr
.. versionadded:: 0.9.0
"""
info = self if isinstance(self, Info) else self.info
ch_names = info["ch_names"]
# first check and assemble clean mappings of index and name
unit_changes = dict()
for ch_name, ch_type in mapping.items():
if ch_name not in ch_names:
raise ValueError(
"This channel name (%s) doesn't exist in " "info." % ch_name
)
c_ind = ch_names.index(ch_name)
if ch_type not in _human2fiff:
raise ValueError(
"This function cannot change to this "
"channel type: %s. Accepted channel types "
"are %s." % (ch_type, ", ".join(sorted(_human2unit.keys())))
)
# Set sensor type
_check_set(info["chs"][c_ind], info["projs"], ch_type)
unit_old = info["chs"][c_ind]["unit"]
unit_new = _human2unit[ch_type]
if unit_old not in _unit2human:
raise ValueError(
"Channel '%s' has unknown unit (%s). Please "
"fix the measurement info of your data." % (ch_name, unit_old)
)
if unit_old != _human2unit[ch_type]:
this_change = (_unit2human[unit_old], _unit2human[unit_new])
if this_change not in unit_changes:
unit_changes[this_change] = list()
unit_changes[this_change].append(ch_name)
# reset unit multiplication factor since the unit has now changed
info["chs"][c_ind]["unit_mul"] = _ch_unit_mul_named[0]
info["chs"][c_ind]["unit"] = _human2unit[ch_type]
if ch_type in ["eeg", "seeg", "ecog", "dbs"]:
coil_type = FIFF.FIFFV_COIL_EEG
elif ch_type == "hbo":
coil_type = FIFF.FIFFV_COIL_FNIRS_HBO
elif ch_type == "hbr":
coil_type = FIFF.FIFFV_COIL_FNIRS_HBR
elif ch_type == "fnirs_cw_amplitude":
coil_type = FIFF.FIFFV_COIL_FNIRS_CW_AMPLITUDE
elif ch_type == "fnirs_fd_ac_amplitude":
coil_type = FIFF.FIFFV_COIL_FNIRS_FD_AC_AMPLITUDE
elif ch_type == "fnirs_fd_phase":
coil_type = FIFF.FIFFV_COIL_FNIRS_FD_PHASE
elif ch_type == "fnirs_od":
coil_type = FIFF.FIFFV_COIL_FNIRS_OD
elif ch_type == "eyetrack_pos":
coil_type = FIFF.FIFFV_COIL_EYETRACK_POS
elif ch_type == "eyetrack_pupil":
coil_type = FIFF.FIFFV_COIL_EYETRACK_PUPIL
else:
coil_type = FIFF.FIFFV_COIL_NONE
info["chs"][c_ind]["coil_type"] = coil_type
msg = "The unit for channel(s) {0} has changed from {1} to {2}."
for this_change, names in unit_changes.items():
_on_missing(
on_missing=on_unit_change,
msg=msg.format(", ".join(sorted(names)), *this_change),
name="on_unit_change",
)
return self
@verbose
def rename_channels(self, mapping, allow_duplicates=False, *, verbose=None):
"""Rename channels.
Parameters
----------
%(mapping_rename_channels_duplicates)s
%(verbose)s
Returns
-------
inst : instance of Raw | Epochs | Evoked
The instance (modified in place).
.. versionchanged:: 0.20
Return the instance.
Notes
-----
.. versionadded:: 0.9.0
"""
from ..channels.channels import rename_channels
from ..io import BaseRaw
info = self if isinstance(self, Info) else self.info
ch_names_orig = list(info["ch_names"])
rename_channels(info, mapping, allow_duplicates)
# Update self._orig_units for Raw
if isinstance(self, BaseRaw):
# whatever mapping was provided, now we can just use a dict
mapping = dict(zip(ch_names_orig, info["ch_names"]))
for old_name, new_name in mapping.items():
if old_name in self._orig_units:
self._orig_units[new_name] = self._orig_units.pop(old_name)
ch_names = self.annotations.ch_names
for ci, ch in enumerate(ch_names):
ch_names[ci] = tuple(mapping.get(name, name) for name in ch)
return self
@verbose
def plot_sensors(
self,
kind="topomap",
ch_type=None,
title=None,
show_names=False,
ch_groups=None,
to_sphere=True,
axes=None,
block=False,
show=True,
sphere=None,
*,
verbose=None,
):
"""Plot sensor positions.
Parameters
----------
kind : str
Whether to plot the sensors as 3d, topomap or as an interactive
sensor selection dialog. Available options 'topomap', '3d',
'select'. If 'select', a set of channels can be selected
interactively by using lasso selector or clicking while holding
control key. The selected channels are returned along with the
figure instance. Defaults to 'topomap'.
ch_type : None | str
The channel type to plot. Available options ``'mag'``, ``'grad'``,
``'eeg'``, ``'seeg'``, ``'dbs'``, ``'ecog'``, ``'all'``. If ``'all'``, all
the available mag, grad, eeg, seeg, dbs, and ecog channels are plotted. If
None (default), then channels are chosen in the order given above.
title : str | None
Title for the figure. If None (default), equals to ``'Sensor
positions (%%s)' %% ch_type``.
show_names : bool | array of str
Whether to display all channel names. If an array, only the channel
names in the array are shown. Defaults to False.
ch_groups : 'position' | array of shape (n_ch_groups, n_picks) | None
Channel groups for coloring the sensors. If None (default), default
coloring scheme is used. If 'position', the sensors are divided
into 8 regions. See ``order`` kwarg of :func:`mne.viz.plot_raw`. If
array, the channels are divided by picks given in the array.
.. versionadded:: 0.13.0
to_sphere : bool
Whether to project the 3d locations to a sphere. When False, the
sensor array appears similar as to looking downwards straight above
the subject's head. Has no effect when kind='3d'. Defaults to True.
.. versionadded:: 0.14.0
axes : instance of Axes | instance of Axes3D | None
Axes to draw the sensors to. If ``kind='3d'``, axes must be an
instance of Axes3D. If None (default), a new axes will be created.
.. versionadded:: 0.13.0
block : bool
Whether to halt program execution until the figure is closed.
Defaults to False.
.. versionadded:: 0.13.0
show : bool
Show figure if True. Defaults to True.
%(sphere_topomap_auto)s
%(verbose)s
Returns
-------
fig : instance of Figure
Figure containing the sensor topography.
selection : list
A list of selected channels. Only returned if ``kind=='select'``.
See Also
--------
mne.viz.plot_layout
Notes
-----
This function plots the sensor locations from the info structure using
matplotlib. For drawing the sensors using PyVista see
:func:`mne.viz.plot_alignment`.
.. versionadded:: 0.12.0
"""
from ..viz.utils import plot_sensors
return plot_sensors(
self if isinstance(self, Info) else self.info,
kind=kind,
ch_type=ch_type,
title=title,
show_names=show_names,
ch_groups=ch_groups,
to_sphere=to_sphere,
axes=axes,
block=block,
show=show,
sphere=sphere,
verbose=verbose,
)
@verbose
def anonymize(self, daysback=None, keep_his=False, verbose=None):
"""Anonymize measurement information in place.
Parameters
----------
%(daysback_anonymize_info)s
%(keep_his_anonymize_info)s
%(verbose)s
Returns
-------
inst : instance of Raw | Epochs | Evoked
The modified instance.
Notes
-----
%(anonymize_info_notes)s
.. versionadded:: 0.13.0
"""
info = self if isinstance(self, Info) else self.info
anonymize_info(info, daysback=daysback, keep_his=keep_his, verbose=verbose)
self.set_meas_date(info["meas_date"]) # unify annot update
return self
def set_meas_date(self, meas_date):
"""Set the measurement start date.
Parameters
----------
meas_date : datetime | float | tuple | None
The new measurement date.
If datetime object, it must be timezone-aware and in UTC.
A tuple of (seconds, microseconds) or float (alias for
``(meas_date, 0)``) can also be passed and a datetime
object will be automatically created. If None, will remove
the time reference.
Returns
-------
inst : instance of Raw | Epochs | Evoked
The modified raw instance. Operates in place.
See Also
--------
mne.io.Raw.anonymize
Notes
-----
If you want to remove all time references in the file, call
:func:`mne.io.anonymize_info(inst.info) <mne.io.anonymize_info>`
after calling ``inst.set_meas_date(None)``.
.. versionadded:: 0.20
"""
from ..annotations import _handle_meas_date
info = self if isinstance(self, Info) else self.info
meas_date = _handle_meas_date(meas_date)
with info._unlock():
info["meas_date"] = meas_date
# clear file_id and meas_id if needed
if meas_date is None:
for key in ("file_id", "meas_id"):
value = info.get(key)
if value is not None:
assert "msecs" not in value
value["secs"] = DATE_NONE[0]
value["usecs"] = DATE_NONE[1]
# The following copy is needed for a test CTF dataset
# otherwise value['machid'][:] = 0 would suffice
_tmp = value["machid"].copy()
_tmp[:] = 0
value["machid"] = _tmp
if hasattr(self, "annotations"):
self.annotations._orig_time = meas_date
return self
class ContainsMixin:
"""Mixin class for Raw, Evoked, Epochs and Info."""
def __contains__(self, ch_type):
"""Check channel type membership.
Parameters
----------
ch_type : str
Channel type to check for. Can be e.g. ``'meg'``, ``'eeg'``,
``'stim'``, etc.
Returns
-------
in : bool
Whether or not the instance contains the given channel type.
Examples
--------
Channel type membership can be tested as::
>>> 'meg' in inst # doctest: +SKIP
True
>>> 'seeg' in inst # doctest: +SKIP
False
"""
info = self if isinstance(self, Info) else self.info
if ch_type == "meg":
has_ch_type = _contains_ch_type(info, "mag") or _contains_ch_type(
info, "grad"
)
else:
has_ch_type = _contains_ch_type(info, ch_type)
return has_ch_type
@property
def compensation_grade(self):
"""The current gradient compensation grade."""
info = self if isinstance(self, Info) else self.info
return get_current_comp(info)
@fill_doc
def get_channel_types(self, picks=None, unique=False, only_data_chs=False):
"""Get a list of channel type for each channel.
Parameters
----------
%(picks_all)s
unique : bool
Whether to return only unique channel types. Default is ``False``.
only_data_chs : bool
Whether to ignore non-data channels. Default is ``False``.
Returns
-------
channel_types : list
The channel types.
"""
info = self if isinstance(self, Info) else self.info
none = "data" if only_data_chs else "all"
picks = _picks_to_idx(info, picks, none, (), allow_empty=False)
ch_types = [channel_type(info, pick) for pick in picks]
if only_data_chs:
ch_types = [
ch_type for ch_type in ch_types if ch_type in _DATA_CH_TYPES_SPLIT
]
if unique:
# set does not preserve order but dict does, so let's just use it
ch_types = list({k: k for k in ch_types}.keys())
return ch_types
def _format_trans(obj, key):
from ..transforms import Transform
try:
t = obj[key]
except KeyError:
pass
else:
if t is not None:
obj[key] = Transform(t["from"], t["to"], t["trans"])
def _check_ch_keys(ch, ci, name='info["chs"]', check_min=True):
ch_keys = set(ch)
bad = sorted(ch_keys.difference(_ALL_CH_KEYS_SET))
if bad:
raise KeyError(f"key{_pl(bad)} errantly present for {name}[{ci}]: {bad}")
if check_min:
bad = sorted(_MIN_CH_KEYS_SET.difference(ch_keys))
if bad:
raise KeyError(
f"key{_pl(bad)} missing for {name}[{ci}]: {bad}",
)
def _check_bads_info_compat(bads, info):
_validate_type(bads, list, "bads")
if not len(bads):
return # e.g. in empty_info
for bi, bad in enumerate(bads):
_validate_type(bad, str, f"bads[{bi}]")
if "ch_names" not in info: # somewhere in init, or deepcopy, or _empty_info, etc.
return
missing = [bad for bad in bads if bad not in info["ch_names"]]
if len(missing) > 0:
raise ValueError(f"bad channel(s) {missing} marked do not exist in info")
class MNEBadsList(list):
"""Subclass of bads that checks inplace operations."""
def __init__(self, *, bads, info):
_check_bads_info_compat(bads, info)
self._mne_info = info
super().__init__(bads)
def extend(self, iterable):
if not isinstance(iterable, list):
iterable = list(iterable)
# can happen during pickling
try:
info = self._mne_info
except AttributeError:
pass # can happen during pickling
else:
_check_bads_info_compat(iterable, info)
return super().extend(iterable)
def append(self, x):
return self.extend([x])
def __iadd__(self, x):
self.extend(x)
return self
# As options are added here, test_meas_info.py:test_info_bad should be updated
def _check_bads(bads, *, info):
return MNEBadsList(bads=bads, info=info)
def _check_description(description, *, info):
_validate_type(description, (None, str), "info['description']")
return description
def _check_dev_head_t(dev_head_t, *, info):