Repository navigation
[MRG+2] Dipole plotter. - #3966
Conversation
|
|
||
| import numpy as np | ||
| from scipy import linalg | ||
| import nibabel as nib |
There was a problem hiding this comment.
this will make it a hard dependency ...
|
Script for testing: It would be nice to compare this to some other plotter. I tried it against |
|
The name should be more descriptive and include some subset of Did you think about and/or try using
Because you want to check locations? What I would do is pick an MRI voxel in Looks like a great start on #2995. I assume you examined the other options outlined there and decided this was better? Yours looks better to me so far. |
| return view_to_disp_mat | ||
|
|
||
|
|
||
| def plot_dipole_3d(dipole, trans, subject, subjects_dir=None, scale_factor=1e9, |
There was a problem hiding this comment.
trans=None default (i.e., use identity), make subject second argument
There was a problem hiding this comment.
Is that safe? Does someone really want to plot the dipoles without applying the transformation?
There was a problem hiding this comment.
It is done this way in (at least) fit_dipole and plot_trans
| def plot_dipole_3d(dipole, trans, subject, subjects_dir=None, scale_factor=1e9, | ||
| block=False, show=True): | ||
| """Plot dipoles in 3-D. Browse through the dipoles using mouse scroll or | ||
| up/down arrows. |
There was a problem hiding this comment.
single line. More descriptive first line involving "mri", "slices", and/or "orthoview"; put interactivity instructions in separate paragraph
|
|
||
| Parameters | ||
| ---------- | ||
| dipole : instance of mne.Dipole |
| SUBJECT. | ||
| subjects_dir : None | str | ||
| The path to the freesurfer subjects reconstructions. It corresponds to | ||
| Freesurfer environment variable SUBJECTS_DIR. The default is None. |
There was a problem hiding this comment.
subjects_dir is usually toward the end, especially since many people don't need to explicitly set this (it's part of the env vars or config vars)
| The path to the freesurfer subjects reconstructions. It corresponds to | ||
| Freesurfer environment variable SUBJECTS_DIR. The default is None. | ||
| scale_factor : float | ||
| The scaling applied to convert amplitudes to voxel sizes for the plot. |
There was a problem hiding this comment.
To physical units (m), you mean? Voxels could/should be shown in mm. You might need to use the affine to get there
There was a problem hiding this comment.
No, that's the scale factor for the amplitude. i.e. the length of the arrow. I'll update the docstring.
| try: | ||
| import nibabel as nib | ||
| except ImportError: | ||
| raise |
| np.linspace(0, dims, dims)) | ||
|
|
||
| fig = plt.figure() | ||
| ax = fig.add_subplot(111, projection='3d') |
There was a problem hiding this comment.
does fig, ax = plt.subplots(1, projection='3d') work?
| fig = plt.figure() | ||
| ax = fig.add_subplot(111, projection='3d') | ||
|
|
||
| trans = _get_trans(trans, fro='head', to='mri')[0] |
There was a problem hiding this comment.
If possible there should be a coord_frame argument. It's might actually be most natural to plot these in head coords
| ax.contourf(gridx, gridy, data[:, yidx][::-1].T, offset=0, zdir='z', | ||
| cmap='gray', zorder=0, alpha=0.5) | ||
| ax.contourf(gridx, data[:, :, zidx][::-1].T[::-1], gridy, offset=0, | ||
| zdir='y', cmap='gray', zorder=0, alpha=0.5) |
There was a problem hiding this comment.
Being able to use a different coordinate frame will be a bit of a pain, but hopefully not too bad. Basically you want to do 3D linear interpolation to choose plane slices through the MRI to show, as opposed to just taking NumPy slices of the 3D array. When in MRI coords you should see that your chosen plane collapses to just use the interpolation grid anyway, so it's a more general way to formulate this.
Not sure if there is a simpler way...
There was a problem hiding this comment.
So the idea is to take endpoints of the plane and then transform these to form the plane in mri space and then pick the points from the mri image for plotting? Sounds like a lot of work and computation. I'm not sure it's worth the effort, unless you have a clear idea how to do it efficiently.
There was a problem hiding this comment.
So the idea is to take endpoints of the plane
No, nothing about endpoints specifically.
Think about it this way. What coordinate frame is the data currently plotted in? Let's say I want to plot it in the head coordinate frame (which perhaps should be the default). How would we do it?
One way is with LinearNDInterpolator from SciPy. That way we can take slices through our regularly spaced 3D grid (i.e., MRI) in the X/Y/Z directions of the head coordinate frame instead of the only current option, which is taking slices (via NumPy) in the X/Y/Z directions of the MRI coordinate frame.
It's also possible/likely that nibabel actually gives you a way to apply an affine transformation to the MRI -- that would be even easier. In this scheme, you'd just apply the inverse of the head_mri_t to the MRI, and then your current NumPy slices would work.
Make sense?
There was a problem hiding this comment.
It could be as easy as using nibabel.processing.resample_from_to, with the affine being our mri_head_t['trans']. Then you can just take ndarray slices of the resulting resampled image, instead of the original.
| fig.canvas.key_press_event('up') | ||
| fig.canvas.key_press_event('down') | ||
| fig.canvas.key_press_event('a') # some other key | ||
| matplotlib.pyplot.close('all') |
There was a problem hiding this comment.
This is unsafe. Doing import matplotlib doesn't automatically import the matplotlib.pyplot namespace. This will only work if we have by chance done import matplotilb.pyplot elsewhere, so you should explicitly import it here (as we always do) to be safe
Yeah, that could be done. Also, the crosshair plot could be quite easily be implemented with this. So perhaps a second mode for this plotter. |
|
Maybe I'll leave the crosshair mode to another PR too (if we want it). Mpl does not seem to handle intersecting planes too well, so each segment would have to be plotted separately. |
| Freesurfer environment variable SUBJECTS_DIR. The default is None. | ||
| scale_factor : float | ||
| The scaling applied to convert amplitudes to vector (arrow) lengths for | ||
| the plot. Defaults to 1e9. |
There was a problem hiding this comment.
I know it's the scale factor for the amplitude, that was clear enough already. What isn't clear is the units. I think it should say something like "... to convert from amplitude in Am to arrow length in mm, e.g., 1e9 (default) makes a 10 nAm dipole appear with a length of 10 mm in the plot" (if this is indeed what the conversion factor is)
There was a problem hiding this comment.
... And while we're at it, I'd make it the factor to convert from nAm to mm. It's probably the most natural choice for dipole data
| ax.contourf(gridx, gridy, data[:, yidx][::-1].T, offset=0, zdir='z', | ||
| cmap='gray', zorder=0, alpha=0.5) | ||
| ax.contourf(gridx, data[:, :, zidx][::-1].T[::-1], gridy, offset=0, | ||
| zdir='y', cmap='gray', zorder=0, alpha=0.5) |
There was a problem hiding this comment.
So the idea is to take endpoints of the plane
No, nothing about endpoints specifically.
Think about it this way. What coordinate frame is the data currently plotted in? Let's say I want to plot it in the head coordinate frame (which perhaps should be the default). How would we do it?
One way is with LinearNDInterpolator from SciPy. That way we can take slices through our regularly spaced 3D grid (i.e., MRI) in the X/Y/Z directions of the head coordinate frame instead of the only current option, which is taking slices (via NumPy) in the X/Y/Z directions of the MRI coordinate frame.
It's also possible/likely that nibabel actually gives you a way to apply an affine transformation to the MRI -- that would be even easier. In this scheme, you'd just apply the inverse of the head_mri_t to the MRI, and then your current NumPy slices would work.
Make sense?
|
Also, it would be cool if it were possible to choose between plotting the images at the outer axis limits (as it's done now) versus as a "crosshair" centered at the dipole location. I've seen plotters do the latter, too. That can be a follow-up PR, but any idea if it's possible with matplotlib 3D? |
Hmm... this would be pretty surprising, since Here is a complete (copy-paste runnable) version of your example, equivalently called using with It's possible/likely we might need to take into account the existing affine in our transformation. Let's try passing the current Original and resampled match here: In other words, the resampling function needs to to be supplied a final/destination NIfTI affine. So unfortunately we'll need to look through http://nipy.org/nibabel/nifti_images.html#the-nifti-affines to sort this out. Coming back to our problem, Let's get some handle on what the result should look like: So the We can at least get something like this with a first-pass solution:
One example reason we need to think about these things is that although many MRIs are sampled on a 1mm grid, they aren't all sampled that way. So we should probably always resample to a 1mm grid to be safe. And we might also want to resample so that our The problem is that, even with this transform, we're talking about RAS space, but I think we need Freesurfer RAS, which comes from In any case, this stuff is annoying to work through, but to properly plot the MRI slices alongside data from MRI or head coordinate frames, I think we need to get through it, assuming we want our X/Y/Z axis labels to be correct in terms of the 0, 0, 0 being at the center of the MRI or head coordinate system. |
50bdf1c to
0f5add2
Compare
|
This is ready for review. |
larsoner
left a comment
There was a problem hiding this comment.
Otherwise LGTM.
Also, have you verified the locations? I think i had suggested using FreeView to select some voxel (which gives you both the voxel index and RAS coordinates) and making sure your plotter shows it in the correct location?
It might also be worth selecting a point that we know is on the cortical surface, and cross-checking the surf['rr'] value to see if it corresponds to the vox2ras or vox2ras_tkr one. I think it'll be the latter...
| from .viz import plot_dipole_amplitudes | ||
| return plot_dipole_amplitudes([self], [color], show) | ||
|
|
||
| def plot_mri_orthoview(self, trans, subject, subjects_dir=None, |
There was a problem hiding this comment.
can you use the docstring-copying decorator?
| Freesurfer environment variable SUBJECTS_DIR. If None (default), | ||
| SUBJECTS_DIR is read from environment or config file. | ||
| scale_factor : float | ||
| The scaling applied to convert amplitudes to vector (arrow) lengths for |
There was a problem hiding this comment.
Need to mention units first. "... to convert dipole amplitudes (Am) to arrow lengths (mm) for the plot. Default is 1e9, i.e. 1 nAm becomes 1 mm."
There was a problem hiding this comment.
is this really necessary? I think it's hard anyway to evaluate dipole strength based on the length of such a tiny arrow.
There was a problem hiding this comment.
also you can have dipoles of amplitude 100 nAm and some of 5 nAm so a bit amplitude variation
| affine_to = trans['trans'].copy() | ||
| affine_to[:3, 3] *= 1000 # to mm | ||
| affine_to = np.dot(affine_to, t1.affine) | ||
| t1 = resample_from_to(t1, (t1.get_shape(), affine_to)) |
There was a problem hiding this comment.
I think we might always need to resample, otherwise we aren't guaranteed that the units are correct -- MRIs don't have to be sampled in 1mm x 1mm x 1mm voxels...
Did you look into the difference between get_vox2ras and get_vox2ras_tkr? The latter is used in our setup_volume_source_space code so I suspect we'll need to use it.
There was a problem hiding this comment.
Is there some documentation on the difference?
|
I've never been able to get freeview working on my computer. I suppose there's some conflicts with the graphics card. |
| return view_to_disp_mat | ||
|
|
||
|
|
||
| def plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None, |
There was a problem hiding this comment.
could we fuse this with plot_locations or maybe replace it?
| return view_to_disp_mat | ||
|
|
||
|
|
||
| def plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None, |
There was a problem hiding this comment.
also how do you specify what dipole you plot? it seems you only plot the first one.
There was a problem hiding this comment.
OK I see that I can use interactions to see all dipoles but I am thinking this is a surprising as a default. I would expect to see all dipoles by default. Can we have an interactive=True | False param?
|
I'm not sure what the freeview figure is supposed to show, but looking at the code of |
Codecov Report
@@ Coverage Diff @@
## master #3966 +/- ##
==========================================
- Coverage 86.12% 77.64% -8.48%
==========================================
Files 350 350
Lines 63137 63294 +157
Branches 9629 9651 +22
==========================================
- Hits 54375 49143 -5232
- Misses 6085 11606 +5521
+ Partials 2677 2545 -132Continue to review full report at Codecov.
|
|
For starters, it gives you the coordinate of vertex 0 (as does the surface
read directly). It also shows you where it should appear in the MRI. Does
your code put it in the correct place?
|
|
I still think that the approach here isn't ideal. The X/Y/Z axes are in currently voxels (right?), which is not as useful as them being in the standard coordinate frames we deal with, namely Also, the isoline approach here is a little bit abnormal/unexpected. I'd make that an option, and make the default to be a standard MRI viz. |
|
...also, maybe the title should have a second line, which is the dipole coordinates in the given (head or MRI) coordinate frame in mm (like |
33f636b to
6f428af
Compare
| ori = dipole.ori | ||
| dd = (dims / 2.) / 1000. | ||
| gridx, gridy = np.meshgrid(np.linspace(-dd, dd, dims), | ||
| np.linspace(-dd, dd, dims)) |
There was a problem hiding this comment.
Why does the grid depend on the coordinate frame? Can this be unified so that no matter what coordinate frame we're in we can use the same lines here? It might require e.g. just providing dims for the non-head case
There was a problem hiding this comment.
I'm not sure I understand the question. Doesn't it depend on the coordinate frame by definition (eg. -0.1 - 0.1 vs. 0 - 256)?
There was a problem hiding this comment.
Doesn't it depend on the coordinate frame by definition (eg. -0.1 - 0.1 vs. 0 - 256)?
The center of the "head coordinate frame" and the "MRI coordinate frame" are both very close to one another:
python -c "import mne; print(mne.read_trans('mne_data/MNE-sample-data/MEG/sample/sample_audvis_raw-trans.fif'))"
<Transform | head->MRI (surface RAS)>
[[ 0.99930954 0.01275934 0.0348942 0.00206991]
[ 0.00998479 0.81240475 -0.58300853 0.01130214]
[-0.03578702 0.58295429 0.81171638 -0.02755522]
[ 0. 0. 0. 1. ]]
So either way the bounds should be very similar, e.g. (-0.1, 0.1).
You're probably thinking of the "MRI voxel coordinate frame", which is not the same as the "MRI coordinate frame". See my old image of FreeView -- the MRI coords (tkr) are centered toward the middle, so something like (-0.1, 0.1) should also work as bounds when plotting in that coordinate frame.
There was a problem hiding this comment.
I'm wondering if there's any sense having the mri space as an option then. The only difference would be having the interpolated slices in head space.
|
if you have dipoles in MNI space and you have the MNI MRI template would
that work?
|
|
It is useful to be able to switch between coordinate frames, including both
head and MRI. We do it in plot_trans. Eventually we might even want to add
the MEG device coordinate frame. So generalizing treatment of coordinate
frame now is both future compatible and helps ensure we're slicing
everything properly.
|
|
ok for me then :)
|
b49fd83 to
fb7347b
Compare
e1502cd to
e93adad
Compare
| """ | ||
| import matplotlib.pyplot as plt | ||
| from mpl_toolkits.mplot3d import Axes3D | ||
| from .. import Dipole |
There was a problem hiding this comment.
This is because from ..dipole import Dipole (as opposed to from .. import Dipole) at the top creates a circular import?
| Parameters | ||
| ---------- | ||
| dipole : instance of mne.Dipole | ||
| The dipole to plot. |
There was a problem hiding this comment.
I would actually probably get rid of this docstring since these are all documented above.
But if you want to keep them, this is now out of date (can also be list)
| else: | ||
| dipole_locs = np.array([apply_trans(trans['trans'], loc) for loc | ||
| in dipole.pos]) | ||
| ori = [apply_trans(trans['trans'], o) for o in dipole.ori] |
There was a problem hiding this comment.
this needs a move=False in apply_trans
| scatter_points = dipole.pos * 1e3 | ||
| else: | ||
| dipole_locs = np.array([apply_trans(trans['trans'], loc) for loc | ||
| in dipole.pos]) |
There was a problem hiding this comment.
You shouldn't need to iterate over loc, apply_trans handles arrays. You might need a couple of transposes, can't remember
| dipole_locs = np.array([apply_trans(trans['trans'], loc) for loc | ||
| in dipole.pos]) | ||
| ori = [apply_trans(trans['trans'], o) for o in dipole.ori] | ||
| # Position in meters -> voxels. |
There was a problem hiding this comment.
you shouldn't ever be in voxels, but always in mm either in one coordinate frame or the other...?
|
@jaeilepp I give you my +1 once you addressed @Eric89GXL 's comments |
|
Just minor style stuff from Travis: |
|
... and this looks great: +1 for merge once the minor style things are fixed. Thanks for going through so many iterations with me @jaeilepp! |










Dipole plotter using mpl 3D.
