예제 #1
0
    def convert_fs_subj_to_tvb_surf(self, subject: Optional[str]=None):
        """
        Merge surfaces and roi maps. Write out in TVB format.
        """

        subjects_dir = os.environ['SUBJECTS_DIR']

        if subject is None:
            subject = os.environ['SUBJECT']

        lh_surf_path = os.path.join(subjects_dir, subject, 'surf', 'lh.pial')
        rh_surf_path = os.path.join(subjects_dir, subject, 'surf', 'rh.pial')
        lh_annot_path = os.path.join(
            subjects_dir, subject, 'label', 'lh.aparc.annot')
        rh_annot_path = os.path.join(
            subjects_dir, subject, 'label', 'rh.aparc.annot')

        lh_surface = IOUtils.read_surface(lh_surf_path, False)
        rh_surface = IOUtils.read_surface(rh_surf_path, False)

        lh_annot = IOUtils.read_annotation(lh_annot_path)
        rh_annot = IOUtils.read_annotation(rh_annot_path)

        surface, region_mapping = self.surface_service.merge_lh_rh(lh_surface, rh_surface, lh_annot.region_mapping,
                                                                   rh_annot.region_mapping)

        numpy.savetxt('%s_ctx_roi_map.txt' %
                      (subject,), region_mapping.flat[:], '%i')
        TVBWriter().write_surface_zip('%s_pial_surf.zip' % (subject,), surface)
예제 #2
0
 def test_write_annotation(self):
     file_path = get_data_file(
         self.subject, self.annot_path, "lh.aparc.annot")
     annotation = IOUtils.read_annotation(file_path)
     out_annotation_path = self.temp_file_path("lh-test.aparc.annot")
     IOUtils.write_annotation(out_annotation_path, annotation)
     new_annotation = IOUtils.read_annotation(out_annotation_path)
     self.assertEqual(annotation.region_names, new_annotation.region_names)
예제 #3
0
 def annot_to_conn_conf(self, annot_path, type, conn_conf_path, first_idx=0):
     annotation_lh = IOUtils.read_annotation(os.path.join(annot_path, "lh." + type + ".annot"))
     annotation_rh = IOUtils.read_annotation(os.path.join(annot_path, "rh." + type + ".annot"))
     with open(conn_conf_path, 'w') as fd:
         for id, name in enumerate(annotation_lh.region_names):
             if type == "aparc" and name != "unknown":
                 name = "lh-" + name
             fd.write('%d\t%s\n' % (id + first_idx, name))
         first_idx += len(annotation_lh.region_names)
         for id, name in enumerate(annotation_rh.region_names):
             if (name == "unknown"):
                 first_idx -= 1
                 continue
             if type == "aparc" and name != "unknown":
                 name = "rh-" + name
             fd.write('%d\t%s\n' % (id + first_idx, name))
     return first_idx + len(annotation_rh.region_names)
예제 #4
0
파일: processor.py 프로젝트: sipv/tvb-recon
 def overlap_surface_annotation(self,
                                surface_path,
                                annotation,
                                snapshot_name=SNAPSHOT_NAME):
     annotation = IOUtils.read_annotation(annotation)
     surface = IOUtils.read_surface(surface_path, False)
     self.writer.write_surface_with_annotation(
         surface, annotation,
         self.generate_file_name('surface_annotation', snapshot_name))
예제 #5
0
    def annot_to_lut(self, annot_path, lut_path=None, subject=None, prefix=''):
        """
        This function creates from an annotation a new lut_file, or adds new
        entries to an existing lut file. In the latter case, new entries have
        labels greater than the maximum alredy existing label inside the lut
        file.

        Parameters
        ----------
        annot_path : str, os.PathLike
            path to annotation.
        lut_path : str, os.PathLike
            path to existing or new LUT file.
        subject : str, optional
            subject name if provided, otherwise env var $SUBJECT is used
        prefiw : str, optional
            prefix for region names (i.e., "ctx-lh-")

        """
        annotation = IOUtils.read_annotation(annot_path)
        subject = subject or os.environ['SUBJECT']
        # If this is an already existing lut file:
        lut_path = lut_path or default_lut_path()
        if os.path.isfile(lut_path):
            # ...find the maximum label in it and add 1
            add_lbl = 1 + \
                      numpy.max(self.read_lut(
                          lut_path=lut_path, key_mode='label')[0])
        else:
            # ...else, set it to 0
            add_lbl = 0
        with open(lut_path, 'a') as fd:
            if add_lbl == 0:
                # TODO: we should include an environment variable for
                # freesurfer version, and print it here
                fd.write("#$Id: %s %s\n\n" % (lut_path, datetime.now()))
                fd.write('#No.\tLabel Name: \tR   G   B   A   \n')
            else:
                fd.write('\n')
            fd.write("""
#Patient: {subject}
#User: {user}
#Annotation path: {annot_path}
#Time: {time}

""".format(subject=subject,
            user=os.path.split(os.path.expanduser('~'))[-1],
            annot_path=annot_path,
            time=datetime.now()))
            # TODO: align columns
            # NOTE!!! that the fourth and fifth columns of color_table are not
            # used in the lut file!!!
            for name, (r, g, b, dummy1, dummy2), lbl in \
                    zip(annotation.region_names, annotation.regions_color_table,
                        list(range(len(annotation.region_names)))):
                fd.write('%d\t%s\t%d %d %d %d\n' %
                         (lbl + add_lbl, prefix + name, r, g, b, 0))
예제 #6
0
 def annot_to_conn_conf(self,
                        annot_path,
                        type,
                        conn_conf_path,
                        first_idx=0):
     annotation_lh = IOUtils.read_annotation(
         os.path.join(annot_path, "lh." + type + ".annot"))
     annotation_rh = IOUtils.read_annotation(
         os.path.join(annot_path, "rh." + type + ".annot"))
     with open(conn_conf_path, 'w') as fd:
         for id, name in enumerate(annotation_lh.region_names):
             if type == "aparc" and name != "unknown":
                 name = "lh-" + name
             fd.write('%d\t%s\n' % (id + first_idx, name))
         first_idx += len(annotation_lh.region_names)
         for id, name in enumerate(annotation_rh.region_names):
             if (name == "unknown"):
                 first_idx -= 1
                 continue
             if type == "aparc" and name != "unknown":
                 name = "rh-" + name
             fd.write('%d\t%s\n' % (id + first_idx, name))
     return first_idx + len(annotation_rh.region_names)
예제 #7
0
 def test_overlap_surface_annotation(self):
     writer = ImageWriter(SNAPSHOTS_DIRECTORY)
     surface_path = get_data_file(self.head2, "SurfaceCortical.h5")
     surface = IOUtils.read_surface(surface_path, False)
     annot_path = get_data_file(self.head2, "RegionMapping.h5")
     annot = IOUtils.read_annotation(annot_path)
     annot.region_names = ['reg1', 'reg2']
     annot.regions_color_table = numpy.array(
         [[200, 200, 200, 255, 30567], [100, 150, 200, 255, 30568]])
     resulted_file_name = self.processor.generate_file_name(
         'surface_annotation', SNAPSHOT_NAME)
     writer.write_surface_with_annotation(surface, annot, resulted_file_name)
     fname = '%s0' % (resulted_file_name, )
     self._assert_writer_path_exists(fname)
예제 #8
0
    def test_aseg_surf_conc_annot(self,):
        out_surf_path = get_temporary_files_path("out_aseg")
        out_annot_path = get_temporary_files_path("out_annot")
        labels = "10 11"
        colorLUT = get_data_file("colorLUT.txt")
        self.service.aseg_surf_conc_annot(
            data_path, out_surf_path, out_annot_path, labels, colorLUT)
        self.assertTrue(os.path.exists(out_surf_path))
        self.assertTrue(os.path.exists(out_annot_path))

        surface_parser = FreesurferIO()
        surface = surface_parser.read(out_surf_path, False)
        self.assertEqual(len(surface.vertices), 5714)
        self.assertEqual(len(surface.triangles), 11420)

        annotation = IOUtils.read_annotation(out_annot_path)
        assert_array_equal(
                annotation.regions_color_table,
                [[0, 118, 14, 0, 947712], [122, 186, 220, 0, 14465658]])
예제 #9
0
 def test_parse_h5_annotation(self):
     h5_path = get_data_file('head2', 'RegionMapping.h5')
     annotation = IOUtils.read_annotation(h5_path)
     self.assertEqual(annotation.region_mapping.size, 16)
예제 #10
0
def compute_region_details(atlas_suffix: AtlasSuffix, fs_color_lut: os.PathLike, t1: os.PathLike, lh_cort: os.PathLike,
                           rh_cort: os.PathLike, lh_cort_annot: os.PathLike, rh_cort_annot: os.PathLike,
                           lh_subcort: os.PathLike, rh_subcort: os.PathLike, lh_subcort_annot: os.PathLike,
                           rh_subcort_annot: os.PathLike):
    annot_cort_lh = IOUtils.read_annotation(lh_cort_annot)
    annot_cort_rh = IOUtils.read_annotation(rh_cort_annot)

    annot_subcort_lh = IOUtils.read_annotation(lh_subcort_annot)
    annot_subcort_rh = IOUtils.read_annotation(rh_subcort_annot)

    mapping = MappingService(atlas_suffix, annot_cort_lh, annot_cort_rh, annot_subcort_lh, annot_subcort_rh)
    mapping.generate_region_mapping_for_cort_annot(annot_cort_lh, annot_cort_rh)
    mapping.generate_region_mapping_for_subcort_annot(annot_subcort_lh, annot_subcort_rh)

    surface_service = SurfaceService()

    surf_cort_lh = IOUtils.read_surface(lh_cort, False)
    surf_cort_rh = IOUtils.read_surface(rh_cort, False)

    full_cort_surface = surface_service.merge_surfaces([surf_cort_lh, surf_cort_rh])

    surf_subcort_lh = IOUtils.read_surface(lh_subcort, False)
    surf_subcort_rh = IOUtils.read_surface(rh_subcort, False)

    full_subcort_surface = surface_service.merge_surfaces([surf_subcort_lh, surf_subcort_rh])

    genericIO.write_list_to_txt_file(mapping.cort_region_mapping, AsegFiles.RM_CORT_TXT.value.replace("%s", atlas_suffix))
    genericIO.write_list_to_txt_file(mapping.subcort_region_mapping,
                                     AsegFiles.RM_SUBCORT_TXT.value.replace("%s", atlas_suffix))

    vox2ras_file = "vox2ras.txt"
    subprocess.call(["mri_info", "--vox2ras", t1, "--o", vox2ras_file])

    surf_subcort_filename = "surface_subcort.zip"
    IOUtils.write_surface(surf_subcort_filename, full_subcort_surface)

    surf_cort_filename = "surface_cort.zip"
    IOUtils.write_surface(surf_cort_filename, full_cort_surface)

    os.remove(vox2ras_file)

    cort_subcort_full_surf = surface_service.merge_surfaces([full_cort_surface, full_subcort_surface])
    cort_subcort_full_region_mapping = mapping.cort_region_mapping + mapping.subcort_region_mapping

    dict_fs_custom = mapping.get_mapping_for_connectome_generation()
    genericIO.write_dict_to_txt_file(dict_fs_custom, AsegFiles.FS_CUSTOM_TXT.value.replace("%s", atlas_suffix))

    region_areas = surface_service.compute_areas_for_regions(mapping.get_all_regions(), cort_subcort_full_surf,
                                                             cort_subcort_full_region_mapping)
    genericIO.write_list_to_txt_file(region_areas, AsegFiles.AREAS_TXT.value.replace("%s", atlas_suffix))

    region_centers = surface_service.compute_centers_for_regions(mapping.get_all_regions(), cort_subcort_full_surf,
                                                                 cort_subcort_full_region_mapping)
    cort_subcort_lut = mapping.get_entire_lut()
    region_names = list(cort_subcort_lut.values())

    with open(AsegFiles.CENTERS_TXT.value.replace("%s", atlas_suffix), "w") as f:
        for idx, (val_x, val_y, val_z) in enumerate(region_centers):
            f.write("%s %.2f %.2f %.2f\n" % (region_names[idx], val_x, val_y, val_z))

    region_orientations = surface_service.compute_orientations_for_regions(mapping.get_all_regions(),
                                                                           cort_subcort_full_surf,
                                                                           cort_subcort_full_region_mapping)

    lh_region_centers = surface_service.compute_centers_for_regions(mapping.get_lh_regions(), surf_cort_lh,
                                                                    mapping.lh_region_mapping)
    lh_region_orientations = surface_service.compute_orientations_for_regions(mapping.get_lh_regions(), surf_cort_lh,
                                                                              mapping.lh_region_mapping)
    with open(AsegFiles.LH_DIPOLES_TXT.value.replace("%s", atlas_suffix), "w") as f:
        for idx, (val_x, val_y, val_z) in enumerate(lh_region_centers):
            f.write("%.2f %.2f %.2f %.2f %.2f %.2f\n" % (
                val_x, val_y, val_z, lh_region_orientations[idx][0], lh_region_orientations[idx][1],
                lh_region_orientations[idx][2]))

    rh_region_centers = surface_service.compute_centers_for_regions(mapping.get_rh_regions(), surf_cort_rh,
                                                                    mapping.rh_region_mapping)
    rh_region_orientations = surface_service.compute_orientations_for_regions(mapping.get_rh_regions(), surf_cort_rh,
                                                                              mapping.rh_region_mapping)
    with open(AsegFiles.RH_DIPOLES_TXT.value.replace("%s", atlas_suffix), "w") as f:
        for idx, (val_x, val_y, val_z) in enumerate(rh_region_centers):
            f.write("%.2f %.2f %.2f %.2f %.2f %.2f\n" % (
                val_x, val_y, val_z, rh_region_orientations[idx][0], rh_region_orientations[idx][1],
                rh_region_orientations[idx][2]))

    numpy.savetxt(AsegFiles.ORIENTATIONS_TXT.value.replace("%s", atlas_suffix), region_orientations, fmt='%.2f %.2f %.2f')

    annotation_service = AnnotationService()
    lut_dict, _, _ = annotation_service.read_lut(fs_color_lut, "name")
    rm_index_dict = mapping.get_mapping_for_aparc_aseg(lut_dict)
    genericIO.write_dict_to_txt_file(rm_index_dict, AsegFiles.RM_TO_APARC_ASEG_TXT.value.replace("%s", atlas_suffix))

    genericIO.write_list_to_txt_file(mapping.is_cortical_region_mapping(),
                                     AsegFiles.CORTICAL_TXT.value.replace("%s", atlas_suffix))
