Esempio n. 1
0
    def get_parameters_to_save(self, config):
        for subsection in config[self.parameter_section_name]:
            parameters_keep_tmp = config.get(self.parameter_section_name,
                                             subsection).split(",")
            self.parameters_keep = self.parameters_keep + parameters_keep_tmp

        self.parameters_keep = unique_elements_lists(self.parameters_keep)

        if self._strip_spaces:
            self.parameters_keep = strip_spaces_list(self.parameters_keep)
Esempio n. 2
0
def summary_run(args):
    # if args.structures_file_path is None:
    #     args.structures_file_path = get_structures_path()
    #     reference_structures_table = pd.read_csv(args.structures_file_path)
    # else:
    #     raise NotImplementedError(
    #         "Only the Allen adult mouse atlas is " "currently supported."
    #     )
    reference_structures_table = pd.read_csv(get_structures_path())

    if not args.regions and not args.regions_list:
        # regions = list(pd.read_csv(args.structures_file_path)["name"])
        regions = list(pd.read_csv(get_structures_path())["name"])

    else:
        regions = []
        if args.regions:
            regions = regions + args.regions
        if args.regions_list:
            regions = regions + list(pd.read_csv(args.regions_list)["name"])

    regions = remove_empty_string(regions)
    regions = unique_elements_lists(regions)
    csvs_folder = args.csv_dir
    destination_folder = os.path.join(args.csv_dir, "summary")

    csvs_names = [f for f in os.listdir(csvs_folder) if f.endswith(".csv")]
    if len(csvs_names) == 0:
        raise FileNotFoundError(
            "No CSV files were found in the directory: "
            "{}. Please check the arguments".format(csvs_folder))

    csvs_paths = [os.path.join(csvs_folder, f) for f in csvs_names]

    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    for csv_file_path in csvs_paths:
        print("CSV file: {}".format(os.path.basename(csv_file_path)))
        summary = make_summary_df_for_brain(
            csv_file_path,
            regions,
            reference_structures_table,
            sum_regions=args.sum_regions,
        )
        filename = os.path.basename(csv_file_path)
        dest_path = os.path.join(destination_folder, filename)

        summary.to_csv(dest_path, index=False)
    print("Done!")
Esempio n. 3
0
        def save_curation(viewer):
            """Save file"""
            if not CURATED_POINTS:
                print("No cells have been confirmed or toggled, not saving")
            else:
                unique_cells = unique_elements_lists(CURATED_POINTS)
                points = viewer.layers[1].data[unique_cells]
                labels = viewer.layers[1].properties["cell"][unique_cells]
                labels = labels.astype("int")
                labels = labels + 1

                cells_to_save = []
                for idx, point in enumerate(points):
                    cell = Cell([point[2], point[1], point[0]], labels[idx])
                    cells_to_save.append(cell)

                print(f"Saving results to: {output_filename}")
                save_cells(cells_to_save, output_filename)
Esempio n. 4
0
def analyse_region_brain_areas(
    label_layer,
    destination_directory,
    annotations,
    hemispheres,
    structures_reference_df,
    extension=".csv",
    ignore_empty=True,
):
    """

    :param label_layer: napari labels layer (with segmented regions)
    :param np.array annotations: numpy array of the brain area annotations
    :param np.array hemispheres: numpy array of hemipshere annotations
    :param structures_reference_df: Pandas dataframe with "id" column (matching
    the values in "annotations" and a "name column"
    :param ignore_empty: If True, don't analyse empty regions
    """

    data = label_layer.data
    if ignore_empty:
        if data.sum() == 0:
            return

    # swap data back to original orientation from napari orientation
    data = np.swapaxes(data, 2, 0)
    name = label_layer.name

    masked_annotations = data.astype(bool) * annotations

    # TODO: don't hardcode hemisphere value. Get from atlas config
    annotations_left, annotations_right = lateralise_atlas(
        masked_annotations,
        hemispheres,
        left_hemisphere_value=2,
        right_hemisphere_value=1,
    )

    unique_vals_left, counts_left = np.unique(annotations_left,
                                              return_counts=True)
    unique_vals_right, counts_right = np.unique(annotations_right,
                                                return_counts=True)

    voxel_volume = get_voxel_volume(source_custom_config_amap())
    voxel_volume_in_mm = voxel_volume / (1000**3)

    df = initialise_df(
        "structure_name",
        "left_volume_mm3",
        "left_percentage_of_total",
        "right_volume_mm3",
        "right_percentage_of_total",
        "total_volume_mm3",
        "percentage_of_total",
    )

    sampled_structures = unique_elements_lists(
        list(unique_vals_left) + list(unique_vals_right))
    total_volume_region = get_total_volume_regions(unique_vals_left,
                                                   unique_vals_right,
                                                   counts_left, counts_right)

    for atlas_value in sampled_structures:
        if atlas_value != 0:
            try:
                df = add_structure_volume_to_df(
                    df,
                    atlas_value,
                    structures_reference_df,
                    unique_vals_left,
                    unique_vals_right,
                    counts_left,
                    counts_right,
                    voxel_volume_in_mm,
                    total_volume_voxels=total_volume_region,
                )

            except UnknownAtlasValue:
                print(
                    "Value: {} is not in the atlas structure reference file. "
                    "Not calculating the volume".format(atlas_value))
    filename = destination_directory / (name + extension)
    df.to_csv(filename, index=False)
Esempio n. 5
0
def analyse_region_brain_areas(
    label_layer,
    atlas_layer_data,
    hemispheres,
    destination_directory,
    atlas,
    extension=".csv",
    ignore_empty=True,
):
    """

    :param label_layer: napari labels layer (with segmented regions)

    :param ignore_empty: If True, don't analyse empty regions
    """

    data = label_layer.data
    if ignore_empty:
        if data.sum() == 0:
            return

    name = label_layer.name

    masked_annotations = data.astype(bool) * atlas_layer_data

    annotations_left, annotations_right = lateralise_atlas_image(
        masked_annotations,
        hemispheres,
        left_hemisphere_value=atlas.left_hemisphere_value,
        right_hemisphere_value=atlas.right_hemisphere_value,
    )

    unique_vals_left, counts_left = np.unique(annotations_left,
                                              return_counts=True)
    unique_vals_right, counts_right = np.unique(annotations_right,
                                                return_counts=True)
    voxel_volume_in_mm = np.prod(atlas.resolution) / (1000**3)

    df = initialise_df(
        "structure_name",
        "left_volume_mm3",
        "left_percentage_of_total",
        "right_volume_mm3",
        "right_percentage_of_total",
        "total_volume_mm3",
        "percentage_of_total",
    )

    sampled_structures = unique_elements_lists(
        list(unique_vals_left) + list(unique_vals_right))
    total_volume_region = get_total_volume_regions(unique_vals_left,
                                                   unique_vals_right,
                                                   counts_left, counts_right)

    for atlas_value in sampled_structures:
        if atlas_value != 0:
            try:
                df = add_structure_volume_to_df(
                    df,
                    atlas_value,
                    atlas.structures,
                    unique_vals_left,
                    unique_vals_right,
                    counts_left,
                    counts_right,
                    voxel_volume_in_mm,
                    total_volume_voxels=total_volume_region,
                )

            except KeyError:
                print(f"Value: {atlas_value} is not in the atlas structure"
                      f" reference file. Not calculating the volume")
    filename = destination_directory / (name + extension)
    df.to_csv(filename, index=False)
Esempio n. 6
0
def test_unique_elements_list():
    list_in = [1, 2, 2, "a", "b", 1, "a", "dog"]
    unique_list = [1, 2, "a", "b", "dog"]
    assert list_tools.unique_elements_lists(list_in) == unique_list