File: inverse.py

package info (click to toggle)
python-mne 0.17%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 95,104 kB
  • sloc: python: 110,639; makefile: 222; sh: 15
file content (1795 lines) | stat: -rw-r--r-- 69,633 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
# -*- coding: utf-8 -*-
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
#          Matti Hamalainen <msh@nmr.mgh.harvard.edu>
#          Teon Brooks <teon.brooks@gmail.com>
#
# License: BSD (3-clause)

from copy import deepcopy
from math import sqrt
import numpy as np
from scipy import linalg

from ._eloreta import _compute_eloreta
from ..fixes import _safe_svd
from ..io.compensator import get_current_comp
from ..io.constants import FIFF
from ..io.open import fiff_open
from ..io.tag import find_tag
from ..io.matrix import (_read_named_matrix, _transpose_named_matrix,
                         write_named_matrix)
from ..io.proj import (_read_proj, make_projector, _write_proj,
                       _needs_eeg_average_ref_proj)
from ..io.tree import dir_tree_find
from ..io.write import (write_int, write_float_matrix, start_file,
                        start_block, end_block, end_file, write_float,
                        write_coord_trans, write_string)

from ..io.pick import channel_type, pick_info, pick_types
from ..cov import _get_whitener, _read_cov, _write_cov, Covariance
from ..forward import (compute_depth_prior, _read_forward_meas_info,
                       write_forward_meas_info, is_fixed_orient,
                       compute_orient_prior, convert_forward_solution)
from ..source_space import (_read_source_spaces_from_tree,
                            find_source_space_hemi, _get_vertno,
                            _write_source_spaces_to_fid, label_src_vertno_sel)
from ..transforms import _ensure_trans, transform_surface_to
from ..source_estimate import _make_stc, _get_src_type
from ..utils import check_fname, logger, verbose, warn


class InverseOperator(dict):
    """InverseOperator class to represent info from inverse operator."""

    def copy(self):
        """Return a copy of the InverseOperator."""
        return InverseOperator(deepcopy(self))

    def __repr__(self):  # noqa: D105
        """Summarize inverse info instead of printing all."""
        entr = '<InverseOperator'

        nchan = len(pick_types(self['info'], meg=True, eeg=False))
        entr += ' | ' + 'MEG channels: %d' % nchan
        nchan = len(pick_types(self['info'], meg=False, eeg=True))
        entr += ' | ' + 'EEG channels: %d' % nchan

        entr += (' | Source space: %s with %d sources'
                 % (self['src'].kind, self['nsource']))
        source_ori = {FIFF.FIFFV_MNE_UNKNOWN_ORI: 'Unknown',
                      FIFF.FIFFV_MNE_FIXED_ORI: 'Fixed',
                      FIFF.FIFFV_MNE_FREE_ORI: 'Free'}
        entr += ' | Source orientation: %s' % source_ori[self['source_ori']]
        entr += '>'

        return entr


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 '
                             'channel %s which is not present in '
                             'the data. You should compute a new inverse '
                             'operator restricted to the good data '
                             'channels.' % name)
    return sel


@verbose
def read_inverse_operator(fname, verbose=None):
    """Read the inverse operator decomposition from a FIF file.

    Parameters
    ----------
    fname : string
        The name of the FIF file, which ends with -inv.fif or -inv.fif.gz.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    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'))

    #
    #   Open the file, create directory
    #
    logger.info('Reading inverse operator decomposition from %s...'
                % fname)
    f, tree, _ = fiff_open(fname, preload=True)
    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('No inverse solutions in %s' % 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('No parent MRI information in %s' % 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)

        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)

        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)
        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', -1)), 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('Could not transform source space (%s)' % 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, verbose=None):
    """Write an inverse operator to a FIF file.

    Parameters
    ----------
    fname : string
        The name of the FIF file, which ends with -inv.fif or -inv.fif.gz.
    inv : dict
        The inverse operator.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    See Also
    --------
    read_inverse_operator
    """
    check_fname(fname, 'inverse operator', ('-inv.fif', '-inv.fif.gz',
                                            '_inv.fif', '_inv.fif.gz'))

    #
    #   Open the file, create directory
    #
    logger.info('Write inverse operator decomposition in %s...' % fname)

    # Create the file and save the essentials
    fid = start_file(fname)
    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)
    end_file(fid)

    fid.close()

###############################################################################
# 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')

    n, p = vec.shape
    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 +
                         'are not present in the data (%s)' % missing_ch_names)
    _check_comps(inv['info'], info, 'inverse')


def _check_or_prepare(inv, nave, lambda2, method, method_params, prepared):
    """Check if inverse was prepared, or prepare it."""
    if not prepared:
        inv = prepare_inverse_operator(
            inv, nave, lambda2, method, method_params)
    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, 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
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    Returns
    -------
    inv : instance of InverseOperator
        Prepared inverse operator.
    """
    if nave <= 0:
        raise ValueError('The number of averages should be positive')

    logger.info('Preparing the inverse operator for use...')
    inv = orig.copy()
    #
    #   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
    #
    sing = np.array(inv['sing'], dtype=np.float64)
    with np.errstate(invalid='ignore'):  # if lambda2==0
        inv['reginv'] = np.where(sing > 0, sing / (sing ** 2 + lambda2), 0)
    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'], _, _ = _get_whitener(
        inv['noise_cov'], pca=False, prepared=True)

    #
    #   Finally, compute the noise-normalization factors
    #
    inv['noisenorm'] = []
    if method != 'MNE':
        logger.info('    Computing noise-normalization factors (%s)...'
                    % method)
    if method == 'eLORETA':
        _compute_eloreta(inv, lambda2, method_params)
    elif method != 'MNE':
        # 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. + 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, 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').

    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 carthesian coordicates of the direction of the source
        dipoles.
    """  # noqa: E501
    eigen_leads = inv['eigen_leads']['data']
    source_cov = inv['source_cov']['data'][:, None]
    if method in ('dSPM', 'sLORETA'):
        noise_norm = inv['noisenorm'][:, None]
    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, inv['src'])

        if method != "MNE":
            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]

    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.')

        # keep only the normal components
        eigen_leads = eigen_leads[2::3]
        source_cov = source_cov[2::3]

    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
    #
    if inv['eigen_leads_weighted']:
        #
        #     R^0.5 has been already factored in
        #
        logger.info('    Eigenleads already weighted ... ')
        K = np.dot(eigen_leads, trans)
    else:
        #
        #     R^0.5 has to be factored in
        #
        logger.info('    Eigenleads need to be weighted ...')
        K = np.sqrt(source_cov) * np.dot(eigen_leads, trans)

    return K, noise_norm, vertno, source_nn


def _check_comps(info, data_info, kind):
    """Check for compatibility between compensation grades."""
    comp = get_current_comp(info)
    data_comp = get_current_comp(data_info)
    if comp != data_comp and \
            any(c not in (None, 0) for c in (comp, data_comp)):
        raise RuntimeError('compensation grade mismatch between %s (%s) '
                           'and data (%s), consider recomputing the %s.'
                           % (kind, comp, data_comp, kind))


def _check_method(method):
    """Check the method."""
    if method not in ['MNE', 'dSPM', 'sLORETA', 'eLORETA']:
        raise ValueError('method parameter should be "MNE", "dSPM", '
                         '"sLORETA" or "eLORETA", got %s.' % (method,))


def _check_ori(pick_ori, source_ori):
    """Check pick_ori."""
    if pick_ori not in [None, 'normal', 'vector']:
        raise RuntimeError('pick_ori must be None, "normal" or "vector", not '
                           '%s' % pick_ori)
    if pick_ori == 'vector' and source_ori != FIFF.FIFFV_MNE_FREE_ORI:
        raise RuntimeError('pick_ori="vector" cannot be combined with an '
                           'inverse operator with fixed orientations.')


def _check_loose_forward(loose, forward):
    """Check the compatibility between loose and forward."""
    src_kind = forward['src'].kind
    if src_kind != 'surface':
        if loose == 'auto':
            loose = 1.
        if loose != 1:
            raise ValueError('loose parameter has to be 1 or "auto" for '
                             'non-surface source space (Got loose=%s for %s '
                             'source space).' % (loose, src_kind))
    else:  # surface
        if loose == 'auto':
            loose = 0.2
        # put the forward solution in fixed orientation if it's not already
        if loose == 0. and not is_fixed_orient(forward):
            logger.info('Converting forward solution to fixed orietnation')
            forward = convert_forward_solution(forward, force_fixed=True,
                                               use_cps=True)
        elif loose < 1. and not forward['surf_ori']:
            logger.info('Converting forward solution to surface orientation')
            forward = convert_forward_solution(forward, surf_ori=True,
                                               use_cps=True)

    assert loose is not None
    loose = float(loose)
    if loose < 0 or loose > 1:
        raise ValueError('loose must be between 0 and 1, got %s' % loose)

    if loose == 0. and not is_fixed_orient(forward):
        forward = convert_forward_solution(forward, force_fixed=True,
                                           use_cps=True)

    return loose, forward


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 is mandatory for inverse '
                         'modeling, use set_eeg_reference method.')
    if info['custom_ref_applied']:
        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'][0].get('subject_his_id', None)


@verbose
def apply_inverse(evoked, inverse_operator, lambda2=1. / 9., method="dSPM",
                  pick_ori=None, prepared=False, label=None,
                  method_params=None, return_residual=False, 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 [1]_, dSPM (default) [2]_, sLORETA [3]_, or
        eLORETA [4]_.
    pick_ori : None | "normal" | "vector"
        If "normal", rather than pooling the orientations by taking the norm,
        only the radial component is kept. This is only implemented
        when working with loose orientations.
        If "vector", no pooling of the orientations is done and the vector
        result will be returned in the form of a
        :class:`mne.VectorSourceEstimate` object. This is only implemented when
        working with loose orientations.
    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
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    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

    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 [4]_ defines how to compute inverses for fixed- and
    free-orientation inverses. In the free orientation case, the X/Y/Z
    orientation triplet for each location is effectively multiplied by a
    3x3 weight matrix. This is the behavior obtained with
    ``force_equal=False`` parameter.

    However, other noise normalization methods (dSPM, sLORETA) multiply all
    orientations for a given location by a single value.
    Using ``force_equal=True`` mimics this behavior by modifying the iterative
    algorithm to choose uniform weights (equivalent to a 3x3 diagonal matrix
    with equal entries).

    It is necessary to use ``force_equal=True``
    with loose orientation inverses (e.g., ``loose=0.2``), otherwise the
    solution resembles a free-orientation inverse (``loose=1.0``).
    It is thus recommended to use ``force_equal=True`` for loose orientation
    and ``force_equal=False`` for free orientation inverses. This is the
    behavior used when the parameter ``force_equal=None`` (default behavior).

    References
    ----------
    .. [1] Hamalainen M S and Ilmoniemi R. Interpreting magnetic fields of
           the brain: minimum norm estimates. Medical & Biological Engineering
           & Computing, 32(1):35-42, 1994.
    .. [2] Dale A, Liu A, Fischl B, Buckner R. (2000) Dynamic statistical
           parametric mapping: combining fMRI and MEG for high-resolution
           imaging of cortical activity. Neuron, 26:55-67.
    .. [3] Pascual-Marqui RD (2002), Standardized low resolution brain
           electromagnetic tomography (sLORETA): technical details. Methods
           Find. Exp. Clin. Pharmacology, 24(D):5-12.
    .. [4] Pascual-Marqui RD (2007). Discrete, 3D distributed, linear imaging
           methods of electric neuronal activity. Part 1: exact, zero error
           localization. arXiv:0710.3341
    """
    _check_reference(evoked, inverse_operator['info']['ch_names'])
    _check_method(method)
    if method == 'eLORETA' and return_residual:
        raise ValueError('eLORETA does not currently support return_residual')
    _check_ori(pick_ori, inverse_operator['source_ori'])
    #
    #   Set up the inverse according to the parameters
    #
    nave = evoked.nave

    _check_ch_names(inverse_operator, evoked.info)

    inv = _check_or_prepare(inverse_operator, nave, lambda2, method,
                            method_params, prepared)

    #
    #   Pick the correct channels from the data
    #
    sel = _pick_channels_inverse_operator(evoked.ch_names, inv)
    logger.info('Applying inverse operator to "%s"...' % (evoked.comment,))
    logger.info('    Picked %d channels from the data' % len(sel))
    logger.info('    Computing inverse...')
    K, noise_norm, vertno, source_nn = _assemble_kernel(inv, label, method,
                                                        pick_ori)
    sol = np.dot(K, evoked.data[sel])  # apply imaging kernel
    logger.info('    Computing residual...')
    # x̂(t) = G ĵ(t) = C ** 1/2 U Π w(t)
    # where the diagonal matrix Π has elements πk = λk γk
    Pi = inv['sing'] * inv['reginv']
    data_w = np.dot(inv['whitener'],  # C ** -0.5
                    np.dot(inv['proj'], evoked.data[sel]))
    w_t = np.dot(inv['eigen_fields']['data'], data_w)  # U.T @ data
    data_est = np.dot(inv['colorer'],  # C ** 0.5
                      np.dot(inv['eigen_fields']['data'].T,  # U
                             Pi[:, np.newaxis] * w_t))
    data_est_w = np.dot(inv['whitener'], np.dot(inv['proj'], data_est))
    var_exp = 1 - ((data_est_w - data_w) ** 2).sum() / (data_w ** 2).sum()
    logger.info('    Explained %5.1f%% variance' % (100 * var_exp,))
    if return_residual:
        residual = evoked.copy()
        residual.data[sel] -= data_est
    is_free_ori = (inverse_operator['source_ori'] ==
                   FIFF.FIFFV_MNE_FREE_ORI and pick_ori != 'normal')

    if is_free_ori and pick_ori != 'vector':
        logger.info('    Combining the current components...')
        sol = combine_xyz(sol)

    if noise_norm is not None:
        logger.info('    %s...' % (method,))
        if is_free_ori and pick_ori == 'vector':
            noise_norm = noise_norm.repeat(3, axis=0)
        sol *= noise_norm

    tstep = 1.0 / evoked.info['sfreq']
    tmin = float(evoked.times[0])
    subject = _subject_from_inverse(inverse_operator)

    src_type = _get_src_type(inverse_operator['src'], vertno)
    stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,
                    vector=(pick_ori == 'vector'), source_nn=source_nn,
                    src_type=src_type)
    logger.info('[done]')

    return (stc, residual) if return_residual else stc