예제 #11
0
파일: surface.py 프로젝트: sipv/tvb-recon
    def sample_vol_on_surf(self,
                           surf_path,
                           vol_path,
                           annot_path,
                           out_surf_path,
                           cras_path,
                           add_string='',
                           vertex_neighbourhood=1,
                           add_lbl=[],
                           lut_path=None):
        """
        Sample a volume of a specific label on a surface, by keeping only those surface vertices, the nearest voxel of
        which is of the given label (+ of possibly additional target labels, such as white matter).
        Allow optionally for vertices within a given voxel distance vn from the target voxels.
        """

        lut_path = lut_path or default_lut_path()

        # Read the inputs
        surface = IOUtils.read_surface(surf_path, False)

        annotation = IOUtils.read_annotation(annot_path)
        labels = self.annotation_service.annot_names_to_labels(
            annotation.region_names, add_string=add_string, lut_path=lut_path)
        region_mapping_indexes = numpy.unique(annotation.region_mapping)

        volume_parser = VolumeIO()
        volume = volume_parser.read(vol_path)
        ras2vox_affine_matrix = numpy.linalg.inv(volume.affine_matrix)

        cras = numpy.loadtxt(cras_path)

        grid, n_grid = self.__prepare_grid(vertex_neighbourhood)

        # Initialize the output mask:
        verts_out_mask = numpy.repeat([False], surface.vertices.shape[0])
        for label_index in range(len(region_mapping_indexes)):

            self.logger.info("%s",
                             add_string + annotation.region_names[label_index])

            # Get the indexes of the vertices corresponding to this label:
            verts_indices_of_label, = numpy.where(
                annotation.region_mapping[:] ==
                region_mapping_indexes[label_index])
            verts_indices_of_label_size = verts_indices_of_label.size
            if verts_indices_of_label_size == 0:
                continue

            # Add any additional labels
            all_labels = [labels[label_index]] + add_lbl

            # get the vertices for current label and add cras to take them to
            # scanner ras
            verts_of_label = surface.vertices[verts_indices_of_label, :]
            verts_of_label += numpy.repeat(numpy.expand_dims(cras, 1).T,
                                           verts_indices_of_label_size,
                                           axis=0)

            # Compute the nearest voxel coordinates using the affine transform
            ijk = numpy.round(
                ras2vox_affine_matrix.dot(numpy.c_[verts_of_label, numpy.ones(verts_indices_of_label_size)].T)[:3].T) \
                .astype('i')

            # Get the labels of these voxels:
            surf_vxls = volume.data[ijk[:, 0], ijk[:, 1], ijk[:, 2]]

            # Vertex mask to keep: those that correspond to voxels of one of
            # the target labels
            # surf_vxls==lbl if only one target label
            verts_keep, = numpy.where(numpy.in1d(surf_vxls, all_labels))
            verts_out_mask[verts_indices_of_label[verts_keep]] = True

            if vertex_neighbourhood > 0:
                # These are now the remaining indexes to be checked for
                # neighboring voxels
                verts_indices_of_label = numpy.delete(verts_indices_of_label,
                                                      verts_keep)
                ijk = numpy.delete(ijk, verts_keep, axis=0)

                for vertex_index in range(verts_indices_of_label.size):
                    # Generate the specific grid centered at the voxel ijk
                    ijk_grid = grid + \
                        numpy.tile(ijk[vertex_index, :], (n_grid, 1))

                    # Remove voxels outside the volume
                    indexes_within_limits = numpy.all(
                        [(ijk_grid[:, 0] >= 0),
                         (ijk_grid[:, 0] < volume.dimensions[0]),
                         (ijk_grid[:, 1] >= 0),
                         (ijk_grid[:, 1] < volume.dimensions[1]),
                         (ijk_grid[:, 2] >= 0),
                         (ijk_grid[:, 2] < volume.dimensions[2])],
                        axis=0)
                    ijk_grid = ijk_grid[indexes_within_limits, :]
                    surf_vxls = volume.data[ijk_grid[:, 0], ijk_grid[:, 1],
                                            ijk_grid[:, 2]]

                    # If any of the neighbors is of the target labels include
                    # the current vertex
                    # surf_vxls==lbl if only one target label
                    if numpy.any(numpy.in1d(surf_vxls, all_labels)):
                        verts_out_mask[
                            verts_indices_of_label[vertex_index]] = True

        # Vertex indexes and vertices to keep:
        verts_out_indices, = numpy.where(verts_out_mask)
        verts_out = surface.vertices[verts_out_indices]

        # TODO maybe: make sure that all voxels of this label correspond to at least one vertex.
        # Create a similar mask for faces by picking only triangles of which
        # all 3 vertices are included
        face_out_mask = numpy.c_[verts_out_mask[surface.triangles[:, 0]],
                                 verts_out_mask[surface.triangles[:, 1]],
                                 verts_out_mask[surface.triangles[:, 2]]].all(
                                     axis=1)
        faces_out = surface.triangles[face_out_mask]

        # The old vertices' indexes of faces have to be transformed to the new
        # vrtx_out_inds:
        for iF in range(faces_out.shape[0]):
            for vertex_index in range(3):
                faces_out[iF, vertex_index], = numpy.where(
                    faces_out[iF, vertex_index] == verts_out_indices)

        surface.vertices = verts_out
        surface.triangles = faces_out

        # Write the output surfaces and annotations to files. Also write files
        # with the indexes of vertices to keep.
        IOUtils.write_surface(out_surf_path, surface)

        annotation.set_region_mapping(
            annotation.get_region_mapping_by_indices([verts_out_indices]))
        IOUtils.write_annotation(out_surf_path + ".annot", annotation)

        numpy.save(out_surf_path + "-idx.npy", verts_out_indices)
        numpy.savetxt(out_surf_path + "-idx.txt", verts_out_indices, fmt='%d')
