Beispiel #1
0
def test_feature_vector_of_endpoints():
    # Test subclassing Feature
    class VectorOfEndpointsFeature(dipymetric.Feature):
        def __init__(self):
            super(VectorOfEndpointsFeature, self).__init__(False)

        def infer_shape(self, streamline):
            return (1, streamline.shape[1])

        def extract(self, streamline):
            return streamline[[-1]] - streamline[[0]]

    feature_types = [dipymetric.VectorOfEndpointsFeature(),
                     VectorOfEndpointsFeature()]
    for feature in feature_types:
        for s in [s1, s2, s3, s4]:
            # Test method infer_shape
            assert_equal(feature.infer_shape(s), (1, s.shape[1]))

            # Test method extract
            features = feature.extract(s)
            assert_equal(features.shape, (1, s.shape[1]))
            assert_array_almost_equal(features, s[[-1]] - s[[0]])

        # This feature type is not order invariant
        assert_false(feature.is_order_invariant)
        for s in [s1, s2, s3, s4]:
            features = feature.extract(s)
            features_flip = feature.extract(s[::-1])
            # The flip features are simply the negative of the features.
            assert_array_almost_equal(features, -features_flip)
Beispiel #2
0
def test_feature_midpoint():
    # Test subclassing Feature
    class MidpointFeature(dipymetric.Feature):
        def __init__(self):
            super(MidpointFeature, self).__init__(is_order_invariant=False)

        def infer_shape(self, streamline):
            return (1, streamline.shape[1])

        def extract(self, streamline):
            return streamline[[len(streamline)//2]]

    for feature in [dipymetric.MidpointFeature(), MidpointFeature()]:
        for s in [s1, s2, s3, s4]:
            # Test method infer_shape
            assert_equal(feature.infer_shape(s), (1, s.shape[1]))

            # Test method extract
            features = feature.extract(s)
            assert_equal(features.shape, (1, s.shape[1]))
            assert_array_almost_equal(features, s[len(s)//2][None, :])

        # This feature type is not order invariant
        assert_false(feature.is_order_invariant)
        for s in [s1, s2, s3, s4]:
            features = feature.extract(s)
            features_flip = feature.extract(s[::-1])
            if len(s) % 2 == 0:
                assert_true(np.any(np.not_equal(features, features_flip)))
            else:
                assert_array_equal(features, features_flip)
Beispiel #3
0
def test_identity_feature():
    # Test subclassing Feature
    class IdentityFeature(dipymetric.Feature):
        def __init__(self):
            super(IdentityFeature, self).__init__(is_order_invariant=False)

        def infer_shape(self, streamline):
            return streamline.shape

        def extract(self, streamline):
            return streamline

    for feature in [dipymetric.IdentityFeature(), IdentityFeature()]:
        for s in [s1, s2, s3, s4]:
            # Test method infer_shape
            assert_equal(feature.infer_shape(s), s.shape)

            # Test method extract
            features = feature.extract(s)
            assert_equal(features.shape, s.shape)
            assert_array_equal(features, s)

        # This feature type is not order invariant
        assert_false(feature.is_order_invariant)
        for s in [s1, s2, s3, s4]:
            features = feature.extract(s)
            features_flip = feature.extract(s[::-1])
            assert_array_equal(features_flip, s[::-1])
            assert_true(np.any(np.not_equal(features, features_flip)))
Beispiel #4
0
def test_mppca_flow():
    with TemporaryDirectory() as out_dir:
        S0 = 100 + 2 * np.random.standard_normal((22, 23, 30, 20))
        data_path = os.path.join(out_dir, "random_noise.nii.gz")
        save_nifti(data_path, S0, np.eye(4))

        mppca_flow = MPPCAFlow()
        mppca_flow.run(data_path, out_dir=out_dir)
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_denoised']))
        assert_false(os.path.isfile(
                mppca_flow.last_generated_outputs['out_sigma']))

        mppca_flow._force_overwrite = True
        mppca_flow.run(data_path, return_sigma=True, pca_method='svd',
                       out_dir=out_dir)
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_denoised']))
        assert_true(os.path.isfile(
                mppca_flow.last_generated_outputs['out_sigma']))

        denoised_path = mppca_flow.last_generated_outputs['out_denoised']
        denoised_data = load_nifti_data(denoised_path)
        assert_greater(denoised_data.min(), S0.min())
        assert_less(denoised_data.max(), S0.max())
        npt.assert_equal(np.round(denoised_data.mean()), 100)
Beispiel #5
0
def test_as_native():
    arr = np.arange(5)  # native
    assert_equal(arr.dtype.byteorder, '=')
    narr = as_native_array(arr)
    assert_true(arr is narr)
    sdt = arr.dtype.newbyteorder('s')
    barr = arr.astype(sdt)
    assert_equal(barr.dtype.byteorder, SWAPPED_ORDER)
    narr = as_native_array(barr)
    assert_false(barr is narr)
    assert_array_equal(barr, narr)
    assert_equal(narr.dtype.byteorder, NATIVE_ORDER)
Beispiel #6
0
def test_as_native():
    arr = np.arange(5)  # native
    assert_equal(arr.dtype.byteorder, '=')
    narr = as_native_array(arr)
    assert_true(arr is narr)
    sdt = arr.dtype.newbyteorder('s')
    barr = arr.astype(sdt)
    assert_equal(barr.dtype.byteorder, SWAPPED_ORDER)
    narr = as_native_array(barr)
    assert_false(barr is narr)
    assert_array_equal(barr, narr)
    assert_equal(narr.dtype.byteorder, NATIVE_ORDER)
Beispiel #7
0
def test_mask():
    with TemporaryDirectory() as out_dir:
        data_path, _, _ = get_fnames('small_25')
        volume, affine = load_nifti(data_path)

        mask_flow = MaskFlow()

        mask_flow.run(data_path, 10, out_dir=out_dir, ub=9)
        assert_false(mask_flow.last_generated_outputs)

        mask_flow.run(data_path, 10, out_dir=out_dir)
        mask_path = mask_flow.last_generated_outputs['out_mask']
        mask_data, mask_affine = load_nifti(mask_path)
        npt.assert_equal(mask_data.shape, volume.shape)
        npt.assert_array_almost_equal(mask_affine, affine)
Beispiel #8
0
def test_cluster_attributes_and_constructor():
    cluster = Cluster()
    assert_equal(type(cluster), Cluster)

    assert_equal(cluster.id, 0)
    assert_array_equal(cluster.indices, [])
    assert_equal(len(cluster), 0)

    # Duplicate
    assert_equal(cluster, Cluster(cluster.id, cluster.indices,
                                  cluster.refdata))
    assert_false(
        cluster != Cluster(cluster.id, cluster.indices, cluster.refdata))

    # Invalid comparison
    assert_raises(TypeError, cluster.__cmp__, cluster)
Beispiel #9
0
def test_cluster_centroid_attributes_and_constructor():
    centroid = np.zeros(features_shape)
    cluster = ClusterCentroid(centroid)
    assert_equal(type(cluster), ClusterCentroid)

    assert_equal(cluster.id, 0)
    assert_array_equal(cluster.indices, [])
    assert_array_equal(cluster.centroid, np.zeros(features_shape))
    assert_equal(len(cluster), 0)

    # Duplicate
    assert_equal(cluster, ClusterCentroid(centroid))
    assert_false(cluster != ClusterCentroid(centroid))
    assert_false(cluster == ClusterCentroid(centroid + 1))

    # Invalid comparison
    assert_raises(TypeError, cluster.__cmp__, cluster)
Beispiel #10
0
def test_cluster_centroid_attributes_and_constructor():
    centroid = np.zeros(features_shape)
    cluster = ClusterCentroid(centroid)
    assert_equal(type(cluster), ClusterCentroid)

    assert_equal(cluster.id, 0)
    assert_array_equal(cluster.indices, [])
    assert_array_equal(cluster.centroid, np.zeros(features_shape))
    assert_equal(len(cluster), 0)

    # Duplicate
    assert_equal(cluster, ClusterCentroid(centroid))
    assert_false(cluster != ClusterCentroid(centroid))
    assert_false(cluster == ClusterCentroid(centroid+1))

    # Invalid comparison
    assert_raises(TypeError, cluster.__cmp__, cluster)
Beispiel #11
0
def test_feature_resample():
    from dipy.tracking.streamline import set_number_of_points

    # Test subclassing Feature
    class ResampleFeature(dipysfeature.Feature):
        def __init__(self, nb_points):
            super(ResampleFeature, self).__init__(is_order_invariant=False)
            self.nb_points = nb_points
            if nb_points <= 0:
                msg = ("ResampleFeature: `nb_points` must be strictly"
                       " positive: {0}").format(nb_points)
                raise ValueError(msg)

        def infer_shape(self, streamline):
            return (self.nb_points, streamline.shape[1])

        def extract(self, streamline):
            return set_number_of_points(streamline, self.nb_points)

    assert_raises(ValueError, dipysfeature.ResampleFeature, nb_points=0)
    assert_raises(ValueError, ResampleFeature, nb_points=0)

    max_points = max(map(len, [s1, s2, s3, s4]))
    for nb_points in [2, 5, 2 * max_points]:
        for feature in [
                dipysfeature.ResampleFeature(nb_points),
                ResampleFeature(nb_points)
        ]:
            for s in [s1, s2, s3, s4]:
                # Test method infer_shape
                assert_equal(feature.infer_shape(s), (nb_points, s.shape[1]))

                # Test method extract
                features = feature.extract(s)
                assert_equal(features.shape, (nb_points, s.shape[1]))
                assert_array_almost_equal(features,
                                          set_number_of_points(s, nb_points))

            # This feature type is not order invariant
            assert_false(feature.is_order_invariant)
            for s in [s1, s2, s3, s4]:
                features = feature.extract(s)
                features_flip = feature.extract(s[::-1])
                assert_array_equal(features_flip,
                                   set_number_of_points(s[::-1], nb_points))
                assert_true(np.any(np.not_equal(features, features_flip)))
Beispiel #12
0
def test_cluster_attributes_and_constructor():
    cluster = Cluster()
    assert_equal(type(cluster), Cluster)

    assert_equal(cluster.id, 0)
    assert_array_equal(cluster.indices, [])
    assert_equal(len(cluster), 0)

    # Duplicate
    assert_equal(cluster, Cluster(cluster.id,
                                  cluster.indices,
                                  cluster.refdata))
    assert_false(cluster != Cluster(cluster.id,
                                    cluster.indices,
                                    cluster.refdata))

    # Invalid comparison
    assert_raises(TypeError, cluster.__cmp__, cluster)
Beispiel #13
0
def test_mask():
    with TemporaryDirectory() as out_dir:
        data_path, _, _ = get_fnames('small_25')
        vol_img = nib.load(data_path)
        volume = vol_img.get_data()

        mask_flow = MaskFlow()

        mask_flow.run(data_path, 10, out_dir=out_dir, ub=9)
        assert_false(mask_flow.last_generated_outputs)

        mask_flow.run(data_path, 10, out_dir=out_dir)
        mask_path = mask_flow.last_generated_outputs['out_mask']
        mask_img = nib.load(mask_path)
        mask_data = mask_img.get_data()
        npt.assert_equal(mask_data.shape, volume.shape)
        npt.assert_array_almost_equal(mask_img.affine, vol_img.affine)
        npt.assert_equal(mask_data.dtype, np.uint8)
Beispiel #14
0
def test_feature_resample():
    from dipy.tracking.streamline import set_number_of_points

    # Test subclassing Feature
    class ResampleFeature(dipymetric.Feature):
        def __init__(self, nb_points):
            super(ResampleFeature, self).__init__(is_order_invariant=False)
            self.nb_points = nb_points
            if nb_points <= 0:
                msg = ("ResampleFeature: `nb_points` must be strictly"
                       " positive: {0}").format(nb_points)
                raise ValueError(msg)

        def infer_shape(self, streamline):
            return (self.nb_points, streamline.shape[1])

        def extract(self, streamline):
            return set_number_of_points(streamline, self.nb_points)

    assert_raises(ValueError, dipymetric.ResampleFeature, nb_points=0)
    assert_raises(ValueError, ResampleFeature, nb_points=0)

    max_points = max(map(len, [s1, s2, s3, s4]))
    for nb_points in [2, 5, 2*max_points]:
        for feature in [dipymetric.ResampleFeature(nb_points),
                        ResampleFeature(nb_points)]:
            for s in [s1, s2, s3, s4]:
                # Test method infer_shape
                assert_equal(feature.infer_shape(s), (nb_points, s.shape[1]))

                # Test method extract
                features = feature.extract(s)
                assert_equal(features.shape, (nb_points, s.shape[1]))
                assert_array_almost_equal(features,
                                          set_number_of_points(s, nb_points))

            # This feature type is not order invariant
            assert_false(feature.is_order_invariant)
            for s in [s1, s2, s3, s4]:
                features = feature.extract(s)
                features_flip = feature.extract(s[::-1])
                assert_array_equal(features_flip,
                                   set_number_of_points(s[::-1], nb_points))
                assert_true(np.any(np.not_equal(features, features_flip)))
Beispiel #15
0
def test_cluster_map_comparison_with_object():
    nb_clusters = 4
    cluster_map = ClusterMap()
    # clusters = []
    for i in range(nb_clusters):
        new_cluster = Cluster(indices=range(i))
        cluster_map.add_cluster(new_cluster)
        # clusters.append(new_cluster)

    # Comparison with another ClusterMap object
    other_cluster_map = copy.deepcopy(cluster_map)
    assert_equal(cluster_map, other_cluster_map)

    other_cluster_map = copy.deepcopy(cluster_map)
    assert_false(cluster_map != other_cluster_map)

    other_cluster_map = copy.deepcopy(cluster_map)
    assert_raises(NotImplementedError, cluster_map.__le__, other_cluster_map)

    # Comparison with an object that is not a ClusterMap or int
    assert_raises(NotImplementedError, cluster_map.__le__, float(42))
Beispiel #16
0
def test_cluster_map_comparison_with_object():
    nb_clusters = 4
    cluster_map = ClusterMap()
    # clusters = []
    for i in range(nb_clusters):
        new_cluster = Cluster(indices=range(i))
        cluster_map.add_cluster(new_cluster)
        # clusters.append(new_cluster)

    # Comparison with another ClusterMap object
    other_cluster_map = copy.deepcopy(cluster_map)
    assert_equal(cluster_map, other_cluster_map)

    other_cluster_map = copy.deepcopy(cluster_map)
    assert_false(cluster_map != other_cluster_map)

    other_cluster_map = copy.deepcopy(cluster_map)
    assert_raises(NotImplementedError, cluster_map.__le__, other_cluster_map)

    # Comparison with an object that is not a ClusterMap or int
    assert_raises(NotImplementedError, cluster_map.__le__, float(42))
Beispiel #17
0
def test_particle_filtering_traking_workflows():
    with TemporaryDirectory() as out_dir:
        dwi_path, bval_path, bvec_path = get_fnames('small_64D')
        volume, affine = load_nifti(dwi_path)

        # Create some mask
        mask = np.ones_like(volume[:, :, :, 0], dtype=np.uint8)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        save_nifti(mask_path, mask, affine)

        simple_wm = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
                              [0, 0, 1, 1, 1, 1, 0, 1, 0, 0],
                              [0, 0, 1, 0, 1, 0, 1, 0, 0, 0],
                              [0, 0, 1, 0, 1, 1, 0, 1, 0, 0],
                              [0, 0, 0, 1, 1, 0, 1, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              ])
        simple_wm = np.dstack([np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape),
                               simple_wm, simple_wm, simple_wm,
                               simple_wm, simple_wm, simple_wm,
                               np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape)])
        simple_gm = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 1, 1, 0, 0, 1, 1, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 1, 0, 1, 0],
                              [0, 1, 1, 0, 1, 1, 1, 0, 1, 1],
                              [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
                              ])
        simple_gm = np.dstack([np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape),
                               simple_gm, simple_gm, simple_gm,
                               simple_gm, simple_gm, simple_gm,
                               np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape)])
        simple_csf = np.ones(simple_wm.shape) - simple_wm - simple_gm

        wm_path = join(out_dir, 'tmp_wm.nii.gz')
        gm_path = join(out_dir, 'tmp_gm.nii.gz')
        csf_path = join(out_dir, 'tmp_csf.nii.gz')

        for path, arr in zip([wm_path, gm_path, csf_path],
                             [simple_wm, simple_gm, simple_csf]):
            save_nifti(path, arr.astype(np.uint8), affine)

        # CSD Reconstruction
        reconst_csd_flow = ReconstCSDFlow()
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", message=descoteaux07_legacy_msg,
                category=PendingDeprecationWarning)
            reconst_csd_flow.run(dwi_path, bval_path, bvec_path, mask_path,
                                 out_dir=out_dir, extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']

        # Test tracking
        pf_track_pam = PFTrackingPAMFlow()
        assert_equal(pf_track_pam.get_short_name(), 'track_pft')
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", message=descoteaux07_legacy_msg,
                category=PendingDeprecationWarning)
            pf_track_pam.run(pam_path, wm_path, gm_path, csf_path, seeds_path)
        tractogram_path = \
            pf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test that tracking returns seeds
        pf_track_pam = PFTrackingPAMFlow()
        pf_track_pam._force_overwrite = True
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", message=descoteaux07_legacy_msg,
                category=PendingDeprecationWarning)
            pf_track_pam.run(pam_path,
                             wm_path,
                             gm_path,
                             csf_path,
                             seeds_path,
                             save_seeds=True)
        tractogram_path = \
            pf_track_pam.last_generated_outputs['out_tractogram']
        assert_true(tractogram_has_seeds(tractogram_path))
        assert_true(seeds_are_same_space_as_streamlines(tractogram_path))
