Пример #1
0
def test_zoom():
    s = AnatomicalSpace("asl", resolution=(1, 1, 1))
    t = AnatomicalSpace("asl", resolution=(1, 1, 2))

    m = np.array(
        [
            [[1, 9, 15, 17, 20, 25], [1, 9, 15, 17, 20, 25]],
            [[2, 18, 30, 34, 40, 50], [2, 18, 30, 34, 40, 50]],
        ]
    ).astype(np.float)

    assert np.allclose(
        s.map_stack_to(t, m),
        np.array(
            [
                [[1.0, 16.20454545, 25.0], [1.0, 16.20454545, 25.0]],
                [[2.0, 32.40909091, 50.0], [2.0, 32.40909091, 50.0]],
            ]
        ),
    )

    assert np.allclose(
        s.map_stack_to(t, m, interp_order=1),
        np.array(
            [
                [[1.0, 16.0, 25.0], [1.0, 16.0, 25.0]],
                [[2.0, 32.0, 50.0], [2.0, 32.0, 50.0]],
            ]
        ),
    )
Пример #2
0
def test_stack_copy(copy_flag):
    source_stack = np.random.rand(3, 4, 2)
    source_space = AnatomicalSpace("asl")
    pre_copy = source_stack.copy()

    mapped_stack = source_space.map_stack_to(
        "lsp", source_stack, copy=copy_flag
    )

    mapped_stack[0, 1, 1] = 1

    assert np.allclose(source_stack, pre_copy) == copy_flag
Пример #3
0
def test_stack_flips(src_o, tgt_o, src_shape, tgt_shape):
    source_stack = create_label_array(src_o, src_shape)
    target_stack = create_label_array(tgt_o, tgt_shape)

    source_space = AnatomicalSpace(src_o)

    # Test both mapping to AnatomicalSpace obj and origin with decorator:
    for target_space in [tgt_o, AnatomicalSpace(tgt_o)]:
        # Check all corners of the mapped stack:
        mapped_stack = source_space.map_stack_to(target_space, source_stack)
        for indexes in itertools.product([0, -1], repeat=3):
            assert set(mapped_stack[indexes]) == set(target_stack[indexes])
Пример #4
0
def test_points_mapping():
    points = np.array([[0, 0, 0], [10, 10, 10], [1000, 1000, 1000]])
    source_space = AnatomicalSpace(
        "psl", shape=(1000, 1000, 1000), resolution=(1, 1, 1)
    )
    target_space = AnatomicalSpace(
        "asl", shape=(100, 100, 100), resolution=(10, 10, 10)
    )
    mapped_points = source_space.map_points_to(target_space, points)

    assert np.allclose(
        mapped_points,
        np.array([[100.0, 0.0, 0.0], [99.0, 1.0, 1.0], [0.0, 100.0, 100.0]]),
    )
Пример #5
0
def test_shape_decorator(valid_origins):
    correct_shape = (20, 30, 10)
    origin = "asl"
    source_space = AnatomicalSpace(origin, correct_shape)

    target_space = AnatomicalSpace(origin, correct_shape)
    correct_mat = source_space.transformation_matrix_to(target_space)

    # Check if we can overwrite none or different orientations:
    for args in [(origin, None), (origin, correct_shape[::-1])]:
        new_shape_mat = AnatomicalSpace(*args).transformation_matrix_to(
            target_space
        )

        assert np.allclose(correct_mat, new_shape_mat)
Пример #6
0
def create_label_array(origin, half_shape):
    """Create stack with string labels marking regions for testing.

    Parameters
    ----------
    origin : str
        Valid origin for a AnatomicalSpace obj.
    half_shape : tuple
        Half shape of the stack on each axis.

    Returns
    -------
    np.array of chars
        array with elements describing an anatomical location (e.g. "als", "pir)

    """
    space = AnatomicalSpace(origin)
    arrays = []
    for lims, hs in zip(space.axes_description, half_shape):
        arrays.append(
            np.array(
                [
                    lims[0],
                ]
                * hs
                + [
                    lims[1],
                ]
                * hs
            )
        )

    x, y, z = np.meshgrid(*arrays, indexing="ij")

    return char_add(char_add(x, y), z)
Пример #7
0
def test_labels_iterations(orig, lab, sect, normals):
    space = AnatomicalSpace(orig)

    assert space.axis_labels == lab
    assert space.sections == sect
    assert space.plane_normals == normals
    assert space.index_pairs == ((1, 2), (0, 2), (0, 1))
Пример #8
0
def test_comparison():
    assert AnatomicalSpace("asl") == AnatomicalSpace("asl")
    assert AnatomicalSpace("asl") != AnatomicalSpace("als")

    for k in ["offset", "shape", "resolution"]:
        assert AnatomicalSpace("asl", **{k: [1, 2, 3]}) == AnatomicalSpace(
            "asl", **{k: [1, 2, 3]}
        )
        assert AnatomicalSpace("asl", **{k: [1, 2, 3]}) != AnatomicalSpace(
            "asl", **{k: [4, 5, 3]}
        )
