Skip to content

MRG+1: check info against compensation chans - #5133

Merged
agramfort merged 20 commits into
mne-tools:masterfrom
bloyl:info_compchans
Apr 30, 2018
Merged

agramfort merged 20 commits into
mne-tools:masterfrom
bloyl:info_compchans

Conversation

@bloyl

@bloyl bloyl commented Apr 14, 2018

Copy link
Copy Markdown
Contributor

@larsoner, take a look at this.

The main difference from what we discussed is that I removed the check_comp flags, as that mechanism seemed like something that could start to be abused and would lead to headaches later.

Closes #5127

@larsoner larsoner left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main difference from what we discussed is that I removed the check_comp flags, as that mechanism seemed like something that could start to be abused and would lead to headaches later.

Agreed. A different option would be not to add it to pick_info but rather have pick_info wrap immediately to a new private _pick_info where it is exposed. Then it will only be used by us internally e.g. in _pick_drop_channels.

But this is (probably?) functionally equivalent to the stuff you have now, so either way is fine with me.

Comment thread mne/channels/channels.py Outdated
from ..io.compensator import get_current_comp
from ..io.constants import FIFF
from ..io.meas_info import anonymize_info, Info
from ..io.meas_info import anonymize_info, Info, _bad_chans_comp

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you will have a flake error here, it's unused

Comment thread mne/io/meas_info.py Outdated
# should this be thought of as a bug?
return False, []

# only include compensation channels that would effect selected channels

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

affect

Comment thread mne/io/meas_info.py Outdated
comp_names.extend(comp['data']['col_names'])
comp_names = sorted(set(comp_names))

missing_ch_names = list(set(comp_names).difference(ch_names))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorted here is a bit better than list

Comment thread mne/io/tests/test_meas_info.py Outdated
assert ret == expected_result
assert len(missing) == 17
if comp != 0:
pytest.raises(RuntimeError, Epochs, raw, events, None, -0.2, 0.2,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI the "modern" way to do this is:

with pytest.raises(RuntimeError, match='something from the error string'):
    Epochs(...)

It is a bit more precise than using pytest.raises as a drop-in for assert_raises

Comment thread mne/io/tests/test_pick.py Outdated
raw_ctf = read_raw_fif(fname_ctf_raw)
raw_ctf.apply_gradient_compensation(2)
infos.append(raw_ctf.info)
# infos.append(raw_ctf.info)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert or remove? Probably remove based on the "directly" comment below

Comment thread mne/viz/topomap.py
this_ch['ch_name'] = clean_ch_names[ii]
info['bads'] = _clean_names(info['bads'])
for comp in info['comps']:
comp['data']['col_names'] = _clean_names(comp['data']['col_names'])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will modify the object inplace. Do we know that it has been copied already everywhere _prepare_topo_plot is used?

Is there some new test that shows why this is necessary (i.e., fails on master but passes here)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

info is a copy see https://github.com/mne-tools/mne-python/blob/master/mne/viz/topomap.py#L37

mne/viz/tests/test_topomap.py::test_ctf_plotting currently fails without this line.

I can probably eliminate this line if we drop the comp matrices from the info before calling _prepare_topo_plot. I imagine this is also a problem from the other topomap plotting functions- currently only plot_evoked_topomap drops the comp matrices. I'll look at others

@bloyl

bloyl commented Apr 14, 2018

Copy link
Copy Markdown
Contributor Author

Skipping the check (check_comps==True) created an info that would fail info._check_consistency(), so all subsequent calls to _check_consistency would also have to skip the check. It just seemed like it would spread.

WIth this model, if a developer is confident that the comp mats aren't going to be used they should remove them from the info. info['comps'] = []. In practice other then plotting, I don't think this should come up very often.

@codecov

codecov Bot commented Apr 14, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #5133 into master will increase coverage by 0.03%.
The diff coverage is 92.09%.

@@            Coverage Diff             @@
##           master    #5133      +/-   ##
==========================================
+ Coverage   88.18%   88.21%   +0.03%     
==========================================
  Files         358      358              
  Lines       65944    66143     +199     
  Branches    11210    11245      +35     
==========================================
+ Hits        58150    58347     +197     
- Misses       4958     4963       +5     
+ Partials     2836     2833       -3

@bloyl

bloyl commented Apr 14, 2018 •

Copy link
Copy Markdown
Contributor Author

What do I need to do to run tests that depend on MNE-C locally?

And is it possible to look at my old travis results? they disappeared with my [ci skip] commit?

@larsoner

Copy link
Copy Markdown
Member

What do I need to do to run tests that depend on MNE-C locally?

download and install/configure MNE-C

And is it possible to look at my old travis results? they disappeared with my [ci skip] commit?

Yes, scroll up to your previous commit on GitHub and you'll see a red X, click on it and it will show the CI statuses including Travis. You can also go to the Travis site and navigate to it. But here is the link:

https://travis-ci.org/mne-tools/mne-python/builds/366382806?utm_source=github_status&utm_medium=notification

@larsoner larsoner added this to the 0.16 milestone Apr 15, 2018
@larsoner larsoner changed the title check info against compensation chans WIP: check info against compensation chans Apr 15, 2018
@bloyl

bloyl commented Apr 15, 2018

Copy link
Copy Markdown
Contributor Author

I have 2 questions regarding the last commit (0c67672 )

  1. Does fieldtrip server provide any mechanism to differentiate meg coil types? This information is needed to determine the compensation status (https://github.com/mne-tools/mne-python/blob/master/mne/io/compensator.py#L13) the logic of which I don't quite follow.
  2. make_forward_solution takes an argument call ignore_ref which is described as
    ignore_ref : bool
        If True, do not include reference channels in compensation. This
        option should be True for KIT files, since forward computation
        with reference channels is not currently supported.

Base on this information i remove the comp matrices from the info object so that it is self consistent.
My question is... What checks are made to assure that a fwd, and inv_op and a data set are compatible?

@bloyl

bloyl commented Apr 15, 2018

Copy link
Copy Markdown
Contributor Author

ignoring my poor spelling....
the only test failing is test_make_forward_solution_kit. I can't run this locally due to my mne-c setup (I guess?)

I'll see if it works on a different setup during the week.

FYI locally test_make_forward_solution_kit fails with:

E               IOError: [Errno 2] No such file or directory: '/tmp/tmpB_qQ1R/temp-fwd.fif'
fname      = '/tmp/tmpB_qQ1R/temp-fwd.fif'

The mne command that executes is

mne_do_forward_solution --subject sample --meas /home/bloyl/PycharmProjects/mne-python/mne/forward/tests/../../io/kit/tests/data/test_bin_raw.fif --fwd temp-fwd.fif --destdir /tmp/tmpB_qQ1R --src /tmp/tmp_mne_tempdir_Hm4W11/sample-oct-2-src.fif --bem /home/bloyl/mne_data/MNE-testing-data/subjects/sample/bem/sample-1280-bem-sol.fif --mri /home/bloyl/PycharmProjects/mne-python/mne/forward/tests/../../io/kit/tests/data/trans-sample.fif --megonly

This command completes creating temp-fwd.fif but the file is in the cwd as opposed to /tmp/tmpB_qQ1R. which is where the test looks for it.

@larsoner

Copy link
Copy Markdown
Member

I pushed a commit that fixes the problem. It was pretty straightforward, feel free to look. But now that we have several places where we need this info['comps'] = [] business, the _pick_info(..., check_comps=False) is starting to look like a nicer API, no?

@larsoner

Copy link
Copy Markdown
Member

Does fieldtrip server provide any mechanism to differentiate meg coil types?

You can provide a meas_info struct of your own (info=None), which would then have the proper types. You'd probably need to do this for CTF. You could probably use any previously recorded file from the same system (except the dev_head_t would be different).

Base on this information i remove the comp matrices from the info object so that it is self consistent.
My question is... What checks are made to assure that a fwd, and inv_op and a data set are compatible?

It looks like comps is stored in forward so we should keep it there. I can't recall the consistency checks that we do, but hopefully satisfying the unit tests will be enough to ensure we maintain backward and forward compatibility.

@larsoner

Copy link
Copy Markdown
Member

Comment thread mne/forward/_make_forward.py Outdated
compchs = pick_info(info, picks)['chs']
comp_info = info.copy()
comp_info['comps'] = []
compchs = pick_info(comp_info, picks)['chs']

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think these changes are needed. that pick_info should be fine. ref_meg=True so unless the compensation matrices depend on non reference channels this should pass.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Argh yes you are right

Comment thread mne/forward/_make_forward.py Outdated
comps, info['comps'] = info['comps'], [] # avoid picking errors
info = pick_info(info, pick_types(info, meg=meg, eeg=eeg, ref_meg=False,
exclude=[]))
info['comps'] = comps

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm torn here.
I like backward compatibility and comps have been retained in fwd.info till now.
However, this code will create an info object that will not pass info._check_consistency() in comp matrices are present causing potential issues on reading/writing or other serializations.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends on when _check_consistency gets called, and it must not for forward, otherwise tests would not pass (assuming we do an I/O test for CTF, which I hope we do!).

If we add a consistency check we can make an exception like ._check_consistency(check_comps=False)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope no I/O tests for CTF forwards with compensation mats.

@bloyl bloyl mentioned this pull request Apr 16, 2018
@bloyl

bloyl commented Apr 16, 2018 •

Copy link
Copy Markdown
Contributor Author

I think the core question is this:

Do we think that in order for a meas_info object that has compensation matrices (len(info['comps']>0) to pass ._check_consistency() it needs to also include channel information about the channels used in those matrices?

If the answer is no then we can remove the hard check from ._check_consistency() and only have it in _pick_info() This is the easiest way to maintain backward compatibility, but it comes at the expense that (as a CTF user) I am less confident that these matrices are being used correctly through out the code base.

If the answer is yes (and I fall into this group) we could add a check_comps keyword to ._check_consistency with a default of True. we would then have to identify which calls to .check_consistency need comp_check=False. We would not want to create objects that require check_comps to be False, so we would try hard to avoid adding a check_comps KW to other methods (I.E. pick_info). This would allow us to remove the keyword altogether at some point in the future.

just my 2cnts, I'll be happy to implement either path.

@larsoner

Copy link
Copy Markdown
Member

But there is also an API issue here: if you put it in _check_consistency but not _pick_info (second option), then you have now split "how to skip the check", because you'll need one type of workaround in the evoked plotting (hacking info['comps']) and another in the forward code (_check_consistency(check_comps=False)).

How about we combine 1 and 2. Add _pick_info(..., check_comps=True) that eventually passes this to _check_consistency(..., check_comps=True). Then in evoked plotting and in forward code we pass a check_comps=False argument to some function that both eventually lead to negating the same check. Then it's easy to find where we have hacked the system, but we keep the internal simplicity.

@bloyl

bloyl commented Apr 17, 2018

Copy link
Copy Markdown
Contributor Author

I think the problem with _pick_info(.., check_comps=True) and the work around in the forward code (as opposed to using info['comps'] = []) is that _pick_info(...) path results in a meas_info instance that will not pass the default ._check_consistency(..., check_comps=True).

so for forward objects this means using check_comps=False, for reading and writing to disk and converting to strings. For other objects I don't know. My concern is that as problems come up, which they will due to the lack of CTF testing, there will be an impulse to maintain backward compatibility by skipping the check.

An alternative is to only create infos that pass ._check_consistency(..., check_comps=True), for the forward code this would mean info['comps'] = [] or retaining comp_channels if there are comps matrices (ref_meg=True). This way developers would need to decide if comps are important or not. for instance it doesn't seem like forward objects care at all about comp matrices as since they don't seem to read them back from disk (https://github.com/mne-tools/mne-python/blob/master/mne/forward/forward.py#L249)

@larsoner

Copy link
Copy Markdown
Member

Hmm. It does seem simplest to drop info['comps'] from the forward info. After all, if an evoked or other object has compensation and is used with the forward (usually probably with an inverse), its own info['comps'] should give us a way to undo the compensation.

@bloyl

bloyl commented Apr 17, 2018

Copy link
Copy Markdown
Contributor Author

info['comps'] = [] in the forward info passes all tests locally.

Additionally, I'm now concerned about testing coverage with CTF data. For instance if we had merged following 3b5f4b0 (which had a green dashboard) we wouldn't have been able call write_forward_solution on any data with comp channels. print fwd would have failed as well.

@larsoner

Copy link
Copy Markdown
Member

+1 for gradually increasing coverage, feel free to do it here if you want

@larsoner

Copy link
Copy Markdown
Member

@bloyl is this good to go from your end?

FYI we are finally really pushing to release, hopefully this week.

@agramfort

Copy link
Copy Markdown
Member

if there is no what's new update needed +1 for MRG

@larsoner

Copy link
Copy Markdown
Member

I think it fits in with what we have already done for comps so no need for whats_new as long as @bloyl agrees

@bloyl

bloyl commented Apr 24, 2018

Copy link
Copy Markdown
Contributor Author

This currently breaks ICA for CTF data. I'll have a commit in a few minutes.

@bloyl

bloyl commented Apr 25, 2018

Copy link
Copy Markdown
Contributor Author

With the latest commits - this PR makes it through on of my analysis scripts

Comment thread mne/forward/tests/test_make_forward.py Outdated
write_forward_solution(fname_temp, fwd_py)
fwd_py2 = read_forward_solution(fname_temp)
_compare_forwards(fwd_py, fwd_py2, 274, n_src)
fwd_py.__repr__() # __repr__ also calls _check_consistency

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For future reference repr(...) is a slightly cleaner way to do this (but don't need to change here)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would change it

@larsoner larsoner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you write an update to the API section, since we are technically changing the behavior of forward such that both new computations and round-trip I/O with old CTF forward (at least with my suggestion/comment below) will now be different?

raise RuntimeError('No MEG or EEG channels found.')

# pick out final info
info['comps'] = []

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect you'll also need one of these in read_forward_solution. If in <= 0.15 someone computed a CTF forward, it will have this field, so I think they will get an error on your assert( statement in inverse.py. Right?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can certainly add it. I don't think it will ever be needed as from looking at
_read_forward_meas_info https://github.com/mne-tools/mne-python/blob/master/mne/forward/forward.py#L249 It doesn't look like comps is ever set from anything.

do you want it to be silent or issue a RuntimeWarning

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right -- I just tried creating a CTF forward on master, writing to disk, reading it, and fwd['info']['comps'] does indeed go away. So nothing to do here, I think.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you think of the following at https://github.com/mne-tools/mne-python/blob/master/mne/forward/forward.py#L501

        # remove comp matrcies.
        if fwd['info']['comps']:
            fwd['info']['comps'] = []
            warn('Removing compensation matrices found in measurement info ' +
                 'of forward operator', UserWarning)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you do not need the + and I would make it a bit more explanatory "..., this should not affect application of the forward model but it will change the model if it's written back to disk" or so, to give people a sense of what the consequences are

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok no change.
Do you still want an update to the api section?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that we don't need it anymore

with pytest.raises(RuntimeError, match='Compensation grade of ICA'):
ica.apply(inst)
with pytest.raises(RuntimeError, match='Compensation grade of ICA'):
ica.get_sources(inst)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How long does this take to run? Can we set the number of iterations to some tiny number (1 or 2) to make it faster, since we don't actually care if the decomp is any good?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test_ica::test_ica_ctf takes 6 seconds with max_iter=2 and 12 seconds without the default max_iter

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good speedup, let's add it

@larsoner

Copy link
Copy Markdown
Member

Examples look reasonable to me, feel free to revert the CircleCI-related changes if you want

Comment thread mne/tests/test_cov.py

# make sure comps matrices was not removed from raw
if not raw.info['comps']:
raise RuntimeError('Comps matrices removed')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can just be assert raw.info['comps']

@larsoner

Copy link
Copy Markdown
Member

@bloyl what else is left to do here? There are only a few PRs blocking release, it would be good to include this one.

@bloyl

bloyl commented Apr 27, 2018

Copy link
Copy Markdown
Contributor Author

i'm done. The things I have run have worked. So I think its good to go.

Comment thread mne/forward/forward.py Outdated
#
fwd['info'] = _read_forward_meas_info(tree, fid)

# remove comp matrcies.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo

Comment thread mne/forward/tests/test_make_forward.py Outdated
write_forward_solution(fname_temp, fwd_py)
fwd_py2 = read_forward_solution(fname_temp)
_compare_forwards(fwd_py, fwd_py2, 274, n_src)
fwd_py.__repr__() # __repr__ also calls _check_consistency

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would change it

Comment thread mne/preprocessing/ica.py Outdated
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')

# confirm ica.compensation_grade == inst.compensation_Grade

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small g

Comment thread mne/preprocessing/ica.py Outdated
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')

# confirm ica.compensation_grade == inst.compensation_Grade

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small g

Comment thread mne/preprocessing/ica.py Outdated
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')

# confirm ica.compensation_grade == inst.compensation_Grade

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small g

You should avoid the code dupes below

@agramfort

Copy link
Copy Markdown
Member

@bloyl can you address my comments asap so we can release in the next few days? thx heaps

@larsoner larsoner changed the title WIP: check info against compensation chans MRG+1: check info against compensation chans Apr 30, 2018
@agramfort
agramfort merged commit 786945e into mne-tools:master Apr 30, 2018
@agramfort

Copy link
Copy Markdown
Member

thx @bloyl

@bloyl
bloyl deleted the info_compchans branch May 3, 2018 13:18
britta-wstnr pushed a commit to britta-wstnr/mne-python that referenced this pull request Jul 5, 2018
* ensure comp channels are retained through picked etc.

* make compenstation checks mandatory on all infos

* move error message to pick_info

* add read/write ctf fwd test with compchans

* FIX ica and comp_chans

* Fix: prepare_forward + prepare_cov
Comment thread mne/cov.py
in zip(n_epochs, data_mean)]

if info['comps']:
info['comps'] = []

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this does an in-place modification of the info. Is this desired? compute_covariance should not change epochs.info IMO. It led me to a long debugging session with a colleague ...

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That does sound like a bug, possibly avoidable with info = info.copy() in a line above

bloyl added a commit to bloyl/mne-python that referenced this pull request Oct 4, 2018
bloyl added a commit to bloyl/mne-python that referenced this pull request Oct 4, 2018
bloyl added a commit to bloyl/mne-python that referenced this pull request Oct 8, 2018
bloyl added a commit to bloyl/mne-python that referenced this pull request Oct 10, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants