Repository: mne-tools/mne-python

Issue:
Apply_inverse problem
Hi All, 

Anyone can help me with the error when I run apply_inverse "EEG average reference is mandatory for inverse modeling, use set_eeg_reference" method. 
I don't have an EEG data. Also, I put EEG=False in the argument. 
It seems everything looks fine to me. Maybe anyone can help me to find the error.  

-----------------
Here is the script
-----------------
    src_morph = mne.morph_source_spaces(src,'fsaverage',subjects_dir=subj_dir)
    
    model = mne.make_bem_model(subject=subj, ico=4, conductivity=conductivity, subjects_dir=subj_dir)
            
    bem = mne.make_bem_solution(model)
 
    fwd_morph = mne.make_forward_solution(raw.info, trans=trans, src=src_morph, bem=bem, fname=None, meg=True, eeg=False, mindist=0.0, n_jobs=2)
    fwd_morph = mne.pick_types_forward(fwd_morph, meg=True, eeg=False)

    cov = mne.compute_raw_covariance(raw, tmin=0, tmax=30)
    
    inv_morph = mne.minimum_norm.make_inverse_operator(raw.info, fwd_morph, cov, loose=None, depth=0.8)

    stc_morph = mne.minimum_norm.apply_inverse_raw(raw, inv_morph, lambda2, method, pick_ori='normal', buffer_size=25000)



Discussion:
what error do you get? Please show us what print(raw.info) gives.

Alex,

Here is the information:

print(raw.info)
<Info | 28 non-empty fields
    acq_pars : 'str | 21614 items
    bads : 'list | 0 items
    buffer_size_sec : 'numpy.float64 | 1.0
    ch_names : 'list | MEG0113, MEG0112, MEG0111, MEG0122, MEG0123, MEG0121, ...
    chs : 'list | 324 items (GRAD: 204, MAG: 102, STIM: 5, EEG: 8, EOG: 2, ECG: 1, MISC: 2)
    comps : 'list | 0 items
    custom_ref_applied : 'bool | False
    description : 'str | 17 items
    dev_head_t : 'mne.transforms.Transform | 3 items
    dig : 'list | 115 items
    events : 'list | 0 items
    experimenter : 'str | 3 items
    file_id : 'dict | 4 items
    highpass : 'float | 0.10000000149011612 Hz
    hpi_meas : 'list | 1 items
    hpi_results : 'list | 1 items
    hpi_subsystem : 'dict | 2 items
    line_freq : 'float | 50.0
    lowpass : 'float | 330.0 Hz
    meas_date : 'numpy.ndarray | 2017-09-18 15:04:54
    meas_id : 'dict | 4 items
    nchan : 'int | 324
    proc_history : 'list | 1 items
    proj_id : 'numpy.ndarray | 1 items
    proj_name : 'str | 8 items
    projs : 'list | 0 items
    sfreq : 'float | 1000.0 Hz
    subject_info : 'dict | 6 items
    acq_stim : 'NoneType
    ctf_head_t : 'NoneType
    dev_ctf_t : 'NoneType
    kit_system_id : 'NoneType
    xplotter_layout : 'NoneType
If you do `raw.pick_types(meg=True, eeg=False)` it should work as a workaround.

We must have some subtle problem where we check for avg eeg ref before all picking is done, as in this case the forward does not / should not have EEG channels.
Thank you Eric, the issue has been resolved. 

Good to hear @hendriksantosa. Let's leave this open because we do have a bug with our checking I think.

Resolving patch:
diff --git a/mne/io/pick.py b/mne/io/pick.py
--- a/mne/io/pick.py
+++ b/mne/io/pick.py
@@ -395,7 +395,7 @@ def pick_info(info, sel=(), copy=True):
         raise ValueError('No channels match the selection.')
 
     # make sure required the compensation channels are present
-    if len(info['comps']) > 0:
+    if len(info.get('comps', [])) > 0:
         ch_names = [info['ch_names'][idx] for idx in sel]
         _, comps_missing = _bad_chans_comp(info, ch_names)
         current_comp = get_current_comp(info)
diff --git a/mne/minimum_norm/inverse.py b/mne/minimum_norm/inverse.py
--- a/mne/minimum_norm/inverse.py
+++ b/mne/minimum_norm/inverse.py
@@ -787,12 +787,17 @@ def _check_loose_forward(loose, forward):
     return loose, forward
 
 
-def _check_reference(inst):
+def _check_reference(inst, ch_names=None):
     """Check for EEG ref."""
-    if _needs_eeg_average_ref_proj(inst.info):
+    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, picks)
+    if _needs_eeg_average_ref_proj(info):
         raise ValueError('EEG average reference is mandatory for inverse '
                          'modeling, use set_eeg_reference method.')
-    if inst.info['custom_ref_applied']:
+    if info['custom_ref_applied']:
         raise ValueError('Custom EEG reference is not allowed for inverse '
                          'modeling.')
 
@@ -903,7 +908,7 @@ def apply_inverse(evoked, inverse_operator, lambda2=1. / 9., method="dSPM",
            methods of electric neuronal activity. Part 1: exact, zero error
            localization. arXiv:0710.3341
     """
-    _check_reference(evoked)
+    _check_reference(evoked, inverse_operator['info']['ch_names'])
     _check_method(method)
     _check_ori(pick_ori, inverse_operator['source_ori'])
     #
@@ -1019,7 +1024,7 @@ def apply_inverse_raw(raw, inverse_operator, lambda2, method="dSPM",
     apply_inverse_epochs : Apply inverse operator to epochs object
     apply_inverse : Apply inverse operator to evoked object
     """
-    _check_reference(raw)
+    _check_reference(raw, inverse_operator['info']['ch_names'])
     _check_method(method)
     _check_ori(pick_ori, inverse_operator['source_ori'])
 
@@ -1715,7 +1720,7 @@ def estimate_snr(evoked, inv, verbose=None):
     .. versionadded:: 0.9.0
     """  # noqa: E501
     from scipy.stats import chi2
-    _check_reference(evoked)
+    _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)


Test patch:
diff --git a/mne/minimum_norm/tests/test_inverse.py b/mne/minimum_norm/tests/test_inverse.py
--- a/mne/minimum_norm/tests/test_inverse.py
+++ b/mne/minimum_norm/tests/test_inverse.py
@@ -470,10 +470,9 @@ def test_apply_inverse_operator():
     # Test that no errors are raised with loose inverse ops and picking normals
     noise_cov = read_cov(fname_cov)
     fwd = read_forward_solution_meg(fname_fwd)
-    inv_op2 = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1,
-                                    fixed='auto', depth=None)
-    apply_inverse(evoked, inv_op2, 1 / 9., method='MNE',
-                  pick_ori='normal')
+    inv_op_meg = make_inverse_operator(evoked.info, fwd, noise_cov, loose=1,
+                                       fixed='auto', depth=None)
+    apply_inverse(evoked, inv_op_meg, 1 / 9., method='MNE', pick_ori='normal')
 
     # Test we get errors when using custom ref or no average proj is present
     evoked.info['custom_ref_applied'] = True
@@ -482,6 +481,9 @@ def test_apply_inverse_operator():
     evoked.info['projs'] = []  # remove EEG proj
     pytest.raises(ValueError, apply_inverse, evoked, inv_op, lambda2, "MNE")
 
+    # But test that we do not get EEG-related errors on MEG-only inv (gh-4650)
+    apply_inverse(evoked, inv_op_meg, 1. / 9.)
+
 
 @testing.requires_testing_data
 def test_make_inverse_operator_fixed():