Skip to content

WIP: extract head position pos from CTF data - #4088

Merged
larsoner merged 6 commits into
mne-tools:masterfrom
bloyl:ctf_chpi_pos
Apr 8, 2018
Merged

larsoner merged 6 commits into
mne-tools:masterfrom
bloyl:ctf_chpi_pos

Conversation

@bloyl

@bloyl bloyl commented Mar 23, 2017

Copy link
Copy Markdown
Contributor

This is in need of a regression test and more importantly some other CTF users who have some cHPI data to evaluate it.

@larsoner

Copy link
Copy Markdown
Member

Travis says your new test does not pass.

Do you know any CTF folks who could test this? I might actually have some CTF data with HPI information encoded, but couldn't really verify its quality beyond making sure the resulting positions/rotations look not terrible.

@bloyl

bloyl commented Mar 24, 2017

Copy link
Copy Markdown
Contributor Author

Yeah, the test fails to enforce that the I add a regression test once we are convinced that its working. The regression test can use existing CTF data in the testing sample but I want to confirm its working on a bigger test set. then I'll remove the assert_true(False) at the end of the test. That will also fix the flake warning of an unused variable.

Unfortunately I don't know any CTF users who also are mne-python users. I am going to try to acquire a phantom run today but that will be a somewhat qualitative test. IE I start moving the phantom +z at 2 sec and start to rotate around 5 sec. Other than that I'm not sure what I can do.

One thing that might be important is that the pick_channel_regex matches the right channels on all CTF machines. I think only the numbers after the - change in the channel names but I don't really know.

@larsoner

Copy link
Copy Markdown
Member

I am going to try to acquire a phantom run today but that will be a somewhat qualitative test. IE I start moving the phantom +z at 2 sec and start to rotate around 5 sec. Other than that I'm not sure what I can do.

That would be great. If you can try to make the recording short but still usable, we could add it to the testing dataset.

One thing that might be important is that the pick_channel_regex matches the right channels on all CTF machines.

I think that getting it to work with your data is the right first step. Then we can wait to hear from others if it doesn't work, and iterate. At the very least I can check the data that I have, which I think are from Montreal.

@bloyl

bloyl commented Apr 14, 2017

Copy link
Copy Markdown
Contributor Author

@Eric89GXL How do you want to handle mne-test-data pulls?

do you want separate PRs for each mne-python PR?

@larsoner

Copy link
Copy Markdown
Member

Yeah ideally the PRs will match, makes checking things a bit easier.

@bloyl

bloyl commented Apr 14, 2017

Copy link
Copy Markdown
Contributor Author

ok testing data for this PR is in mne-tools/mne-testing-data#21

@bloyl

bloyl commented Apr 14, 2017

Copy link
Copy Markdown
Contributor Author

@Eric89GXL
Updating to test-data release 32 will make the ctf tests (that were written for this PR) pass.

however it will make the artemis reader tests fail because those tests are looking for data that was removed in release 32? Thoughts on how to deal with that.

@larsoner

Copy link
Copy Markdown
Member

Once both your PRs are merged we should be good, right?

If so, I assume those will be fixed in your other PR. We can let them fail here for now, and merge your other PR first. Then we are only merging with green CIs. Sound good?

@bloyl

bloyl commented Apr 17, 2017

Copy link
Copy Markdown
Contributor Author

works for me.

@codecov-io

codecov-io commented Apr 20, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #4088 into master will increase coverage by <.01%.
The diff coverage is 96.29%.

@@            Coverage Diff             @@
##           master    #4088      +/-   ##
==========================================
+ Coverage   88.05%   88.05%   +<.01%     
==========================================
  Files         356      356              
  Lines       65140    65192      +52     
  Branches    11105    11112       +7     
==========================================
+ Hits        57358    57408      +50     
- Misses       4958     4959       +1     
- Partials     2824     2825       +1

@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.

In your testing, does this work well?

Where does ctf_chpi_pos_fname come from? Can we take it as some sort of ground truth to compare to?

Otherwise LGTM

Comment thread mne/chpi.py Outdated
return(apply_trans(trans, pts, move=move))


def extract_head_pos_ctf(raw, gof_limit=0.98):

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.

Probably calculate because we're actually doing some computation/estimation here, not just extracting values (that's the trivial part).

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.

... and we've probably talked about this before, but maybe we should just have one calculate_head_positions(raw) function. If you pass a CTF raw, it uses this code. If you pass Neuromag raw, it uses the Neuromag code. WDYT?

If you think we should do it, but do it in a separate PR, then let's make this function private for now.

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'll change the name to _calculate_head_pos_ctf and make it private.

I like the idea of having a single method eventually. I had been hoping to evaluate the mne chpi fitting by feeding it CTF data, but it seems that ctf filters out the cHPI frequencies so that doesn't work.
I would suggest that we use this a little while and then make a new PR where we make calculate_head_positions a public method and at that time we think through how to unify things.

Comment thread mne/chpi.py Outdated
hpi_picks = []
for i in [2, 1, 3]:
hpi_picks.extend(pick_channels_regexp(raw.info['ch_names'],
'HLC00%d[123]-.*' % i))

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 don't see any checking that pick_channels_regexp actually gives you channels in the right order.

You might just want to pick channels with a single regex, then check that you actually have the correct channels while doing the necessary reordering.

Comment thread mne/chpi.py Outdated
-----
CTF continuous head monitoring stores the x,y,z location (m) of each chpi
coil as separate channels in the dataset.
HLC001[123]-* - nasion

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.

These * will probably cause Sphinx to complain. You can either escape them with \ (since it's in a string it should actually be \\ or use an r'' string) or change the nomenclature.

Comment thread mne/chpi.py Outdated


def extract_head_pos_ctf(raw, gof_limit=0.98):
"""Extract MaxFilter-formatted head position parameters from ctf dataset.

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.

We don't need to call them MaxFilter-formatted in the title. (You can do it in the notes if you want.) I think we're probably going to standardize around using the (N, 10) ndarray format. If we always labeled whose format it was (derived from) in the title, we'd have some long names...

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 was just following the pattern from the other methods.

I do find this pos/quat nomenclature a bit confusing.

For instance the method _apply_quat should really be in mne.transforms but the quat isn't quite a quaternion so I left it in chpi.
I guess I could refactor it into taking a real quaternion and a translation and then put it in mne.transforms ,what do you think?

@larsoner

larsoner commented Apr 21, 2017 via email

Copy link
Copy Markdown
Member

@bloyl

bloyl commented Apr 22, 2017

Copy link
Copy Markdown
Contributor Author

So the unfortunately the numbers in ctf_chpi_pos_fname come from this code written out to a pos file.

I did visualize the changes in head locations, and it did match what was expected. Which now as i sit on the train forget what was, but i think its an p -> A translation

@larsoner

Copy link
Copy Markdown
Member

Sounds good.

When this is good to go from your end please set the title to MRG and ping me to have a look

@bloyl

bloyl commented Apr 22, 2017 •

Copy link
Copy Markdown
Contributor Author

I am happy that this is working on our ctf data.
It would be good if other CTF users (@dengemann @jona-sassenhagen maybe?) also gave it a try

@bloyl bloyl closed this Apr 22, 2017
@bloyl bloyl reopened this Apr 22, 2017
@larsoner

Copy link
Copy Markdown
Member

I'm not sure if any CTF users have done movement tracking stuff.

@christianbrodbeck do you have any experience with this?

@jona-sassenhagen

Copy link
Copy Markdown
Contributor

What's holding up this one?

@bloyl

bloyl commented Oct 20, 2017 via email

Copy link
Copy Markdown
Contributor Author

@jona-sassenhagen

jona-sassenhagen commented Oct 20, 2017 via email

Copy link
Copy Markdown
Contributor

@bloyl

bloyl commented Oct 20, 2017 via email

Copy link
Copy Markdown
Contributor Author

@larsoner

Copy link
Copy Markdown
Member

@jona-sassenhagen do you have any with continuous HPI turned on during the recording? If not, is it easy to get some (preferably with some known movements forward/back, rotations, etc.)

@jona-sassenhagen

jona-sassenhagen commented Oct 20, 2017 via email

Copy link
Copy Markdown
Contributor

@bloyl

bloyl commented Oct 25, 2017 via email

Copy link
Copy Markdown
Contributor Author

@larsoner

Copy link
Copy Markdown
Member

Couldn't you use this PR's branch and run _calculate_head_pos_ctf(...) on the data and see if the result is sensible, i.e. no errors raised and you actually get different positions with mne.viz.plot_head_positions?

@larsoner

larsoner commented Apr 6, 2018

Copy link
Copy Markdown
Member

@jona-sassenhagen can you check some CTF data for head position information when you get a chance? See a couple of posts above.

@jona-sassenhagen

jona-sassenhagen commented Apr 6, 2018 •

Copy link
Copy Markdown
Contributor

ed.: redacted

I'm dropboxing an evoked CTF file, does that help?

@larsoner

larsoner commented Apr 6, 2018

Copy link
Copy Markdown
Member

Evoked probably not. I think this will need raw data.

@larsoner

larsoner commented Apr 6, 2018

Copy link
Copy Markdown
Member

... and it sounds like Luke's suggestion requires running something at the CTF acquisition machine, "headMotionDetect"?

@jona-sassenhagen

Copy link
Copy Markdown
Contributor

https://www.dropbox.com/s/mu7lvy38hcod21k/test-raw.fif?dl=0

Ok, here is a 1s Raw fif file then :)

Or do we need the unconverted CTF files? Cause they're huge.

@larsoner

larsoner commented Apr 6, 2018

Copy link
Copy Markdown
Member

Rebasing to latest master (for improvements) and running on your FIF file:

import mne
raw = mne.io.read_raw_fif('test-raw.fif')
head_pos = mne.chpi._calculate_head_pos_ctf(raw)
mne.viz.plot_head_positions(head_pos, info=raw.info)

I get:

  File "/home/larsoner/custombuilds/mne-python/mne/chpi.py", line 241, in _calculate_head_pos_ctf
    raise RuntimeError('Bad coil fit! (g=%7.3f)' % (g,))
RuntimeError: Bad coil fit! (g= -0.354)

If I comment out the GOF check (not a great idea) it at least runs and gives:

figure_1-1

The positions are reasonable but the quaternions are probably too large (unless the head was very tilted).

@bloyl I take it this file does not have actually cHPI on? Do you see some way to detect this from the header to tell people cHPI was not on, rather than telling them that the coil fit was bad?

If not, even in the bad-coil-fit case the Neuromag head pos calculation will use the last known position and move on to the next time point. The CTF code should probably also use this strategy in case there is a large artifact that disrupts cHPI or something.

@jona-sassenhagen

Copy link
Copy Markdown
Contributor

The positions are reasonable but the quaternions are probably too large

Could we reverse the polarity of the neutron flow?

@bloyl

bloyl commented Apr 6, 2018

Copy link
Copy Markdown
Contributor Author

So this took some digging.... but cHPI does seem to be on for test file. However the fif file is bad. I'm not sure when or how it was created but it seem like the ident codes for the NAS and RPA fids/coils are switched.

Running the following

import mne
from mne.io.constants import FIFF
from mne.transforms import apply_trans
raw = mne.io.read_raw_fif('/home/bloyl/Downloads/test-raw.fif')

map = {FIFF.FIFFV_POINT_LPA: 'LPA',FIFF.FIFFV_POINT_RPA: 'RPA',
       FIFF.FIFFV_POINT_NASION: 'NAS'}

# Look in the dig points
chpi_locs_head = sorted([d for d in raw.info['dig']
                         if d['kind'] == 2], key=lambda x: x['ident'])
for p in chpi_locs_head:
    r = p['r']
    print ("%s - (%0.6f, %0.6f, %0.6f)" % (map[p['ident']], r[0], r[1], r[2]))
print('\n\n')

# Look in HPI results used in cHPI code.
chpi_locs_dev = sorted([d for d in raw.info['hpi_results'][-1]
                       ['dig_points']], key=lambda x: x['ident'])
for p in chpi_locs_dev:
    r = apply_trans(raw.info['dev_head_t'], p['r'])
    print ("%s - (%0.6f, %0.6f, %0.6f)" % (map[p['ident']], r[0], r[1], r[2]))

returns

LPA - (-0.067706, -0.000000, 0.000000)
NAS - (0.064001, -0.000000, 0.000000)
RPA - (-0.000000, 0.106507, 0.000000)

LPA - (-0.067706, -0.000000, -0.000000)
NAS - (0.064001, -0.000000, -0.000000)
RPA - (0.000000, 0.106507, -0.000000)

Which has NAS and RPA switched.
If I switch the order in the chpi code. I get perfect goodness of fit (g=1.000)

@larsoner

larsoner commented Apr 6, 2018

Copy link
Copy Markdown
Member

This sounds like independent confirmation that your code works, then, given we fix the encoding of LPA/RPA/Nasion elsewhere.

Can you rebase and we can see if the CIs pass? If so we can probably merge this.

@bloyl

bloyl commented Apr 7, 2018

Copy link
Copy Markdown
Contributor Author

Rebased and tests are passing.

@larsoner

larsoner commented Apr 8, 2018

Copy link
Copy Markdown
Member

Great, thanks @bloyl !

@larsoner
larsoner merged commit 5210993 into mne-tools:master Apr 8, 2018
@bloyl
bloyl deleted the ctf_chpi_pos branch April 10, 2018 13:21
britta-wstnr pushed a commit to britta-wstnr/mne-python that referenced this pull request Jul 5, 2018
* ENH: extract pos from ctf

* Fix Flake8

* FIX: added regression test and test data

* Fix:Method Name Change

* FIX: spelling :)

* Fix: Resp to reviews
@jeythekey

Copy link
Copy Markdown
Contributor

@bloyl thanks for that contribution, seems to work great.
I needed to make one minor modification, in order to be compatible with data loaded with the clean_names-option set to True:
In line 187, the - has to be removed from the matching pattern.
I could also make a PR for that ;)

@agramfort

Copy link
Copy Markdown
Member

any usability PR is welcome

@jeythekey

Copy link
Copy Markdown
Contributor

When using mne.chpi._calculate_head_pos_ctf to extract the head movement for preloaded and cropped data (i.e. with raw.first_samp>0), I get the following error when using the returned pos matrix for maxwell filtering movement compensation:

~/PYTHON/anaconda3/envs/mne_r/lib/python3.6/site-packages/mne/preprocessing/maxwell.py in _check_pos(pos, head_frame, raw, st_fixed, sfreq)
    823         raise ValueError('Head position time points must be greater than '
    824                          'first sample offset, but found %0.4f < %0.4f'
--> 825                          % (t[0], raw._first_time))
    826     max_dist = np.sqrt(np.sum(pos[:, 4:7] ** 2, axis=1)).max()
    827     if max_dist > 1.:

ValueError: Head position time points must be greater than first sample offset, but found 0.0000 < 43.7867

This check is in accordance with raw._first_time being subtracted in _check_pos (L. 832).

Also events.average_movements (L. 2852) assumes the t in pos to be rel. 0.

--> The time vector calculated in mne.chpi._calculate_head_pos_ctf should be shifted by ­­raw._first_time.

I this time made a 1-line-PR for that ;)

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.

6 participants