Exemple #1
0
    def test_tractogram_to_world(self):
        tractogram = DATA['lazy_tractogram'].copy()
        affine = np.random.RandomState(1234).randn(4, 4)
        affine[-1] = [0, 0, 0, 1]  # Remove perspective projection.

        # Apply the affine to the streamlines, then bring them back
        # to world space in a lazy manner.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_array_equal(transformed_tractogram.affine_to_rasmm,
                           np.linalg.inv(affine))

        tractogram_world = transformed_tractogram.to_world()
        assert_true(tractogram_world is not transformed_tractogram)
        assert_array_almost_equal(tractogram_world.affine_to_rasmm,
                                  np.eye(4))
        for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Calling to_world twice should do nothing.
        tractogram_world = tractogram_world.to_world()
        assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4))
        for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Calling to_world when affine_to_rasmm is None should fail.
        tractogram = DATA['lazy_tractogram'].copy()
        tractogram.affine_to_rasmm = None
        assert_raises(ValueError, tractogram.to_world)
Exemple #2
0
    def test_tractogram_to_world(self):
        tractogram = DATA['lazy_tractogram'].copy()
        affine = np.random.RandomState(1234).randn(4, 4)
        affine[-1] = [0, 0, 0, 1]  # Remove perspective projection.

        # Apply the affine to the streamlines, then bring them back
        # to world space in a lazy manner.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_array_equal(transformed_tractogram.affine_to_rasmm,
                           np.linalg.inv(affine))

        tractogram_world = transformed_tractogram.to_world()
        assert_true(tractogram_world is not transformed_tractogram)
        assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4))
        for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Calling to_world twice should do nothing.
        tractogram_world = tractogram_world.to_world()
        assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4))
        for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Calling to_world when affine_to_rasmm is None should fail.
        tractogram = DATA['lazy_tractogram'].copy()
        tractogram.affine_to_rasmm = None
        assert_raises(ValueError, tractogram.to_world)
Exemple #3
0
    def test_tractogram_apply_affine(self):
        tractogram = DATA["tractogram"].copy()
        affine = np.eye(4)
        scaling = np.array((1, 2, 3), dtype=float)
        affine[range(3), range(3)] = scaling

        # Apply the affine to the streamline in a lazy manner.
        transformed_tractogram = tractogram.apply_affine(affine, lazy=True)
        assert_true(type(transformed_tractogram) is LazyTractogram)
        check_tractogram(
            transformed_tractogram,
            streamlines=[s * scaling for s in DATA["streamlines"]],
            data_per_streamline=DATA["data_per_streamline"],
            data_per_point=DATA["data_per_point"],
        )
        assert_array_equal(transformed_tractogram.affine_to_rasmm, np.dot(np.eye(4), np.linalg.inv(affine)))
        # Make sure streamlines of the original tractogram have not been
        # modified.
        assert_arrays_equal(tractogram.streamlines, DATA["streamlines"])

        # Apply the affine to the streamlines in-place.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_true(transformed_tractogram is tractogram)
        check_tractogram(
            tractogram,
            streamlines=[s * scaling for s in DATA["streamlines"]],
            data_per_streamline=DATA["data_per_streamline"],
            data_per_point=DATA["data_per_point"],
        )

        # Apply affine again and check the affine_to_rasmm.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_array_equal(
            transformed_tractogram.affine_to_rasmm,
            np.dot(np.eye(4), np.dot(np.linalg.inv(affine), np.linalg.inv(affine))),
        )

        # Check that applying an affine and its inverse give us back the
        # original streamlines.
        tractogram = DATA["tractogram"].copy()
        affine = np.random.RandomState(1234).randn(4, 4)
        affine[-1] = [0, 0, 0, 1]  # Remove perspective projection.

        tractogram.apply_affine(affine)
        tractogram.apply_affine(np.linalg.inv(affine))
        assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4))
        for s1, s2 in zip(tractogram.streamlines, DATA["streamlines"]):
            assert_array_almost_equal(s1, s2)

        # Test applying the identity transformation.
        tractogram = DATA["tractogram"].copy()
        tractogram.apply_affine(np.eye(4))
        for s1, s2 in zip(tractogram.streamlines, DATA["streamlines"]):
            assert_array_almost_equal(s1, s2)

        # Test removing affine_to_rasmm
        tractogram = DATA["tractogram"].copy()
        tractogram.affine_to_rasmm = None
        tractogram.apply_affine(affine)
        assert_true(tractogram.affine_to_rasmm is None)
Exemple #4
0
    def test_tractogram_apply_affine(self):
        tractogram = DATA['tractogram'].copy()
        affine = np.eye(4)
        scaling = np.array((1, 2, 3), dtype=float)
        affine[range(3), range(3)] = scaling

        # Apply the affine to the streamline in a lazy manner.
        transformed_tractogram = tractogram.apply_affine(affine, lazy=True)
        assert_true(type(transformed_tractogram) is LazyTractogram)
        check_tractogram(
            transformed_tractogram,
            streamlines=[s * scaling for s in DATA['streamlines']],
            data_per_streamline=DATA['data_per_streamline'],
            data_per_point=DATA['data_per_point'])
        assert_array_equal(transformed_tractogram.affine_to_rasmm,
                           np.dot(np.eye(4), np.linalg.inv(affine)))
        # Make sure streamlines of the original tractogram have not been
        # modified.
        assert_arrays_equal(tractogram.streamlines, DATA['streamlines'])

        # Apply the affine to the streamlines in-place.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_true(transformed_tractogram is tractogram)
        check_tractogram(
            tractogram,
            streamlines=[s * scaling for s in DATA['streamlines']],
            data_per_streamline=DATA['data_per_streamline'],
            data_per_point=DATA['data_per_point'])

        # Apply affine again and check the affine_to_rasmm.
        transformed_tractogram = tractogram.apply_affine(affine)
        assert_array_equal(
            transformed_tractogram.affine_to_rasmm,
            np.dot(np.eye(4),
                   np.dot(np.linalg.inv(affine), np.linalg.inv(affine))))

        # Check that applying an affine and its inverse give us back the
        # original streamlines.
        tractogram = DATA['tractogram'].copy()
        affine = np.random.RandomState(1234).randn(4, 4)
        affine[-1] = [0, 0, 0, 1]  # Remove perspective projection.

        tractogram.apply_affine(affine)
        tractogram.apply_affine(np.linalg.inv(affine))
        assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4))
        for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Test applying the identity transformation.
        tractogram = DATA['tractogram'].copy()
        tractogram.apply_affine(np.eye(4))
        for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']):
            assert_array_almost_equal(s1, s2)

        # Test removing affine_to_rasmm
        tractogram = DATA['tractogram'].copy()
        tractogram.affine_to_rasmm = None
        tractogram.apply_affine(affine)
        assert_true(tractogram.affine_to_rasmm is None)
Exemple #5
0
 def _data_gen():
     for d in zip(*data):
         data_for_points = {'fa': d[1],
                            'colors': d[2]}
         data_for_streamline = {'mean_curvature': d[3],
                                'mean_torsion': d[4],
                                'mean_colors': d[5]}
         yield TractogramItem(d[0],
                              data_for_streamline,
                              data_for_points)
Exemple #6
0
 def _data_gen():
     for d in zip(*data):
         data_for_points = {'fa': d[1], 'colors': d[2]}
         data_for_streamline = {
             'mean_curvature': d[3],
             'mean_torsion': d[4],
             'mean_colors': d[5]
         }
         yield TractogramItem(d[0], data_for_streamline,
                              data_for_points)
def bench_load_trk():
    rng = np.random.RandomState(42)
    dtype = 'float32'
    NB_STREAMLINES = 5000
    NB_POINTS = 1000
    points = [
        rng.rand(NB_POINTS, 3).astype(dtype) for i in range(NB_STREAMLINES)
    ]
    scalars = [
        rng.rand(NB_POINTS, 10).astype(dtype) for i in range(NB_STREAMLINES)
    ]

    repeat = 10

    with InTemporaryDirectory():
        trk_file = "tmp.trk"
        tractogram = Tractogram(points, affine_to_rasmm=np.eye(4))
        TrkFile(tractogram).save(trk_file)

        streamlines_old = [
            d[0] - 0.5 for d in tv.read(trk_file, points_space="rasmm")[0]
        ]
        mtime_old = measure('tv.read(trk_file, points_space="rasmm")', repeat)
        print("Old: Loaded {:,} streamlines in {:6.2f}".format(
            NB_STREAMLINES, mtime_old))

        trk = nib.streamlines.load(trk_file, lazy_load=False)
        streamlines_new = trk.streamlines
        mtime_new = measure('nib.streamlines.load(trk_file, lazy_load=False)',
                            repeat)
        print("\nNew: Loaded {:,} streamlines in {:6.2}".format(
            NB_STREAMLINES, mtime_new))
        print("Speedup of {:.2f}".format(mtime_old / mtime_new))
        for s1, s2 in zip(streamlines_new, streamlines_old):
            assert_array_equal(s1, s2)

    # Points and scalars
    with InTemporaryDirectory():

        trk_file = "tmp.trk"
        tractogram = Tractogram(points,
                                data_per_point={'scalars': scalars},
                                affine_to_rasmm=np.eye(4))
        TrkFile(tractogram).save(trk_file)

        streamlines_old = [
            d[0] - 0.5 for d in tv.read(trk_file, points_space="rasmm")[0]
        ]

        scalars_old = [
            d[1] for d in tv.read(trk_file, points_space="rasmm")[0]
        ]
        mtime_old = measure('tv.read(trk_file, points_space="rasmm")', repeat)
        msg = "Old: Loaded {:,} streamlines with scalars in {:6.2f}"
        print(msg.format(NB_STREAMLINES, mtime_old))

        trk = nib.streamlines.load(trk_file, lazy_load=False)
        scalars_new = trk.tractogram.data_per_point['scalars']
        mtime_new = measure('nib.streamlines.load(trk_file, lazy_load=False)',
                            repeat)
        msg = "New: Loaded {:,} streamlines with scalars in {:6.2f}"
        print(msg.format(NB_STREAMLINES, mtime_new))
        print("Speedup of {:2f}".format(mtime_old / mtime_new))
        for s1, s2 in zip(scalars_new, scalars_old):
            assert_array_equal(s1, s2)
Exemple #8
0
 def _data_gen():
     for d in zip(*data):
         data_for_points = {"fa": d[1], "colors": d[2]}
         data_for_streamline = {"mean_curvature": d[3], "mean_torsion": d[4], "mean_colors": d[5]}
         yield TractogramItem(d[0], data_for_streamline, data_for_points)