Пример #9
0
def test_point_transform(src_o, tgt_o, src_shape, tgt_shape):
    # Create an array with descriptive space labels:
    source_stack = create_label_array(src_o, src_shape)

    # Create spaces objects:
    source_space = AnatomicalSpace(src_o, shape=[s * 2 for s in src_shape])

    # Test both mapping to AnatomicalSpace obj and origin with decorator:
    for target_space in [tgt_o, AnatomicalSpace(tgt_o)]:

        # Define grid of points sampling 4 points per axis:
        grid_positions = [[1, s - 1, s + 1, s * 2 - 1] for s in src_shape]
        source_pts = np.array(list(itertools.product(*grid_positions)))

        # Map points and stack to target space:
        mapped_pts = source_space.map_points_to(target_space, source_pts)
        mapped_stack = source_space.map_stack_to(target_space, source_stack)

        # Check that point coordinates keep the same values:
        for p_source, p_mapped in zip(source_pts, mapped_pts):
            p_s, p_m = [tuple(p.astype(np.int)) for p in [p_source, p_mapped]]

            assert source_stack[p_s] == mapped_stack[p_m]
Пример #10
0
    def __init__(self, path):
        self.root_dir = Path(path)
        self.metadata = read_json(self.root_dir / METADATA_FILENAME)

        # Load structures list:
        structures_list = read_json(self.root_dir / STRUCTURES_FILENAME)
        self.structures_list = structures_list  # keep to generate tree and dataframe views when necessary

        # Add entry for file paths:
        for struct in structures_list:
            struct["mesh_filename"] = (
                self.root_dir / MESHES_DIRNAME / "{}.obj".format(struct["id"])
            )

        self.structures = StructuresDict(structures_list)

        # Instantiate SpaceConvention object describing the current atlas:
        self.space = AnatomicalSpace(
            origin=self.orientation,
            shape=self.shape,
            resolution=self.resolution,
        )

        self._reference = None

        try:
            self.additional_references = AdditionalRefDict(
                references_list=self.metadata["additional_references"],
                data_path=self.root_dir,
            )
        except KeyError:
            warnings.warn(
                "This atlas seems to be outdated as no additional_references list "
                "is found in metadata!"
            )

        self._annotation = None
        self._hemispheres = None
        self._lookup = None
Пример #11
0
def test_origin_types(origin):
    space = AnatomicalSpace(origin)
    assert space.axes_description == ("rl", "si", "ap")
Пример #12
0
def test_init_failures(origin, errortype):
    with pytest.raises(errortype) as error:
        _ = AnatomicalSpace(origin)
    assert str(errortype).split("'")[1] in str(error)
Пример #13
0
def test_stack_map_offset(s_dict, t_dict, f_in, result):
    s = AnatomicalSpace(**s_dict)
    t = AnatomicalSpace(**t_dict)

    assert np.allclose(t.map_stack_to(s, np.ones((2, 2, 2)), **f_in), result)
Пример #14
0
def test_spaceconvention():
    with pytest.deprecated_call():
        assert SpaceConvention("asl") == AnatomicalSpace("asl")
Пример #15
0
def test_point_transform_fail():
    s = AnatomicalSpace("asl")
    with pytest.raises(TypeError) as error:
        s.map_points_to("psl", np.array([[0, 1, 2], [0, 1, 2]]))
    assert "The source space should have a shape" in str(error)
Пример #16
0
def test_iteration():
    assert list(AnatomicalSpace("asl")) == ["a", "s", "l"]
Пример #17
0
def test_properties(o, axs_order, origin):
    space = AnatomicalSpace(o)
    assert space.axes_order == axs_order
    assert space.origin == origin
    assert space.origin_string == o
Пример #18
0
def test_print():
    print(AnatomicalSpace("asl"))
Пример #19
0
if not datafile.exists():
    raise ValueError(
        "Before running this example you need to download the data for gene expression of the line brn3c:GFP from https://fishatlas.neuro.mpg.de/lines/"
    )


# 1. load the data
print("Loading data")
data = imio.load.load_any(datafile)

# 2. aligned the data to the scene's atlas' axes
print("Transforming data")
scene = Scene(atlas_name="mpin_zfish_1um")

source_space = AnatomicalSpace(
    "ira"
)  # for more info: https://docs.brainglobe.info/bg-space/usage
target_space = scene.atlas.space
transformed_stack = source_space.map_stack_to(target_space, data)

# 3. create a Volume vedo actor and smooth
print("Creating volume")
vol = Volume(transformed_stack, origin=scene.root.origin()).medianSmooth()


# 4. Extract a surface mesh from the volume actor
print("Extracting surface")
SHIFT = [-20, 15, 30]  # fine tune mesh position
mesh = (
    vol.isosurface(threshold=20).c(blue_grey).decimate().clean().addPos(*SHIFT)
)