@verbose
def apply_inverse_raw(raw, inverse_operator, lambda2, method="dSPM",
                      label=None, start=None, stop=None, nave=1,
                      time_func=None, pick_ori=None, buffer_size=None,
                      prepared=False, method_params=None, verbose=None):
    """Apply inverse operator to Raw data.

    Parameters
    ----------
    raw : Raw object
        Raw data.
    inverse_operator : dict
        Inverse operator.
    lambda2 : float
        The regularization parameter.
    method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
        Use minimum norm, dSPM (default), sLORETA, or eLORETA.
    label : Label | None
        Restricts the source estimates to a given label. If None,
        source estimates will be computed for the entire source space.
    start : int
        Index of first time sample (index not time is seconds).
    stop : int
        Index of first time sample not to include (index not time is seconds).
    nave : int
        Number of averages used to regularize the solution.
        Set to 1 on raw data.
    time_func : callable
        Linear function applied to sensor space time series.
    pick_ori : None | "normal" | "vector"
        If "normal", rather than pooling the orientations by taking the norm,
        only the radial component is kept. This is only implemented
        when working with loose orientations.
        If "vector", no pooling of the orientations is done and the vector
        result will be returned in the form of a
        :class:`mne.VectorSourceEstimate` object. This does not work when using
        an inverse operator with fixed orientations.
    buffer_size : int (or None)
        If not None, the computation of the inverse and the combination of the
        current components is performed in segments of length buffer_size
        samples. While slightly slower, this is useful for long datasets as it
        reduces the memory requirements by approx. a factor of 3 (assuming
        buffer_size << data length).
        Note that this setting has no effect for fixed-orientation inverse
        operators.
    prepared : bool
        If True, do not call :func:`prepare_inverse_operator`.
    method_params : dict | None
        Additional options for eLORETA. See Notes of :func:`apply_inverse`.

        .. versionadded:: 0.16
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    Returns
    -------
    stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate
        The source estimates.

    See Also
    --------
    apply_inverse_epochs : Apply inverse operator to epochs object
    apply_inverse : Apply inverse operator to evoked object
    """
    _check_reference(raw, inverse_operator['info']['ch_names'])
    _check_method(method)
    _check_ori(pick_ori, inverse_operator['source_ori'])
    _check_ch_names(inverse_operator, raw.info)

    #
    #   Set up the inverse according to the parameters
    #
    inv = _check_or_prepare(inverse_operator, nave, lambda2, method,
                            method_params, prepared)

    #
    #   Pick the correct channels from the data
    #
    sel = _pick_channels_inverse_operator(raw.ch_names, inv)
    logger.info('Applying inverse to raw...')
    logger.info('    Picked %d channels from the data' % len(sel))
    logger.info('    Computing inverse...')

    data, times = raw[sel, start:stop]

    if time_func is not None:
        data = time_func(data)

    K, noise_norm, vertno, source_nn = _assemble_kernel(inv, label, method,
                                                        pick_ori)

    is_free_ori = (inverse_operator['source_ori'] ==
                   FIFF.FIFFV_MNE_FREE_ORI and pick_ori != 'normal')

    if buffer_size is not None and is_free_ori:
        # Process the data in segments to conserve memory
        n_seg = int(np.ceil(data.shape[1] / float(buffer_size)))
        logger.info('    computing inverse and combining the current '
                    'components (using %d segments)...' % (n_seg))

        # Allocate space for inverse solution
        n_times = data.shape[1]

        n_dipoles = K.shape[0] if pick_ori == 'vector' else K.shape[0] // 3
        sol = np.empty((n_dipoles, n_times), dtype=np.result_type(K, data))

        for pos in range(0, n_times, buffer_size):
            sol_chunk = np.dot(K, data[:, pos:pos + buffer_size])
            if pick_ori != 'vector':
                sol_chunk = combine_xyz(sol_chunk)
            sol[:, pos:pos + buffer_size] = sol_chunk

            logger.info('        segment %d / %d done..'
                        % (pos / buffer_size + 1, n_seg))
    else:
        sol = np.dot(K, data)
        if is_free_ori and pick_ori != 'vector':
            logger.info('    combining the current components...')
            sol = combine_xyz(sol)

    if noise_norm is not None:
        if pick_ori == 'vector' and is_free_ori:
            noise_norm = noise_norm.repeat(3, axis=0)
        sol *= noise_norm

    tmin = float(times[0])
    tstep = 1.0 / raw.info['sfreq']
    subject = _subject_from_inverse(inverse_operator)
    src_type = _get_src_type(inverse_operator['src'], vertno)
    stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,
                    vector=(pick_ori == 'vector'), source_nn=source_nn,
                    src_type=src_type)
    logger.info('[done]')

    return stc


def _apply_inverse_epochs_gen(epochs, inverse_operator, lambda2, method='dSPM',
                              label=None, nave=1, pick_ori=None,
                              prepared=False, method_params=None,
                              verbose=None):
    """Generate inverse solutions for epochs. Used in apply_inverse_epochs."""
    _check_method(method)
    _check_ori(pick_ori, inverse_operator['source_ori'])
    _check_ch_names(inverse_operator, epochs.info)

    #
    #   Set up the inverse according to the parameters
    #
    inv = _check_or_prepare(inverse_operator, nave, lambda2, method,
                            method_params, prepared)

    #
    #   Pick the correct channels from the data
    #
    sel = _pick_channels_inverse_operator(epochs.ch_names, inv)
    logger.info('Picked %d channels from the data' % len(sel))
    logger.info('Computing inverse...')
    K, noise_norm, vertno, source_nn = _assemble_kernel(inv, label, method,
                                                        pick_ori)

    tstep = 1.0 / epochs.info['sfreq']
    tmin = epochs.times[0]

    is_free_ori = (inverse_operator['source_ori'] ==
                   FIFF.FIFFV_MNE_FREE_ORI and pick_ori != 'normal')

    if pick_ori == 'vector' and noise_norm is not None:
        noise_norm = noise_norm.repeat(3, axis=0)

    if not is_free_ori and noise_norm is not None:
        # premultiply kernel with noise normalization
        K *= noise_norm

    subject = _subject_from_inverse(inverse_operator)
    for k, e in enumerate(epochs):
        logger.info('Processing epoch : %d' % (k + 1))
        if is_free_ori:
            # Compute solution and combine current components (non-linear)
            sol = np.dot(K, e[sel])  # apply imaging kernel

            logger.info('combining the current components...')
            if pick_ori != 'vector':
                sol = combine_xyz(sol)

            if noise_norm is not None:
                sol *= noise_norm
        else:
            # Linear inverse: do computation here or delayed
            if len(sel) < K.shape[1]:
                sol = (K, e[sel])
            else:
                sol = np.dot(K, e[sel])

        src_type = _get_src_type(inverse_operator['src'], vertno)
        stc = _make_stc(sol, vertno, tmin=tmin, tstep=tstep, subject=subject,
                        vector=(pick_ori == 'vector'), source_nn=source_nn,
                        src_type=src_type)

        yield stc

    logger.info('[done]')


