Skip to content

computing forward model using EEG electrode coords MRI voxel space? #3877

Closed

Description

@russellu

hey, so i'm working through this tutorial here:
http://martinos.org/mne/stable/auto_tutorials/plot_forward.html#sphx-glr-auto-tutorials-plot-forward-py

about the head model and forward computation, but i'm having trouble getting my EEG electrodes in a form that MNE can recognize.
right now, i have electrode locations as freesurfer voxel coordinates (in the 256x256x256 freesurfer volume).
electrode_scalp

i'm wondering if there is a way to bypass all the fiducial/digitization stuff, since i already have the electrode locations in MRI space (the data is from simultaneous EEG-FMRI experiments, so we were able to image the EEG cap in the scanner and consequently the electrodes are already aligned to the T1.

Activity

  1. christianbrodbeck commented on Dec 29, 2016

    @christianbrodbeck
    Member

    Since all coordinates have RAS representations (http://martinos.org/mne/stable/manual/source_localization/forward.html#meg-eeg-and-mri-coordinate-systems) I think the straight forward solution would be to create and use an identity transform, which should be pretty quick (http://martinos.org/mne/stable/generated/mne.Transform.html). MNE uses [m], is the FreeSurfer coordinate frame in [m] or in [mm]? That would have to be taken into account.

    In principle each coordinate is accompanied by a variable indicating which coordinate frame it's in, but I am not sure if all functions would support having non-standard coordinate frames, i.e. adding channels with coordinates in the MRI coordinate frame.

    In [6]: epochs.info['chs'][0]
    Out[6]: 
    {'cal': 3.1600000394149674e-09,
     'ch_name': u'MEG 0113',
     'coil_type': 3012,
     'coord_frame': 1,  # <--
     'kind': 1,
     'loc': array([-0.1066    ,  0.0464    , -0.0604    , -0.0127    ,  0.0057    ,
            -0.99990302, -0.186801  , -0.98240298, -0.0033    , -0.98232698,
             0.18674099,  0.013541  ]),
     'logno': 113,
     'range': 0.00030517578125,
     'scanno': 1,
     'unit': 201,
     'unit_mul': 0}
  2. russellu commented on Dec 29, 2016

    @russellu
    Author

    i see...so you're saying i should just manually change the coordinate frame variable in my epochs.info, so that it is set to freesurfer RAS?

  3. christianbrodbeck commented on Dec 29, 2016

    @christianbrodbeck
    Member

    Actually I meant to suggest that you use standard coordinate frames, but you could leave the sensor coordinates unchanged, so that you can use identity matrices as transform matrices between coordinate frames (taking into account unit conversion). I don't think having a non-standard origin/orientation (e.g. Neuromag space but not having the origin between the ears) of the sensor positions will affect much (although it is possible that you might get unexpected results from plots that expect a certain orientation).

    I don't know if all functions are built to support objects with coordinates in non-standard coordinate frames, so I would not suggest doing that without checking the functions, but someone else might know more.

  4. larsoner commented on Dec 29, 2016

    @larsoner
    Member
  5. larsoner commented on Dec 29, 2016

    @larsoner
    Member

    Okay on a real computer so I can answer more fully.

    i'm wondering if there is a way to bypass all the fiducial/digitization stuff, since i already have the electrode locations in MRI space

    Yes you can but some things will not work so well. The difference between what is required to do it properly vs. incompletely is mostly just getting the MRI voxels for LPA/RPA/Nasion.

    The best procedure would be something like:

    1. Get eeg channel locations in MRI voxels.
    2. Get LPA/Nasion/RPA in MRI voxels.
    3. Use nibabel's get_affine or maybe get_vox2ras_tkr (I think the latter) to convert your voxels to mm or m.
    4. Ensure these points are in meters.
    5. Construct a DigMontage with nasion, lpa, rpa, and dig_ch_pos arguments and use convert=True.
    6. Use raw.apply_montage, which should set the dig information that the forward code needs.
    7. Use get_ras_to_neuromag_trans to get the head<->MRI transform matrix.
    8. You probably need to turn that matrix into a proper Transform with trans = mne.Transform('mri', 'head', trans_matrix).
    9. Use plot_trans to see if it all worked correctly.

    If this works, we can make it simpler in a few different ways (e.g., avoiding use of get_ras_to_neuromag_trans). But first let's get it working.

    If you can't or don't want to get the fiducials, you can skip step 2 and instead pass something like lpa=[-0.1, 0, 0], rpa=[0.1, 0, 0], nasion=[0, 0.1, 0] to DigMontage, which should effectively set the head and MRI coordinate frames equal. Then you should also skip steps 7 and 8 and use an identity head<->MRI transform.

  6. russellu commented on Dec 30, 2016

    @russellu
    Author

    thanks for the help. i got up to step 6, but i can't find an apply_montage function, and when i try to set_montage with my DigMontage, it crashes (i'm using the non-fiducial method btw).
    also, what do you mean by use convert=True in 5? i couldn't find any convert option in the doc for that function.

    here is the code:

    import nibabel as nib
    path = '/media/sf_shared/all_subs_freesurfer_segs/sub1_alex/mri/' 
    img=nib.load(path+'T1.mgz') # T1
    vox2ras = img.get_header().get_vox2ras() # transform matrix
    coords = nib.load(path+'coords.nii.gz') # brain with color-coded coords
    coordvol = coords.get_data() 
    
    # mat file with electrode labels corresponding to coords above
    elabs = scipy.io.loadmat('/media/sf_shared/subutes/a2_good/elabs.mat')
    elabs = elabs['elabs'][0]
    
    # find the voxel indices of each coordinate
    allcoords = np.zeros([elabs.shape[0],4])
    for i in np.arange(0,elabs.shape[0]):
        val = i+1 ; # ignore 0 (background)
        ind_i = np.where(coordvol==val)
        allcoords[i,0] = ind_i[0][0]
        allcoords[i,1] = ind_i[1][0]    
        allcoords[i,2] = ind_i[2][0]
        allcoords[i,3] = 1 ; 
        print val
    
    # multiply voxel indices by transformation matrix
    ras_elecs = np.dot(vox2ras,allcoords.T)/1000 # apply RAS transform
    
    # define fids
    lpa=[-0.1, 0, 0]
    rpa=[0.1, 0, 0]
    nasion=[0, 0.1, 0]
    
    # create electrode label - coordinate dictionary
    elec_dic = {} 
    for i in np.arange(0,allcoords.shape[0]):
        elec_dic[str(elabs[i][0])] = ras_elecs[0:2,i]
    
    # create digital montage             
    dig_mont = mne.channels.DigMontage(hsp=[],hpi=[],elp=[],
        point_names=[],nasion=nasion,lpa=lpa,rpa=rpa,dig_ch_pos=elec_dic)
    
    # set montage (no raw.apply_montage was found)
    raw.set_montage(dig_mont)
    
    
    
    here is the error of the set_montage call (i assume its because the coords are 3d?)
    `Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/local/lib/python2.7/dist-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
        execfile(filename, namespace)
      File "/usr/local/lib/python2.7/dist-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
        builtins.execfile(filename, *where)
      File "/home/brain/projects/eegpython/montage.py", line 58, in <module>
        raw.set_montage(dig_mont)
      File "<string>", line 2, in set_montage
      File "/usr/local/lib/python2.7/dist-packages/mne/utils.py", line 708, in verbose
        return function(*args, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/mne/channels/channels.py", line 425, in set_montage
        _set_montage(self.info, montage)
      File "/usr/local/lib/python2.7/dist-packages/mne/channels/montage.py", line 701, in _set_montage
        dig_ch_pos=montage.dig_ch_pos)
      File "/usr/local/lib/python2.7/dist-packages/mne/io/meas_info.py", line 509, in _make_dig_points
        if hpi.shape[1] == 3:
    IndexError: tuple index out of range`
    
  7. jona-sassenhagen commented on Dec 30, 2016

    @jona-sassenhagen
    Contributor

    I think this is also relevant to me. I will see if it works for me.

    @russellu I have updated your comment to make the code look like code :)

  8. russellu commented on Dec 31, 2016

    @russellu
    Author

    hey jona, thanks for fixing my post. did you manage to get it working? i'm still confused over the use of digMontage, i guess i'm supposed to load the montage as a fif (after saving my RAS coordinates as a dig montage fif, not sure how to do this though) because the digMontage function has no 'convert' option...

    also i'm still not able to find an apply_montage function...were you talking about set_montage, Eric?
    thanks

  9. larsoner commented on Dec 31, 2016

    @larsoner
    Member
  10. modified the milestone: on Jan 6, 2017
  11. modified the milestones: 0.15, on Jan 17, 2017
  12. larsoner commented on Jan 17, 2017

    @larsoner
    Member

    @russellu this is on hold a little bit until we take care of #3893 (we'll address this then) probably next month. In the meantime you at least have something that works, right?

  13. russellu commented on Jan 17, 2017

    @russellu
    Author

    Hey Eric, yeah i'm using brainstorm for the moment but i will switch back when you get this handled, thanks!

  14. larsoner commented on May 4, 2017

    @larsoner
    Member

    @russellu just wanted to let you know that @jona-sassenhagen has developed a workflow for this. He will open a PR soon to demo the workflow. Hopefully that will work while we sort out a simpler workflow.

  15. russellu commented on May 4, 2017

    @russellu
    Author

    @Eric89GXL @jona-sassenhagen awesome, thanks! btw are any of you gonna be at ohbm this summer?

  16. agramfort commented on May 5, 2017

    @agramfort
    SponsorMember
  17. jona-sassenhagen commented on May 6, 2017

    @jona-sassenhagen
    Contributor

    @russellu I hope Eric hasn't promised more than I can keep :) I think what I did only concerns 1-4 and 7-8 of Eric's post.

    My situation is that we can identify the fiducials in MRI space, and that is our only coreg info, so we have to get the precise location of the fiducials into MNE. So what I am doing is:

    • identify the points in question on the T1; I use mne_analyze -> load surface -> view MRI, but you can also use freeview; here, you can find the position of the coreg markers in RAS.
    • then, I use this function to create a trans file:
    def _make_trans(subj, fids_ras, subjects_dir=subjects_dir, write=True):
        trans_matrix = mne.transforms.get_ras_to_neuromag_trans(**fids_ras)
        trans = mne.Transform('mri', 'head', trans_matrix)
        if write:
            fname = subjects_dir + "{subj}/{subj}_fid-trans.fif".format(subj=subj)
            mne.write_trans(fname, trans)
        return trans
    

    (where fids_ras is a dictionary with keys rpa, lpa, nasion and values being an array of the RAS coordinates divided by 1000 - get_ras_to_neuromag_trans expects the coordinates in meters, but freesurfer tells them in mm. E.g.:

    {"rpa":np.array([73.0, 6.0, -65.0]) / 1000,
          "lpa":np.array([-65.0, 7.0, -73.0]) / 1000,
          "nasion":np.array([1.0, 105.0, -13.0]) / 1000}
    

    From what I can tell, you've set up the vox2ras transfer correctly btw.
    )

    Then I use this file for my coreg and FWD.

    I'm not sure how much that helps you in your case though!

    The key insight was that it's pretty easy to map something from MRI to head space: freesurfer's Volume RAS ~ Surface RAS, and that you can feed into mne.transforms.get_ras_to_neuromag_trans for a trans matrix.

  18. larsoner commented on May 8, 2017

    @larsoner
    Member

    I mentioned this on Gitter, but I think this could make for a nice little example (and eventually tutorial). You could try to replicate the process with the sample subject, for example.

  19. jona-sassenhagen commented on May 8, 2017

    @jona-sassenhagen
    Contributor

    Yup, I think will try. I'm interested in the average error of this coreg procedure.

  20. removed this from the 0.15 milestone on Aug 4, 2017
  21. self-assigned this
    on Aug 4, 2017
  22. added this to the 0.20 milestone on Sep 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions