Skip to content

ENH: Write source spaces and BEMs to HDF5 #4831

Closed

Description

@d-van-de-velden

Dear mne-python,

I am currently working at the Forschungszentrum Jülich on my master thesis. I perform an spatio-temporal clustering statistical test on volumetric source activities from an MFT calculation.
Therefore I created a volume source space for all the volume labels, which were identified by FreeSurfer. Since I set the volume source space up for all the volume labels in my subject, mne-python encountered a problem, while saving the resulting source-space.fif-file. The common way to create the volume label wise source spaces is to create an entire volume source space for each label and save the significant vertice indices for the label in src['vertno'], while the remaining volume source space is exactly the same for any label and also saved. Since this is done, in my case for ~46 labels, I end up with a large source space file, which is, in the end, not able to be saved by mne-python, as the fif-file is larger than 2GB.
Despite this saving problem, which can be avoided with a work around, I encountered a more sincere problem. Multiple vertices (~3000 out of 17000) are considered to be part of multiple labels, so a large number of vertices is to be considered a vertice in (e.g.) 'Right-Cerebral-White-Matter' as well as 'Right-Cerebral-Cortex'.

This will result in subsequent faults , hence I want to ask for help for a solution, which will create a more suitable volume source space to store as well as referencing each vertice to just one specific label.

Since I am very interested in the solution in detail, I am open for / willing to participate in any discussion.

Yours sincerely,
Daniel van de Velden

P.S.: My work around to get all the labels vertices is looping over all labels, create the whole volume source space, grabbing the src['vertno'] info from it and store it separately in a dictionary. Then I delete the source space and go for the next with the next volume label. After this is done for all labels, I create an entire volume source space without any labels restrictions.