@verbose
def apply_inverse_epochs(epochs, inverse_operator, lambda2, method="dSPM",
                         label=None, nave=1, pick_ori=None,
                         return_generator=False, prepared=False,
                         method_params=None, verbose=None):
    """Apply inverse operator to Epochs.

    Parameters
    ----------
    epochs : Epochs object
        Single trial epochs.
    inverse_operator : dict
        Inverse operator.
    lambda2 : float
        The regularization parameter.
    method : "MNE" | "dSPM" | "sLORETA" | "eLORETA"
        Use minimum norm, dSPM (default), sLORETA, or eLORETA.
    label : Label | None
        Restricts the source estimates to a given label. If None,
        source estimates will be computed for the entire source space.
    nave : int
        Number of averages used to regularize the solution.
        Set to 1 on single Epoch by default.
    pick_ori : None | "normal" | "vector"
        If "normal", rather than pooling the orientations by taking the norm,
        only the radial component is kept. This is only implemented
        when working with loose orientations.
        If "vector", no pooling of the orientations is done and the vector
        result will be returned in the form of a
        :class:`mne.VectorSourceEstimate` object. This does not work when using
        an inverse operator with fixed orientations.
    return_generator : bool
        Return a generator object instead of a list. This allows iterating
        over the stcs without having to keep them all in memory.
    prepared : bool
        If True, do not call :func:`prepare_inverse_operator`.
    method_params : dict | None
        Additional options for eLORETA. See Notes of :func:`apply_inverse`.

        .. versionadded:: 0.16
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`
        and :ref:`Logging documentation <tut_logging>` for more).

    Returns
    -------
    stc : list of (SourceEstimate | VectorSourceEstimate | VolSourceEstimate)
        The source estimates for all epochs.

    See Also
    --------
    apply_inverse_raw : Apply inverse operator to raw object
    apply_inverse : Apply inverse operator to evoked object
    """
    stcs = _apply_inverse_epochs_gen(
        epochs, inverse_operator, lambda2, method=method, label=label,
        nave=nave, pick_ori=pick_ori, verbose=verbose, prepared=prepared,
        method_params=method_params)

    if not return_generator:
        # return a list
        stcs = [stc for stc in stcs]

    return stcs


# XXX what is this???
'''
def _xyz2lf(Lf_xyz, normals):
    """Reorient leadfield to one component matching the normal to the cortex

    This program takes a leadfield matrix computed for dipole components
    pointing in the x, y, and z directions, and outputs a new lead field
    matrix for dipole components pointing in the normal direction of the
    cortical surfaces and in the two tangential directions to the cortex
    (that is on the tangent cortical space). These two tangential dipole
    components are uniquely determined by the SVD (reduction of variance).

    Parameters
    ----------
    Lf_xyz: array of shape [n_sensors, n_positions x 3]
        Leadfield
    normals : array of shape [n_positions, 3]
        Normals to the cortex

    Returns
    -------
    Lf_cortex : array of shape [n_sensors, n_positions x 3]
        Lf_cortex is a leadfield matrix for dipoles in rotated orientations, so
        that the first column is the gain vector for the cortical normal dipole
        and the following two column vectors are the gain vectors for the
        tangential orientations (tangent space of cortical surface).
    """
    n_sensors, n_dipoles = Lf_xyz.shape
    n_positions = n_dipoles // 3
    Lf_xyz = Lf_xyz.reshape(n_sensors, n_positions, 3)
    n_sensors, n_positions, _ = Lf_xyz.shape
    Lf_cortex = np.zeros_like(Lf_xyz)

    for k in range(n_positions):
        lf_normal = np.dot(Lf_xyz[:, k, :], normals[k])
        lf_normal_n = lf_normal[:, None] / linalg.norm(lf_normal)
        P = np.eye(n_sensors, n_sensors) - np.dot(lf_normal_n, lf_normal_n.T)
        lf_p = np.dot(P, Lf_xyz[:, k, :])
        U, s, Vh = linalg.svd(lf_p)
        Lf_cortex[:, k, 0] = lf_normal
        Lf_cortex[:, k, 1:] = np.c_[U[:, 0] * s[0], U[:, 1] * s[1]]

    Lf_cortex = Lf_cortex.reshape(n_sensors, n_dipoles)
    return Lf_cortex
'''


###############################################################################
# Assemble the inverse operator

@verbose
def _prepare_forward(forward, info, noise_cov, pca=False, rank=None,
                     verbose=None):
    """Prepare forward solution for inverse solvers."""
    # fwd['sol']['row_names'] may be different order from fwd['info']['chs']
    fwd_sol_ch_names = forward['sol']['row_names']
    ch_names = [c['ch_name'] for c in info['chs']
                if ((c['ch_name'] not in info['bads'] and
                     c['ch_name'] not in noise_cov['bads']) and
                    (c['ch_name'] in fwd_sol_ch_names and
                     c['ch_name'] in noise_cov.ch_names))]

    if not len(info['bads']) == len(noise_cov['bads']) or \
            not all(b in noise_cov['bads'] for b in info['bads']):
        logger.info('info["bads"] and noise_cov["bads"] do not match, '
                    'excluding bad channels from both')

    # check the compensation grade
    _check_comps(forward['info'], info, 'forward')

    n_chan = len(ch_names)
    logger.info("Computing inverse operator with %d channels." % n_chan)

    whitener, _, noise_cov, n_nzero = _get_whitener(
        noise_cov, info, ch_names, rank, pca)

    gain = forward['sol']['data']

    # This actually reorders the gain matrix to conform to the info ch order
    fwd_idx = [fwd_sol_ch_names.index(name) for name in ch_names]
    gain = gain[fwd_idx]
    # Any function calling this helper will be using the returned fwd_info
    # dict, so fwd['sol']['row_names'] becomes obsolete and is NOT re-ordered

    info_idx = [info['ch_names'].index(name) for name in ch_names]
    fwd_info = pick_info(info, info_idx)

    return fwd_info, gain, noise_cov, whitener, n_nzero


@verbose
def make_inverse_operator(info, forward, noise_cov, loose='auto', depth=0.8,
                          fixed='auto', limit_depth_chs=True, rank=None,
                          use_cps=True, verbose=None):
    """Assemble inverse operator.

    Parameters
    ----------
    info : dict
        The measurement info to specify the channels to include.
        Bad channels in info['bads'] are not used.
    forward : dict
        Forward operator.
    noise_cov : instance of Covariance
        The noise covariance matrix.
    loose : float in [0, 1] | 'auto'
        Value that weights the source variances of the dipole components
        that are parallel (tangential) to the cortical surface. If loose
        is 0 then the solution is computed with fixed orientation,
        and fixed must be True or "auto".
        If loose is 1, it corresponds to free orientations.
        The default value ('auto') is set to 0.2 for surface-oriented source
        space and set to 1.0 for volumetric, discrete, or mixed source spaces,
        unless ``fixed is True`` in which case the value 0. is used.
    depth : None | float in [0, 1]
        Depth weighting coefficients. If None, no depth weighting is performed.
    fixed : bool | 'auto'
        Use fixed source orientations normal to the cortical mantle. If True,
        the loose parameter must be "auto" or 0. If 'auto', the loose value
        is used.
    limit_depth_chs : bool
        If True, use only grad channels in depth weighting (equivalent to MNE
        C code). If grad channels aren't present, only mag channels will be
        used (if no mag, then eeg). If False, use all channels.
    rank : None | int | dict
        Specified rank of the noise covariance matrix. If None, the rank is
        detected automatically. If int, the rank is specified for the MEG
        channels. A dictionary with entries 'eeg' and/or 'meg' can be used
        to specify the rank for each modality.
    use_cps : None | bool (default True)
        Whether to use cortical patch statistics to define normal
        orientations. Only used when converting to surface orientation
        (i.e., for surface source spaces and ``loose < 1``).
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`).

    Returns
    -------
    inv : instance of InverseOperator
        Inverse operator.

    Notes
    -----
    For different sets of options (**loose**, **depth**, **fixed**) to work,
    the forward operator must have been loaded using a certain configuration
    (i.e., with **force_fixed** and **surf_ori** set appropriately). For
    example, given the desired inverse type (with representative choices
    of **loose** = 0.2 and **depth** = 0.8 shown in the table in various
    places, as these are the defaults for those parameters):

        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | Inverse desired                             | Forward parameters allowed                 |
        +=====================+===========+===========+===========+=================+==============+
        |                     | **loose** | **depth** | **fixed** | **force_fixed** | **surf_ori** |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Loose constraint, | 0.2       | 0.8       | False     | False           | True         |
        | | Depth weighted    |           |           |           |                 |              |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Loose constraint  | 0.2       | None      | False     | False           | True         |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Free orientation, | 1.0       | 0.8       | False     | False           | True         |
        | | Depth weighted    |           |           |           |                 |              |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Free orientation  | 1.0       | None      | False     | False           | True | False |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Fixed constraint, | 0.0       | 0.8       | True      | False           | True         |
        | | Depth weighted    |           |           |           |                 |              |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+
        | | Fixed constraint  | 0.0       | None      | True      | True            | True         |
        +---------------------+-----------+-----------+-----------+-----------------+--------------+

    Also note that, if the source space (as stored in the forward solution)
    has patch statistics computed, these are used to improve the depth
    weighting. Thus slightly different results are to be expected with
    and without this information.
    """  # noqa: E501
    is_fixed_ori = is_fixed_orient(forward)

    # These gymnastics are necessary due to the redundancy between
    # "fixed" and "loose"
    if fixed == 'auto':
        if loose == 'auto':
            fixed, loose = False, 0.2
        else:
            fixed = True if float(loose) == 0 else False
    if fixed:
        if loose not in ['auto', 0.]:
            raise ValueError('When invoking make_inverse_operator with '
                             'fixed=True, loose must be 0. or "auto", '
                             'got %s' % (loose,))
        loose = 0.
    if loose == 0.:
        if fixed not in (True, 'auto'):
            raise ValueError('If loose==0., then fixed must be True or "auto",'
                             'got %s' % (fixed,))
        fixed = True

    if fixed and not is_fixed_ori:
        # Here we use loose=1. because computation of depth priors is improved
        # by operating on the free orientation forward; see code at the
        # comment below "Deal with fixed orientation forward / inverse"
        loose = 1.
    if is_fixed_ori:
        if not fixed:
            raise ValueError(
                'Forward operator has fixed orientation and can only '
                'be used to make a fixed-orientation inverse '
                'operator.')
        if fixed and depth is not None:
            raise ValueError(
                'For a fixed orientation inverse solution with depth '
                'weighting, the forward solution must be free-orientation and '
                'in surface orientation')

    # depth=None can use fixed fwd, depth=0<x<1 must use free ori
    if depth is not None:
        if not (0 < depth <= 1):
            raise ValueError('depth should be a scalar between 0 and 1')
        if is_fixed_ori:
            raise ValueError('You need a free-orientation, surface-oriented '
                             'forward solution to do depth weighting even '
                             'when calculating a fixed-orientation inverse.')

    loose, forward = _check_loose_forward(loose, forward)

    if (depth is not None or loose != 1) and not forward['surf_ori']:
        logger.info('Forward is not surface oriented, converting.')
        forward = convert_forward_solution(forward, surf_ori=True,
                                           use_cps=use_cps)

    #
    # 1. Read the bad channels
    # 2. Read the necessary data from the forward solution matrix file
    # 3. Load the projection data
    # 4. Load the sensor noise covariance matrix and attach it to the forward
    #

    # For now we always have pca=False. It does not seem to affect calculations
    # and is also backward-compatible with MNE-C
    gain_info, gain, noise_cov, whitener, n_nzero = \
        _prepare_forward(forward, info, noise_cov, pca=False, rank=rank)
    forward['info']._check_consistency()

    #
    # 5. Compose the depth-weighting matrix
    #

    if depth is not None:
        patch_areas = forward.get('patch_areas', None)
        depth_prior = compute_depth_prior(gain, gain_info, is_fixed_ori,
                                          exp=depth, patch_areas=patch_areas,
                                          limit_depth_chs=limit_depth_chs)
    else:
        depth_prior = np.ones(gain.shape[1], dtype=gain.dtype)

    # Deal with fixed orientation forward / inverse
    if fixed:
        if depth is not None:
            # Convert the depth prior into a fixed-orientation one
            logger.info('    Picked elements from a free-orientation '
                        'depth-weighting prior into the fixed-orientation one')
        if not is_fixed_ori:
            # Convert to the fixed orientation forward solution now
            depth_prior = depth_prior[2::3]
            forward = convert_forward_solution(
                forward, surf_ori=forward['surf_ori'], force_fixed=True,
                use_cps=use_cps)
            is_fixed_ori = is_fixed_orient(forward)
            gain_info, gain, noise_cov, whitener, n_nzero = \
                _prepare_forward(forward, info, noise_cov, pca=False,
                                 verbose=False)

    logger.info("Computing inverse operator with %d channels."
                % len(gain_info['ch_names']))

    #
    # 6. Compose the source covariance matrix
    #

    logger.info('Creating the source covariance matrix')
    source_cov = depth_prior.copy()
    depth_prior = dict(data=depth_prior, kind=FIFF.FIFFV_MNE_DEPTH_PRIOR_COV,
                       bads=[], diag=True, names=[], eig=None,
                       eigvec=None, dim=depth_prior.size, nfree=1,
                       projs=[])

    # apply loose orientations
    if not is_fixed_ori:
        orient_prior = compute_orient_prior(forward, loose=loose)
        source_cov *= orient_prior
        orient_prior = dict(data=orient_prior,
                            kind=FIFF.FIFFV_MNE_ORIENT_PRIOR_COV,
                            bads=[], diag=True, names=[], eig=None,
                            eigvec=None, dim=orient_prior.size, nfree=1,
                            projs=[])
    else:
        orient_prior = None

    # 7. Apply fMRI weighting (not done)

    #
    # 8. Apply the linear projection to the forward solution
    # 9. Apply whitening to the forward computation matrix
    #
    logger.info('Whitening the forward solution.')
    gain = np.dot(whitener, gain)

    # 10. Exclude the source space points within the labels (not done)

    #
    # 11. Do appropriate source weighting to the forward computation matrix
    #

    # Adjusting Source Covariance matrix to make trace of G*R*G' equal
    # to number of sensors.
    logger.info('Adjusting source covariance matrix.')
    source_std = np.sqrt(source_cov)
    gain *= source_std[None, :]
    trace_GRGT = linalg.norm(gain, ord='fro') ** 2
    scaling_source_cov = n_nzero / trace_GRGT
    source_cov *= scaling_source_cov
    gain *= sqrt(scaling_source_cov)

    source_cov = dict(data=source_cov, dim=source_cov.size,
                      kind=FIFF.FIFFV_MNE_SOURCE_COV, diag=True,
                      names=[], projs=[], eig=None, eigvec=None,
                      nfree=1, bads=[])

    # now np.trace(np.dot(gain, gain.T)) == n_nzero
    # logger.info(np.trace(np.dot(gain, gain.T)), n_nzero)

    #
    # 12. Decompose the combined matrix
    #

    logger.info('Computing SVD of whitened and weighted lead field '
                'matrix.')
    eigen_fields, sing, eigen_leads = _safe_svd(gain, full_matrices=False)
    logger.info('    largest singular value = %g' % np.max(sing))
    logger.info('    scaling factor to adjust the trace = %g' % trace_GRGT)

    eigen_fields = dict(data=eigen_fields.T, col_names=gain_info['ch_names'],
                        row_names=[], nrow=eigen_fields.shape[1],
                        ncol=eigen_fields.shape[0])
    eigen_leads = dict(data=eigen_leads.T, nrow=eigen_leads.shape[1],
                       ncol=eigen_leads.shape[0], row_names=[],
                       col_names=[])
    nave = 1.0

    # Handle methods
    has_meg = False
    has_eeg = False
    ch_idx = [k for k, c in enumerate(info['chs'])
              if c['ch_name'] in gain_info['ch_names']]
    for idx in ch_idx:
        ch_type = channel_type(info, idx)
        if ch_type == 'eeg':
            has_eeg = True
        if (ch_type == 'mag') or (ch_type == 'grad'):
            has_meg = True
    if has_eeg and has_meg:
        methods = FIFF.FIFFV_MNE_MEG_EEG
    elif has_meg:
        methods = FIFF.FIFFV_MNE_MEG
    else:
        methods = FIFF.FIFFV_MNE_EEG

    # We set this for consistency with mne C code written inverses
    if depth is None:
        depth_prior = None
    inv_op = dict(eigen_fields=eigen_fields, eigen_leads=eigen_leads,
                  sing=sing, nave=nave, depth_prior=depth_prior,
                  source_cov=source_cov, noise_cov=noise_cov,
                  orient_prior=orient_prior, projs=deepcopy(info['projs']),
                  eigen_leads_weighted=False, source_ori=forward['source_ori'],
                  mri_head_t=deepcopy(forward['mri_head_t']),
                  methods=methods, nsource=forward['nsource'],
                  coord_frame=forward['coord_frame'],
                  source_nn=forward['source_nn'].copy(),
                  src=deepcopy(forward['src']), fmri_prior=None)
    inv_info = deepcopy(forward['info'])
    inv_info['bads'] = [bad for bad in info['bads']
                        if bad in inv_info['ch_names']]
    inv_info._check_consistency()
    inv_op['units'] = 'Am'
    inv_op['info'] = inv_info

    return InverseOperator(inv_op)


