-
Notifications
You must be signed in to change notification settings - Fork 429
/
bundles.py
753 lines (630 loc) · 27.9 KB
/
bundles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
from time import time
from itertools import chain
import logging
import numpy as np
from dipy.tracking.streamline import (set_number_of_points, nbytes,
select_random_set_of_streamlines)
from dipy.segment.clustering import qbx_and_merge
from dipy.tracking.distances import (bundles_distances_mdf,
bundles_distances_mam)
from dipy.align.streamlinear import (StreamlineLinearRegistration,
BundleMinDistanceMetric,
BundleSumDistanceMatrixMetric,
BundleMinDistanceAsymmetricMetric)
from dipy.tracking.streamline import Streamlines, length
from nibabel.affines import apply_affine
def check_range(streamline, gt, lt):
length_s = length(streamline)
if (length_s > gt) & (length_s < lt):
return True
else:
return False
logger = logging.getLogger(__name__)
def bundle_adjacency(dtracks0, dtracks1, threshold):
""" Find bundle adjacency between two given tracks/bundles
Parameters
----------
dtracks0 : Streamlines
White matter tract from one subject
dtracks1 : Streamlines
White matter tract from another subject
threshold : float
Threshold controls
how much strictness user wants while calculating bundle adjacency
between two bundles. Smaller threshold means bundles should be strictly
adjacent to get higher BA score.
Returns
-------
res : Float
Bundle adjacency score between two tracts
References
----------
.. [Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for
tractography simplification, Frontiers in Neuroscience,
vol 6, no 175, 2012.
"""
d01 = bundles_distances_mdf(dtracks0, dtracks1)
pair12 = []
for i in range(len(dtracks0)):
if np.min(d01[i, :]) < threshold:
j = np.argmin(d01[i, :])
pair12.append((i, j))
pair12 = np.array(pair12)
pair21 = []
# solo2 = []
for i in range(len(dtracks1)):
if np.min(d01[:, i]) < threshold:
j = np.argmin(d01[:, i])
pair21.append((i, j))
pair21 = np.array(pair21)
A = len(pair12) / np.float(len(dtracks0))
B = len(pair21) / np.float(len(dtracks1))
res = 0.5 * (A + B)
return res
def ba_analysis(recognized_bundle, expert_bundle, nb_pts=20, threshold=5.):
""" Calculates bundle adjacency score between two given bundles
Parameters
----------
recognized_bundle : Streamlines
Extracted bundle from the whole brain tractogram (eg: AF_L)
expert_bundle : Streamlines
Model bundle used as reference while extracting similar type bundle
from inout tractogram
nb_pts : integer (default 20)
Discretizing streamlines to have nb_pts number of points
threshold : float (default 5)
Threshold used for in computing bundle adjacency. Threshold controls
how much strictness user wants while calculating bundle adjacency
between two bundles. Smaller threshold means bundles should be strictly
adjacent to get higher BA score.
Returns
-------
Bundle adjacency score between two tracts
References
----------
.. [Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for
tractography simplification, Frontiers in Neuroscience,
vol 6, no 175, 2012.
"""
recognized_bundle = set_number_of_points(recognized_bundle, nb_pts)
expert_bundle = set_number_of_points(expert_bundle, nb_pts)
return bundle_adjacency(recognized_bundle, expert_bundle, threshold)
def cluster_bundle(bundle, clust_thr, rng, nb_pts=20, select_randomly=500000):
""" Clusters bundles
Parameters
----------
bundle : Streamlines
White matter tract
clust_thr : float
clustering threshold used in quickbundles
rng : RandomState
nb_pts: integer (default 20)
Discretizing streamlines to have nb_points number of points
select_randomly: integer (default 500000)
Randomly select streamlines from the input bundle
Returns
-------
centroids : Streamlines
clustered centroids of the input bundle
References
----------
.. [Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for
tractography simplification, Frontiers in Neuroscience,
vol 6, no 175, 2012.
"""
model_cluster_map = qbx_and_merge(bundle, clust_thr,
nb_pts=nb_pts,
select_randomly=select_randomly,
rng=rng)
centroids = model_cluster_map.centroids
return centroids
def bundle_shape_similarity(bundle1, bundle2, rng, threshold=5):
""" Calculates bundle shape similarity between two given bundles using
bundle adjacency (BA) metric
Parameters
----------
bundle1 : Streamlines
White matter tract from one subject (eg: AF_L)
bundle2 : Streamlines
White matter tract from another subject (eg: AF_L)
rng : RandomState
threshold : float (default 5)
Threshold used for in computing bundle adjacency. Threshold controls
how much strictness user wants while calculating shape similarity
between two bundles. Smaller threshold means bundles should be strictly
similar to get higher shape similarity score.
Returns
-------
ba_value : Float
Bundle similarity score between two tracts
References
----------
.. [Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for
tractography simplification, Frontiers in Neuroscience,
vol 6, no 175, 2012.
"""
if len(bundle1) == 0 or len(bundle2) == 0:
return 0
bundle1_centroids = cluster_bundle(bundle1, clust_thr=[1.25],
rng=rng)
bundle2_centroids = cluster_bundle(bundle2, clust_thr=[1.25],
rng=rng)
bundle1_centroids = Streamlines(bundle1_centroids)
bundle2_centroids = Streamlines(bundle2_centroids)
ba_value = ba_analysis(bundle1_centroids, bundle2_centroids,
threshold)
return ba_value
class RecoBundles(object):
def __init__(self, streamlines, greater_than=50, less_than=1000000,
cluster_map=None, clust_thr=15, nb_pts=20,
rng=None, verbose=False):
""" Recognition of bundles
Extract bundles from a participants' tractograms using model bundles
segmented from a different subject or an atlas of bundles.
See [Garyfallidis17]_ for the details.
Parameters
----------
streamlines : Streamlines
The tractogram in which you want to recognize bundles.
greater_than : int, optional
Keep streamlines that have length greater than
this value (default 50)
less_than : int, optional
Keep streamlines have length less than this value (default 1000000)
cluster_map : QB map, optional.
Provide existing clustering to start RB faster (default None).
clust_thr : float, optional.
Distance threshold in mm for clustering `streamlines`.
Default: 15.
nb_pts : int, optional.
Number of points per streamline (default 20)
rng : RandomState
If None define RandomState in initialization function.
Default: None
verbose: bool, optional.
If True, log information.
Notes
-----
Make sure that before creating this class that the streamlines and
the model bundles are roughly in the same space.
Also default thresholds are assumed in RAS 1mm^3 space. You may
want to adjust those if your streamlines are not in world coordinates.
References
----------
.. [Garyfallidis17] Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
"""
map_ind = np.zeros(len(streamlines))
for i in range(len(streamlines)):
map_ind[i] = check_range(streamlines[i], greater_than, less_than)
map_ind = map_ind.astype(bool)
self.orig_indices = np.array(list(range(0, len(streamlines))))
self.filtered_indices = np.array(self.orig_indices[map_ind])
self.streamlines = Streamlines(streamlines[map_ind])
self.nb_streamlines = len(self.streamlines)
self.verbose = verbose
if self.verbose:
logger.info("target brain streamlines length = %s" % len(streamlines))
logger.info("After refining target brain streamlines" +
"length = %s" % len(self.streamlines))
self.start_thr = [40, 25, 20]
if rng is None:
self.rng = np.random.RandomState()
else:
self.rng = rng
if cluster_map is None:
self._cluster_streamlines(clust_thr=clust_thr, nb_pts=nb_pts)
else:
if self.verbose:
t = time()
self.cluster_map = cluster_map
self.cluster_map.refdata = self.streamlines
self.centroids = self.cluster_map.centroids
self.nb_centroids = len(self.centroids)
self.indices = [cluster.indices for cluster in self.cluster_map]
if self.verbose:
logger.info(' Streamlines have %d centroids'
% (self.nb_centroids,))
logger.info(' Total loading duration %0.3f sec. \n'
% (time() - t,))
def _cluster_streamlines(self, clust_thr, nb_pts):
if self.verbose:
t = time()
logger.info('# Cluster streamlines using QBx')
logger.info(' Tractogram has %d streamlines'
% (len(self.streamlines), ))
logger.info(' Size is %0.3f MB' % (nbytes(self.streamlines),))
logger.info(' Distance threshold %0.3f' % (clust_thr,))
# TODO this needs to become a default parameter
thresholds = self.start_thr + [clust_thr]
merged_cluster_map = qbx_and_merge(self.streamlines, thresholds,
nb_pts, None, self.rng,
self.verbose)
self.cluster_map = merged_cluster_map
self.centroids = merged_cluster_map.centroids
self.nb_centroids = len(self.centroids)
self.indices = [cluster.indices for cluster in self.cluster_map]
if self.verbose:
logger.info(' Streamlines have %d centroids'
% (self.nb_centroids,))
logger.info(' Total duration %0.3f sec. \n' % (time() - t,))
def recognize(self, model_bundle, model_clust_thr,
reduction_thr=10,
reduction_distance='mdf',
slr=True,
slr_num_threads=None,
slr_metric=None,
slr_x0=None,
slr_bounds=None,
slr_select=(400, 600),
slr_method='L-BFGS-B',
pruning_thr=5,
pruning_distance='mdf'):
""" Recognize the model_bundle in self.streamlines
Parameters
----------
model_bundle : Streamlines
model_clust_thr : float
reduction_thr : float
reduction_distance : string
mdf or mam (default mdf)
slr : bool
Use Streamline-based Linear Registration (SLR) locally
(default True)
slr_metric : BundleMinDistanceMetric
slr_x0 : array
(default None)
slr_bounds : array
(default None)
slr_select : tuple
Select the number of streamlines from model to neirborhood of
model to perform the local SLR.
slr_method : string
Optimization method (default 'L-BFGS-B')
pruning_thr : float
pruning_distance : string
MDF ('mdf') and MAM ('mam')
Returns
-------
recognized_transf : Streamlines
Recognized bundle in the space of the model tractogram
recognized_labels : array
Indices of recognized bundle in the original tractogram
References
----------
.. [Garyfallidis17] Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
"""
if self.verbose:
t = time()
logger.info('## Recognize given bundle ## \n')
model_centroids = self._cluster_model_bundle(
model_bundle,
model_clust_thr=model_clust_thr)
neighb_streamlines, neighb_indices = self._reduce_search_space(
model_centroids,
reduction_thr=reduction_thr,
reduction_distance=reduction_distance)
if len(neighb_streamlines) == 0:
return Streamlines([]), []
if slr:
transf_streamlines, slr1_bmd = self._register_neighb_to_model(
model_bundle,
neighb_streamlines,
metric=slr_metric,
x0=slr_x0,
bounds=slr_bounds,
select_model=slr_select[0],
select_target=slr_select[1],
method=slr_method,
num_threads=slr_num_threads)
else:
transf_streamlines = neighb_streamlines
pruned_streamlines, labels = self._prune_what_not_in_model(
model_centroids,
transf_streamlines,
neighb_indices,
pruning_thr=pruning_thr,
pruning_distance=pruning_distance)
if self.verbose:
logger.info('Total duration of recognition time is %0.3f sec.\n'
% (time()-t,))
return pruned_streamlines, self.filtered_indices[labels]
def refine(self, model_bundle, pruned_streamlines, model_clust_thr,
reduction_thr=14,
reduction_distance='mdf',
slr=True,
slr_metric=None,
slr_x0=None,
slr_bounds=None,
slr_select=(400, 600),
slr_method='L-BFGS-B',
pruning_thr=6,
pruning_distance='mdf'):
""" Refine and recognize the model_bundle in self.streamlines
This method expects once pruned streamlines as input. It refines the
first ouput of recobundle by applying second local slr (optional),
and second pruning. This method is useful when we are dealing with
noisy data or when we want to extract small tracks from tractograms.
Parameters
----------
model_bundle : Streamlines
pruned_streamlines : Streamlines
model_clust_thr : float
reduction_thr : float
reduction_distance : string
mdf or mam (default mam)
slr : bool
Use Streamline-based Linear Registration (SLR) locally
(default True)
slr_metric : BundleMinDistanceMetric
slr_x0 : array
(default None)
slr_bounds : array
(default None)
slr_select : tuple
Select the number of streamlines from model to neirborhood of
model to perform the local SLR.
slr_method : string
Optimization method (default 'L-BFGS-B')
pruning_thr : float
pruning_distance : string
MDF ('mdf') and MAM ('mam')
Returns
-------
recognized_transf : Streamlines
Recognized bundle in the space of the model tractogram
recognized_labels : array
Indices of recognized bundle in the original tractogram
References
----------
.. [Garyfallidis17] Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based registration and
clustering, Neuroimage, 2017.
"""
if self.verbose:
t = time()
logger.info('## Refine recognize given bundle ## \n')
model_centroids = self._cluster_model_bundle(
model_bundle,
model_clust_thr=model_clust_thr)
pruned_model_centroids = self._cluster_model_bundle(
pruned_streamlines,
model_clust_thr=model_clust_thr)
neighb_streamlines, neighb_indices = self._reduce_search_space(
pruned_model_centroids,
reduction_thr=reduction_thr,
reduction_distance=reduction_distance)
if len(neighb_streamlines) == 0: # if no streamlines recognized
return Streamlines([]), []
if self.verbose:
logger.info("2nd local Slr")
if slr:
transf_streamlines, slr2_bmd = self._register_neighb_to_model(
model_bundle,
neighb_streamlines,
metric=slr_metric,
x0=slr_x0,
bounds=slr_bounds,
select_model=slr_select[0],
select_target=slr_select[1],
method=slr_method)
if self.verbose:
logger.info("pruning after 2nd local Slr")
pruned_streamlines, labels = self._prune_what_not_in_model(
model_centroids,
transf_streamlines,
neighb_indices,
pruning_thr=pruning_thr,
pruning_distance=pruning_distance)
if self.verbose:
logger.info('Total duration of recognition time is %0.3f sec.\n'
% (time()-t,))
return pruned_streamlines, self.filtered_indices[labels]
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 _cluster_model_bundle(self, model_bundle, model_clust_thr, nb_pts=20,
select_randomly=500000):
if self.verbose:
t = time()
logger.info('# Cluster model bundle using QBX')
logger.info(' Model bundle has %d streamlines'
% (len(model_bundle), ))
logger.info(' Distance threshold %0.3f' % (model_clust_thr,))
thresholds = self.start_thr + [model_clust_thr]
model_cluster_map = qbx_and_merge(model_bundle, thresholds,
nb_pts=nb_pts,
select_randomly=select_randomly,
rng=self.rng)
model_centroids = model_cluster_map.centroids
nb_model_centroids = len(model_centroids)
if self.verbose:
logger.info(' Model bundle has %d centroids'
% (nb_model_centroids,))
logger.info(' Duration %0.3f sec. \n' % (time() - t, ))
return model_centroids
def _reduce_search_space(self, model_centroids,
reduction_thr=20, reduction_distance='mdf'):
if self.verbose:
t = time()
logger.info('# Reduce search space')
logger.info(' Reduction threshold %0.3f' % (reduction_thr,))
logger.info(' Reduction distance {}'.format(reduction_distance))
if reduction_distance.lower() == 'mdf':
if self.verbose:
logger.info(' Using MDF')
centroid_matrix = bundles_distances_mdf(model_centroids,
self.centroids)
elif reduction_distance.lower() == 'mam':
if self.verbose:
logger.info(' Using MAM')
centroid_matrix = bundles_distances_mam(model_centroids,
self.centroids)
else:
raise ValueError('Given reduction distance not known')
centroid_matrix[centroid_matrix > reduction_thr] = np.inf
mins = np.min(centroid_matrix, axis=0)
close_clusters_indices = list(np.where(mins != np.inf)[0])
close_clusters = self.cluster_map[close_clusters_indices]
neighb_indices = [cluster.indices for cluster in close_clusters]
neighb_streamlines = Streamlines(chain(*close_clusters))
nb_neighb_streamlines = len(neighb_streamlines)
if nb_neighb_streamlines == 0:
if self.verbose:
logger.info('You have no neighbor streamlines... ' +
'No bundle recognition')
return Streamlines([]), []
if self.verbose:
logger.info(' Number of neighbor streamlines %d' %
(nb_neighb_streamlines,))
logger.info(' Duration %0.3f sec. \n' % (time() - t,))
return neighb_streamlines, neighb_indices
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:
logger.info('# 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:
logger.info(' Square-root of BMD is %.3f' % (np.sqrt(slr_bmd),))
if slr_iterations is not None:
logger.info(' Number of iterations %d' % (slr_iterations,))
logger.info(' Matrix size {}'.format(slm.matrix.shape))
original = np.get_printoptions()
np.set_printoptions(3, suppress=True)
logger.info(transf_matrix)
logger.info(slm.xopt)
np.set_printoptions(**original)
logger.info(' Duration %0.3f sec. \n' % (time() - t,))
return transf_streamlines, slr_bmd
def _prune_what_not_in_model(self, model_centroids,
transf_streamlines,
neighb_indices,
mdf_thr=5,
pruning_thr=10,
pruning_distance='mdf'):
if self.verbose:
if pruning_thr < 0:
logger.info('Pruning_thr has to be greater or equal to 0')
logger.info('# Prune streamlines using the MDF distance')
logger.info(' Pruning threshold %0.3f' % (pruning_thr,))
logger.info(' Pruning distance {}'.format(pruning_distance))
t = time()
thresholds = [40, 30, 20, 10, mdf_thr]
rtransf_cluster_map = qbx_and_merge(transf_streamlines,
thresholds, nb_pts=20,
select_randomly=500000,
rng=self.rng)
if self.verbose:
logger.info(' QB Duration %0.3f sec. \n' % (time() - t, ))
rtransf_centroids = rtransf_cluster_map.centroids
if pruning_distance.lower() == 'mdf':
if self.verbose:
logger.info(' Using MDF')
dist_matrix = bundles_distances_mdf(model_centroids,
rtransf_centroids)
elif pruning_distance.lower() == 'mam':
if self.verbose:
logger.info(' Using MAM')
dist_matrix = bundles_distances_mam(model_centroids,
rtransf_centroids)
else:
raise ValueError('Given pruning distance is not available')
dist_matrix[np.isnan(dist_matrix)] = np.inf
dist_matrix[dist_matrix > pruning_thr] = np.inf
pruning_matrix = dist_matrix.copy()
if self.verbose:
logger.info(' Pruning matrix size is (%d, %d)'
% pruning_matrix.shape)
mins = np.min(pruning_matrix, axis=0)
pruned_indices = [rtransf_cluster_map[i].indices
for i in np.where(mins != np.inf)[0]]
pruned_indices = list(chain(*pruned_indices))
idx = np.array(pruned_indices)
if len(idx) == 0:
if self.verbose:
logger.info(' You have removed all streamlines')
return Streamlines([]), []
pruned_streamlines = transf_streamlines[idx]
initial_indices = list(chain(*neighb_indices))
final_indices = [initial_indices[i] for i in pruned_indices]
labels = final_indices
if self.verbose:
msg = ' Number of centroids: %d'
logger.info(msg % (len(rtransf_centroids),))
msg = ' Number of streamlines after pruning: %d'
logger.info(msg % (len(pruned_streamlines),))
logger.info(' Duration %0.3f sec. \n' % (time() - t, ))
return pruned_streamlines, labels