Exemplo n.º 1
0
 def __init__(self,
              snapshots_directory: os.PathLike,
              snapshot_count: int = 0):
     self.generic_io = GenericIO()
     self.writer = ImageWriter(snapshots_directory)
     self.snapshot_count = snapshot_count
     self.logger = get_logger(__name__)
Exemplo n.º 2
0
 def write_surface_zip(self, zip_fname, surface):
     generic_io = GenericIO()
     sv = generic_io.np_save_strio(surface.vertices, '%f')
     sf = generic_io.np_save_strio(surface.triangles, '%d')
     szf = StringIO()
     zf = zipfile.ZipFile(szf, 'w')
     zf.writestr('vertices.txt', sv.getvalue())
     zf.writestr('triangles.txt', sf.getvalue())
     zf.close()
     with open(zip_fname, 'wb') as fd:
         fd.write(szf.getvalue())
Exemplo n.º 3
0
def generate_schema_txt(ct_labeled_volume, schema_dir, schema_file):
    sensor_name = "sensor%s_"

    volumeIO = VolumeIO()
    vol = volumeIO.read(ct_labeled_volume)
    labels_nr = numpy.unique(vol.data).size

    schema_dict = dict()
    schema_dict.update({lbl: sensor_name % lbl for lbl in range(labels_nr)})

    genericIO = GenericIO()
    genericIO.write_dict_to_txt_file(schema_dict, os.path.join(schema_dir, schema_file))
Exemplo n.º 4
0
def generate_schema_txt(ct_labeled_volume, schema_dir, schema_file):
    sensor_name = "sensor%s_"

    volumeIO = VolumeIO()
    vol = volumeIO.read(ct_labeled_volume)
    labels_nr = numpy.unique(vol.data).size

    schema_dict = dict()
    schema_dict.update({lbl: sensor_name % lbl for lbl in range(labels_nr)})

    genericIO = GenericIO()
    genericIO.write_dict_to_txt_file(schema_dict,
                                     os.path.join(schema_dir, schema_file))
Exemplo n.º 5
0
def create_tvb_dataset(atlas_suffix: AtlasSuffix, mri_direc: os.PathLike,
                       region_details_direc: os.PathLike,
                       weights_file: os.PathLike,
                       tracts_file: os.PathLike,
                       out_dir: os.PathLike,
                       bring_t1=False):
    weights_matrix = numpy.loadtxt(str(weights_file), dtype='i', delimiter=' ')
    weights_matrix += weights_matrix.T

    tracts_matrix = numpy.loadtxt(str(tracts_file), dtype='f', delimiter=' ')
    tracts_matrix += tracts_matrix.T

    is_cortical_rm = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CORTICAL_TXT.value.replace("%s", atlas_suffix)), usecols=[0],
        dtype='i')
    region_names = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CENTERS_TXT.value.replace("%s", atlas_suffix)), usecols=[0],
        dtype="str")
    region_centers = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CENTERS_TXT.value.replace("%s", atlas_suffix)), usecols=[1, 2, 3])
    region_areas = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.AREAS_TXT.value.replace("%s", atlas_suffix)), usecols=[0])
    region_orientations = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.ORIENTATIONS_TXT.value.replace("%s", atlas_suffix)),
        usecols=[0, 1, 2])
    rm_idx = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.RM_TO_APARC_ASEG_TXT.value.replace("%s", atlas_suffix)),
        usecols=[0, 1], dtype='i')
    rm_index_dict = dict(zip(rm_idx[:, 0], rm_idx[:, 1]))
    print(rm_index_dict)

    genericIO = GenericIO()
    genericIO.write_connectivity_zip(out_dir, weights_matrix, tracts_matrix, is_cortical_rm, region_names,
                                     region_centers, region_areas, region_orientations, atlas_suffix)

    aparc_aseg_file = os.path.join(mri_direc, T1Files.APARC_ASEG_NII_GZ.value.replace("%s", atlas_suffix))
    aparc_aseg_volume = IOUtils.read_volume(aparc_aseg_file)

    volume_service = VolumeService()
    aparc_aseg_cor_volume = volume_service.change_labels_of_aparc_aseg(atlas_suffix, aparc_aseg_volume, rm_index_dict,
                                                                       weights_matrix.shape[0])
    IOUtils.write_volume(os.path.join(out_dir, OutputConvFiles.APARC_ASEG_COR_NII_GZ.value.replace("%s", atlas_suffix)),
                         aparc_aseg_cor_volume)

    if bring_t1:
        shutil.copy2(os.path.join(mri_direc, "T1.nii.gz"), out_dir)