def compute_rank_inverse(inv):
    """Compute the rank of a linear inverse operator (MNE, dSPM, etc.).

    Parameters
    ----------
    inv : instance of InverseOperator
        The inverse operator.

    Returns
    -------
    rank : int
        The rank of the inverse operator.
    """
    # this code shortened from prepare_inverse_operator
    eig = inv['noise_cov']['eig']
    if not inv['noise_cov']['diag']:
        rank = np.sum(eig > 0)
    else:
        ncomp = make_projector(inv['projs'], inv['noise_cov']['names'])[1]
        rank = inv['noise_cov']['dim'] - ncomp
    return rank


# #############################################################################
# SNR Estimation

@verbose
def estimate_snr(evoked, inv, verbose=None):
    r"""Estimate the SNR as a function of time for evoked data.

    Parameters
    ----------
    evoked : instance of Evoked
        Evoked instance.
    inv : instance of InverseOperator
        The inverse operator.
    verbose : bool, str, int, or None
        If not None, override default verbose level (see :func:`mne.verbose`).

    Returns
    -------
    snr : ndarray, shape (n_times,)
        The SNR estimated from the whitened data.
    snr_est : ndarray, shape (n_times,)
        The SNR estimated using the mismatch between the unregularized
        solution and the regularized solution.

    Notes
    -----
    ``snr_est`` is estimated by using different amounts of inverse
    regularization and checking the mismatch between predicted and
    measured whitened data.

    In more detail, given our whitened inverse obtained from SVD:

    .. math::

        \tilde{M} = R^\frac{1}{2}V\Gamma U^T

    The values in the diagonal matrix :math:`\Gamma` are expressed in terms
    of the chosen regularization :math:`\lambda\approx\frac{1}{\rm{SNR}^2}`
    and singular values :math:`\lambda_k` as:

    .. math::

        \gamma_k = \frac{1}{\lambda_k}\frac{\lambda_k^2}{\lambda_k^2 + \lambda^2}

    We also know that our predicted data is given by:

    .. math::

        \hat{x}(t) = G\hat{j}(t)=C^\frac{1}{2}U\Pi w(t)

    And thus our predicted whitened data is just:

    .. math::

        \hat{w}(t) = U\Pi w(t)

    Where :math:`\Pi` is diagonal with entries entries:

    .. math::

        \lambda_k\gamma_k = \frac{\lambda_k^2}{\lambda_k^2 + \lambda^2}

    If we use no regularization, note that :math:`\Pi` is just the
    identity matrix. Here we test the squared magnitude of the difference
    between unregularized solution and regularized solutions, choosing the
    biggest regularization that achieves a :math:`\chi^2`-test significance
    of 0.001.

    .. versionadded:: 0.9.0
    """  # noqa: E501
    from scipy.stats import chi2
    _check_reference(evoked, inv['info']['ch_names'])
    _check_ch_names(inv, evoked.info)
    inv = prepare_inverse_operator(inv, evoked.nave, 1. / 9., 'MNE')
    sel = _pick_channels_inverse_operator(evoked.ch_names, inv)
    logger.info('Picked %d channels from the data' % len(sel))
    data_white = np.dot(inv['whitener'], np.dot(inv['proj'], evoked.data[sel]))
    data_white_ef = np.dot(inv['eigen_fields']['data'], data_white)
    n_ch, n_times = data_white.shape

    # Adapted from mne_analyze/regularization.c, compute_regularization
    n_zero = (inv['noise_cov']['eig'] <= 0).sum()
    n_ch_eff = n_ch - n_zero
    logger.info('Effective nchan = %d - %d = %d'
                % (n_ch, n_zero, n_ch_eff))
    del n_ch
    signal = np.sum(data_white ** 2, axis=0)  # sum of squares across channels
    snr = signal / n_ch_eff

    # Adapted from noise_regularization
    lambda2_est = np.empty(n_times)
    lambda2_est.fill(10.)
    remaining = np.ones(n_times, bool)

    # deal with low SNRs
    bad = (snr <= 1)
    lambda2_est[bad] = np.inf
    remaining[bad] = False

    # parameters
    lambda_mult = 0.99
    sing2 = (inv['sing'] * inv['sing'])[:, np.newaxis]
    val = chi2.isf(1e-3, n_ch_eff)
    for n_iter in range(1000):
        # get_mne_weights (ew=error_weights)
        # (split newaxis creation here for old numpy)
        f = sing2 / (sing2 + lambda2_est[np.newaxis][:, remaining])
        f[inv['sing'] == 0] = 0
        ew = data_white_ef[:, remaining] * (1.0 - f)
        # check condition
        err = np.sum(ew * ew, axis=0)
        remaining[np.where(remaining)[0][err < val]] = False
        if not remaining.any():
            break
        lambda2_est[remaining] *= lambda_mult
    else:
        warn('SNR estimation did not converge')
    snr_est = 1.0 / np.sqrt(lambda2_est)
    snr = np.sqrt(snr)
    return snr, snr_est