예제 #12
0
 def test_parse_annotation(self):
     file_path = get_data_file(
         self.subject, self.annot_path, "lh.aparc.annot")
     annot = IOUtils.read_annotation(file_path)
     self.assertEqual(_expected_region_names, annot.region_names)
예제 #13
0
    def annot_to_lut(self,
                     annot_path,
                     lut_path=None,
                     subject=None,
                     prefix=''):
        """
        This function creates from an annotation a new lut_file, or adds new
        entries to an existing lut file. In the latter case, new entries have
        labels greater than the maximum alredy existing label inside the lut
        file.

        Parameters
        ----------
        annot_path : str, os.PathLike
            path to annotation.
        lut_path : str, os.PathLike
            path to existing or new LUT file.
        subject : str, optional
            subject name if provided, otherwise env var $SUBJECT is used
        prefiw : str, optional
            prefix for region names (i.e., "ctx-lh-")

        """
        annotation = IOUtils.read_annotation(annot_path)
        subject = subject or os.environ['SUBJECT']
        # If this is an already existing lut file:
        lut_path = lut_path or default_lut_path()
        if os.path.isfile(lut_path):
            # ...find the maximum label in it and add 1
            add_lbl = 1 + \
                      numpy.max(self.read_lut(
                          lut_path=lut_path, key_mode='label')[0])
        else:
            # ...else, set it to 0
            add_lbl = 0
        with open(lut_path, 'a') as fd:
            if add_lbl == 0:
                # TODO: we should include an environment variable for
                # freesurfer version, and print it here
                fd.write("#$Id: %s %s\n\n" % (lut_path, datetime.now()))
                fd.write('#No.\tLabel Name: \tR   G   B   A   \n')
            else:
                fd.write('\n')
            fd.write("""
#Patient: {subject}
#User: {user}
#Annotation path: {annot_path}
#Time: {time}

""".format(
                subject=subject,
                user=os.path.split(os.path.expanduser('~'))[-1],
                annot_path=annot_path,
                time=datetime.now())
            )
            # TODO: align columns
            # NOTE!!! that the fourth and fifth columns of color_table are not
            # used in the lut file!!!
            for name, (r, g, b, dummy1, dummy2), lbl in \
                    zip(annotation.region_names, annotation.regions_color_table,
                        list(range(len(annotation.region_names)))):
                fd.write('%d\t%s\t%d %d %d %d\n' %
                         (lbl + add_lbl, prefix + name, r, g, b, 0))
예제 #14
0
    def sample_vol_on_surf(self, surf_path: str, vol_path: str, annot_path: str, out_surf_path: str,
                           cras_path: str, add_string: str='', vertex_neighbourhood: int=1,
                           add_lbl: list=[], lut_path: Optional[str]=None) -> (Surface, Annotation):
        """
        Sample a volume of a specific label on a surface, by keeping only those surface vertices, the nearest voxel of
        which is of the given label (+ of possibly additional target labels, such as white matter).
        Allow optionally for vertices within a given voxel distance vn from the target voxels.
        """

        lut_path = lut_path or default_lut_path()

        # Read the inputs
        surface = IOUtils.read_surface(surf_path, False)

        annotation = IOUtils.read_annotation(annot_path)
        labels = self.annotation_service.annot_names_to_labels(annotation.region_names,
                                                               add_string=add_string, lut_path=lut_path)
        region_mapping_indexes = numpy.unique(annotation.region_mapping)

        volume_parser = VolumeIO()
        volume = volume_parser.read(vol_path)
        ras2vox_affine_matrix = numpy.linalg.inv(volume.affine_matrix)

        cras = numpy.loadtxt(cras_path)

        grid, n_grid = self.__prepare_grid(vertex_neighbourhood)

        # Initialize the output mask:
        verts_out_mask = numpy.repeat([False], surface.vertices.shape[0])
        for label_index in range(len(region_mapping_indexes)):

            self.logger.info("%s", add_string +
                             annotation.region_names[label_index])

            # Get the indexes of the vertices corresponding to this label:
            verts_indices_of_label, = numpy.where(
                annotation.region_mapping[:] == region_mapping_indexes[label_index])
            verts_indices_of_label_size = verts_indices_of_label.size
            if verts_indices_of_label_size == 0:
                continue

            # Add any additional labels
            all_labels = [labels[label_index]] + add_lbl

            # get the vertices for current label and add cras to take them to
            # scanner ras
            verts_of_label = surface.vertices[verts_indices_of_label, :]
            verts_of_label += numpy.repeat(numpy.expand_dims(
                cras, 1).T, verts_indices_of_label_size, axis=0)

            # Compute the nearest voxel coordinates using the affine transform
            ijk = numpy.round(
                ras2vox_affine_matrix.dot(numpy.c_[verts_of_label, numpy.ones(verts_indices_of_label_size)].T)[:3].T) \
                .astype('i')

            # Get the labels of these voxels:
            surf_vxls = volume.data[ijk[:, 0], ijk[:, 1], ijk[:, 2]]

            # Vertex mask to keep: those that correspond to voxels of one of
            # the target labels
            # surf_vxls==lbl if only one target label
            verts_keep, = numpy.where(numpy.in1d(surf_vxls, all_labels))
            verts_out_mask[verts_indices_of_label[verts_keep]] = True

            if vertex_neighbourhood > 0:
                # These are now the remaining indexes to be checked for
                # neighboring voxels
                verts_indices_of_label = numpy.delete(
                    verts_indices_of_label, verts_keep)
                ijk = numpy.delete(ijk, verts_keep, axis=0)

                for vertex_index in range(verts_indices_of_label.size):
                    # Generate the specific grid centered at the voxel ijk
                    ijk_grid = grid + \
                               numpy.tile(ijk[vertex_index, :], (n_grid, 1))

                    # Remove voxels outside the volume
                    indexes_within_limits = numpy.all([(ijk_grid[:, 0] >= 0), (ijk_grid[:, 0] < volume.dimensions[0]),
                                                       (ijk_grid[:, 1] >= 0), (ijk_grid[
                                                                               :, 1] < volume.dimensions[1]),
                                                       (ijk_grid[:, 2] >= 0), (ijk_grid[:, 2] < volume.dimensions[2])],
                                                      axis=0)
                    ijk_grid = ijk_grid[indexes_within_limits, :]
                    surf_vxls = volume.data[
                        ijk_grid[:, 0], ijk_grid[:, 1], ijk_grid[:, 2]]

                    # If any of the neighbors is of the target labels include
                    # the current vertex
                    # surf_vxls==lbl if only one target label
                    if numpy.any(numpy.in1d(surf_vxls, all_labels)):
                        verts_out_mask[
                            verts_indices_of_label[vertex_index]] = True

        # Vertex indexes and vertices to keep:
        verts_out_indices, = numpy.where(verts_out_mask)
        verts_out = surface.vertices[verts_out_indices]

        # TODO maybe: make sure that all voxels of this label correspond to at least one vertex.
        # Create a similar mask for faces by picking only triangles of which
        # all 3 vertices are included
        face_out_mask = numpy.c_[
            verts_out_mask[surface.triangles[:, 0]], verts_out_mask[surface.triangles[:, 1]], verts_out_mask[
                surface.triangles[:, 2]]].all(axis=1)
        faces_out = surface.triangles[face_out_mask]

        # The old vertices' indexes of faces have to be transformed to the new
        # vrtx_out_inds:
        for iF in range(faces_out.shape[0]):
            for vertex_index in range(3):
                faces_out[iF, vertex_index], = numpy.where(
                    faces_out[iF, vertex_index] == verts_out_indices)

        surface.vertices = verts_out
        surface.triangles = faces_out

        # Write the output surfaces and annotations to files. Also write files
        # with the indexes of vertices to keep.
        IOUtils.write_surface(out_surf_path, surface)

        annotation.set_region_mapping(
            annotation.get_region_mapping_by_indices([verts_out_indices]))
        IOUtils.write_annotation(out_surf_path + ".annot", annotation)

        numpy.save(out_surf_path + "-idx.npy", verts_out_indices)
        numpy.savetxt(out_surf_path + "-idx.txt", verts_out_indices, fmt='%d')

        return surface, annotation