Exemplo n.º 6
0
def create_tvb_dataset(atlas_suffix: AtlasSuffix, mri_direc: os.PathLike,
                       region_details_direc: os.PathLike,
                       weights_file: os.PathLike,
                       tracts_file: os.PathLike,
                       out_dir: os.PathLike,
                       bring_t1=False):
    weights_matrix = numpy.loadtxt(str(weights_file), dtype='i', delimiter=',')
    weights_matrix += weights_matrix.T

    tracts_matrix = numpy.loadtxt(str(tracts_file), dtype='f', delimiter=',')
    tracts_matrix += tracts_matrix.T

    is_cortical_rm = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CORTICAL_TXT.value.replace("%s", atlas_suffix)), usecols=[0],
        dtype='i')
    region_names = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CENTERS_TXT.value.replace("%s", atlas_suffix)), usecols=[0],
        dtype="str")
    region_centers = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.CENTERS_TXT.value.replace("%s", atlas_suffix)), usecols=[1, 2, 3])
    region_areas = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.AREAS_TXT.value.replace("%s", atlas_suffix)), usecols=[0])
    region_orientations = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.ORIENTATIONS_TXT.value.replace("%s", atlas_suffix)),
        usecols=[0, 1, 2])
    rm_idx = numpy.genfromtxt(
        os.path.join(region_details_direc, AsegFiles.RM_TO_APARC_ASEG_TXT.value.replace("%s", atlas_suffix)),
        usecols=[0, 1], dtype='i')
    rm_index_dict = dict(zip(rm_idx[:, 0], rm_idx[:, 1]))
    print(rm_index_dict)

    genericIO = GenericIO()
    genericIO.write_connectivity_zip(out_dir, weights_matrix, tracts_matrix, is_cortical_rm, region_names,
                                     region_centers, region_areas, region_orientations, atlas_suffix)

    aparc_aseg_file = os.path.join(mri_direc, T1Files.APARC_ASEG_NII_GZ.value.replace("%s", atlas_suffix))
    aparc_aseg_volume = IOUtils.read_volume(aparc_aseg_file)

    volume_service = VolumeService()
    aparc_aseg_cor_volume = volume_service.change_labels_of_aparc_aseg(atlas_suffix, aparc_aseg_volume, rm_index_dict,
                                                                       weights_matrix.shape[0])
    IOUtils.write_volume(os.path.join(out_dir, OutputConvFiles.APARC_ASEG_COR_NII_GZ.value.replace("%s", atlas_suffix)),
                         aparc_aseg_cor_volume)

    if bring_t1:
        shutil.copy2(os.path.join(mri_direc, "T1.nii.gz"), out_dir)
Exemplo n.º 7
0
    def compute_seeg_gain_matrix(self, seeg_xyz: os.PathLike, cort_file: os.PathLike, subcort_file: os.PathLike,
                                 cort_rm: os.PathLike, subcort_rm: os.PathLike,
                                 out_gain_mat: os.PathLike) -> numpy.ndarray:
        genericIO = GenericIO()

        sensors = numpy.genfromtxt(seeg_xyz, usecols=[1, 2, 3])

        cort_vertices = genericIO.read_field_from_zip("vertices.txt", cort_file)
        cort_triangles = genericIO.read_field_from_zip("triangles.txt", cort_file, dtype="i")
        cort_surf = Surface(cort_vertices, cort_triangles)
        cort_normals = cort_surf.vertex_normals()
        cort_areas = cort_surf.get_vertex_areas()

        subcort_vertices = genericIO.read_field_from_zip("vertices.txt", subcort_file)
        subcort_triangles = genericIO.read_field_from_zip("triangles.txt", subcort_file, dtype="i")
        subcort_surf = Surface(subcort_vertices, subcort_triangles)
        subcort_areas = subcort_surf.get_vertex_areas()

        cort_rm = list(numpy.genfromtxt(cort_rm, usecols=[0], dtype='i'))
        subcort_rm = list(numpy.genfromtxt(subcort_rm, usecols=[0], dtype='i'))
        region_list = numpy.unique(cort_rm + subcort_rm)

        nr_regions = len(region_list)
        nr_vertices = cort_surf.vertices.shape[0] + subcort_surf.vertices.shape[0]

        verts_regions_mat = self._get_verts_regions_matrix(nr_vertices, nr_regions, cort_rm + subcort_rm)

        gain_matrix = self._gain_matrix_dipole(cort_surf.vertices, cort_normals, cort_areas, sensors)

        gain_matrix_subcort = self._gain_matrix_inv_square(subcort_surf.vertices, subcort_areas, sensors)

        gain_total = numpy.concatenate((gain_matrix, gain_matrix_subcort), axis=1)

        gain_out = gain_total @ verts_regions_mat
        numpy.savetxt(out_gain_mat, gain_out)

        return gain_out
Exemplo n.º 8
0
        "-ss", help='Create snapshots of the transformed surface', action="store_true")

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_arguments()

    surface_path = os.path.expandvars(args.surface_path)
    output_path = os.path.expandvars(args.output_path)

    logger = get_logger(__name__)

    image_processor = ImageProcessor(snapshots_directory=os.environ[SNAPSHOTS_DIRECTORY_ENVIRON_VAR],
                                     snapshot_count=int(os.environ.get(SNAPSHOT_NUMBER_ENVIRON_VAR, 0)))
    generic_io = GenericIO()

    logger.info("The surface transformation process has began")
    surface_io = IOUtils.surface_io_factory(surface_path)
    surface = surface_io.read(surface_path, False)

    if len(args.matrix_paths) is not 0:
        transformation_matrices = []

        for transform_matrix_path in args.matrix_paths:
            transformation_matrices.append(
                numpy.array(generic_io.read_transformation_matrix(os.path.expandvars(transform_matrix_path))))

        for i in range(len(surface.vertices)):
            for j in range(len(transformation_matrices)):
                if len(transformation_matrices[j]) > 3:
Exemplo n.º 9
0
    return parser.parse_args()


if __name__ == "__main__":
    args = parse_arguments()

    surface_path = os.path.expandvars(args.surface_path)
    output_path = os.path.expandvars(args.output_path)

    logger = get_logger(__name__)

    image_processor = ImageProcessor(
        snapshots_directory=os.environ[SNAPSHOTS_DIRECTORY_ENVIRON_VAR],
        snapshot_count=int(os.environ.get(SNAPSHOT_NUMBER_ENVIRON_VAR, 0)))
    generic_io = GenericIO()

    logger.info("The surface transformation process has began")
    surface_io = IOUtils.surface_io_factory(surface_path)
    surface = surface_io.read(surface_path, False)

    if len(args.matrix_paths) is not 0:
        transformation_matrices = []

        for transform_matrix_path in args.matrix_paths:
            transformation_matrices.append(
                numpy.array(
                    generic_io.read_transformation_matrix(
                        os.path.expandvars(transform_matrix_path))))

        for i in range(len(surface.vertices)):
Exemplo n.º 10
0
def test_read_cc_point():
    generic_io = GenericIO()
    file_path = get_data_file("fsaverage_modified",
                              "scripts", "ponscc.cut.log")
    cc_point = generic_io.read_cc_point(file_path, GenericIO.point_line_flag)
    assert cc_point == [100.0, 100.0, 100.0, 1]
Exemplo n.º 11
0
class ImageProcessor(object):
    def __init__(self, snapshots_directory, snapshot_count=0):
        self.generic_io = GenericIO()
        self.writer = ImageWriter(snapshots_directory)
        self.snapshot_count = snapshot_count
        self.logger = get_logger(__name__)

    def generate_file_name(self,
                           current_projection,
                           snapshot_name=SNAPSHOT_NAME):
        file_name = snapshot_name + "_" + \
            current_projection + "_" + str(self.snapshot_count)
        return file_name

    def read_t1_affine_matrix(self):
        t1_volume = IOUtils.read_volume(
            os.path.join(os.environ[MRI_DIRECTORY], os.environ[T1_RAS_VOLUME]))
        return t1_volume.affine_matrix

    def show_single_volume(self,
                           volume_path,
                           use_cc_point,
                           snapshot_name=SNAPSHOT_NAME):

        volume = IOUtils.read_volume(volume_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume.get_center_point()

        for projection in PROJECTIONS:
            try:
                x_axis_coords, y_axis_coords, volume_matrix = volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = volume.get_center_point()
                x_axis_coords, y_axis_coords, volume_matrix = volume.slice_volume(
                    projection, new_ras)
                self.logger.info(
                    "The volume center point has been used for %s snapshot of %s.",
                    projection, volume_path)

            self.writer.write_matrix(
                x_axis_coords, y_axis_coords, volume_matrix,
                self.generate_file_name(projection, snapshot_name))

    def overlap_2_volumes(self,
                          background_path,
                          overlay_path,
                          use_cc_point,
                          snapshot_name=SNAPSHOT_NAME):

        background_volume = IOUtils.read_volume(background_path)
        overlay_volume = IOUtils.read_volume(overlay_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = background_volume.get_center_point()

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = background_volume.slice_volume(
                    projection, ras)
                x1, y1, overlay_matrix = overlay_volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = background_volume.get_center_point()
                x, y, background_matrix = background_volume.slice_volume(
                    projection, new_ras)
                x1, y1, overlay_matrix = overlay_volume.slice_volume(
                    projection, new_ras)
                self.logger.info(
                    "The volume center point has been used for %s snapshot of %s and %s.",
                    projection, background_path, overlay_path)

            self.writer.write_2_matrices(
                x, y, background_matrix, x1, y1, overlay_matrix,
                self.generate_file_name(projection, snapshot_name))

    def overlap_3_volumes(self,
                          background_path,
                          overlay_1_path,
                          overlay_2_path,
                          use_cc_point,
                          snapshot_name=SNAPSHOT_NAME):

        volume_background = IOUtils.read_volume(background_path)
        volume_overlay_1 = IOUtils.read_volume(overlay_1_path)
        volume_overlay_2 = IOUtils.read_volume(overlay_2_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume_background.get_center_point()

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = volume_background.slice_volume(
                    projection, ras)
                x1, y1, overlay_1_matrix = volume_overlay_1.slice_volume(
                    projection, ras)
                x2, y2, overlay_2_matrix = volume_overlay_2.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = volume_background.get_center_point()
                x, y, background_matrix = volume_background.slice_volume(
                    projection, new_ras)
                x1, y1, overlay_1_matrix = volume_overlay_1.slice_volume(
                    projection, new_ras)
                x2, y2, overlay_2_matrix = volume_overlay_2.slice_volume(
                    projection, new_ras)
                self.logger.info(
                    "The volume center point has been used for %s snapshot of %s, %s and %s.",
                    projection, background_path, overlay_1_path,
                    overlay_2_path)

            self.writer.write_3_matrices(
                x, y, background_matrix, x1, y1, overlay_1_matrix, x2, y2,
                overlay_2_matrix,
                self.generate_file_name(projection, snapshot_name))

    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))

    def overlap_volume_surfaces(self,
                                volume_background,
                                surfaces_path,
                                use_center_surface,
                                use_cc_point,
                                snapshot_name=SNAPSHOT_NAME):
        volume = IOUtils.read_volume(volume_background)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume.get_center_point()

        surfaces = [
            IOUtils.read_surface(os.path.expandvars(surface),
                                 use_center_surface)
            for surface in surfaces_path
        ]

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = volume.slice_volume(projection, ras)
            except IndexError:
                ras = volume.get_center_point()
                x, y, background_matrix = volume.slice_volume(projection, ras)
                self.logger.info(
                    "The volume center point has been used for %s snapshot of %s and %s.",
                    projection, volume_background, surfaces_path)

            clear_flag = True
            for surface_index, surface in enumerate(surfaces):
                surf_x_array, surf_y_array = surface.cut_by_plane(
                    projection, ras)
                self.writer.write_matrix_and_surfaces(x, y, background_matrix,
                                                      surf_x_array,
                                                      surf_y_array,
                                                      surface_index,
                                                      clear_flag)
                clear_flag = False
            self.writer.save_figure(
                self.generate_file_name(projection, snapshot_name))

    def show_aparc_aseg_with_new_values(
            self,
            aparc_aseg_volume_path,
            region_values_path,
            background_volume_path,
            use_cc_point,
            fs_to_conn_indices_mapping_path=FS_TO_CONN_INDICES_MAPPING_PATH,
            snapshot_name=SNAPSHOT_NAME):
        """

        Parameters
        ----------
        aparc_aseg_volume_path
        region_values_path
        background_volume_path
        use_cc_point
        fs_to_conn_indices_mapping_path
        snapshot_name

        Returns
        -------

        """

        aparc_aseg_volume = IOUtils.read_volume(aparc_aseg_volume_path)

        fs_to_conn_indices_mapping = {}
        with open(fs_to_conn_indices_mapping_path, 'r') as fd:
            for line in fd.readlines():
                key, _, val = line.strip().split()
                fs_to_conn_indices_mapping[int(key)] = int(val)

        len_fs_conn = len(fs_to_conn_indices_mapping)

        conn_measure = np.loadtxt(region_values_path)
        npad = len_fs_conn - conn_measure.size
        conn_measure = np.pad(conn_measure, (0, npad), 'constant')

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = aparc_aseg_volume.get_center_point()

        background_volume = None
        if background_volume_path:
            background_volume = IOUtils.read_volume(background_volume_path)

        for projection in PROJECTIONS:
            self._aparc_aseg_projection(aparc_aseg_volume,
                                        aparc_aseg_volume_path, projection,
                                        ras, fs_to_conn_indices_mapping,
                                        background_volume,
                                        background_volume_path, snapshot_name,
                                        conn_measure)

    def _aparc_aseg_projection(self, aparc_aseg_volume, aparc_aseg_volume_path,
                               projection, ras, fs_to_conn_indices_mapping,
                               background_volume, background_volume_path,
                               snapshot_name, conn_measure):

        try:
            slice = aparc_aseg_volume.slice_volume(projection, ras)
        except IndexError:
            new_ras = aparc_aseg_volume.get_center_point()
            slice = aparc_aseg_volume.slice_volume(projection, new_ras)
            msg = "The volume center point has been used for %s snapshot of %s."
            self.logger.info(msg, projection, aparc_aseg_volume_path)

        x_axis_coords, y_axis_coords, aparc_aseg_matrix = slice

        for i, row in enumerate(aparc_aseg_matrix):
            for j, el in enumerate(row):
                if el > 0:
                    if el in fs_to_conn_indices_mapping:
                        idx = fs_to_conn_indices_mapping.get(el)
                        new_val = conn_measure[int(idx)]
                        aparc_aseg_matrix[i, j] = new_val
                    else:
                        aparc_aseg_matrix[i, j] = -1

        if background_volume_path == '':
            self.writer.write_matrix(
                x_axis_coords, y_axis_coords, aparc_aseg_matrix,
                self.generate_file_name(projection, snapshot_name), 'hot')
        else:
            try:
                bx_axis_coords, by_axis_coords, bvolume_matrix = background_volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = aparc_aseg_volume.get_center_point()
                bx_axis_coords, by_axis_coords, bvolume_matrix = background_volume.slice_volume(
                    projection, new_ras)
                self.logger.info(
                    "The volume center point has been used for %s snapshot of %s and %s.",
                    projection, aparc_aseg_volume_path, background_volume_path)

            self.writer.write_2_matrices(
                bx_axis_coords, by_axis_coords, bvolume_matrix, x_axis_coords,
                y_axis_coords, aparc_aseg_matrix,
                self.generate_file_name(projection, snapshot_name))
Exemplo n.º 12
0
import argparse
import subprocess
import os
import numpy
from tvb.recon.algo.service.annotation import AnnotationService
from tvb.recon.algo.service.mapping_service import MappingService
from tvb.recon.algo.service.surface import SurfaceService
from tvb.recon.dax import AtlasSuffix
from tvb.recon.dax.mappings import AsegFiles
from tvb.recon.io.factory import IOUtils
from tvb.recon.io.generic import GenericIO

genericIO = GenericIO()


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()
Exemplo n.º 13
0
 def __init__(self, snapshots_directory: os.PathLike, snapshot_count: int=0):
     self.generic_io = GenericIO()
     self.writer = ImageWriter(snapshots_directory)
     self.snapshot_count = snapshot_count
     self.logger = get_logger(__name__)
Exemplo n.º 14
0
class ImageProcessor(object):

    def __init__(self, snapshots_directory: os.PathLike, snapshot_count: int=0):
        self.generic_io = GenericIO()
        self.writer = ImageWriter(snapshots_directory)
        self.snapshot_count = snapshot_count
        self.logger = get_logger(__name__)

    def generate_file_name(self, current_projection: os.PathLike,
                           snapshot_name: os.PathLike=SNAPSHOT_NAME) -> str:
        file_name = snapshot_name + "_" + \
            current_projection + "_" + str(self.snapshot_count)
        return file_name

    def read_t1_affine_matrix(self) -> np.ndarray:
        t1_volume = IOUtils.read_volume(os.path.join(
            os.environ[MRI_DIRECTORY], os.environ[T1_RAS_VOLUME]))
        return t1_volume.affine_matrix

    def show_single_volume(self, volume_path: os.PathLike, use_cc_point: bool,
                           snapshot_name: os.PathLike=SNAPSHOT_NAME):

        volume = IOUtils.read_volume(volume_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume.get_center_point()

        for projection in PROJECTIONS:
            try:
                x_axis_coords, y_axis_coords, volume_matrix = volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = volume.get_center_point()
                x_axis_coords, y_axis_coords, volume_matrix = volume.slice_volume(
                    projection, new_ras)
                self.logger.info("The volume center point has been used for %s snapshot of %s.", projection,
                                 volume_path)

            self.writer.write_matrix(x_axis_coords, y_axis_coords, volume_matrix,
                                     self.generate_file_name(projection, snapshot_name))

    def overlap_2_volumes(self, background_path: os.PathLike, overlay_path: os.PathLike,
                          use_cc_point: bool, snapshot_name: str=SNAPSHOT_NAME):

        background_volume = IOUtils.read_volume(background_path)
        overlay_volume = IOUtils.read_volume(overlay_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = background_volume.get_center_point()

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = background_volume.slice_volume(
                    projection, ras)
                x1, y1, overlay_matrix = overlay_volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = background_volume.get_center_point()
                x, y, background_matrix = background_volume.slice_volume(
                    projection, new_ras)
                x1, y1, overlay_matrix = overlay_volume.slice_volume(
                    projection, new_ras)
                self.logger.info("The volume center point has been used for %s snapshot of %s and %s.", projection,
                                 background_path, overlay_path)

            self.writer.write_2_matrices(x, y, background_matrix, x1, y1, overlay_matrix,
                                         self.generate_file_name(projection, snapshot_name))

    def overlap_3_volumes(self, background_path: os.PathLike, overlay_1_path: os.PathLike,
                          overlay_2_path: os.PathLike, use_cc_point: bool,
                          snapshot_name: str=SNAPSHOT_NAME):

        volume_background = IOUtils.read_volume(background_path)
        volume_overlay_1 = IOUtils.read_volume(overlay_1_path)
        volume_overlay_2 = IOUtils.read_volume(overlay_2_path)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume_background.get_center_point()

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = volume_background.slice_volume(
                    projection, ras)
                x1, y1, overlay_1_matrix = volume_overlay_1.slice_volume(
                    projection, ras)
                x2, y2, overlay_2_matrix = volume_overlay_2.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = volume_background.get_center_point()
                x, y, background_matrix = volume_background.slice_volume(
                    projection, new_ras)
                x1, y1, overlay_1_matrix = volume_overlay_1.slice_volume(
                    projection, new_ras)
                x2, y2, overlay_2_matrix = volume_overlay_2.slice_volume(
                    projection, new_ras)
                self.logger.info("The volume center point has been used for %s snapshot of %s, %s and %s.", projection,
                                 background_path, overlay_1_path, overlay_2_path)

            self.writer.write_3_matrices(x, y, background_matrix, x1, y1, overlay_1_matrix, x2, y2, overlay_2_matrix,
                                         self.generate_file_name(projection, snapshot_name))

    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))

    def overlap_volume_surfaces(self, volume_background: os.PathLike, surfaces_path: os.PathLike,
                                use_center_surface: bool, use_cc_point: bool, snapshot_name: str=SNAPSHOT_NAME):
        volume = IOUtils.read_volume(volume_background)

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = volume.get_center_point()

        surfaces = [IOUtils.read_surface(os.path.expandvars(surface), use_center_surface) for surface in
                    surfaces_path]

        for projection in PROJECTIONS:
            try:
                x, y, background_matrix = volume.slice_volume(projection, ras)
            except IndexError:
                ras = volume.get_center_point()
                x, y, background_matrix = volume.slice_volume(projection, ras)
                self.logger.info("The volume center point has been used for %s snapshot of %s and %s.", projection,
                                 volume_background, surfaces_path)

            clear_flag = True
            for surface_index, surface in enumerate(surfaces):
                surf_x_array, surf_y_array = surface.cut_by_plane(
                    projection, ras)
                self.writer.write_matrix_and_surfaces(x, y, background_matrix, surf_x_array, surf_y_array,
                                                      surface_index, clear_flag)
                clear_flag = False
            self.writer.save_figure(
                self.generate_file_name(projection, snapshot_name))

    def show_aparc_aseg_with_new_values(
            self, aparc_aseg_volume_path: os.PathLike, region_values_path: os.PathLike,
            background_volume_path: os.PathLike, use_cc_point: bool,
            fs_to_conn_indices_mapping_path: os.PathLike=FS_TO_CONN_INDICES_MAPPING_PATH,
            snapshot_name: str=SNAPSHOT_NAME):
        """

        Parameters
        ----------
        aparc_aseg_volume_path
        region_values_path
        background_volume_path
        use_cc_point
        fs_to_conn_indices_mapping_path
        snapshot_name

        Returns
        -------

        """

        aparc_aseg_volume = IOUtils.read_volume(aparc_aseg_volume_path)

        fs_to_conn_indices_mapping = {}
        with open(fs_to_conn_indices_mapping_path, 'r') as fd:
            for line in fd.readlines():
                key, _, val = line.strip().split()
                fs_to_conn_indices_mapping[int(key)] = int(val)

        len_fs_conn = len(fs_to_conn_indices_mapping)

        conn_measure = np.loadtxt(region_values_path)
        npad = len_fs_conn - conn_measure.size
        conn_measure = np.pad( conn_measure, (0, npad), 'constant')

        if use_cc_point:
            ras = self.generic_io.get_ras_coordinates(
                self.read_t1_affine_matrix())
        else:
            ras = aparc_aseg_volume.get_center_point()

        background_volume = None
        if background_volume_path:
            background_volume = IOUtils.read_volume(background_volume_path)

        for projection in PROJECTIONS:
            self._aparc_aseg_projection(
                aparc_aseg_volume, aparc_aseg_volume_path, projection, ras,
                fs_to_conn_indices_mapping,
                background_volume, background_volume_path,
                snapshot_name, conn_measure
            )

    def _aparc_aseg_projection(
            self, aparc_aseg_volume: os.PathLike, aparc_aseg_volume_path: os.PathLike, projection: np.ndarray,
            ras: Union[np.ndarray, list], fs_to_conn_indices_mapping: dict,
            background_volume: Volume, background_volume_path: os.PathLike, snapshot_name: str,
            conn_measure: Union[np.ndarray, list]):

        try:
            slice = aparc_aseg_volume.slice_volume(projection, ras)
        except IndexError:
            new_ras = aparc_aseg_volume.get_center_point()
            slice = aparc_aseg_volume.slice_volume( projection, new_ras)
            msg = "The volume center point has been used for %s snapshot of %s."
            self.logger.info(msg, projection, aparc_aseg_volume_path)

        x_axis_coords, y_axis_coords, aparc_aseg_matrix  = slice

        for i, row in enumerate(aparc_aseg_matrix):
            for j, el in enumerate(row):
                if el > 0:
                    if el in fs_to_conn_indices_mapping:
                        idx = fs_to_conn_indices_mapping.get(el)
                        new_val = conn_measure[int(idx)]
                        aparc_aseg_matrix[i, j] = new_val
                    else:
                        aparc_aseg_matrix[i, j] = -1

        if background_volume_path == '':
            self.writer.write_matrix(x_axis_coords, y_axis_coords, aparc_aseg_matrix,
                                     self.generate_file_name(projection, snapshot_name), 'hot')
        else:
            try:
                bx_axis_coords, by_axis_coords, bvolume_matrix = background_volume.slice_volume(
                    projection, ras)
            except IndexError:
                new_ras = aparc_aseg_volume.get_center_point()
                bx_axis_coords, by_axis_coords, bvolume_matrix = background_volume.slice_volume(
                    projection, new_ras)
                self.logger.info("The volume center point has been used for %s snapshot of %s and %s.", projection,
                                 aparc_aseg_volume_path, background_volume_path)

            self.writer.write_2_matrices(bx_axis_coords, by_axis_coords, bvolume_matrix, x_axis_coords,
                                         y_axis_coords,
                                         aparc_aseg_matrix,
                                         self.generate_file_name(projection, snapshot_name))
Exemplo n.º 15
0
class FreeViewController(object):
    logger = get_logger(__name__)
    generic_io = GenericIO()

    target_screenshot_name = SNAPSHOT_NAME
    target_file = "slices.txt"
    cameraPositionsFileName = "cameraPositions.txt"
    in_point_file = "$SUBJ_DIR/scripts/ponscc.cut.log"
    point_line_flag = "CC-CRS"
    in_matrix_file = 'matrix.txt'

    folder_figures = os.environ[SNAPSHOTS_DIRECTORY_ENVIRON_VAR]

    def write_snapshot_camera_positions(self, projection):
        """
        TODO
        """
        count_number = int(os.environ[SNAPSHOT_NUMBER_ENVIRON_VAR])
        file_ref = open(self.cameraPositionsFileName, 'wb')
        png_path = self._get_image_name(count_number, projection, "1")
        file_ref.write("-cam Azimuth 0 Elevation 0 -ss %s\n" % png_path)
        png_path = self._get_image_name(count_number, projection, "2")
        file_ref.write("-cam Azimuth 90 Elevation 0 -ss %s\n" % png_path)
        png_path = self._get_image_name(count_number, projection, "3")
        file_ref.write("-cam Azimuth 180 Elevation 0 -ss %s\n" % png_path)
        png_path = self._get_image_name(count_number, projection, "4")
        file_ref.write("-cam Azimuth 270 Elevation 0 -ss %s\n" % png_path)
        png_path = self._get_image_name(count_number, projection, "5")
        file_ref.write("-cam Azimuth 0 Elevation 90 -ss %s\n" % png_path)
        png_path = self._get_image_name(count_number, projection, "6")
        file_ref.write("-cam Azimuth 0 Elevation 180 -ss %s\n" % png_path)
        file_ref.write(" -quit")
        file_ref.close()
        self.logger.info("It was written  " + self.cameraPositionsFileName)

    def _get_image_name(self, count_number, projection, suffix):
        return os.path.join(
            self.folder_figures, self.target_screenshot_name +
            str(count_number) + projection + suffix + SNAPSHOT_EXTENSION)

    def prepare_screenshot(self):
        matrix = self.generic_io.read_transformation_matrix(
            self.in_matrix_file)
        self.logger.info("Read idx2rsa matrix: %s" % matrix)

        vector = self.generic_io.read_cc_point(self.in_point_file,
                                               self.point_line_flag)
        self.logger.info("Read vector: %s" % vector)

        a = numpy.array(matrix)
        b = numpy.array(vector)
        ras_vector = a.dot(b)
        self.logger.info("Computed RAS vector: %s" % ras_vector)

        ras_string = ' '.join(map(str, ras_vector[:-1]))
        self._write_screenshot_command(self.target_file,
                                       self.target_screenshot_name, projection,
                                       ras_string)

    def _write_screenshot_command(self, file_path, shot_name, projection,
                                  ras_position):
        """
        Open slices.txt file and write the current screen-shot instruction: target_file_name and position
        """
        count_number = int(os.environ[SNAPSHOT_NUMBER_ENVIRON_VAR])
        file_ref = open(file_path, 'wb')
        png_path = os.path.join(
            self.folder_figures,
            shot_name + str(count_number) + projection + SNAPSHOT_EXTENSION)
        file_ref.write("-ras %s -ss %s" % (ras_position, png_path))
        file_ref.write(" -quit")
        file_ref.close()
        self.logger.info("It was written " + file_path)
Exemplo n.º 16
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)