Beispiel #18
0
def test_local_fiber_tracking_workflow():
    with TemporaryDirectory() as out_dir:
        data_path, bval_path, bvec_path = get_fnames('small_64D')
        volume, affine = load_nifti(data_path)
        mask = np.ones_like(volume[:, :, :, 0], dtype=np.uint8)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        save_nifti(mask_path, mask, affine)

        reconst_csd_flow = ReconstCSDFlow()
        reconst_csd_flow.run(data_path,
                             bval_path,
                             bvec_path,
                             mask_path,
                             out_dir=out_dir,
                             extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']
        mask_path = mask_flow.last_generated_outputs['out_mask']

        gfa_img, gfa_affine = load_nifti(gfa_path)
        save_nifti(gfa_path, gfa_img, gfa_affine)

        # Test tracking with pam no sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        assert_equal(lf_track_pam.get_short_name(), 'track_local')
        lf_track_pam.run(pam_path, gfa_path, seeds_path)
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with binary stopping criterion
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, mask_path, seeds_path, use_binary_mask=True)

        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path,
                         gfa_path,
                         seeds_path,
                         tracking_method="eudx")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and deterministic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path,
                         gfa_path,
                         seeds_path,
                         tracking_method="deterministic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and probabilistic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path,
                         gfa_path,
                         seeds_path,
                         tracking_method="probabilistic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and closest peaks getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path,
                         gfa_path,
                         seeds_path,
                         tracking_method="closestpeaks")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test that tracking returns seeds
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path,
                         gfa_path,
                         seeds_path,
                         tracking_method="deterministic",
                         save_seeds=True)
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_true(tractogram_has_seeds(tractogram_path))
        assert_true(seeds_are_same_space_as_streamlines(tractogram_path))
Beispiel #19
0
def test_is_tripwire():
    assert_false(is_tripwire(object()))
    assert_true(is_tripwire(TripWire('some message')))
Beispiel #20
0
def test_particle_filtering_traking_workflows():
    with TemporaryDirectory() as out_dir:
        dwi_path, bval_path, bvec_path = get_fnames('small_64D')
        vol_img = nib.load(dwi_path)
        volume = vol_img.get_data()

        # Create some mask
        mask = np.ones_like(volume[:, :, :, 0])
        mask_img = nib.Nifti1Image(mask.astype(np.uint8), vol_img.affine)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        nib.save(mask_img, mask_path)

        simple_wm = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
                              [0, 0, 1, 1, 1, 1, 0, 1, 0, 0],
                              [0, 0, 1, 0, 1, 0, 1, 0, 0, 0],
                              [0, 0, 1, 0, 1, 1, 0, 1, 0, 0],
                              [0, 0, 0, 1, 1, 0, 1, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              ])
        simple_wm = np.dstack([np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape),
                               simple_wm, simple_wm, simple_wm,
                               simple_wm, simple_wm, simple_wm,
                               np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape)])
        simple_gm = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 1, 1, 0, 0, 1, 1, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 1, 0, 1, 0],
                              [0, 1, 1, 0, 1, 1, 1, 0, 1, 1],
                              [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
                              ])
        simple_gm = np.dstack([np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape),
                               simple_gm, simple_gm, simple_gm,
                               simple_gm, simple_gm, simple_gm,
                               np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape)])
        simple_csf = np.ones(simple_wm.shape) - simple_wm - simple_gm

        wm_path = join(out_dir, 'tmp_wm.nii.gz')
        gm_path = join(out_dir, 'tmp_gm.nii.gz')
        csf_path = join(out_dir, 'tmp_csf.nii.gz')

        for path, arr in zip([wm_path, gm_path, csf_path],
                             [simple_wm, simple_gm, simple_csf]):
            nib.save(nib.Nifti1Image(arr.astype(np.uint8), vol_img.affine),
                     path)

        # CSD Reconstruction
        reconst_csd_flow = ReconstCSDFlow()
        reconst_csd_flow.run(dwi_path, bval_path, bvec_path, mask_path,
                             out_dir=out_dir, extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']

        # Test tracking
        pf_track_pam = PFTrackingPAMFlow()
        assert_equal(pf_track_pam.get_short_name(), 'track_pft')
        pf_track_pam.run(pam_path, wm_path, gm_path, csf_path, seeds_path)
        tractogram_path = \
            pf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test that tracking returns seeds
        pf_track_pam = PFTrackingPAMFlow()
        pf_track_pam._force_overwrite = True
        pf_track_pam.run(pam_path,
                         wm_path,
                         gm_path,
                         csf_path,
                         seeds_path,
                         save_seeds=True)
        tractogram_path = \
            pf_track_pam.last_generated_outputs['out_tractogram']
        assert_true(tractogram_has_seeds(tractogram_path))
        assert_true(seeds_are_same_space_as_streamlines(tractogram_path))
Beispiel #21
0
def test_is_tripwire():
    assert_false(is_tripwire(object()))
    assert_true(is_tripwire(TripWire('some message')))
Beispiel #22
0
def test_local_fiber_tracking_workflow():
    with TemporaryDirectory() as out_dir:
        data_path, bval_path, bvec_path = get_fnames('small_64D')
        vol_img = nib.load(data_path)
        volume = vol_img.get_data()
        mask = np.ones_like(volume[:, :, :, 0])
        mask_img = nib.Nifti1Image(mask.astype(np.uint8), vol_img.affine)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        nib.save(mask_img, mask_path)

        reconst_csd_flow = ReconstCSDFlow()
        reconst_csd_flow.run(data_path, bval_path, bvec_path, mask_path,
                             out_dir=out_dir, extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']
        mask_path = mask_flow.last_generated_outputs['out_mask']

        # Put identity in gfa path to prevent impossible to use
        # local tracking because of affine containing shearing.
        gfa_img = nib.load(gfa_path)
        save_nifti(gfa_path, gfa_img.get_data(), np.eye(4), gfa_img.header)

        # Test tracking with pam no sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        assert_equal(lf_track_pam.get_short_name(), 'track_local')
        lf_track_pam.run(pam_path, gfa_path, seeds_path)
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with binary tissue classifier
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, mask_path, seeds_path,
                         use_binary_mask=True)

        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="eudx")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and deterministic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="deterministic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and probabilistic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="probabilistic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and closest peaks getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="closestpeaks")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test that tracking returns seeds
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="deterministic",
                         save_seeds=True)
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_true(tractogram_has_seeds(tractogram_path))
        assert_true(seeds_are_same_space_as_streamlines(tractogram_path))
Beispiel #23
0
def test_metric_cosine():
    feature = dipymetric.VectorOfEndpointsFeature()

    class CosineMetric(dipymetric.Metric):
        def __init__(self, feature):
            super(CosineMetric, self).__init__(feature=feature)

        def are_compatible(self, shape1, shape2):
            # Cosine metric works on vectors.
            return shape1 == shape2 and shape1[0] == 1

        def dist(self, v1, v2):
            # Check if we have null vectors
            if norm(v1) == 0:
                return 0. if norm(v2) == 0 else 1.

            v1_normed = v1.astype(np.float64) / norm(v1.astype(np.float64))
            v2_normed = v2.astype(np.float64) / norm(v2.astype(np.float64))
            cos_theta = np.dot(v1_normed, v2_normed.T)
            # Make sure it's in [-1, 1], i.e. within domain of arccosine
            cos_theta = np.minimum(cos_theta, 1.)
            cos_theta = np.maximum(cos_theta, -1.)
            return np.arccos(cos_theta) / np.pi  # Normalized cosine distance

    for metric in [CosineMetric(feature), dipymetric.CosineMetric(feature)]:
        # Test special cases of the cosine distance.
        v0 = np.array([[0, 0, 0]], dtype=np.float32)
        v1 = np.array([[1, 2, 3]], dtype=np.float32)
        v2 = np.array([[1, -1./2, 0]], dtype=np.float32)
        v3 = np.array([[-1, -2, -3]], dtype=np.float32)

        assert_equal(metric.dist(v0, v0), 0.)   # dot-dot
        assert_equal(metric.dist(v0, v1), 1.)   # dot-line
        assert_equal(metric.dist(v1, v1), 0.)   # collinear
        assert_equal(metric.dist(v1, v2), 0.5)  # orthogonal
        assert_equal(metric.dist(v1, v3), 1.)   # opposite

        # All possible pairs
        for s1, s2 in itertools.product(*[streamlines]*2):
            # Extract features since metric doesn't
            # work directly on streamlines
            f1 = metric.feature.extract(s1)
            f2 = metric.feature.extract(s2)

            # Test method are_compatible
            are_vectors = f1.shape[0] == 1 and f2.shape[0] == 1
            same_dimension = f1.shape[1] == f2.shape[1]
            assert_equal(metric.are_compatible(f1.shape, f2.shape),
                         are_vectors and same_dimension)

            # Test method dist if features are compatible
            if metric.are_compatible(f1.shape, f2.shape):
                distance = metric.dist(f1, f2)
                if np.all(f1 == f2):
                    assert_almost_equal(distance, 0.)

                assert_almost_equal(distance, dipymetric.dist(metric, s1, s2))
                assert_greater_equal(distance, 0.)
                assert_less_equal(distance, 1.)

        # This metric type is not order invariant
        assert_false(metric.is_order_invariant)
        # All possible pairs
        for s1, s2 in itertools.product(*[streamlines]*2):
            f1 = metric.feature.extract(s1)
            f2 = metric.feature.extract(s2)

            if not metric.are_compatible(f1.shape, f2.shape):
                continue

            f1_flip = metric.feature.extract(s1[::-1])
            f2_flip = metric.feature.extract(s2[::-1])

            distance = metric.dist(f1, f2)
            assert_almost_equal(metric.dist(f1_flip, f2_flip), distance)

            if not np.all(f1_flip == f2_flip):
                assert_false(metric.dist(f1, f2_flip) == distance)
                assert_false(metric.dist(f1_flip, f2) == distance)
Beispiel #24
0
def test_metric_cosine():
    feature = dipysfeature.VectorOfEndpointsFeature()

    class CosineMetric(dipysmetric.Metric):
        def __init__(self, feature):
            super(CosineMetric, self).__init__(feature=feature)

        def are_compatible(self, shape1, shape2):
            # Cosine metric works on vectors.
            return shape1 == shape2 and shape1[0] == 1

        def dist(self, v1, v2):
            # Check if we have null vectors
            if norm(v1) == 0:
                return 0. if norm(v2) == 0 else 1.

            v1_normed = v1.astype(np.float64) / norm(v1.astype(np.float64))
            v2_normed = v2.astype(np.float64) / norm(v2.astype(np.float64))
            cos_theta = np.dot(v1_normed, v2_normed.T)
            # Make sure it's in [-1, 1], i.e. within domain of arccosine
            cos_theta = np.minimum(cos_theta, 1.)
            cos_theta = np.maximum(cos_theta, -1.)
            return np.arccos(cos_theta) / np.pi  # Normalized cosine distance

    for metric in [CosineMetric(feature), dipysmetric.CosineMetric(feature)]:
        # Test special cases of the cosine distance.
        v0 = np.array([[0, 0, 0]], dtype=np.float32)
        v1 = np.array([[1, 2, 3]], dtype=np.float32)
        v2 = np.array([[1, -1. / 2, 0]], dtype=np.float32)
        v3 = np.array([[-1, -2, -3]], dtype=np.float32)

        assert_equal(metric.dist(v0, v0), 0.)  # dot-dot
        assert_equal(metric.dist(v0, v1), 1.)  # dot-line
        assert_equal(metric.dist(v1, v1), 0.)  # collinear
        assert_equal(metric.dist(v1, v2), 0.5)  # orthogonal
        assert_equal(metric.dist(v1, v3), 1.)  # opposite

        # All possible pairs
        for s1, s2 in itertools.product(*[streamlines] * 2):
            # Extract features since metric doesn't
            # work directly on streamlines
            f1 = metric.feature.extract(s1)
            f2 = metric.feature.extract(s2)

            # Test method are_compatible
            are_vectors = f1.shape[0] == 1 and f2.shape[0] == 1
            same_dimension = f1.shape[1] == f2.shape[1]
            assert_equal(metric.are_compatible(f1.shape, f2.shape), are_vectors
                         and same_dimension)

            # Test method dist if features are compatible
            if metric.are_compatible(f1.shape, f2.shape):
                distance = metric.dist(f1, f2)
                if np.all(f1 == f2):
                    assert_almost_equal(distance, 0.)

                assert_almost_equal(distance, dipysmetric.dist(metric, s1, s2))
                assert_greater_equal(distance, 0.)
                assert_less_equal(distance, 1.)

        # This metric type is not order invariant
        assert_false(metric.is_order_invariant)
        # All possible pairs
        for s1, s2 in itertools.product(*[streamlines] * 2):
            f1 = metric.feature.extract(s1)
            f2 = metric.feature.extract(s2)

            if not metric.are_compatible(f1.shape, f2.shape):
                continue

            f1_flip = metric.feature.extract(s1[::-1])
            f2_flip = metric.feature.extract(s2[::-1])

            distance = metric.dist(f1, f2)
            assert_almost_equal(metric.dist(f1_flip, f2_flip), distance)

            if not np.all(f1_flip == f2_flip):
                assert_false(metric.dist(f1, f2_flip) == distance)
                assert_false(metric.dist(f1_flip, f2) == distance)
Beispiel #25
0
def test_particule_filtering_traking_workflows():
    with TemporaryDirectory() as out_dir:
        dwi_path, bval_path, bvec_path = get_fnames('small_64D')
        vol_img = nib.load(dwi_path)
        volume = vol_img.get_data()

        # Create some mask
        mask = np.ones_like(volume[:, :, :, 0])
        mask_img = nib.Nifti1Image(mask.astype(np.uint8), vol_img.affine)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        nib.save(mask_img, mask_path)

        simple_wm = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
                              [0, 0, 1, 1, 1, 1, 0, 1, 0, 0],
                              [0, 0, 1, 0, 1, 0, 1, 0, 0, 0],
                              [0, 0, 1, 0, 1, 1, 0, 1, 0, 0],
                              [0, 0, 0, 1, 1, 0, 1, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                              ])
        simple_wm = np.dstack([np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape),
                               simple_wm, simple_wm, simple_wm,
                               simple_wm, simple_wm, simple_wm,
                               np.zeros(simple_wm.shape),
                               np.zeros(simple_wm.shape)])
        simple_gm = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
                              [0, 0, 1, 1, 0, 0, 1, 1, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 0, 0, 0, 1],
                              [1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                              [0, 1, 0, 0, 0, 0, 1, 0, 1, 0],
                              [0, 1, 1, 0, 1, 1, 1, 0, 1, 1],
                              [0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
                              ])
        simple_gm = np.dstack([np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape),
                               simple_gm, simple_gm, simple_gm,
                               simple_gm, simple_gm, simple_gm,
                               np.zeros(simple_gm.shape),
                               np.zeros(simple_gm.shape)])
        simple_csf = np.ones(simple_wm.shape) - simple_wm - simple_gm

        wm_path = join(out_dir, 'tmp_wm.nii.gz')
        gm_path = join(out_dir, 'tmp_gm.nii.gz')
        csf_path = join(out_dir, 'tmp_csf.nii.gz')

        for path, arr in zip([wm_path, gm_path, csf_path],
                             [simple_wm, simple_gm, simple_csf]):
            nib.save(nib.Nifti1Image(arr.astype(np.uint8), vol_img.affine),
                     path)

        # CSD Reconstruction
        reconst_csd_flow = ReconstCSDFlow()
        reconst_csd_flow.run(dwi_path, bval_path, bvec_path, mask_path,
                             out_dir=out_dir, extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']

        # Test tracking
        pf_track_pam = PFTrackingPAMFlow()
        assert_equal(pf_track_pam.get_short_name(), 'track_pft')
        pf_track_pam.run(pam_path, wm_path, gm_path, csf_path, seeds_path)
        tractogram_path = \
            pf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))
