Repository navigation
MRG+1: HPI support for Artemis123 - #4069
Conversation
larsoner
left a comment
There was a problem hiding this comment.
Looks like a reasonable approach to me. But there are some functional changes, like no more high-pass, that we should discuss.
Can you enumerate those here? Taking care of the comment about documenting the procedure would help tackle that.
| best_order = None | ||
| best_g = -999 | ||
| best_quat = id_quat | ||
| for i in itertools.permutations(np.arange(len(head_pnts))): |
There was a problem hiding this comment.
can you use a more descriptive name than i? Maybe at least ord?
|
|
||
| def _fit_dev_head_trans(dev_pnts, head_pnts): | ||
| """Compute Device to Head transform allowing for permutiatons of points.""" | ||
| import itertools |
There was a problem hiding this comment.
this is a standard lib so you can import at the top
| best_g = -999 | ||
| best_quat = id_quat | ||
| for i in itertools.permutations(np.arange(len(head_pnts))): | ||
| head_pnts_tmp = head_pnts[np.array(i)] |
There was a problem hiding this comment.
Do you need np.array(i) because i is a tuple?
There was a problem hiding this comment.
yeah i is a tuple, so indexing doesn't work. I could probably do list if that is preferable?
| (quat_to_rot(best_quat[:3]), | ||
| best_quat[3:][:, np.newaxis]), axis=1) | ||
| dev_head_t = np.concatenate((dev_head_t, [[0, 0, 0, 1.]])) | ||
| return dev_head_t, best_order |
There was a problem hiding this comment.
Can you take a minute to add a header at the top of the file documenting what each step/function is used for? It would help me understand, e.g., what this function is used for, and also help us structure things moving forward.
I probably should have done this originally. So if you want, I can add one in master, you can rebase, and then put your changes in there.
There was a problem hiding this comment.
Can you add one to the master and I'll add to/maintain it through this process. That way the format will be what you want it to be from the start.
| hp_ind = np.where(freqs >= hpi_freqs.min())[0][0] - 2 | ||
| hp_window = np.concatenate( | ||
| [[0], np.repeat(np.hanning(hp_ind - 1)[:(hp_ind - 1) // 2], | ||
| 2)])[np.newaxis] |
There was a problem hiding this comment.
I was removing things that weren't being used. If we want to do HP filtering then we can add this back in.
There was a problem hiding this comment.
Ahh right. Perhaps I had been using it at one point and then realized it shouldn't be necessary...
| # 1. Fit amplitudes for each channel from each of the N cHPI sinusoids | ||
| # | ||
| sin_fit = _fit_cHPI_amplitudes(raw, time_sl, hpi, fit_time) | ||
|
|
| # | ||
| sin_fit = _fit_cHPI_amplitudes(raw, time_sl, hpi, fit_time) | ||
|
|
||
| # skip this window if it bad. |
There was a problem hiding this comment.
There are a lot of datasets for which fitting could fail briefly, so I don't think we should raise an Exception. We could make this a parameter, I guess. bad_sin_fit='warn' default with 'ignore' | 'raise' options?
There was a problem hiding this comment.
I don't know what the right convention is. I tend not to like needing to check that a return variable is defined to know if something worked.
In C++ I would say that a function should raise an exception if it can't complete. The calling function would then be in charge of logging the error message and deciding what to do.
This would have _fit_cHPI_amplitudes raise an exception and the call to it be wrapped in a try/except blcok
There was a problem hiding this comment.
I tend not to like needing to check that a return variable is defined to know if something worked.
We usually use this pattern (e.g., return None) instead of try/except. But here I don't think you need to with my proposal, since the bad_sin_fit parameter can take care of it?
| good = not d_bad.any() | ||
|
|
||
| # filter coil fits based on the correspodnace to digitization geometry | ||
| use_mask = np.ones(hpi['n_freqs'], bool) |
| logger.info(_time_prefix(fit_time) + | ||
| 'Bad coil fit! (g=%7.3f)' % (g,)) | ||
| continue | ||
|
|
| if points_: | ||
| return np.array([points_[i]['r'] for i in FIDUCIAL_ORDER]) | ||
| else: | ||
| return np.array([]) |
There was a problem hiding this comment.
This is necessary for when a user does plot_sensors(..., dig=True) but there are no fiducials?
There was a problem hiding this comment.
For instance if you load a ctf dataset but don't supply a pos file, you get hpi dig points but no fids.
At some point it might be of interest to distinguish between digitized fiducials and hpi locaitons and MEG fit fids and hpi locations. For instance for my case i was constantly plotting digitized HPI locations along with the FIT hpi locations to visually see where errors might be cropping up.
Codecov Report
@@ Coverage Diff @@
## master #4069 +/- ##
=========================================
+ Coverage 86.12% 86.2% +0.07%
=========================================
Files 350 356 +6
Lines 63553 64319 +766
Branches 9689 9792 +103
=========================================
+ Hits 54734 55443 +709
- Misses 6137 6174 +37
- Partials 2682 2702 +20 |
cb44c25 to
03cece5
Compare
|
@bloyl actually I want something like this now (extract coil positions as a function of time) as a post-acquisition quick data sanity check. It seems like your code would facilitate this. Do you have time to clean this up, or would it be worthwhile for me to take over? |
|
I have it about where I want it so I can try to finish it up tomorrow or early next week. Do you have an api in mind? I could add an additional return to chpi._calculate_chpi_positions or add a similar method to _calculate_chpi_positions that would return the cHPI locations either as an array of dig structures or an array of this_coil_dev_rrs. |
Let's go with the latter. The HPI position calculation code can take a while to run, and by making a separate method, we can skip the second optimization step (dev_head_t fitting). I think it can be made sufficiently DRY by using private functions, some of which you've possibly already refactored here. |
|
CIs are happy, is this ready for review/merge from your end? |
|
This doesn't have your method added to it. I was actually just finishing up that up and was about to push it. Also, what do you think of changing the name of the existing method That would free up _calcualte_chpi_locations to do what you want without confusing it with the other method. |
|
Eventually |
| return x, 1. - result / denom | ||
|
|
||
|
|
||
| def _fit_dev_head_trans(dev_pnts, head_pnts): |
There was a problem hiding this comment.
This should be renamed to something like _fit_coil_order_dev_head_trans because it does both, and based on the currenty name I thought you were going to also use this for the continuous fitting of (Neuromag) data.
Incidentally, Neuromag sometimes gets it wrong, so we might want to eventually use a function like this in cases where the coil locations are way off -- we could sample the data at some intervals and have a confidence estimate about which coils are where. But this is definitely something for later, this is a good starting point for it.
|
|
||
| def _fit_dev_head_trans(dev_pnts, head_pnts): | ||
| """Compute Device to Head transform allowing for permutiatons of points.""" | ||
| id_quat = np.concatenate([rot_to_quat(np.eye(3)), [0.0, 0.0, 0.0]]) |
There was a problem hiding this comment.
FYI rot_to_quat(eye(3)) == np.zeros(3), but I don't mind this either because it's explicit
| dev_head_t = np.concatenate( | ||
| (quat_to_rot(best_quat[:3]), | ||
| best_quat[3:][:, np.newaxis]), axis=1) | ||
| dev_head_t = np.concatenate((dev_head_t, [[0, 0, 0, 1.]])) |
There was a problem hiding this comment.
This operation comes up a lot so at some point we should make a _quat_to_dev_head_t and inverse, feel free to add here or we'll do it later
There was a problem hiding this comment.
I would say we leave this until later. At some point it should get added as a utility method to transforms.py but its not really a quat to trans so we should name it something better.
|
|
||
| Returns | ||
| ------- | ||
| hpi - Dict |
There was a problem hiding this comment.
let's get rid of this or format it the standard way
| chpi_digs.append(dig) | ||
|
|
||
| last['fit_time'] = fit_time | ||
| last['coil_dev_rrs'] = this_coil_dev_rrs |
There was a problem hiding this comment.
At some point we might be able to combine this with the _calculate_chpi_positions function (and just have it stop its loop early) but my guess is it might become too complicated. So I think this is an acceptable split.
For my use case, I probably also want the inter-coil distances, but I'll add that in a follow-up PR.
| If not None, override default verbose level (see mne.verbose). | ||
| pos_fname : str or None (defulat None) | ||
| If not None, load digitized head points from this file | ||
| head_loc : bool (default False) |
| head_loc : bool (default False) | ||
| If True attempt to perform head localization using HPI coils. If no | ||
| HPI coils are in info['dig'] hpic coils are assumed to be in canonical | ||
| order of fiducial points (nas, rpa, lpa). |
There was a problem hiding this comment.
Is this the same as CTF? If so, please note somehow
There was a problem hiding this comment.
... and I'm not quite sure what this parameter does. Does it do continuous head localization? If so that should really be done by a call to _calculate_chpi_positions. If it computes info['dev_head_t'] then it should explicitly mention computing the initial device to head coordinate transform.
There was a problem hiding this comment.
Is this the same as CTF?
I'm not sure what you mean. The concept is the same ie the assumption is that chpi coils are placed at the fiducial locations but the order is most likely not that same.
There was a problem hiding this comment.
Yeah I mean the same as CTF in that the coils are at the fiducials and in the same order. If it's not necessarily the same order (I guess it doesn't need to be, really) then no need to mention it.
But it would be good to change the parameter description, and maybe also the name (but I can't think of a good one). head_loc is a bit of a misnomer, maybe just add_trans if it's indeed computing the info['dev_head_t']? Should it default to True? If so then it's a form of bugfix so I think it's okay from an API standpoint.
Does it fail gracefully if True but no loc is possible?
There was a problem hiding this comment.
So I pushed some changes. let me know what you think.
I think leaving it as head_loc makes sense. it is performing HPI localization and then setting info['dev_head_t], add_trans while technically correct isn't really meaningful.
It defaults to True because the artemis scanner doesn't perform any of these computations so the file doesn't have a dev_head_t. So in order to have a meaningful head coordinate system you need to do head_localization.
I think it fails gracefully. If less then 3 chpi coils are on it doesn't issues a warning and sets the dev_head_t to identity. If you don't supply and digitization points and also get the ordering wrong (You plugged the coils into the wrong physical ports) then there is no way to catch that error. You'll get a dev_head_t that is incorrect.
| input_fname = fname + '.bin' | ||
| elif ext != '.bin': | ||
| raise RuntimeError('Valid artemis123 files must end in \'txt\'' + | ||
| ' or \'.bin\'.') |
There was a problem hiding this comment.
we usually use double-quotes within strings to avoid these escape characters
|
|
||
| hpi = [nas, rpa, lpa] | ||
| self.info['dig'] = _make_dig_points(nasion=nas, lpa=lpa, | ||
| rpa=rpa, hpi=hpi) |
There was a problem hiding this comment.
This branching seems too extensive. Can't you do:
if pos_fname is None:
logger.info('Assuming ...')
...
info['dig'] = ...
...
and then have the localization parts (computing info['hpi_results']) conserved?
| if points_: | ||
| return np.array([points_[i]['r'] for i in FIDUCIAL_ORDER]) | ||
| else: | ||
| return np.array([]) |
| If True attempt to perform initial head localization (compute initial | ||
| evice to head coordinate transform) using HPI coils. If no | ||
| HPI coils are in info['dig'] hpi coils are assumed to be in canonical | ||
| order of fiducial points (nas, rpa, lpa). |
There was a problem hiding this comment.
I think leaving it as head_loc makes sense. it is performing HPI localization and then setting info['dev_head_t], add_trans while technically correct isn't really meaningful.
But head_loc will not convey the meaning of what is going on. This could mean continuous head localization, etc. And even worse, loc is an entry in info['chs'][ii].
How about head_trans, add_head_trans, add_trans, or compute_trans?
If less then 3 chpi coils are on it doesn't issues a warning and sets the dev_head_t to identity.
In this case it should set it to None actually. It's possible (even if unlikely) to get identity in real data, None is used by MNE to mean "could not be computed" which is appropriate here.
If you don't supply and digitization points and also get the ordering wrong (You plugged the coils into the wrong physical ports) then there is no way to catch that error.
I thought in your code you had it do all permutations of coil orderings, so it should still work in this case, no?
There was a problem hiding this comment.
add_head_trans it is.
In this case it should set it to None actually. It's possible (even if unlikely) to get identity in real data, None is used by MNE to mean "could not be computed" which is appropriate here.
dev_head_t is set to identity in https://github.com/mne-tools/mne-python/blob/master/mne/io/meas_info.py#L1538. If the desired default/unset behavior is None I would think the change should happen there. I also don;t have an issue the head cords and device cords being the same space (identity transform). I imagine having dev_head_t=None may break things that I would like to work even when no coils are being used. Such as plotting the sensor locations or doing dipole fits in phantoms etc.
I thought in your code you had it do all permutations of coil orderings
That only happens if there are independent measures of the hpi locations (ie from the digitization). without that i can only assume a mapping from hpis to fiducials etc.
There was a problem hiding this comment.
Once you make a decision about head_dev_t=None I can push the change to add_head_trans
There was a problem hiding this comment.
It should probably be None but let's save it for another PR, since it's in _empty_info I agree we'd need to change it there (and see what the problems would be).
|
Good to go from your end, then? |
|
Yeah I think so. |
|
+1 for merge from me |
| 5. Use a linear model (DC + linear slope + sin + cos terms set up | ||
| in ``_setup_hpi_struct``) to fit sinusoidal amplitudes to MEG | ||
| channels. Use SVD to determine the phase/amplitude of the sinusoids. | ||
| This step is accomplished using using ``_fit_cHPI_amplitudes`` |
| raw : instance of Raw | ||
| Raw data with cHPI information. | ||
| t_win : list, shape (2) | ||
| Time window to fit. If None entire data run is used. |
There was a problem hiding this comment.
I suppose this is ndarray, shape (n_CHPI, 3) | None
| return loc | ||
|
|
||
|
|
||
| def _read_pos(fname): |
There was a problem hiding this comment.
This looks a lot like _read_pos from mne/io/ctf/eeg.py. Can you check if you can reuse some part of the code and maybe move the reused part to mne/io/utils?
There was a problem hiding this comment.
You are correct that both of these methods read in files generated by the same digitization program (written by CTF). The issue is that I don't think the behavior of _read_pos in mne/io/ctf/eeg.py is correct.
For instance the transform used to move the digitization points to head space is computed using the fid locations computed for the MEG HPIs not their polhemous coordinates. Also the coord_frame of the locations (FIFFV_MNE_COORD_CTF_HEAD) isn't correct once the transformation transformations['t_ctf_head_head'] is applied.
That stuff I could make backward compatible but the ident coding (https://github.com/mne-tools/mne-python/blob/master/mne/io/ctf/eeg.py#L83-L87) is harder to maintain and also doesn't make a whole lot of sense.
Assuming there Is there still a refactoring of the dig structure planned, my vote would be to leave the code as is and to add both methods to the list of things that need to be rethought and refactored. as part of that refactoring effort.
There was a problem hiding this comment.
@bloyl I think that so far the Digitization refactoring plans would be mostly independent of these CTF issues. Can you open a new issue for these potential problems? We'll probably need to discuss them a bit (perhaps with Matti, too) and sort them out. Then we can unify here and in the CTF code.
There was a problem hiding this comment.
Ill can do that to itemize the ctf issues, but maybe not for a few days.
Although I do think that a refactored digitization class or structure should provide a way to read in digitized points from a file that supports the various use cases (including these two). and that might be the best time to think though these issues in the abstract. It is also a time where breaking backward comparability might be more understandable/palatable
| raise RuntimeError(mesg % (len(hpi_head), | ||
| len(hpi_dev))) | ||
|
|
||
| # compute initial head to dev transfor and hpi ordering |
|
@jaeilepp that plan okay with you? If so I'll merge once the CIs are happy. |
|
Yeah, that's good for me. |
|
thanks @bloyl 🍻 |
This is an initial stage to get artemis data into a form that can be used with existing cHPI code. Essentially it provides some methods to do basic HPI fitting without digitization or initialization (coming from the scanner).
Next steps are to generate HPI_results structures to facilitate cHPI in a manner similar to what is being used for elekta data and provide better support for edge cases (multiple HPIs, no digitization, in non canonical ordering etc)