Skip to content

decimate_surface breaks the meshes in some cases #7259

Closed

Description

@christian-oreilly

Describe the bug

Meshes reduced in size using decimate_surface are sometime invalid and crash the BEM computation generating a RuntimeError exception with message like Surface inner skull has topological defects: 3 / 5119 vertices have fewer than three neighboring triangles [1381, 1382, 1383].

Steps to reproduce

The following code:

from mne.surface import decimate_surface, read_surface
path = "/usr/local/freesurfer/subjects/ANTS7-5Months3T/bem/inner_skull_large.surf"
from mne.surface import _triangle_neighbors

# Code extracted and slighly modified from mne.surface.complete_surface_info
# for compactness of the example
def check_topological_defect(faces, vertices):
    #    Find neighboring triangles, accumulate vertex normals, normalize
    neighbor_tri = _triangle_neighbors(faces, vertices)

    #   Check for topological defects
    zero, fewer = list(), list()
    for ni, n in enumerate(neighbor_tri):
        if len(n) < 3:
            if len(n) == 0:
                zero.append(ni)
            else:
                fewer.append(ni)
    if len(zero) > 0:
        print('    Vertices do not have any neighboring '
                    'triangles: [%s]' % ', '.join(str(z) for z in zero))
    if len(fewer) > 0:
        print('    Vertices have fewer than three neighboring '
                    'triangles, removing neighbors: [%s]'
                    % ', '.join(str(f) for f in fewer))

vertices, faces = read_surface(path)

print("Checking the full mesh:")
check_topological_defect(faces, len(vertices))

vertices, faces = decimate_surface(vertices, faces, n_triangles=5120)

print("Checking the decimated mesh:")
check_topological_defect(faces, len(vertices))

Produces the following output:

Checking the full mesh:
Checking the decimated mesh:
    Vertices have fewer than three neighboring triangles, removing neighbors: [1381, 1382, 1383]

I can send inner_skull_large.surf by email for you to reproduce this issue.

Expected results

No vertices with fewer than three neighbouring triangles should be introduced by decimate_surface.

Additional information

Platform:      Linux-5.3.0-26-generic-x86_64-with-debian-buster-sid
Python:        3.7.4 (default, Aug 13 2019, 20:35:49)  [GCC 7.3.0]
Executable:    /home/christian/anaconda3/bin/python
CPU:           x86_64: 12 cores
Memory:        31.3 GB

mne:           0.20.dev0
numpy:         1.17.4 {blas=mkl_rt, lapack=mkl_rt}
scipy:         1.4.1
matplotlib:    3.1.2 {backend=Qt5Agg}

sklearn:       0.22.1
numba:         Not found
nibabel:       3.0.0
cupy:          Not found
pandas:        0.25.3
dipy:          Not found
mayavi:        4.6.2 {qt_api=pyqt5, PyQt5=5.14.1}
pyvista:       Not found
vtk:           8.1.2

Activity

  1. christian-oreilly commented on Jan 27, 2020

    @christian-oreilly
    ContributorAuthor

    Hmm... a similar example can be produce with _assert_complete_surface which raise an exception on some decimated surfaces but not on the original surfaces. I can document this also if you'd like.

  2. larsoner commented on Jan 28, 2020

    @larsoner
    Member

    I wrote some of this on GitHub, but here are some suggestions (eventually we should add these to https://mne.tools/dev/overview/faq.html#my-watershed-bem-meshes-look-incorrect):

    1. Old MNE-C used https://www.mathworks.com/help/matlab/ref/reducepatch.html, which you could try
    2. In theory you could use a sequence of Freesurfer commands to decimate the surfaces, or better starting from the labeled MRI: mri_tessellate, mris_extract_main_component, mri_smooth, mris_inflate, mris_sphere, then mne.surface._get_ico_surface(4)

    I think what we might want to do eventually is make an alternative mode for decimate_surface that uses the last four of those things (three Freesurfer commands and our internal ico stuff) to decimate a given surface. But let's see if it actually works for your use case first.

  3. christian-oreilly commented on Jan 28, 2020

    @christian-oreilly
    ContributorAuthor

    Thanks for this infor @larsoner I am not so familiar with these functions. I got the following working

    path_bem=/usr/local/freesurfer/subjects/ANTS7-5Months3T/bem_test
    mris_extract_main_component $path_bem/inner_skull_large.surf $path_bem/inner_skull_large.orig
    mris_smooth -nw $path_bem/inner_skull_large.orig $path_bem/inner_skull_large.smooth
    mris_inflate $path_bem/inner_skull_large.smooth $path_bem/inner_skull_large.inflated
    

    but then

    mris_sphere $path_bem/inner_skull_large.inflated $path_bem/inner_skull_large.sphere
    

    generated

    == Number of threads available to mris_sphere for OpenMP = 1 == 
    reading original vertex positions...
    MRISreadVertexPosition(smoothwm): could not open file /usr/local/freesurfer/subjects/ANTS7-5Months3T/bem_test/rh.smoothwm
    No such file or directory
    MRISreadOriginalProperties: could not read surface file smoothwm
    No such file or directory
    

    Obviously, smoothwm has nothing to do with what I am doing here. I am using this functions on a head surface that has not much to do with wm surfaces computed on a separate pipeline (i.e., the bem surfaces I am processing have not been obtained from the watershed algorithm used by the recon_all pipeline). Also, it is not specific to a given hemisphere... In any case, mris_sphere documentation is quite small so I have not much to work with.

    Then, looking at the code from mne.surface._get_ico_surface(4)

    def _get_ico_surface(grade, patch_stats=False):
        """Return an icosahedral surface of the desired grade."""
        # always use verbose=False since users don't need to know we're pulling
        # these from a file
        from .bem import read_bem_surfaces
        ico_file_name = op.join(op.dirname(__file__), 'data',
                                'icos.fif.gz')
        ico = read_bem_surfaces(ico_file_name, patch_stats, s_id=9000 + grade,
                                verbose=False)
        return ico
    

    it seems to return a generic ico suface, not related to my specific surface. How do I "apply" the output of this function to my surface to obtain the downsampled version?

    In any case, with the file I had the issue reported herein, using the output mris_extract_main_component already fix the issue. Apparently, there was quite a few detached components

    counting number of connected components...
       77447 voxel in cpt #1: X=0 [v=77447,e=232341,f=154894] located at (0.901746, -10.199737, 8.243619)
       80 voxel in cpt #2: X=2 [v=80,e=234,f=156] located at (0.414000, -22.717093, -21.907677)
       368 voxel in cpt #3: X=2 [v=368,e=1098,f=732] located at (5.412456, 13.986076, 14.498794)
       116 voxel in cpt #4: X=2 [v=116,e=342,f=228] located at (-15.907030, -18.071302, 21.209974)
       6 voxel in cpt #5: X=2 [v=6,e=12,f=8] located at (-1.001188, 5.507027, -16.020658)
       6 voxel in cpt #6: X=2 [v=6,e=12,f=8] located at (32.042393, 20.525843, -12.015538)
       455 voxel in cpt #7: X=2 [v=455,e=1359,f=906] located at (-4.331089, 13.432364, 14.983730)
       34 voxel in cpt #8: X=2 [v=34,e=96,f=64] located at (30.156767, 19.783537, -13.507011)
       20 voxel in cpt #9: X=2 [v=20,e=54,f=36] located at (2.762841, 4.895272, -16.419605)
       10 voxel in cpt #10: X=2 [v=10,e=24,f=16] located at (18.023563, -18.023563, 21.027493)
       10 voxel in cpt #11: X=2 [v=10,e=24,f=16] located at (17.022253, -16.020947, 22.028799)
    For the whole surface: X=20 [v=78552,e=235596,f=157064]
    11 components have been found
    keeping component #1 with 77447 vertices
    done
    

    I still have an issue from _assert_complete_surface complaining about Surface is not complete (sum of solid angles yielded 1.00004, should be 1.) on another files though. This is not resolved by using the output of mris_extract_main_component and mris_smooth.

  4. christian-oreilly commented on Jan 28, 2020

    @christian-oreilly
    ContributorAuthor

    Nevermind the question about how use mne.surface._get_ico_surface(4), I just seen your comments on Gitter

    find the nearest neighbors to an ICO-4 (standard BEM size in MNE IIRC) surface obtained with mne.surface._get_ico_surface(4), then simply subselect vertices from the original mesh based on these nearest neighbors and your triangulation is that of the ICO-4 mesh

  5. christian-oreilly commented on Jan 28, 2020

    @christian-oreilly
    ContributorAuthor

    @larsoner Do you have a pointer of something I could read to get a conceptual explanation of what is the idea here Surface is not complete (sum of solid angles yielded 1.00004, should be 1.) (i.e., what is this sum of solid angle and why it should be 1 for a complete surface)? It would make it easier for me to understand what could create departure from this in my mesh.

    Also, since the check in _assert_inside (that fails for two other of my meshes) is also based on the _get_solids output, it seems that better understanding what is going on there might be the solution for the issues I have with my three remaining problematic meshes.

  6. larsoner commented on Jan 29, 2020

    @larsoner
    Member

    This suggests that our current version of decimate_surface does not preserve the topological properties of the surface. In this case it seems to have probably created a hole (?) in the previously complete mesh.

    This suggests that the Freesurfer way of doing things (which will maintain a complete triangulation) might indeed be better, if we can get it to work.

  7. larsoner commented on Jan 29, 2020

    @larsoner
    Member

    Looks like you are using John Richards public Infants NITRC dataset. So I can test locally.

    but then ... generated

    Looks like you:

    Here is a gist. Run the Freesurfer bash commands at the top of the Python file, then actually run the Python file:

    $ python -u mri.py
    Creating the BEM geometry...
    Going from 4th to 4th subdivision of an icosahedron (n_tri: 5120 -> 5120)
    Going from 4th to 4th subdivision of an icosahedron (n_tri: 5120 -> 5120)
    Going from 4th to 4th subdivision of an icosahedron (n_tri: 5120 -> 5120)
    outer skin  CM is   0.74  -4.31   6.35 mm
    outer skull CM is   1.98  12.99  10.68 mm
    inner skull CM is   2.05  13.59  11.76 mm
    Checking that outer skull surface is inside outer skin  surface...
    Checking that inner skull surface is inside outer skull surface...
    Checking distance between outer skin  and outer skull surfaces...
    Minimum distance between the outer skin  and outer skull surfaces is approximately    0.0 mm
    Checking distance between outer skull and inner skull surfaces...
    Minimum distance between the outer skull and inner skull surfaces is approximately    0.0 mm
    Surfaces passed the basic topology checks.
    Complete.
    

    And see:

    $ freeview -v $MRI -f mysubj/bem/inner_skull.surf -f mysubj/bem/outer_skull.surf -f mysubj/bem/outer_skin.surf 
    

    Screenshot from 2020-01-29 11-09-57

    If you can confirm that this works for you, I can work on making some helper functions that would you to do the mri_tesselate through mris_sphere (plus Python downsampling) steps in Python. I think it makes sense to leave the mri_binarize step to the user.

  8. christian-oreilly commented on Jan 29, 2020

    @christian-oreilly
    ContributorAuthor

    @larsoner Seems to work pretty well indeed. It is a shame that I had to loose so many time trying to accomplish the same things with approaches...! I'll check that it works fine for all subjects. My goal (and it is almost completed) is to produce population-average for infants at 3, 4.5, 6, 7.5, 9, 12, 18, and 24 months old so that they could be used for analyses in infants, much as fsaverage is used for analyses in adults when no MRI is available for source reconstruction. Pial and WM surfaces have been obtained using John Richards averages and Lilla Zollei FS pipeline for infants. It took quite a bit of debuging but it seems to work fine now, minus some last bugs...

    infants_atlas_labeled_small

    I though it could be nice to add these to python-MNE, so that other researchers can use it. I know I missed it for my own research in any cases, and that other researchers also do. I can prepare a PR for that when I am done if you think it is a good idea to add it to MNE.

  9. larsoner commented on Jan 29, 2020

    @larsoner
    Member

    That would be great. I've worked with those data a bit (as well as the infant pipeline) and ended up deciding to go the volumetric source space rather than surface source space route. We should chat at some point to figure this stuff out.

  10. christian-oreilly commented on Jan 29, 2020

    @christian-oreilly
    ContributorAuthor

    Sure. I would be happy to hear about your experience with this and why you chose in the end not to go for surface sources.

    It looks like the freesurfer code produces valid meshes but at the price of a very approximative fit to the source data. On this figure, the BEM mask is color-coded as a lookup table, the meshes I obtained with marching cube + Laplacian smoothing + decimation are in green, the surfaces obtained with freesurfer as in purple :
    Screenshot from 2020-01-29 13-21-08

    On a more fundamental level, I am a bit doubtful about the BEM mask to start with. As can be seen on this picture, the green surfaces that were following quite closely the BEM segmentation do not seem to follow very well the skull. I am not very knowledgeable about MRI but this seems very obvious even for my untrained eye.

    Screenshot from 2020-01-29 13-28-39

    This is probably an issue to discuss with John Richard...

  11. larsoner commented on Jan 29, 2020

    @larsoner
    Member

    Yes let's coordinate on a time to chat about this, see my responses on gitter. Too much ground to cover here...

  12. christian-oreilly commented on Jan 29, 2020

    @christian-oreilly
    ContributorAuthor

    FYI, I corrected the meshes that had topological defects or that were not watertight using

    import pymeshfix
    import numpy as np
    from nibabel.freesurfer.io import read_geometry, write_geometry
    from mne.surface import decimate_surface, read_surface
    from mne.surface import _triangle_neighbors
    from mne.bem import _get_solids
    
    
    def surface_is_complete(faces, vertices):
        """Check the sum of solid angles as seen from inside."""
        cm = vertices.mean(axis=0)
        tot_angle = _get_solids(vertices[faces], cm[np.newaxis, :])[0]
        prop = tot_angle / (2 * np.pi)
        return np.abs(prop - 1.0) < 1e-5
    
    def correction_two_neighboring_tri(faces, vertices, faulty_vert_ind):
        
        ind_faces_to_remove = []
        new_faces = []
        for ind in faulty_vert_ind:
            ind_faces = np.where(faces == ind)[0]
            ind_faces_to_remove.extend(ind_faces)
            face1, face2 = faces[ind_faces]
            new_face = np.unique(np.concatenate((face1, face2)))
            new_face = np.delete(new_face, np.where(new_face == ind))
            assert(len(new_face) == 3)  # If == 4, it means that face1 and face2 do not share a common edge
    
            new_det = np.linalg.det(vertices[new_face])
            assert(new_det)  # If zero, the three points are colinear
    
            # Algning the normals
            det1 = np.linalg.det(vertices[face1])
            if np.sign(det1) == np.sign(new_det):
                new_face = new_face[[1, 0, 2]]        
            
            new_faces.append(new_face)
         
        return np.array(ind_faces_to_remove, dtype=int), new_faces
        #faces = faces.remove(ind_faces_to_remove)
        #return np.concatenate((faces, faces_to_add))
        
    def reindex_vertices(faces, vertices, ind_vertices_to_remove):
        decrement = np.cumsum(np.zeros(vertices.shape[0], dtype=int) + 
                              np.in1d(np.arange(vertices.shape[0]), ind_vertices_to_remove))
        vertices = np.delete(vertices, ind_vertices_to_remove, axis=0)
        faces = faces - decrement[faces]    
        return vertices, faces
        
    def get_topological_defects(faces, vertices):
        #    Find neighboring triangles, accumulate vertex normals, normalize
        neighbor_tri = _triangle_neighbors(faces, len(vertices))
    
        #   Check for topological defects
        zero, one, two = list(), list(), list()
        for ni, n in enumerate(neighbor_tri):
            if len(n) < 3:
                if len(n) == 0:
                    zero.append(ni)
                elif len(n) == 1:
                    one.append(ni)
                else:
                    two.append(ni)
                    
        return zero, one, two
        
    def has_topological_defects(faces, vertices):
        zero, one, two = get_topological_defects(faces, vertices)    
        return len(zero) or len(one) or len(two)
            
    # Code extracted and slighly modified from mne.surface.complete_surface_info
    # for compactness of the example
    def fix_topological_defects(faces, vertices):    
        zero, one, two = get_topological_defects(faces, vertices)  
        ind_faces_to_remove = []
        if len(zero) > 0:
            print('    Vertices do not have any neighboring '
                        'triangles: [%s]' % ', '.join(str(z) for z in zero))
            print('    Correcting by removing these vertices.')
            
        if len(one) > 0:
            print('    Vertices have only one neighboring '
                        'triangles: [%s]'
                        % ', '.join(str(f) for f in one))
            print('    Correcting by removing these vertices and their neighboring triangles.')
            ind_faces_to_remove.extend(np.where(faces == one)[0].tolist())
            
        if len(two) > 0:
            print('    Vertices have only two neighboring '
                        'triangles, removing neighbors: [%s]'
                        % ', '.join(str(f) for f in two))
            print('    Correcting by merging the two neighboring '
                        'triangles and removing the faulty vertices.')
            
            ind_faces, faces_to_add = correction_two_neighboring_tri(faces, vertices, two)
            ind_faces_to_remove.extend(ind_faces)  
            faces = np.concatenate((np.delete(faces, np.array(ind_faces_to_remove, dtype=int), axis=0), faces_to_add))
    
        vertices_to_remove = np.concatenate((zero, one, two)).astype(int)
        if len(vertices_to_remove):
            vertices, faces = reindex_vertices(faces, vertices, vertices_to_remove)
        else:
            print("No issue found with the mesh.")
            
        return vertices, faces
            
    
    def repair_holes(vertices,faces):
        # trimesh has a hole fixing function, but it just deals with
        # 3 or 4 vertices holes.
        meshfix = pymeshfix.MeshFix(vertices, faces)
        meshfix.repair()
        vertices = meshfix.v # numpy np.float array
        faces = meshfix.f # numpy np.int32 array
    
        # The return mesh has a solid angle of -1 instead of 1. 
        # Correcting this.
        mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
        trimesh.repair.fix_normals(mesh, multibody=False)
        return mesh.vertices, mesh.faces
    
        
    paths = ["/usr/local/freesurfer/subjects/ANTS3-0Months3T/bem/outer_skin_large.surf",
             "/usr/local/freesurfer/subjects/ANTS4-5Months3T/bem/outer_skin_large.surf",
             "/usr/local/freesurfer/subjects/ANTS2-0Years3T/bem/inner_skull_large.surf"]
                   
    for path in paths: 
        print("Processing path {}...".format(path))
        vertices, faces = read_surface(path)
    
        if has_topological_defects(faces, vertices):
            print("The original mesh has topological defects. Fixing it.")
            vertices, faces = fix_topological_defect(faces, vertices)
            assert(not has_topological_defects(faces, vertices))
    
        if not surface_is_complete(faces, vertices):
            print("The original mesh has holes. Fixing it.")
            vertices, faces = repair_holes(vertices, faces) 
            assert(surface_is_complete(faces, vertices))
    
        vertices, faces = decimate_surface(vertices, faces, n_triangles=5120)
    
        if has_topological_defects(faces, vertices):
            print("The decimated mesh has topological defects. Fixing it.")
            vertices, faces = fix_topological_defect(faces, vertices)
            assert(not has_topological_defects(faces, vertices))
    
        if not surface_is_complete(faces, vertices):
            print("The decimated mesh has holes. Fixing it.")
            vertices, faces = repair_holes(vertices, faces) 
            assert(surface_is_complete(faces, vertices))
    
            
        volume_info = read_geometry(path, read_metadata=True)[2]
        write_geometry(str(Path(path).parent / str(Path(path).name).replace("_large", "")), 
                       vertices, faces, volume_info=volume_info) 
  13. christian-oreilly commented on Jan 30, 2020

    @christian-oreilly
    ContributorAuthor

    FYI, the last problematic mesh I had was causing problem because the BEM file was problematic to start with. There were no skull voxel at some places

    Screenshot from 2020-01-29 17-46-17

    I corrected these by hands and it is now working... So all my meshes works now! :)

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions