def test_recobundles_flow(): with TemporaryDirectory() as out_dir: data_path = get_fnames('fornix') fornix = load_tractogram(data_path, 'same', bbox_valid_check=False).streamlines f = Streamlines(fornix) f1 = f.copy() f2 = f1[:15].copy() f2._data += np.array([40, 0, 0]) f.extend(f2) f2_path = pjoin(out_dir, "f2.trk") sft = StatefulTractogram(f2, data_path, Space.RASMM) save_tractogram(sft, f2_path, bbox_valid_check=False) f1_path = pjoin(out_dir, "f1.trk") sft = StatefulTractogram(f, data_path, Space.RASMM) save_tractogram(sft, f1_path, bbox_valid_check=False) rb_flow = RecoBundlesFlow(force=True) rb_flow.run(f1_path, f2_path, greater_than=0, clust_thr=10, model_clust_thr=5., reduction_thr=10, out_dir=out_dir) labels = rb_flow.last_generated_outputs['out_recognized_labels'] recog_trk = rb_flow.last_generated_outputs['out_recognized_transf'] rec_bundle = load_tractogram(recog_trk, 'same', bbox_valid_check=False).streamlines npt.assert_equal(len(rec_bundle) == len(f2), True) label_flow = LabelsBundlesFlow(force=True) label_flow.run(f1_path, labels) recog_bundle = label_flow.last_generated_outputs['out_bundle'] rec_bundle_org = load_tractogram(recog_bundle, 'same', bbox_valid_check=False).streamlines BMD = BundleMinDistanceMetric() nb_pts = 20 static = set_number_of_points(f2, nb_pts) moving = set_number_of_points(rec_bundle_org, nb_pts) BMD.setup(static, moving) x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0]) # affine bmd_value = BMD.distance(x0.tolist()) npt.assert_equal(bmd_value < 1, True)
def test_recobundles_flow(): with TemporaryDirectory() as out_dir: data_path = get_fnames('fornix') streams, hdr = nib.trackvis.read(data_path) fornix = [s[0] for s in streams] f = Streamlines(fornix) f1 = f.copy() f2 = f1[:15].copy() f2._data += np.array([40, 0, 0]) f.extend(f2) f2_path = pjoin(out_dir, "f2.trk") save_trk(f2_path, f2, affine=np.eye(4)) f1_path = pjoin(out_dir, "f1.trk") save_trk(f1_path, f, affine=np.eye(4)) rb_flow = RecoBundlesFlow(force=True) rb_flow.run(f1_path, f2_path, greater_than=0, clust_thr=10, model_clust_thr=5., reduction_thr=10, out_dir=out_dir) labels = rb_flow.last_generated_outputs['out_recognized_labels'] recog_trk = rb_flow.last_generated_outputs['out_recognized_transf'] rec_bundle, _ = load_trk(recog_trk) npt.assert_equal(len(rec_bundle) == len(f2), True) label_flow = LabelsBundlesFlow(force=True) label_flow.run(f1_path, labels) recog_bundle = label_flow.last_generated_outputs['out_bundle'] rec_bundle_org, _ = load_trk(recog_bundle) BMD = BundleMinDistanceMetric() nb_pts = 20 static = set_number_of_points(f2, nb_pts) moving = set_number_of_points(rec_bundle_org, nb_pts) BMD.setup(static, moving) x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0]) # affine bmd_value = BMD.distance(x0.tolist()) npt.assert_equal(bmd_value < 1, True)
def evaluate_results(self, model_bundle, pruned_streamlines, slr_select): """ Compare the similiarity between two given bundles, model bundle, and extracted bundle. Parameters ---------- model_bundle : Streamlines pruned_streamlines : Streamlines slr_select : tuple Select the number of streamlines from model to neirborhood of model to perform the local SLR. Returns ------- ba_value : float bundle adjacency value between model bundle and pruned bundle bmd_value : float bundle minimum distance value between model bundle and pruned bundle """ spruned_streamlines = Streamlines(pruned_streamlines) recog_centroids = self._cluster_model_bundle( spruned_streamlines, model_clust_thr=1.25) mod_centroids = self._cluster_model_bundle( model_bundle, model_clust_thr=1.25) recog_centroids = Streamlines(recog_centroids) model_centroids = Streamlines(mod_centroids) ba_value = bundle_adjacency(set_number_of_points(recog_centroids, 20), set_number_of_points(model_centroids, 20), threshold=10) BMD = BundleMinDistanceMetric() static = select_random_set_of_streamlines(model_bundle, slr_select[0]) moving = select_random_set_of_streamlines(pruned_streamlines, slr_select[1]) nb_pts = 20 static = set_number_of_points(static, nb_pts) moving = set_number_of_points(moving, nb_pts) BMD.setup(static, moving) x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0]) # affine bmd_value = BMD.distance(x0.tolist()) return ba_value, bmd_value
def _register_neighb_to_model(self, model_bundle, neighb_streamlines, metric=None, x0=None, bounds=None, select_model=400, select_target=600, method='L-BFGS-B', nb_pts=20, num_threads=None): if self.verbose: print('# Local SLR of neighb_streamlines to model') t = time() if metric is None or metric == 'symmetric': metric = BundleMinDistanceMetric(num_threads=num_threads) if metric == 'asymmetric': metric = BundleMinDistanceAsymmetricMetric() if metric == 'diagonal': metric = BundleSumDistanceMatrixMetric() if x0 is None: x0 = 'similarity' if bounds is None: bounds = [(-30, 30), (-30, 30), (-30, 30), (-45, 45), (-45, 45), (-45, 45), (0.8, 1.2)] # TODO this can be speeded up by using directly the centroids static = select_random_set_of_streamlines(model_bundle, select_model, rng=self.rng) moving = select_random_set_of_streamlines(neighb_streamlines, select_target, rng=self.rng) static = set_number_of_points(static, nb_pts) moving = set_number_of_points(moving, nb_pts) slr = StreamlineLinearRegistration(metric=metric, x0=x0, bounds=bounds, method=method) slm = slr.optimize(static, moving) transf_streamlines = neighb_streamlines.copy() transf_streamlines._data = apply_affine( slm.matrix, transf_streamlines._data) transf_matrix = slm.matrix slr_bmd = slm.fopt slr_iterations = slm.iterations if self.verbose: print(' Square-root of BMD is %.3f' % (np.sqrt(slr_bmd),)) if slr_iterations is not None: print(' Number of iterations %d' % (slr_iterations,)) print(' Matrix size {}'.format(slm.matrix.shape)) original = np.get_printoptions() np.set_printoptions(3, suppress=True) print(transf_matrix) print(slm.xopt) np.set_printoptions(**original) print(' Duration %0.3f sec. \n' % (time() - t,)) return transf_streamlines, slr_bmd
def evaluate_results(self, model_bundle, pruned_streamlines, slr_select): """ Comapare the similiarity between two given bundles, model bundle, and extracted bundle. Parameters ---------- model_bundle : Streamlines pruned_streamlines : Streamlines slr_select : tuple Select the number of streamlines from model to neirborhood of model to perform the local SLR. Returns ------- ba_value : float bundle analytics value between model bundle and pruned bundle bmd_value : float bundle minimum distance value between model bundle and pruned bundle """ spruned_streamlines = Streamlines(pruned_streamlines) recog_centroids = self._cluster_model_bundle( spruned_streamlines, model_clust_thr=1.25) mod_centroids = self._cluster_model_bundle( model_bundle, model_clust_thr=1.25) recog_centroids = Streamlines(recog_centroids) model_centroids = Streamlines(mod_centroids) ba_value = ba_analysis(recog_centroids, model_centroids, threshold=10) BMD = BundleMinDistanceMetric() static = select_random_set_of_streamlines(model_bundle, slr_select[0]) moving = select_random_set_of_streamlines(pruned_streamlines, slr_select[1]) nb_pts = 20 static = set_number_of_points(static, nb_pts) moving = set_number_of_points(moving, nb_pts) BMD.setup(static, moving) x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0]) # affine bmd_value = BMD.distance(x0.tolist()) return ba_value, bmd_value
def test_min_vs_min_fast_precision(): static = fornix_streamlines()[:20] moving = fornix_streamlines()[:20] static = [s.astype('f8') for s in static] moving = [m.astype('f8') for m in moving] bmd = BundleMinDistanceMatrixMetric() bmd.setup(static, moving) bmdf = BundleMinDistanceMetric() bmdf.setup(static, moving) x_test = [0.01, 0, 0, 0, 0, 0] print(bmd.distance(x_test)) print(bmdf.distance(x_test)) assert_equal(bmd.distance(x_test), bmdf.distance(x_test))
def _affine_slr(sft_bundle, sft_centroid): x0 = np.zeros((7, )) bounds_dof = [(-10, 10), (-10, 10), (-10, 10), (-5, 5), (-5, 5), (-5, 5), (0.95, 1.05)] metric = BundleMinDistanceMetric(num_threads=1) slr = StreamlineLinearRegistration(metric=metric, method="L-BFGS-B", bounds=bounds_dof, x0=x0, num_threads=1) tmp_bundle = set_number_of_points(sft_bundle.streamlines.copy(), 20) tmp_centroid = set_number_of_points(sft_centroid.streamlines.copy(), 20) slm = slr.optimize(tmp_bundle, tmp_centroid) sft_centroid.streamlines = transform_streamlines(sft_centroid.streamlines, slm.matrix) return sft_centroid
def _register_model_to_neighb(self, slr_num_thread=1, select_model=1000, select_target=1000, slr_transform_type='scaling'): """ Parameters ---------- slr_num_thread : int Number of threads for SLR. Should remain 1 for nearly all use-case. select_model : int Maximum number of clusters to select from the model. select_target : int Maximum number of clusters to select from the neighborhood. slr_transform_type : str Define the transformation for the local SLR. [translation, rigid, similarity, scaling]. Returns ------- transf_neighbor : list The neighborhood clusters transformed into model space. """ possible_slr_transform_type = { 'translation': 0, 'rigid': 1, 'similarity': 2, 'scaling': 3 } static = select_random_set_of_streamlines(self.model_centroids, select_model, self.rng) moving = select_random_set_of_streamlines(self.neighb_centroids, select_target, self.rng) # Tuple 0,1,2 are the min & max bound in x,y,z for translation # Tuple 3,4,5 are the min & max bound in x,y,z for rotation # Tuple 6,7,8 are the min & max bound in x,y,z for scaling # For uniform scaling (similarity), tuple #6 is enough bounds_dof = [(-20, 20), (-20, 20), (-20, 20), (-10, 10), (-10, 10), (-10, 10), (0.8, 1.2), (0.8, 1.2), (0.8, 1.2)] metric = BundleMinDistanceMetric(num_threads=slr_num_thread) slr_transform_type_id = possible_slr_transform_type[slr_transform_type] if slr_transform_type_id >= 0: init_transfo_dof = np.zeros(3) slr = StreamlineLinearRegistration(metric=metric, method="Powell", x0=init_transfo_dof, bounds=bounds_dof[:3], num_threads=slr_num_thread) slm = slr.optimize(static, moving) if slr_transform_type_id >= 1: init_transfo_dof = np.zeros(6) init_transfo_dof[:3] = slm.xopt slr = StreamlineLinearRegistration(metric=metric, x0=init_transfo_dof, bounds=bounds_dof[:6], num_threads=slr_num_thread) slm = slr.optimize(static, moving) if slr_transform_type_id >= 2: if slr_transform_type_id == 2: init_transfo_dof = np.zeros(7) init_transfo_dof[:6] = slm.xopt init_transfo_dof[6] = 1. slr = StreamlineLinearRegistration(metric=metric, x0=init_transfo_dof, bounds=bounds_dof[:7], num_threads=slr_num_thread) slm = slr.optimize(static, moving) else: init_transfo_dof = np.zeros(9) init_transfo_dof[:6] = slm.xopt[:6] init_transfo_dof[6:] = np.array((slm.xopt[6], ) * 3) slr = StreamlineLinearRegistration(metric=metric, x0=init_transfo_dof, bounds=bounds_dof[:9], num_threads=slr_num_thread) slm = slr.optimize(static, moving) self.model_centroids = transform_streamlines(self.model_centroids, np.linalg.inv(slm.matrix))