Beispiel #26
0
def test_local_fiber_tracking_workflow():
    with TemporaryDirectory() as out_dir:
        data_path, bval_path, bvec_path = get_fnames('small_64D')
        vol_img = nib.load(data_path)
        volume = vol_img.get_data()
        mask = np.ones_like(volume[:, :, :, 0])
        mask_img = nib.Nifti1Image(mask.astype(np.uint8), vol_img.affine)
        mask_path = join(out_dir, 'tmp_mask.nii.gz')
        nib.save(mask_img, mask_path)

        reconst_csd_flow = ReconstCSDFlow()
        reconst_csd_flow.run(data_path, bval_path, bvec_path, mask_path,
                             out_dir=out_dir, extract_pam_values=True)

        pam_path = reconst_csd_flow.last_generated_outputs['out_pam']
        gfa_path = reconst_csd_flow.last_generated_outputs['out_gfa']

        # Create seeding mask by thresholding the gfa
        mask_flow = MaskFlow()
        mask_flow.run(gfa_path, 0.8, out_dir=out_dir)
        seeds_path = mask_flow.last_generated_outputs['out_mask']

        # Put identity in gfa path to prevent impossible to use
        # local tracking because of affine containing shearing.
        gfa_img = nib.load(gfa_path)
        save_nifti(gfa_path, gfa_img.get_data(), np.eye(4), gfa_img.header)

        # Test tracking with pam no sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        assert_equal(lf_track_pam.get_short_name(), 'track_local')
        lf_track_pam.run(pam_path, gfa_path, seeds_path)
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="eudx")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and deterministic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="deterministic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and probabilistic getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="probabilistic")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))

        # Test tracking with pam with sh and closestpeaks getter
        lf_track_pam = LocalFiberTrackingPAMFlow()
        lf_track_pam._force_overwrite = True
        lf_track_pam.run(pam_path, gfa_path, seeds_path,
                         tracking_method="closestpeaks")
        tractogram_path = \
            lf_track_pam.last_generated_outputs['out_tractogram']
        assert_false(is_tractogram_empty(tractogram_path))