Пример #1
0
def test_atlas_value_to_name():
    structure_df = load_structures_as_df(structures_csv)
    assert "Interpeduncular nucleus" == structures_tree.atlas_value_to_name(
        100, structure_df
    )

    with pytest.raises(structures_tree.UnknownAtlasValue):
        structures_tree.atlas_value_to_name(100000, structure_df)
Пример #2
0
def test_atlas_value_to_structure_id():
    structure_df = load_structures_as_df(structures_csv)
    assert structure_id_100 == structures_tree.atlas_value_to_structure_id(
        100, structure_df
    )

    with pytest.raises(structures_tree.UnknownAtlasValue):
        structures_tree.atlas_value_to_structure_id(100000, structure_df)
Пример #3
0
def main():
    print("Starting amap viewer")
    args = parser().parse_args()

    structures_path = get_structures_path()
    structures_df = load_structures_as_df(structures_path)

    if not args.memory:
        print("By default amap_vis does not load data into memory. "
              "To speed up visualisation, use the '-m' flag. Be aware "
              "this will make the viewer slower to open initially.")

    paths = Paths(args.amap_directory)
    with napari.gui_qt():
        v = napari.Viewer(title="amap viewer")
        if (Path(paths.registered_atlas_path).exists()
                and Path(paths.boundaries_file_path).exists()):

            if args.raw:
                image_scales = display_raw(v, args)

            else:
                if Path(paths.downsampled_brain_path).exists():
                    image_scales = display_downsampled(v, args, paths)

                else:
                    raise FileNotFoundError(
                        f"The downsampled image: "
                        f"{paths.downsampled_brain_path} could not be found. "
                        f"Please ensure this is the correct "
                        f"directory and that amap has completed. ")

            labels = display_registration(
                v,
                paths.registered_atlas_path,
                paths.boundaries_file_path,
                image_scales,
                memory=args.memory,
            )

            @labels.mouse_move_callbacks.append
            def get_connected_component_shape(layer, event):
                val = layer.get_value()
                if val != 0 and val is not None:
                    try:
                        region = atlas_value_to_name(val, structures_df)
                        msg = f"{region}"
                    except UnknownAtlasValue:
                        msg = "Unknown region"
                else:
                    msg = "No label here!"
                layer.help = msg

        else:
            raise FileNotFoundError(
                f"The directory: '{args.amap_directory}' does not "
                f"appear to be complete. Please ensure this is the correct "
                f"directory and that amap has completed.")
Пример #4
0
def analysis_run(args, file_name="summary_cell_counts.csv"):
    args = prep_atlas_conf(args)

    # if args.structures_file_path is None:
    #     args.structures_file_path = get_structures_path()

    atlas = brainio.load_any(args.paths.registered_atlas_path)
    hemisphere = brainio.load_any(args.paths.hemispheres_atlas_path)

    cells = get_cells_data(
        args.paths.classification_out_file, cells_only=args.cells_only,
    )
    max_coords = get_max_coords(cells)  # Useful for debugging dimensions
    # structures_reference_df = load_structures_as_df(args.structures_file_path)
    structures_reference_df = load_structures_as_df(get_structures_path())

    atlas_pixel_sizes = get_atlas_pixel_sizes(args.atlas_config)
    sample_pixel_sizes = args.x_pixel_um, args.y_pixel_um, args.z_pixel_um

    scales = get_scales(
        sample_pixel_sizes, atlas_pixel_sizes, args.scale_cell_coordinates
    )

    structures_with_cells = set()
    for i, cell in enumerate(tqdm(cells)):
        transform_cell_coords(atlas, cell, scales)

        structure_id = get_structure_from_coordinates(
            atlas,
            cell,
            max_coords,
            order=args.coordinates_order,
            structures_reference_df=structures_reference_df,
        )
        if structure_id is not None:
            cell.structure_id = structure_id

            structures_with_cells.add(structure_id)
        else:
            continue

        cell.hemisphere = get_structure_from_coordinates(
            hemisphere, cell, max_coords, order=args.coordinates_order
        )

    sorted_cell_numbers = get_cells_nbs_df(
        cells, structures_reference_df, structures_with_cells
    )

    combined_hemispheres = combine_df_hemispheres(sorted_cell_numbers)
    df = calculate_densities(combined_hemispheres, args.paths.volume_csv_path)
    df = sanitise_df(df)
    if not os.path.exists(args.output_dir):
        os.makedirs(args.output_dir)
    output_file = os.path.join(args.output_dir, file_name)
    df.to_csv(output_file, index=False)
Пример #5
0
def test_load_structures_df():
    structures = load_structures_as_df(structures_csv)

    assert len(structures) == 1299
    assert (structures.keys() == Index(structure_headers)).all()

    structures_test = list(structures.iloc[100].array)

    assert structures_test[1] == structures_line_100[1]
    assert structures_test[2] == structures_line_100[2]
    assert structures_test[3] == structures_line_100[3]
Пример #6
0
def xml_crop(args, df_query="name"):
    args = prep_atlas_conf(args)

    # if args.reference_structures_file_path is None:
    #     args.reference_structures_file_path = get_structures_path()
    if args.structures_file_path is None:
        args.structures_file_path = get_structures_path()

    # reference_struct_df = pd.read_csv(args.reference_structures_file_path)
    reference_struct_df = pd.read_csv(get_structures_path())

    curate_struct_df = pd.read_csv(args.structures_file_path)

    curate_struct_df = reference_struct_df[reference_struct_df[df_query].isin(
        curate_struct_df[df_query])]

    curated_ids = list(curate_struct_df["structure_id_path"])

    atlas = brainio.load_any(args.registered_atlas_path)
    hemisphere = brainio.load_any(args.hemispheres_atlas_path)

    # structures_reference_df = load_structures_as_df(
    #     args.reference_structures_file_path
    # )
    structures_reference_df = load_structures_as_df(get_structures_path())

    atlas_pixel_sizes = cells_regions.get_atlas_pixel_sizes(args.atlas_config)
    sample_pixel_sizes = args.x_pixel_um, args.y_pixel_um, args.z_pixel_um

    scales = cells_regions.get_scales(sample_pixel_sizes, atlas_pixel_sizes)

    destination_folder = os.path.join(args.xml_dir, "xml_crop")
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    xml_names = [f for f in os.listdir(args.xml_dir) if f.endswith(".xml")]
    xml_paths = [os.path.join(args.xml_dir, f) for f in xml_names]

    for idx, xml_path in enumerate(xml_paths):
        print("Curating file: {}".format(xml_names[idx]))
        cells = cells_regions.get_cells_data(
            xml_path,
            cells_only=args.cells_only,
        )
        max_coords = cells_regions.get_max_coords(cells)

        curated_cells = []
        for i, cell in enumerate(cells):
            cells_regions.transform_cell_coords(atlas, cell, scales)

            structure_id = cells_regions.get_structure_from_coordinates(
                atlas,
                cell,
                max_coords,
                order=args.coordinates_order,
                structures_reference_df=structures_reference_df,
            )
            if structure_id in curated_ids:
                if args.hemisphere_query in [1, 2]:
                    hemisphere = cells_regions.get_structure_from_coordinates(
                        hemisphere,
                        cell,
                        max_coords,
                        order=args.coordinates_order,
                    )
                    if hemisphere is args.hemisphere_query:
                        curated_cells.append(cell)
                else:
                    curated_cells.append(cell)
        cells_to_xml(
            curated_cells,
            os.path.join(destination_folder, xml_names[idx]),
            artifact_keep=True,
        )
    print("Done!")