예제 #15
0
import os
import sys

from tvb.recon.algo.service.mapping_service import MappingService
from tvb.recon.io.factory import IOUtils
from tvb.recon.io.generic import GenericIO

if __name__ == "__main__":
    direc = sys.argv[1]
    out_file = sys.argv[2]

    annot_cort_lh = IOUtils.read_annotation(os.path.join(direc, "lh.aparc.annot"))
    annot_cort_rh = IOUtils.read_annotation(os.path.join(direc, "rh.aparc.annot"))

    annot_subcort_lh = IOUtils.read_annotation(os.path.join(direc, "lh.aseg.annot"))
    annot_subcort_rh = IOUtils.read_annotation(os.path.join(direc, "rh.aseg.annot"))

    mapping = MappingService(annot_cort_lh, annot_cort_rh, annot_subcort_lh, annot_subcort_rh)

    dict_fs_custom = mapping.get_mapping_for_connectome_generation()

    genericIO = GenericIO()
    genericIO.write_dict_to_txt_file(dict_fs_custom, out_file)
예제 #16
0
 def annot_to_conn_conf(self, annot_path, conn_conf_path):
     annotation = IOUtils.read_annotation(annot_path)
     with open(conn_conf_path, 'w') as fd:
         for id, name in enumerate(annotation.region_names):
             fd.write('%d\t%s\n' % (id, name))
예제 #17
0
 def overlap_surface_annotation(
         self, surface_path: os.PathLike, annotation_path: os.PathLike, snapshot_name: str=SNAPSHOT_NAME):
     annotation = IOUtils.read_annotation(annotation_path)
     surface = IOUtils.read_surface(surface_path, False)
     self.writer.write_surface_with_annotation(surface, annotation,
                                               self.generate_file_name('surface_annotation', snapshot_name))