Activity

  1. agramfort commented on Dec 13, 2017

    @agramfort
    SponsorMember
  2. d-van-de-velden commented on Dec 14, 2017

    @d-van-de-velden
    Author

    Of course I can. Sorry I thought I explained it detailed enough. My bad.
    Here you go:

    from mne.datasets import sample
    import mne
    import numpy as np
    
    data_path = sample.data_path()
    subjects_dir = data_path + '/subjects'
    subject = 'sample'
    aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'
    bem_fname = subjects_dir + '/sample/bem/sample-5120-5120-5120-bem-sol.fif'
    grid_space = 5.
    
    volume_labels = mne.get_volume_labels_from_aseg(aseg_fname)
      
    print ' Making Volume Source Space...'
    vsrc = mne.setup_volume_source_space(subject=subject, pos=grid_space,
                                         mri=aseg_fname,
                                         bem=bem_fname, 
                                         volume_label=volume_labels,
                                         subjects_dir=subjects_dir, 
                                         add_interpolator=True,
                                         verbose=None)
    
    volume_source_space_label_dictionary = {}
    for label, vol_src in zip(volume_labels, vsrc):
      vertnos = vol_src['vertno']
      volume_source_space_label_dictionary.update({label:vertnos})
    
    vol_source_space_name = subjects_dir + subject + '/%s_vol-%.4f-src' %(subject, grid_space)
    np.save( vol_source_space_name + '_vertno_labelwise', volume_source_space_label_dictionary)
    mne.write_source_spaces(vol_source_space_name + '.fif', vsrc, overwrite=True)
    
    #vsrc = mne.setup_volume_source_space(subject=subject, pos=grid_space,
    #                                    mri=aseg_fname,
    #                                    bem=bem_fname,
    #                                    subjects_dir=subjects_dir, 
    #                                     add_interpolator=True,
    #                                     verbose=None)
    
    #vol_source_space_name = subjects_dir + subject + '/%s_vol-%.4f-src' %(subject, grid_space)
    #np.save( vol_source_space_name + '_vertno_labelwise', volume_source_space_label_dictionary)
    #mne.write_source_spaces(vol_source_space_name + '.fif', vsrc, overwrite=True)
    

    If you run this code snippet, it will create N numbers of volume source spaces. One for each label. Keeping the whole source space info in every source space, except the src['vertno'] array. This only contains the indices for the vertices, relevant to the chosen volume label. And will be too big to save. A work around is creating a volume source space without volume restrictions but keep the volume_source_space_label_dictionary to keep the information.

    You can also check the volume_source_space_label_dictionary , that many vertices are tend to appear in multiple volume labels.

  3. agramfort commented on Dec 16, 2017

    @agramfort
    SponsorMember

    your script (with tiny changes below) works fine for me:

    from mne.datasets import sample
    import mne
    import numpy as np
    
    data_path = sample.data_path()
    subjects_dir = data_path + '/subjects'
    subject = 'sample'
    aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'
    bem_fname = subjects_dir + '/sample/bem/sample-5120-5120-5120-bem-sol.fif'
    grid_space = 5.
    
    volume_labels = mne.get_volume_labels_from_aseg(aseg_fname)
    
    print(' Making Volume Source Space...')
    vsrc = mne.setup_volume_source_space(subject=subject, pos=grid_space,
                                         mri=aseg_fname,
                                         bem=bem_fname,
                                         volume_label=volume_labels,
                                         subjects_dir=subjects_dir,
                                         add_interpolator=True,
                                         verbose=None)
    
    volume_source_space_label_dictionary = {}
    
    for label, vol_src in zip(volume_labels, vsrc):
        vertnos = vol_src['vertno']
        volume_source_space_label_dictionary.update({label: vertnos})
    
    vsrc = mne.setup_volume_source_space(subject=subject, pos=grid_space,
                                         mri=aseg_fname,
                                         bem=bem_fname,
                                         subjects_dir=subjects_dir,
                                         add_interpolator=True,
                                         verbose=None)
    
    vol_source_space_name = '%s_vol-%.4f-src' % (subject, grid_space)
    mne.write_source_spaces(vol_source_space_name + '.fif', vsrc, overwrite=True)
    
  4. d-van-de-velden commented on Dec 18, 2017

    @d-van-de-velden
    Author

    Good morning Alexandre Gramfort,

    at first I wish you a good start in this week. Respectively, to your tiny changes in this code example I agree with you, that it will run without any error. However this changes bypass the essential error I was talking about. Please try run following code snippet:

    from mne.datasets import sample
    import mne
    import numpy as np
    
    data_path = sample.data_path()
    subjects_dir = data_path + '/subjects'
    subject = 'sample'
    aseg_fname = subjects_dir + '/sample/mri/aseg.mgz'
    bem_fname = subjects_dir + '/sample/bem/sample-5120-5120-5120-bem-sol.fif'
    grid_space = 5.
    
    volume_labels = mne.get_volume_labels_from_aseg(aseg_fname)
    
    print(' Making Volume Source Space...')
    vsrc = mne.setup_volume_source_space(subject=subject, pos=grid_space,
                                         mri=aseg_fname,
                                         bem=bem_fname,
                                         volume_label=volume_labels,
                                         subjects_dir=subjects_dir,
                                         add_interpolator=True,
                                         verbose=None)
    
    volume_source_space_label_dictionary = {}
    
    for label, vol_src in zip(volume_labels, vsrc):
        vertnos = vol_src['vertno']
        volume_source_space_label_dictionary.update({label: vertnos})
    
    vol_source_space_name = '%s_vol-%.4f-src' % (subject, grid_space)
    mne.write_source_spaces(vol_source_space_name + '.fif', vsrc, overwrite=True)
    

    Since the vol_source_space will be too big, it will not be able to be saved, hence the limited fif-file size of 2GB. You will receive the following IOError Message:

      File "/home/daniel/anaconda2/lib/python2.7/site-packages/mne/io/write.py", line 272, in check_fiff_length
        raise IOError('FIFF file exceeded 2GB limit, please split file or '
    
    IOError: FIFF file exceeded 2GB limit, please split file or save to a different format
    

    Additionally I'd like to mention, that for the subject 'fsaverage' and 'sample' there are no vertice duplicates across the labels, but in every subject I created a volume source space for (+24 subjects).
    I also checked the duplicates for their correctness, in case of their allocation to the labels they appear in. After correcting their allocation with the following code snippet I got rid of all duplicates, without losing any loss of a vertice from the entire volume source space.

      from mne.source_space import _get_lut, _get_lut_id, _get_mgz_header
      import nibabel as nib
      from scipy import linalg
      from mne.transforms import apply_trans
      import numpy as np
    
      mgz = nib.load(fname_s_aseg)
      mgz_data = mgz.get_data()
      lut = _get_lut()
      vox2rastkr_trans = _get_mgz_header(fname_s_aseg)['vox2ras_tkr']
      vox2rastkr_trans[:3] /= 1000.
      inv_vox2rastkr_trans = linalg.inv(vox2rastkr_trans)
      all_volume_labels = []
      vol_lab = mne.get_volume_labels_from_aseg(fname_s_aseg)
      for lab in vol_lab: all_volume_labels.append( lab.encode() )
      print '#### Attempting to get rid of vertice duplicates in labels..\n'
      for p, label in enumerate(all_volume_labels):
        lab_arr = label_list_subject[label]
        lab_id = _get_lut_id(lut, label, True)[0]
        del_ver_idx_list = []
      
        for arr_id, i in enumerate(lab_arr, 0):
          lab_vert_coord = subj_src[0]['rr'][i]
          lab_vert_mgz_idx = apply_trans(inv_vox2rastkr_trans, lab_vert_coord)
          orig_idx = mgz_data[int(round(lab_vert_mgz_idx[0])), int(round(lab_vert_mgz_idx[1])), int(round(lab_vert_mgz_idx[2]))]
          
          if orig_idx != lab_id:
            del_ver_idx_list.append(arr_id)
            
        del_ver_idx = np.asarray(del_ver_idx_list)
        label_list_subject[label] = np.delete(label_list_subject[label], del_ver_idx)
      print '[done]'  
    

    Adding this to the actual _make_volume_source_space(surf, pos, exclude, mindist, mri, volume_label) -function, after generously choosing vertices for the VOI, to check if the selected vertices are correct, would solve the duplicate problem.

    Of course, this is just a friendly reference. If my suggestion is rude, false or doesn't work with the functions actual purpose, please let me know. I am very interested in learning and discussion about this subject.

    I also apologize for any trouble this 'issue thread' might cause.

    Have a nice day,
    Daniel

  5. agramfort commented on Dec 19, 2017

    @agramfort
    SponsorMember
  6. d-van-de-velden commented on Dec 19, 2017

    @d-van-de-velden
    Author

    Thank you very much.
    I will go with my work around, so the code with your tiny little changes. Thanks again and a support with hdf5 will be very useful for label-wise volume source space construction.

    If you don't want discuss anything I will close this thread.

    I wish you and your family and friends a merry Christmas,
    Daniel van de Velden

  7. agramfort commented on Dec 19, 2017

    @agramfort
    SponsorMember
  8. pelednoam commented on Sep 27, 2018

    @pelednoam

    Hey, are there any updates on this issue? I'm trying to save ico5 BEM solution, and getting the same error (OSError: FIFF file exceeded 2GB limit, please split file or save to a different format)
    Thanks!

  9. larsoner commented on Sep 27, 2018

    @larsoner
    Member

    Fortunately ConductorModel subclasses a standard class (dict) so for now you can probably hack it with:

    mne.externals.h5io.write_hdf5('my-bem-sol.h5', my_bem_sol)
    my_bem_sol_2 = mne.externals.h5io.read_hdf5('my-bem-sol.h5')
    my_bem_sol_2 = mne.bem.ConductorModel(my_bem_sol_2)
    
  10. larsoner commented on Sep 27, 2018

    @larsoner
    Member

    (incidentally SourceSpaces subclasses the standard class list, too, so the same workaround will probably work for this volume source space)

  11. added this to the 0.20 milestone on Sep 19, 2019
  12. changed the title [-]Multiple vertno indice duplicates in volume_label based Volume-Source-Space[/-] [+]ENH: Write source spaces to HDF5[/+] on Sep 19, 2019
  13. changed the title [-]ENH: Write source spaces to HDF5[/-] [+]ENH: Write source spaces and BEMs to HDF5[/+] on Sep 19, 2019
  14. modified the milestones: 0.20, 0.21 on Mar 4, 2020
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

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions