def test_volume_calc(tmpdir, test_config_path):
    tmpdir = str(tmpdir)
    atlas = Atlas(test_config_path)

    structures_file_path = atlas.get_structures_path()
    registration_config = test_config_path

    volumes_csv_path = os.path.join(tmpdir, "volumes.csv")
    calculate_volumes(
        registered_atlas_path,
        registered_hemispheres_path,
        structures_file_path,
        registration_config,
        volumes_csv_path,
    )

    volumes_validate = pd.read_csv(volumes_validate_path,
                                   sep=",",
                                   header=0,
                                   quotechar='"')
    volumes_test = pd.read_csv(volumes_csv_path,
                               sep=",",
                               header=0,
                               quotechar='"')

    assert (volumes_validate == volumes_test).all().all()
    def __init__(
        self,
        config_path,
        affine_n_steps=6,
        affine_use_n_steps=5,
        freeform_n_steps=6,
        freeform_use_n_steps=4,
        bending_energy_weight=0.95,
        grid_spacing_x=-10,
        smoothing_sigma_reference=-1.0,
        smoothing_sigma_floating=-1.0,
        histogram_n_bins_floating=128,
        histogram_n_bins_reference=128,
    ):
        self.config = get_config_ob(config_path)
        self.transform_program_path = self.__get_binary("transform")
        self.affine_reg_program_path = self.__get_binary("affine")
        self.freeform_reg_program_path = self.__get_binary("freeform")
        self.segmentation_program_path = self.__get_binary("segmentation")

        # affine (reg_aladin)
        self.affine_reg_pyramid_steps = ("-ln", affine_n_steps)
        self.affine_reg_used_pyramid_steps = ("-lp", affine_use_n_steps)

        # freeform (ref_f3d)
        self.freeform_reg_pyramid_steps = ("-ln", freeform_n_steps)
        self.freeform_reg_used_pyramid_steps = ("-lp", freeform_use_n_steps)

        self.freeform_reg_grid_spacing_x = ("-sx", grid_spacing_x)

        self.bending_energy_penalty_weight = ("-be", bending_energy_weight)

        self.reference_image_smoothing_sigma = (
            "-smooR",
            smoothing_sigma_reference,
        )
        self.floating_image_smoothing_sigma = (
            "-smooF",
            smoothing_sigma_floating,
        )

        self.reference_image_histo_n_bins = (
            "--rbn",
            histogram_n_bins_reference,
        )
        self.floating_image_histo_n_bins = ("--fbn", histogram_n_bins_floating)

        # segmentation (reg_resample)
        self.segmentation_interpolation_order = ("-inter", 0)

        # The atlas has been saved to the output folder
        atlas = Atlas(config_path)
        # self.atlas_path = atlas.get_path()
        # self.atlas_brain_path = atlas.get_brain_path()
        # self.hemispheres_path = atlas.get_hemispheres_path()

        pixel_sizes = atlas.get_pixel_sizes_from_config()
        self.atlas_x_pix_size = pixel_sizes["x"]
        self.atlas_y_pix_size = pixel_sizes["y"]
        self.atlas_z_pix_size = pixel_sizes["z"]
Beispiel #3
0
    def get_scaling(self):
        logging.debug("Determining scaling of the figures to the raw image")
        atlas = Atlas(self._registration_config)
        atlas_pixel_sizes = atlas.pix_sizes

        self.atlas_pixel_x_um = atlas_pixel_sizes["x"]
        self.atlas_pixel_y_um = atlas_pixel_sizes["y"]
        self.atlas_pixel_z_um = atlas_pixel_sizes["z"]

        self.x_scaling = round(
            self.x_pixel_um / self.atlas_pixel_x_um,
            self.scaling_rounding_decimals,
        )
        self.y_scaling = round(
            self.y_pixel_um / self.atlas_pixel_y_um,
            self.scaling_rounding_decimals,
        )
        self.z_scaling = round(
            self.z_pixel_um / self.atlas_pixel_z_um,
            self.scaling_rounding_decimals,
        )
        self.position_scaling = [
            self.x_scaling,
            self.y_scaling,
            self.z_scaling,
        ]
