Skip to content

ENH: Add GIfTI output for STC #9286

Description

@pmolfese

Wanted to get thoughts from others who may find this feature useful, and insights into possible straightforward ways to implement.

Describe the new feature or enhancement

In an effort to compare/overlay results in fMRI and EEG/MEG, several of us are seeking an easy way to export MNE source results to GIFTI (and potentially NIFTI in the future). GIFTI would allow other programs (e.g. AFNI, Freesurfer) to then work with source-space data in useful ways (e.g. constrain solutions based on fMRI, make pretty pictures).

Describe your proposed implementation

Add options to mne.SourceSpaces.save( ) or better - a new method .export( ) to allow the export of GIFTI images. For added convenience, with option for hemisphere, time-window of interest, and overwrite. Wrapper for nibabel's GIFTI implementation with nuances for writing the relevant data in.

https://nipy.org/nibabel/reference/nibabel.gifti.html

Additional comments

This would be decently useful for folks trying to do EEG-fMRI simultaneous, MEG & fMRI joint analysis, or anyone interested in taking the source estimates from MNE into other softwares (FieldTrip and BrainStorm both have GIFTI imports).

Activity

  1. welcome commented on Apr 12, 2021

    @welcome

    Hello! 👋 Thanks for opening your first issue here! ❤️ We will try to get back to you soon. 🚴🏽‍♂️

  2. agramfort commented on Apr 13, 2021

    @agramfort
    SponsorMember
  3. jhouck commented on May 10, 2021

    @jhouck
    Contributor

    This would be great. Currently using an amalgamation of MNE-C, Freesurfer, and AFNI to get surface estimates into .nii files.

  4. pmolfese commented on Oct 14, 2021

    @pmolfese
    ContributorAuthor

    Hello again. @jbteves and I finally have some bandwidth to work more on this.

    @agramfort & @larsoner, can you direct us to where the subsampling of the surfaces happens?

    Also @jhouck - can you point us to your code that does work-arounds?

  5. larsoner commented on Oct 14, 2021

    @larsoner
    Member

    @pmolfese I think we're planning on working this into nibabel first, see discussions and hopefully join them (next meeting is a week from tomorrow IIRC!) -- it would be nice not to duplicate efforts here:

    https://nipy.discourse.group/t/collecting-use-cases/58
    https://nipy.discourse.group/t/surface-api-follow-up-meetings/79/9
    nipy/nibabel#1056

    But to answer your question, the subsampling is here (and associated helper functions), it's not the easiest code to read:

    mne-python/mne/surface.py

    Lines 942 to 993 in 022f1a8

    def _create_surf_spacing(surf, hemi, subject, stype, ico_surf, subjects_dir):
    """Load a surf and use the subdivided icosahedron to get points."""
    # Based on load_source_space_surf_spacing() in load_source_space.c
    surf = read_surface(surf, return_dict=True)[-1]
    do_neighbor_vert = (stype == 'spacing')
    complete_surface_info(surf, do_neighbor_vert, copy=False)
    if stype == 'all':
    surf['inuse'] = np.ones(surf['np'], int)
    surf['use_tris'] = None
    elif stype == 'spacing':
    _decimate_surface_spacing(surf, ico_surf)
    surf['use_tris'] = None
    del surf['neighbor_vert']
    else: # ico or oct
    # ## from mne_ico_downsample.c ## #
    surf_name = op.join(subjects_dir, subject, 'surf', hemi + '.sphere')
    logger.info('Loading geometry from %s...' % surf_name)
    from_surf = read_surface(surf_name, return_dict=True)[-1]
    _normalize_vectors(from_surf['rr'])
    if from_surf['np'] != surf['np']:
    raise RuntimeError('Mismatch between number of surface vertices, '
    'possible parcellation error?')
    _normalize_vectors(ico_surf['rr'])
    # Make the maps
    mmap = _compute_nearest(from_surf['rr'], ico_surf['rr'])
    nmap = len(mmap)
    surf['inuse'] = np.zeros(surf['np'], int)
    for k in range(nmap):
    if surf['inuse'][mmap[k]]:
    # Try the nearest neighbors
    neigh = _get_surf_neighbors(surf, mmap[k])
    was = mmap[k]
    inds = np.where(np.logical_not(surf['inuse'][neigh]))[0]
    if len(inds) == 0:
    raise RuntimeError('Could not find neighbor for vertex '
    '%d / %d' % (k, nmap))
    else:
    mmap[k] = neigh[inds[-1]]
    logger.info(' Source space vertex moved from %d to %d '
    'because of double occupation', was, mmap[k])
    elif mmap[k] < 0 or mmap[k] > surf['np']:
    raise RuntimeError('Map number out of range (%d), this is '
    'probably due to inconsistent surfaces. '
    'Parts of the FreeSurfer reconstruction '
    'need to be redone.' % mmap[k])
    surf['inuse'][mmap[k]] = True
    logger.info('Setting up the triangulation for the decimated '
    'surface...')
    surf['use_tris'] = np.array([mmap[ist] for ist in ico_surf['tris']],
    np.int32)

  6. jbteves commented on Oct 15, 2021

    @jbteves
    Contributor

    I'm interesting in joining these discussions, how might I join? I see a standing zoom room in your second link, should I simply join at the appropriate time?

  7. larsoner commented on Oct 15, 2021

    @larsoner
    Member

    @jbteves it would be good to drop a comment in https://nipy.discourse.group/t/surface-api-follow-up-meetings/79/9 to mention your interest just so that other folks know you're coming

  8. jhouck commented on Nov 2, 2021

    @jhouck
    Contributor

    @pmolfese the code is not the best. It relies on the fact that a .stc file is basically a set of concatenated Freesurfer paint (.w) files. With the old MNE-C (2.7.4, ca. 2016), I was using mne_make_movie to extract the surface at the time of interest and export it to a .w file, then freesurfer's mri_surf2vol to convert the .w file to a nifti file. For gifti I think you could use mri_surf2surf. To avoid the old code you can set ftype=w when you save the SourceEstimate in mne-python.

  9. rob-luke commented on Nov 3, 2021

    @rob-luke
    Member

    I will add my name to the linked discussion point too. For MNE-nirs I want to move to source reconstruction next and was planning to integrate tightly with nilearn.

  10. rob-luke commented on Nov 3, 2021

    @rob-luke
    Member

    @pmolfese why did you prefer to export as GIFTI? I am just curious as Im new to this topic. Some of the fNIRS software exports as NIFTI, and wondered if there was a specific reason for choosing between the two?

  11. pmolfese commented on Nov 3, 2021

    @pmolfese
    ContributorAuthor

    @rob-luke - GIFTI mostly comfort in handling source data from other software. There are programs for converting between NIFTI and GIFTI for sure. I suspect ultimately both would be useful.

  12. larsoner commented on Jan 18, 2022

    @larsoner
    Member

    @jbteves you pinged me with an email for a status update here -- so far there has been some progress at the nibabel end. I think our plan is basically to wait for nibabel to make SurfaceImage available, then allow something like stc.as_gifti or something to export a SurfaceImage class from our SourceEstimate class in MNE. (Or maybe someday SourceEstimate can be a wrapper for SurfaceImage -- but that would be more work.) In any case, I think any Gifti export would hopefully come from going STC->SurfaceImage (implemented at the MNE end) then SurfaceImage->Gifti (implemented at the nibabel end).

    So I think at this point the bottleneck is at the nibabel end, maybe there is some way you could help their effort?

    https://nipy.discourse.group/t/preliminary-notes-on-surface-representations/57
    https://nipy.discourse.group/t/surface-api-follow-up-meetings/79
    nipy/nibabel#1056

    Looks like the next meeting is scheduled for 9AM EST Jan 28th if you want to join and discuss!

  13. jbteves commented on Jan 18, 2022

    @jbteves
    Contributor

    Alright, thanks for letting me know!

  14. 8 remaining items

  15. jbteves commented on Mar 7, 2022

    @jbteves
    Contributor

    Opened #10421 for you to take a look.

  16. jbteves commented on Mar 9, 2022

    @jbteves
    Contributor

    Should this be reopened? I think we're still missing the "write to gifti" part.

  17. larsoner commented on Mar 9, 2022

    @larsoner
    Member

    I think the "partially addresses #XYZ" was misread by GitHub, agreed we should reopen

  18. jbteves commented on Mar 9, 2022

    @jbteves
    Contributor

    Thanks! For the GIFTI part should I add another function, or are we wanting to wait for the surface API changes?

  19. larsoner commented on Mar 9, 2022

    @larsoner
    Member

    I think we want nibabel to do the heavy lifting on that, so we'll need to wait at the MNE end for them to have GIFTI export.

    One idea of a backward and forward compatible way for us to get this very easily would be to make BaseSourceEstimate a subclass of nibabel's surface API class. If this works it might be a nice way to transition

  20. pmolfese commented on Jun 14, 2023

    @pmolfese
    ContributorAuthor

    Wondering if we can revisit this since it's been over a year. Trying to make sure perfect doesn't stand in the way of progress.

    We have a working prototype in our specific use cases that may need to be broadened a bit: https://github.com/nimh-cmn/stc2gii_hack

  21. larsoner commented on Jun 14, 2023

    @larsoner
    Member

    Agreed I think the nibabel stuff has stalled (?) and in theory as long as we set the API up decently enough we're future compatible with using their code anyway. So +1 for adding a new method stc.export_gifti(fname, subject=None, subjects_dir=None) to the SourceEstimate class. Then maybe we want a mne.source_estimate.read_gifti(fname, subject=None) or so? That way you could do round-trip testing that a save-load round-trip of the Gifti you get the same data, vertices, etc. (or as much information as you can).

    Feel free to open a PR to integrate the "hack" (nice name 😄 ) code into MNE

  22. pmolfese commented on Jun 14, 2023

    @pmolfese
    ContributorAuthor

    Thanks @larsoner! We'll also need a method to save the decimated surface as GIFTI. Any preferences on a name (and namespace) for that?

  23. larsoner commented on Jun 14, 2023

    @larsoner
    Member

    Maybe if you pass fname='something.gii' we should automatically create 'something-lh.gii' for the decimated left surf and 'something-rh.gii' with the decimated right hemi surf. Would that be a reasonable workflow? If not feel free to propose something that would work better / make more sense -- the use case isn't totally clear to me, I've never used or thought much about gifti and what it can/can't do as a format...

  24. pmolfese commented on Jun 14, 2023

    @pmolfese
    ContributorAuthor

    Ah sorry I'm not typing clear enough even for me!

    In Gifti (I believe) there's the geometry surface file that has the shape, and then we overlay the functional data on top of it. These correspond in MNE terms Source Space and STC, respectfully. That functional data (STC here) doesn't have shape, just the nodes that those time data map onto the geometry. For the STCs, I agree with stc.export_gifti( ) for the saving the functional data.

    But for the downsampled surfaces / geometry I think we'll need to add a case to mne.write_source_spaces( ) as well. Like a format = where folks can specify either FIF or GIFTI. Can attempt to get the mne.read_source_space to also read these downsampled surfaces eventually as well.

  25. larsoner commented on Jun 15, 2023

    @larsoner
    Member

    For the STCs, I agree with stc.export_gifti( ) for the saving the functional data.

    But for the downsampled surfaces / geometry I think we'll need to add a case to mne.write_source_spaces( ) as well.

    Or perhaps a cleaner API would be:

    stc.export_gifti(fname, src=fwd['src'])
    

    i.e., require the user to pass a fname filename and the src source space that was used in creating the STC. (There's plenty of precedent for this in viz and morphing functions so I don't think it's too onerous.) And then export_gifti can just write out whatever file(s) with whatever information is needed to actually use with some downstream gifti tool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions