-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
inverse.py
2257 lines (1984 loc) · 71.7 KB
/
inverse.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: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
from copy import deepcopy
from math import sqrt
import numpy as np
from scipy import linalg
from scipy.stats import chi2
from .._fiff.constants import FIFF
from .._fiff.matrix import (
_read_named_matrix,
_transpose_named_matrix,
write_named_matrix,
)
from .._fiff.open import fiff_open
from .._fiff.pick import channel_type, pick_channels, pick_info, pick_types
from .._fiff.proj import (
_electrode_types,
_needs_eeg_average_ref_proj,
_read_proj,
_write_proj,
make_projector,
)
from .._fiff.tag import find_tag
from .._fiff.tree import dir_tree_find
from .._fiff.write import (
end_block,
start_and_end_file,
start_block,
write_coord_trans,
write_float,
write_float_matrix,
write_int,
write_string,
)
from ..cov import Covariance, _read_cov, _write_cov, compute_whitener, prepare_noise_cov
from ..epochs import BaseEpochs, EpochsArray
from ..evoked import Evoked, EvokedArray
from ..fixes import _safe_svd
from ..forward import (
_read_forward_meas_info,
_select_orient_forward,
compute_depth_prior,
compute_orient_prior,
convert_forward_solution,
is_fixed_orient,
)
from ..forward.forward import _triage_loose, write_forward_meas_info
from ..html_templates import _get_html_template
from ..io import BaseRaw
from ..source_estimate import _get_src_type, _make_stc
from ..source_space._source_space import (
_get_src_nn,
_get_vertno,
_read_source_spaces_from_tree,
_write_source_spaces_to_fid,
find_source_space_hemi,
label_src_vertno_sel,
)
from ..surface import _normal_orth
from ..time_frequency.tfr import _check_tfr_complex
from ..transforms import _ensure_trans, transform_surface_to
from ..utils import (
_check_compensation_grade,
_check_depth,
_check_fname,
_check_option,
_check_src_normal,
_validate_type,
_verbose_safe_false,
check_fname,
logger,
repr_html,
verbose,
warn,
)
from ._eloreta import _compute_eloreta
INVERSE_METHODS = ("MNE", "dSPM", "sLORETA", "eLORETA")
class InverseOperator(dict):
"""InverseOperator class to represent info from inverse operator."""
def copy(self):
"""Return a copy of the InverseOperator."""
return InverseOperator(deepcopy(self))
@property
def _is_surf_ori(self):
surf_ori = False
prior = self["orient_prior"]
if prior is not None:
prior = prior["data"]
if not np.allclose(prior, 1.0):
surf_ori = True
return surf_ori
def _get_chs_and_src_info_for_repr(self):
n_chs_meg = len(pick_types(self["info"], meg=True, eeg=False))
n_chs_eeg = len(pick_types(self["info"], meg=False, eeg=True))
src_space_descr = f"{self['src'].kind} with {self['nsource']} sources"
src_ori_fiff_to_name_map = {
FIFF.FIFFV_MNE_UNKNOWN_ORI: "Unknown",
FIFF.FIFFV_MNE_FIXED_ORI: "Fixed",
FIFF.FIFFV_MNE_FREE_ORI: "Free",
}
src_ori = src_ori_fiff_to_name_map[self["source_ori"]]
if src_ori == "Free" and self._is_surf_ori:
src_ori = f"Loose ({np.min(self['orient_prior']['data'])})"
return n_chs_meg, n_chs_eeg, src_space_descr, src_ori
def __repr__(self): # noqa: D105
"""Summarize inverse info instead of printing all."""
repr_info = self._get_chs_and_src_info_for_repr()
n_chs_meg, n_chs_eeg, src_space_descr, src_ori = repr_info
entr = "<InverseOperator"
entr += f" | MEG channels: {n_chs_meg}"
entr += f" | EEG channels: {n_chs_eeg}"
entr += f" | Source space: {src_space_descr}"
entr += f" | Source orientation: {src_ori}"
entr += ">"
return entr
@repr_html
def _repr_html_(self):
repr_info = self._get_chs_and_src_info_for_repr()
n_chs_meg, n_chs_eeg, src_space_descr, src_ori = repr_info
t = _get_html_template("repr", "inverse_operator.html.jinja")
html = t.render(
channels=f"{n_chs_meg} MEG, {n_chs_eeg} EEG",
source_space_descr=src_space_descr,
source_orientation=src_ori,
)
return html
@property
def ch_names(self):
"""Name of channels attached to the inverse operator."""
return self["info"].ch_names
@property
def info(self):
""":class:`~mne.Info` attached to the inverse operator."""
return self["info"]
def _pick_channels_inverse_operator(ch_names, inv):
"""Return data channel indices to be used knowing an inverse operator.
Unlike ``pick_channels``, this respects the order of ch_names.
"""
sel = list()
for name in inv["noise_cov"].ch_names:
try:
sel.append(ch_names.index(name))
except ValueError:
raise ValueError(
"The inverse operator was computed with "
f"channel {name} which is not present in "
"the data. You should compute a new inverse "
"operator restricted to the good data "
"channels."
)
return sel
@verbose
def read_inverse_operator(fname, *, verbose=None):
"""Read the inverse operator decomposition from a FIF file.
Parameters
----------
fname : path-like
The name of the FIF file, which ends with ``-inv.fif`` or
``-inv.fif.gz``.
%(verbose)s
Returns
-------
inv : instance of InverseOperator
The inverse operator.
See Also
--------
write_inverse_operator, make_inverse_operator
"""
check_fname(
fname,
"inverse operator",
("-inv.fif", "-inv.fif.gz", "_inv.fif", "_inv.fif.gz"),
)
fname = _check_fname(fname=fname, must_exist=True, overwrite="read")
#
# Open the file, create directory
#
logger.info(f"Reading inverse operator decomposition from {fname}...")
f, tree, _ = fiff_open(fname)
with f as fid:
#
# Find all inverse operators
#
invs = dir_tree_find(tree, FIFF.FIFFB_MNE_INVERSE_SOLUTION)
if invs is None or len(invs) < 1:
raise Exception(f"No inverse solutions in {fname}")
invs = invs[0]
#
# Parent MRI data
#
parent_mri = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
if len(parent_mri) == 0:
raise Exception(f"No parent MRI information in {fname}")
parent_mri = parent_mri[0] # take only first one
logger.info(" Reading inverse operator info...")
#
# Methods and source orientations
#
tag = find_tag(fid, invs, FIFF.FIFF_MNE_INCLUDED_METHODS)
if tag is None:
raise Exception("Modalities not found")
inv = dict()
inv["methods"] = int(tag.data.item())
tag = find_tag(fid, invs, FIFF.FIFF_MNE_SOURCE_ORIENTATION)
if tag is None:
raise Exception("Source orientation constraints not found")
inv["source_ori"] = int(tag.data.item())
tag = find_tag(fid, invs, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS)
if tag is None:
raise Exception("Number of sources not found")
inv["nsource"] = int(tag.data.item())
inv["nchan"] = 0
#
# Coordinate frame
#
tag = find_tag(fid, invs, FIFF.FIFF_MNE_COORD_FRAME)
if tag is None:
raise Exception("Coordinate frame tag not found")
inv["coord_frame"] = tag.data
#
# Units
#
tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SOURCE_UNIT)
unit_dict = {
FIFF.FIFF_UNIT_AM: "Am",
FIFF.FIFF_UNIT_AM_M2: "Am/m^2",
FIFF.FIFF_UNIT_AM_M3: "Am/m^3",
}
inv["units"] = unit_dict.get(
int(getattr(tag, "data", np.array([-1])).item()), None
)
#
# The actual source orientation vectors
#
tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SOURCE_ORIENTATIONS)
if tag is None:
raise Exception("Source orientation information not found")
inv["source_nn"] = tag.data
logger.info(" [done]")
#
# The SVD decomposition...
#
logger.info(" Reading inverse operator decomposition...")
tag = find_tag(fid, invs, FIFF.FIFF_MNE_INVERSE_SING)
if tag is None:
raise Exception("Singular values not found")
inv["sing"] = tag.data
inv["nchan"] = len(inv["sing"])
#
# The eigenleads and eigenfields
#
inv["eigen_leads_weighted"] = False
inv["eigen_leads"] = _read_named_matrix(
fid, invs, FIFF.FIFF_MNE_INVERSE_LEADS, transpose=True
)
if inv["eigen_leads"] is None:
inv["eigen_leads_weighted"] = True
inv["eigen_leads"] = _read_named_matrix(
fid, invs, FIFF.FIFF_MNE_INVERSE_LEADS_WEIGHTED, transpose=True
)
if inv["eigen_leads"] is None:
raise ValueError("Eigen leads not found in inverse operator.")
#
# Having the eigenleads as cols is better for the inverse calcs
#
inv["eigen_fields"] = _read_named_matrix(
fid, invs, FIFF.FIFF_MNE_INVERSE_FIELDS
)
logger.info(" [done]")
#
# Read the covariance matrices
#
inv["noise_cov"] = Covariance(
**_read_cov(fid, invs, FIFF.FIFFV_MNE_NOISE_COV, limited=True)
)
logger.info(" Noise covariance matrix read.")
inv["source_cov"] = _read_cov(fid, invs, FIFF.FIFFV_MNE_SOURCE_COV)
logger.info(" Source covariance matrix read.")
#
# Read the various priors
#
inv["orient_prior"] = _read_cov(fid, invs, FIFF.FIFFV_MNE_ORIENT_PRIOR_COV)
if inv["orient_prior"] is not None:
logger.info(" Orientation priors read.")
inv["depth_prior"] = _read_cov(fid, invs, FIFF.FIFFV_MNE_DEPTH_PRIOR_COV)
if inv["depth_prior"] is not None:
logger.info(" Depth priors read.")
inv["fmri_prior"] = _read_cov(fid, invs, FIFF.FIFFV_MNE_FMRI_PRIOR_COV)
if inv["fmri_prior"] is not None:
logger.info(" fMRI priors read.")
#
# Read the source spaces
#
inv["src"] = _read_source_spaces_from_tree(fid, tree, patch_stats=False)
for s in inv["src"]:
s["id"] = find_source_space_hemi(s)
#
# Get the MRI <-> head coordinate transformation
#
tag = find_tag(fid, parent_mri, FIFF.FIFF_COORD_TRANS)
if tag is None:
raise Exception("MRI/head coordinate transformation not found")
mri_head_t = _ensure_trans(tag.data, "mri", "head")
inv["mri_head_t"] = mri_head_t
#
# get parent MEG info
#
inv["info"] = _read_forward_meas_info(tree, fid)
#
# Transform the source spaces to the correct coordinate frame
# if necessary
#
if inv["coord_frame"] not in (FIFF.FIFFV_COORD_MRI, FIFF.FIFFV_COORD_HEAD):
raise Exception(
"Only inverse solutions computed in MRI or "
"head coordinates are acceptable"
)
#
# Number of averages is initially one
#
inv["nave"] = 1
#
# We also need the SSP operator
#
inv["projs"] = _read_proj(fid, tree)
#
# Some empty fields to be filled in later
#
inv["proj"] = [] # This is the projector to apply to the data
inv["whitener"] = [] # This whitens the data
# This the diagonal matrix implementing regularization and the inverse
inv["reginv"] = []
inv["noisenorm"] = [] # These are the noise-normalization factors
#
nuse = 0
for k in range(len(inv["src"])):
try:
inv["src"][k] = transform_surface_to(
inv["src"][k], inv["coord_frame"], mri_head_t
)
except Exception as inst:
raise Exception(f"Could not transform source space ({inst})")
nuse += inv["src"][k]["nuse"]
logger.info(
" Source spaces transformed to the inverse solution coordinate frame"
)
#
# Done!
#
return InverseOperator(inv)
@verbose
def write_inverse_operator(fname, inv, *, overwrite=False, verbose=None):
"""Write an inverse operator to a FIF file.
Parameters
----------
fname : path-like
The name of the FIF file, which ends with ``-inv.fif`` or
``-inv.fif.gz``.
inv : dict
The inverse operator.
%(overwrite)s
.. versionadded:: 1.0
%(verbose)s
See Also
--------
read_inverse_operator
"""
check_fname(
fname,
"inverse operator",
("-inv.fif", "-inv.fif.gz", "_inv.fif", "_inv.fif.gz"),
)
fname = _check_fname(fname=fname, overwrite=overwrite)
_validate_type(inv, InverseOperator, "inv")
#
# Open the file, create directory
#
logger.info(f"Write inverse operator decomposition in {fname}...")
# Create the file and save the essentials
with start_and_end_file(fname) as fid:
_write_inverse_operator(fid, inv)
def _write_inverse_operator(fid, inv):
start_block(fid, FIFF.FIFFB_MNE)
#
# Parent MEG measurement info
#
write_forward_meas_info(fid, inv["info"])
#
# Parent MRI data
#
start_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
write_string(fid, FIFF.FIFF_MNE_FILE_NAME, inv["info"]["mri_file"])
write_coord_trans(fid, inv["mri_head_t"])
end_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
#
# Write SSP operator
#
_write_proj(fid, inv["projs"])
#
# Write the source spaces
#
if "src" in inv:
_write_source_spaces_to_fid(fid, inv["src"])
start_block(fid, FIFF.FIFFB_MNE_INVERSE_SOLUTION)
logger.info(" Writing inverse operator info...")
write_int(fid, FIFF.FIFF_MNE_INCLUDED_METHODS, inv["methods"])
write_int(fid, FIFF.FIFF_MNE_COORD_FRAME, inv["coord_frame"])
udict = {
"Am": FIFF.FIFF_UNIT_AM,
"Am/m^2": FIFF.FIFF_UNIT_AM_M2,
"Am/m^3": FIFF.FIFF_UNIT_AM_M3,
}
if "units" in inv and inv["units"] is not None:
write_int(fid, FIFF.FIFF_MNE_INVERSE_SOURCE_UNIT, udict[inv["units"]])
write_int(fid, FIFF.FIFF_MNE_SOURCE_ORIENTATION, inv["source_ori"])
write_int(fid, FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS, inv["nsource"])
if "nchan" in inv:
write_int(fid, FIFF.FIFF_NCHAN, inv["nchan"])
elif "nchan" in inv["info"]:
write_int(fid, FIFF.FIFF_NCHAN, inv["info"]["nchan"])
write_float_matrix(fid, FIFF.FIFF_MNE_INVERSE_SOURCE_ORIENTATIONS, inv["source_nn"])
write_float(fid, FIFF.FIFF_MNE_INVERSE_SING, inv["sing"])
#
# write the covariance matrices
#
logger.info(" Writing noise covariance matrix.")
_write_cov(fid, inv["noise_cov"])
logger.info(" Writing source covariance matrix.")
_write_cov(fid, inv["source_cov"])
#
# write the various priors
#
logger.info(" Writing orientation priors.")
if inv["depth_prior"] is not None:
_write_cov(fid, inv["depth_prior"])
if inv["orient_prior"] is not None:
_write_cov(fid, inv["orient_prior"])
if inv["fmri_prior"] is not None:
_write_cov(fid, inv["fmri_prior"])
write_named_matrix(fid, FIFF.FIFF_MNE_INVERSE_FIELDS, inv["eigen_fields"])
#
# The eigenleads and eigenfields
#
if inv["eigen_leads_weighted"]:
kind = FIFF.FIFF_MNE_INVERSE_LEADS_WEIGHTED
else:
kind = FIFF.FIFF_MNE_INVERSE_LEADS
_transpose_named_matrix(inv["eigen_leads"])
write_named_matrix(fid, kind, inv["eigen_leads"])
_transpose_named_matrix(inv["eigen_leads"])
#
# Done!
#
logger.info(" [done]")
end_block(fid, FIFF.FIFFB_MNE_INVERSE_SOLUTION)
end_block(fid, FIFF.FIFFB_MNE)
###############################################################################
# Compute inverse solution
def combine_xyz(vec, square=False):
"""Compute the three Cartesian components of a vector or matrix together.
Parameters
----------
vec : 2d array of shape [3 n x p]
Input [ x1 y1 z1 ... x_n y_n z_n ] where x1 ... z_n
can be vectors
Returns
-------
comb : array
Output vector [sqrt(x1^2+y1^2+z1^2), ..., sqrt(x_n^2+y_n^2+z_n^2)]
"""
if vec.ndim != 2:
raise ValueError("Input must be 2D")
if (vec.shape[0] % 3) != 0:
raise ValueError("Input must have 3N rows")
if np.iscomplexobj(vec):
vec = np.abs(vec)
comb = vec[0::3] ** 2
comb += vec[1::3] ** 2
comb += vec[2::3] ** 2
if not square:
comb = np.sqrt(comb)
return comb
def _check_ch_names(inv, info):
"""Check that channels in inverse operator are measurements."""
inv_ch_names = inv["eigen_fields"]["col_names"]
if inv["noise_cov"].ch_names != inv_ch_names:
raise ValueError(
"Channels in inverse operator eigen fields do not "
"match noise covariance channels."
)
data_ch_names = info["ch_names"]
missing_ch_names = sorted(set(inv_ch_names) - set(data_ch_names))
n_missing = len(missing_ch_names)
if n_missing > 0:
raise ValueError(
"%d channels in inverse operator " % n_missing
+ f"are not present in the data ({missing_ch_names})"
)
_check_compensation_grade(inv["info"], info, "inverse")
def _check_or_prepare(inv, nave, lambda2, method, method_params, prepared, copy=True):
"""Check if inverse was prepared, or prepare it."""
if not prepared:
inv = prepare_inverse_operator(
inv, nave, lambda2, method, method_params, copy=copy
)
elif "colorer" not in inv:
raise ValueError(
"inverse operator has not been prepared, but got "
"argument prepared=True. Either pass prepared=False "
"or use prepare_inverse_operator."
)
return inv
@verbose
def prepare_inverse_operator(
orig, nave, lambda2, method="dSPM", method_params=None, copy=True, verbose=None
):
"""Prepare an inverse operator for actually computing the inverse.
Parameters
----------
orig : dict
The inverse operator structure read from a file.
nave : int
Number of averages (scales the noise covariance).
lambda2 : float
The regularization factor. Recommended to be 1 / SNR**2.
method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
Use minimum norm, dSPM (default), sLORETA, or eLORETA.
method_params : dict | None
Additional options for eLORETA. See Notes of :func:`apply_inverse`.
.. versionadded:: 0.16
copy : bool | str
If True (default), copy the inverse. False will not copy.
Can be "non-src" to avoid copying the source space, which typically
is not modified and can be large in memory.
.. versionadded:: 0.21
%(verbose)s
Returns
-------
inv : instance of InverseOperator
Prepared inverse operator.
"""
if nave <= 0:
raise ValueError("The number of averages should be positive")
_validate_type(copy, (bool, str), "copy")
if isinstance(copy, str):
_check_option("copy", copy, ("non-src",), extra="when a string")
logger.info("Preparing the inverse operator for use...")
inv = orig
if copy:
src = orig["src"]
if copy == "non-src":
orig["src"] = None
try:
inv = orig.copy()
finally:
orig["src"] = src
if copy == "non-src":
inv["src"] = src
del orig
#
# Scale some of the stuff
#
scale = float(inv["nave"]) / nave
inv["noise_cov"]["data"] = scale * inv["noise_cov"]["data"]
# deal with diagonal case
if inv["noise_cov"]["data"].ndim == 1:
logger.info(" Diagonal noise covariance found")
inv["noise_cov"]["eig"] = inv["noise_cov"]["data"]
inv["noise_cov"]["eigvec"] = np.eye(len(inv["noise_cov"]["data"]))
inv["noise_cov"]["eig"] = scale * inv["noise_cov"]["eig"]
inv["source_cov"]["data"] = scale * inv["source_cov"]["data"]
#
if inv["eigen_leads_weighted"]:
inv["eigen_leads"]["data"] = sqrt(scale) * inv["eigen_leads"]["data"]
logger.info(
" Scaled noise and source covariance from nave = %d to"
" nave = %d" % (inv["nave"], nave)
)
inv["nave"] = nave
#
# Create the diagonal matrix for computing the regularized inverse
#
inv["reginv"] = _compute_reginv(inv, lambda2)
logger.info(" Created the regularized inverter")
#
# Create the projection operator
#
inv["proj"], ncomp, _ = make_projector(inv["projs"], inv["noise_cov"]["names"])
if ncomp > 0:
logger.info(" Created an SSP operator (subspace dimension = %d)" % ncomp)
else:
logger.info(" The projection vectors do not apply to these channels.")
#
# Create the whitener
#
inv["whitener"], _, inv["colorer"] = compute_whitener(
inv["noise_cov"], pca="white", return_colorer=True
)
#
# Finally, compute the noise-normalization factors
#
inv["noisenorm"] = []
if method == "eLORETA":
_compute_eloreta(inv, lambda2, method_params)
elif method != "MNE":
logger.info(f" Computing noise-normalization factors ({method})...")
# Here we have::
#
# inv['reginv'] = sing / (sing ** 2 + lambda2)
#
# where ``sing`` are the singular values of the whitened gain matrix.
if method == "dSPM":
# dSPM normalization
noise_weight = inv["reginv"]
elif method == "sLORETA":
# sLORETA normalization is given by the square root of the
# diagonal entries of the resolution matrix R, which is
# the product of the inverse and forward operators as:
#
# w = diag(diag(R)) ** 0.5
#
noise_weight = inv["reginv"] * np.sqrt(1.0 + inv["sing"] ** 2 / lambda2)
noise_norm = np.zeros(inv["eigen_leads"]["nrow"])
(nrm2,) = linalg.get_blas_funcs(("nrm2",), (noise_norm,))
if inv["eigen_leads_weighted"]:
for k in range(inv["eigen_leads"]["nrow"]):
one = inv["eigen_leads"]["data"][k, :] * noise_weight
noise_norm[k] = nrm2(one)
else:
for k in range(inv["eigen_leads"]["nrow"]):
one = (
sqrt(inv["source_cov"]["data"][k])
* inv["eigen_leads"]["data"][k, :]
* noise_weight
)
noise_norm[k] = nrm2(one)
#
# Compute the final result
#
if inv["source_ori"] == FIFF.FIFFV_MNE_FREE_ORI:
#
# The three-component case is a little bit more involved
# The variances at three consecutive entries must be squared and
# added together
#
# Even in this case return only one noise-normalization factor
# per source location
#
noise_norm = combine_xyz(noise_norm[:, None]).ravel()
inv["noisenorm"] = 1.0 / np.abs(noise_norm)
logger.info("[done]")
else:
inv["noisenorm"] = []
return InverseOperator(inv)
@verbose
def _assemble_kernel(inv, label, method, pick_ori, use_cps=True, verbose=None):
"""Assemble the kernel.
Simple matrix multiplication followed by combination of the current
components. This does all the data transformations to compute the weights
for the eigenleads.
Parameters
----------
inv : instance of InverseOperator
The inverse operator to use. This object contains the matrices that
will be multiplied to assemble the kernel.
label : Label | None
Restricts the source estimates to a given label. If None,
source estimates will be computed for the entire source space.
method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
Use minimum norm, dSPM, sLORETA, or eLORETA.
pick_ori : None | "normal" | "vector"
Which orientation to pick (only matters in the case of 'normal').
%(use_cps_restricted)s
Returns
-------
K : array, shape (n_vertices, n_channels) | (3 * n_vertices, n_channels)
The kernel matrix. Multiply this with the data to obtain the source
estimate.
noise_norm : array, shape (n_vertices, n_samples) | (3 * n_vertices, n_samples)
Normalization to apply to the source estimate in order to obtain dSPM
or sLORETA solutions.
vertices : list of length 2
Vertex numbers for lh and rh hemispheres that correspond to the
vertices in the source estimate. When the label parameter has been
set, these correspond to the vertices in the label. Otherwise, all
vertex numbers are returned.
source_nn : array, shape (3 * n_vertices, 3)
The direction in cartesian coordicates of the direction of the source
dipoles.
""" # noqa: E501
eigen_leads = inv["eigen_leads"]["data"]
source_cov = inv["source_cov"]["data"]
if method in ("dSPM", "sLORETA"):
noise_norm = inv["noisenorm"][:, np.newaxis]
else:
noise_norm = None
src = inv["src"]
vertno = _get_vertno(src)
source_nn = inv["source_nn"]
if label is not None:
vertno, src_sel = label_src_vertno_sel(label, src)
if method not in ["MNE", "eLORETA"]:
noise_norm = noise_norm[src_sel]
if inv["source_ori"] == FIFF.FIFFV_MNE_FREE_ORI:
src_sel = 3 * src_sel
src_sel = np.c_[src_sel, src_sel + 1, src_sel + 2]
src_sel = src_sel.ravel()
eigen_leads = eigen_leads[src_sel]
source_cov = source_cov[src_sel]
source_nn = source_nn[src_sel]
# vector or normal, might need to rotate
if (
pick_ori == "normal"
and all(s["type"] == "surf" for s in src)
and np.allclose(
inv["source_nn"].reshape(inv["nsource"], 3, 3), np.eye(3), atol=1e-6
)
):
offset = 0
eigen_leads = np.reshape(eigen_leads, (-1, 3, eigen_leads.shape[1])).copy()
source_nn = np.reshape(source_nn, (-1, 3, 3)).copy()
for s, v in zip(src, vertno):
sl = slice(offset, offset + len(v))
source_nn[sl] = _normal_orth(_get_src_nn(s, use_cps, v))
eigen_leads[sl] = np.matmul(source_nn[sl], eigen_leads[sl])
# No need to rotate source_cov because it should be uniform
# (loose=1., and depth weighting is uniform across columns)
offset = sl.stop
eigen_leads.shape = (-1, eigen_leads.shape[2])
source_nn.shape = (-1, 3)
if pick_ori == "normal":
if not inv["source_ori"] == FIFF.FIFFV_MNE_FREE_ORI:
raise ValueError(
"Picking normal orientation can only be done "
"with a free orientation inverse operator."
)
is_loose = 0 < inv["orient_prior"]["data"][0] <= 1
if not is_loose:
raise ValueError(
"Picking normal orientation can only be done "
"when working with loose orientations."
)
trans = np.dot(inv["eigen_fields"]["data"], np.dot(inv["whitener"], inv["proj"]))
trans *= inv["reginv"][:, None]
#
# Transformation into current distributions by weighting the eigenleads
# with the weights computed above
#
K = np.dot(eigen_leads, trans)
if inv["eigen_leads_weighted"]:
#
# R^0.5 has been already factored in
#
logger.info(" Eigenleads already weighted ... ")
else:
#
# R^0.5 has to be factored in
#
logger.info(" Eigenleads need to be weighted ...")
K *= np.sqrt(source_cov)[:, np.newaxis]
if pick_ori == "normal":
K = K[2::3]
return K, noise_norm, vertno, source_nn
def _check_ori(pick_ori, source_ori, src):
"""Check pick_ori."""
_check_option("pick_ori", pick_ori, [None, "normal", "vector"])
_check_src_normal(pick_ori, src)
def _check_reference(inst, ch_names=None):
"""Check for EEG ref."""
info = inst.info
if ch_names is not None:
picks = [
ci for ci, ch_name in enumerate(info["ch_names"]) if ch_name in ch_names
]
info = pick_info(info, sel=picks)
if _needs_eeg_average_ref_proj(info):
raise ValueError(
"EEG average reference (using a projector) is mandatory for "
"modeling, use the method set_eeg_reference(projection=True)"
)
if _electrode_types(info) and info.get("custom_ref_applied", False):
raise ValueError("Custom EEG reference is not allowed for inverse modeling.")
def _subject_from_inverse(inverse_operator):
"""Get subject id from inverse operator."""
return inverse_operator["src"]._subject
@verbose
def apply_inverse(
evoked,
inverse_operator,
lambda2=1.0 / 9.0,
method="dSPM",
pick_ori=None,
prepared=False,
label=None,
method_params=None,
return_residual=False,
use_cps=True,
verbose=None,
):
"""Apply inverse operator to evoked data.
Parameters
----------
evoked : Evoked object
Evoked data.
inverse_operator : instance of InverseOperator
Inverse operator.
lambda2 : float
The regularization parameter.
method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
Use minimum norm :footcite:`HamalainenIlmoniemi1994`,
dSPM (default) :footcite:`DaleEtAl2000`,
sLORETA :footcite:`Pascual-Marqui2002`, or
eLORETA :footcite:`Pascual-Marqui2011`.
%(pick_ori)s
prepared : bool
If True, do not call :func:`prepare_inverse_operator`.
label : Label | None
Restricts the source estimates to a given label. If None,
source estimates will be computed for the entire source space.
method_params : dict | None
Additional options for eLORETA. See Notes for details.
.. versionadded:: 0.16
return_residual : bool
If True (default False), return the residual evoked data.
Cannot be used with ``method=='eLORETA'``.
.. versionadded:: 0.17
%(use_cps_restricted)s
.. versionadded:: 0.20
%(verbose)s
Returns
-------
stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate
The source estimates.
residual : instance of Evoked
The residual evoked data, only returned if return_residual is True.
See Also
--------
apply_inverse_raw : Apply inverse operator to raw object.
apply_inverse_epochs : Apply inverse operator to epochs object.
apply_inverse_tfr_epochs : Apply inverse operator to epochs tfr object.
apply_inverse_cov : Apply inverse operator to covariance object.
Notes
-----
Currently only the ``method='eLORETA'`` has additional options.
It performs an iterative fit with a convergence criterion, so you can
pass a ``method_params`` :class:`dict` with string keys mapping to values
for:
'eps' : float
The convergence epsilon (default 1e-6).
'max_iter' : int
The maximum number of iterations (default 20).
If less regularization is applied, more iterations may be
necessary.
'force_equal' : bool
Force all eLORETA weights for each direction for a given
location equal. The default is None, which means ``True`` for
loose-orientation inverses and ``False`` for free- and
fixed-orientation inverses. See below.
The eLORETA paper :footcite:`Pascual-Marqui2011` defines how to compute
inverses for fixed- and