Beispiel #4
0
def get_structures_path(config=None):
    if config is None:
        config = source_custom_config()
    atlas = Atlas(config)
    return atlas.get_structures_path()
Beispiel #5
0
def main():
    start_time = datetime.now()
    print("Starting ROI transformation")
    args = get_parser().parse_args()

    rois = args.rois
    print(f"ROI file is: {rois}")

    if args.registration_config is None:
        args.registration_config = source_custom_config()
    atlas = Atlas(args.registration_config)
    source_image = args.reg_dir / SOURCE_IMAGE_NAME
    print(f"Source image is: {source_image}")

    destination_image = args.reg_dir / atlas.atlas_conf["default_brain_name"]
    print(f"Destination image is: {destination_image}")

    control_point_file = args.reg_dir / DEFAULT_CONTROL_POINT_FILE
    print(f"Transformation file is: {control_point_file}")

    if args.output_filename is None:
        output_filename = rois.parent / DEFAULT_OUTPUT_FILE_NAME
        temp_output_filename = rois.parent / DEFAULT_TEMP_FILE_NAME
        log_file_path = rois.parent / "roi_transform_log.txt"
        error_file_path = rois.parent / "roi_transform_error.txt"

    else:
        output_filename = args.output_filename
        temp_output_filename = (args.output_filename.parent /
                                DEFAULT_TEMP_FILE_NAME)
        log_file_path = args.output_filename.parent / "roi_transform_log.txt"
        error_file_path = (args.output_filename.parent /
                           "roi_transform_error.txt")
    if not output_filename.parent.exists():
        output_filename.parent.mkdir()
    print(f"Output file is: {output_filename}")

    atlas = brainio.load_nii(str(destination_image), as_array=False)
    atlas_scale = atlas.header.get_zooms()

    atlas_pixel_sizes = cells_regions.get_atlas_pixel_sizes(
        args.registration_config)

    transformation_matrix = np.eye(4)
    for i, axis in enumerate(("x", "y", "z")):
        transformation_matrix[i, i] = atlas_pixel_sizes[axis]

    transform_rois(
        rois,
        source_image,
        destination_image,
        control_point_file,
        output_filename,
        temp_output_filename,
        log_file_path,
        error_file_path,
        roi_reference_image=args.reference_image,
        selem_size=args.selem_size,
        nii_scale=atlas_scale,
        transformation_matrix=transformation_matrix,
        debug=args.debug,
        z_filter_padding=args.z_filter_padding,
    )
    print("Finished. Total time taken: {}".format(datetime.now() - start_time))
Beispiel #6
0
def main(
    registration_config,
    target_brain_path,
    registration_output_folder,
    x_pixel_um=0.02,
    y_pixel_um=0.02,
    z_pixel_um=0.05,
    orientation="coronal",
    flip_x=False,
    flip_y=False,
    flip_z=False,
    affine_n_steps=6,
    affine_use_n_steps=5,
    freeform_n_steps=6,
    freeform_use_n_steps=4,
    bending_energy_weight=0.95,
    grid_spacing=-10,
    smoothing_sigma_reference=-1.0,
    smoothing_sigma_floating=-1.0,
    histogram_n_bins_floating=128,
    histogram_n_bins_reference=128,
    n_free_cpus=2,
    sort_input_file=False,
    save_downsampled=True,
    additional_images_downsample=None,
    boundaries=True,
    debug=False,
):
    """
        The main function that will perform the library calls and
    register the atlas to the brain given on the CLI

    :param registration_config:
    :param target_brain_path:
    :param registration_output_folder:
    :param filtered_brain_path:
    :param x_pixel_um:
    :param y_pixel_um:
    :param z_pixel_um:
    :param orientation:
    :param flip_x:
    :param flip_y:
    :param flip_z:
    :param n_free_cpus:
    :param sort_input_file:
    :param save_downsampled:
    :param additional_images_downsample: dict of
    {image_name: image_to_be_downsampled}
    :return:
    """
    n_processes = get_num_processes(min_free_cpu_cores=n_free_cpus)
    load_parallel = n_processes > 1
    paths = Paths(registration_output_folder)
    atlas = Atlas(registration_config, dest_folder=registration_output_folder)
    run = Run(paths, atlas, boundaries=boundaries, debug=debug)

    if run.preprocess:
        logging.info("Preprocessing data for registration")
        logging.info("Loading data")

        brain = BrainProcessor(
            atlas,
            target_brain_path,
            registration_output_folder,
            x_pixel_um,
            y_pixel_um,
            z_pixel_um,
            original_orientation=orientation,
            load_parallel=load_parallel,
            sort_input_file=sort_input_file,
            n_free_cpus=n_free_cpus,
        )

        # reorients the atlas to the orientation of the sample
        brain.swap_atlas_orientation_to_self()

        # reorients atlas to the nifti (origin is the most ventral, posterior,
        # left voxel) coordinate framework

        flip = flips[orientation]
        brain.flip_atlas(flip)

        # flips if the input data doesnt match the nifti standard
        brain.flip_atlas((flip_x, flip_y, flip_z))

        brain.atlas.save_all()
        if save_downsampled:
            brain.target_brain = brain.target_brain.astype(
                np.uint16, copy=False
            )
            logging.info("Saving downsampled image")
            brain.save(paths.downsampled_brain_path)

        brain.filter()
        logging.info("Saving filtered image")
        brain.save(paths.tmp__downsampled_filtered)

        del brain

    if additional_images_downsample:
        for name, image in additional_images_downsample.items():
            if not check_downsampled(registration_output_folder, name):
                save_downsampled_image(
                    image,
                    name,
                    registration_output_folder,
                    atlas,
                    x_pixel_um=x_pixel_um,
                    y_pixel_um=y_pixel_um,
                    z_pixel_um=z_pixel_um,
                    orientation=orientation,
                    n_free_cpus=n_free_cpus,
                    sort_input_file=sort_input_file,
                    load_parallel=load_parallel,
                )
            else:
                logging.info(f"Image: {name} already downsampled, skipping.")

    if run.register:
        logging.info("Registering")

    if any(
        [
            run.affine,
            run.freeform,
            run.segment,
            run.hemispheres,
            run.inverse_transform,
        ]
    ):
        registration_params = RegistrationParams(
            registration_config,
            affine_n_steps=affine_n_steps,
            affine_use_n_steps=affine_use_n_steps,
            freeform_n_steps=freeform_n_steps,
            freeform_use_n_steps=freeform_use_n_steps,
            bending_energy_weight=bending_energy_weight,
            grid_spacing=grid_spacing,
            smoothing_sigma_reference=smoothing_sigma_reference,
            smoothing_sigma_floating=smoothing_sigma_floating,
            histogram_n_bins_floating=histogram_n_bins_floating,
            histogram_n_bins_reference=histogram_n_bins_reference,
        )
        brain_reg = BrainRegistration(
            registration_config,
            paths,
            registration_params,
            n_processes=n_processes,
        )

    if run.affine:
        logging.info("Starting affine registration")
        brain_reg.register_affine()

    if run.freeform:
        logging.info("Starting freeform registration")
        brain_reg.register_freeform()

    if run.segment:
        logging.info("Starting segmentation")
        brain_reg.segment()

    if run.hemispheres:
        logging.info("Segmenting hemispheres")
        brain_reg.register_hemispheres()

    if run.inverse_transform:
        logging.info("Generating inverse (sample to atlas) transforms")
        brain_reg.generate_inverse_transforms()

    if run.volumes:
        logging.info("Calculating volumes of each brain area")
        calculate_volumes(
            paths.registered_atlas_path,
            paths.hemispheres_atlas_path,
            atlas.get_structures_path(),
            registration_config,
            paths.volume_csv_path,
            left_hemisphere_value=atlas.get_left_hemisphere_value(),
            right_hemisphere_value=atlas.get_right_hemisphere_value(),
        )

    if run.boundaries:
        logging.info("Generating boundary image")
        calc_boundaries(
            paths.registered_atlas_path,
            paths.boundaries_file_path,
            atlas_config=registration_config,
        )

    if run.delete_temp:
        logging.info("Removing registration temp files")
        delete_temp(paths.registration_output_folder, paths)

    logging.info(
        f"amap completed. Results can be found here: "
        f"{registration_output_folder}"
    )