/
streamlinear.py
1472 lines (1135 loc) · 49.2 KB
/
streamlinear.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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import abc
from itertools import combinations
import numpy as np
from dipy.core.optimize import Optimizer
from dipy.align.bundlemin import (_bundle_minimum_distance,
_bundle_minimum_distance_asymmetric,
distance_matrix_mdf)
from dipy.tracking.streamline import (transform_streamlines,
unlist_streamlines,
center_streamlines,
set_number_of_points,
select_random_set_of_streamlines,
length,
Streamlines)
from dipy.segment.clustering import qbx_and_merge
from dipy.core.geometry import (compose_transformations,
compose_matrix,
decompose_matrix)
from time import time
DEFAULT_BOUNDS = [(-35, 35), (-35, 35), (-35, 35),
(-45, 45), (-45, 45), (-45, 45),
(0.6, 1.4), (0.6, 1.4), (0.6, 1.4),
(-10, 10), (-10, 10), (-10, 10)]
logger = logging.getLogger(__name__)
class StreamlineDistanceMetric(metaclass=abc.ABCMeta):
def __init__(self, num_threads=None):
""" An abstract class for the metric used for streamline registration.
If the two sets of streamlines match exactly then method ``distance``
of this object should be minimum.
Parameters
----------
num_threads : int, optional
Number of threads to be used for OpenMP parallelization. If None
(default) the value of OMP_NUM_THREADS environment variable is used
if it is set, otherwise all available threads are used. If < 0 the
maximal number of threads minus |num_threads + 1| is used (enter -1
to use as many threads as possible). 0 raises an error. Only
metrics using OpenMP will use this variable.
"""
self.static = None
self.moving = None
self.num_threads = num_threads
@abc.abstractmethod
def setup(self, static, moving):
pass
@abc.abstractmethod
def distance(self, xopt):
""" calculate distance for current set of parameters.
"""
pass
class BundleMinDistanceMetric(StreamlineDistanceMetric):
""" Bundle-based Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration.
Methods
-------
setup(static, moving)
distance(xopt)
References
----------
.. [Garyfallidis14] Garyfallidis et al., "Direct native-space fiber
bundle alignment for group comparisons", ISMRM,
2014.
"""
def setup(self, static, moving):
""" Setup static and moving sets of streamlines.
Parameters
----------
static : streamlines
Fixed or reference set of streamlines.
moving : streamlines
Moving streamlines.
Notes
-----
Call this after the object is initiated and before distance.
"""
self._set_static(static)
self._set_moving(moving)
def _set_static(self, static):
static_centered_pts, st_idx = unlist_streamlines(static)
self.static_centered_pts = np.ascontiguousarray(static_centered_pts,
dtype=np.float64)
self.block_size = st_idx[0]
def _set_moving(self, moving):
self.moving_centered_pts, _ = unlist_streamlines(moving)
def distance(self, xopt):
""" Distance calculated from this Metric.
Parameters
----------
xopt : sequence
List of affine parameters as an 1D vector,
"""
return bundle_min_distance_fast(xopt,
self.static_centered_pts,
self.moving_centered_pts,
self.block_size,
self.num_threads)
class BundleMinDistanceMatrixMetric(StreamlineDistanceMetric):
""" Bundle-based Minimum Distance aka BMD
This is the cost function used by the StreamlineLinearRegistration
Methods
-------
setup(static, moving)
distance(xopt)
Notes
-----
The difference with BundleMinDistanceMetric is that this creates
the entire distance matrix and therefore requires more memory.
"""
def setup(self, static, moving):
""" Setup static and moving sets of streamlines.
Parameters
----------
static : streamlines
Fixed or reference set of streamlines.
moving : streamlines
Moving streamlines.
Notes
-----
Call this after the object is initiated and before distance.
Num_threads is not used in this class. Use ``BundleMinDistanceMetric``
for a faster, threaded and less memory hungry metric
"""
self.static = static
self.moving = moving
def distance(self, xopt):
""" Distance calculated from this Metric.
Parameters
----------
xopt : sequence
List of affine parameters as an 1D vector
"""
return bundle_min_distance(xopt, self.static, self.moving)
class BundleMinDistanceAsymmetricMetric(BundleMinDistanceMetric):
""" Asymmetric Bundle-based Minimum distance.
This is a cost function that can be used by the
StreamlineLinearRegistration class.
"""
def distance(self, xopt):
""" Distance calculated from this Metric.
Parameters
----------
xopt : sequence
List of affine parameters as an 1D vector
"""
return bundle_min_distance_asymmetric_fast(xopt,
self.static_centered_pts,
self.moving_centered_pts,
self.block_size)
class BundleSumDistanceMatrixMetric(BundleMinDistanceMatrixMetric):
""" Bundle-based Sum Distance aka BMD
This is a cost function that can be used by the
StreamlineLinearRegistration class.
Methods
-------
setup(static, moving)
distance(xopt)
Notes
-----
The difference with BundleMinDistanceMatrixMetric is that it uses
uses the sum of the distance matrix and not the sum of mins.
"""
def distance(self, xopt):
""" Distance calculated from this Metric
Parameters
----------
xopt : sequence
List of affine parameters as an 1D vector
"""
return bundle_sum_distance(xopt, self.static, self.moving)
class JointBundleMinDistanceMetric(StreamlineDistanceMetric):
""" Bundle-based Minimum Distance for joint optimization.
This cost function is used by the StreamlineLinearRegistration class when
running halfway streamline linear registration for unbiased groupwise
bundle registration and atlasing.
It computes the BMD distance after moving both static and moving bundles to
a halfway space in between both.
Methods
-------
setup(static, moving)
distance(xopt)
Notes
-----
In this metric both static and moving bundles are treated equally (i.e.,
there is no static reference bundle as both are intended to move). The
naming convention is kept for consistency.
"""
def setup(self, static, moving):
""" Setup static and moving sets of streamlines.
Parameters
----------
static : streamlines
Set of streamlines
moving : streamlines
Set of streamlines
Notes
-----
Call this after the object is initiated and before distance.
Num_threads is not used in this class.
"""
self.static = static
self.moving = moving
def distance(self, xopt):
""" Distance calculated from this Metric.
Parameters
----------
xopt : sequence
List of affine parameters as an 1D vector. These affine parameters
are used to derive the corresponding halfway transformation
parameters for each bundle.
"""
# Define halfway space transformations
x_static = np.concatenate((xopt[0:6]/2, (1+xopt[6:9])/2, xopt[9:12]/2))
x_moving = np.concatenate((-xopt[0:6]/2, 2/(1+xopt[6:9]),
-xopt[9:12]/2))
# Move static bundle to the halfway space
aff_static = compose_matrix44(x_static)
static = transform_streamlines(self.static, aff_static)
# Move moving bundle to halfway space and compute distance
return bundle_min_distance(x_moving, static, self.moving)
class StreamlineLinearRegistration:
def __init__(self, metric=None, x0="rigid", method='L-BFGS-B',
bounds=None, verbose=False, options=None, evolution=False,
num_threads=None):
r""" Linear registration of 2 sets of streamlines [Garyfallidis15]_.
Parameters
----------
metric : StreamlineDistanceMetric,
If None and fast is False then the BMD distance is used. If fast
is True then a faster implementation of BMD is used. Otherwise,
use the given distance metric.
x0 : array or int or str
Initial parametrization for the optimization.
If 1D array with:
a) 6 elements then only rigid registration is performed with
the 3 first elements for translation and 3 for rotation.
b) 7 elements also isotropic scaling is performed (similarity).
c) 12 elements then translation, rotation (in degrees),
scaling and shearing is performed (affine).
Here is an example of x0 with 12 elements:
``x0=np.array([0, 10, 0, 40, 0, 0, 2., 1.5, 1, 0.1, -0.5, 0])``
This has translation (0, 10, 0), rotation (40, 0, 0) in
degrees, scaling (2., 1.5, 1) and shearing (0.1, -0.5, 0).
If int:
a) 6
``x0 = np.array([0, 0, 0, 0, 0, 0])``
b) 7
``x0 = np.array([0, 0, 0, 0, 0, 0, 1.])``
c) 12
``x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])``
If str:
a) "rigid"
``x0 = np.array([0, 0, 0, 0, 0, 0])``
b) "similarity"
``x0 = np.array([0, 0, 0, 0, 0, 0, 1.])``
c) "affine"
``x0 = np.array([0, 0, 0, 0, 0, 0, 1., 1., 1, 0, 0, 0])``
method : str,
'L_BFGS_B' or 'Powell' optimizers can be used. Default is
'L_BFGS_B'.
bounds : list of tuples or None,
If method == 'L_BFGS_B' then we can use bounded optimization.
For example for the six parameters of rigid rotation we can set
the bounds = [(-30, 30), (-30, 30), (-30, 30),
(-45, 45), (-45, 45), (-45, 45)]
That means that we have set the bounds for the three translations
and three rotation axes (in degrees).
verbose : bool, optional.
If True, if True then information about the optimization is shown.
Default: False.
options : None or dict,
Extra options to be used with the selected method.
evolution : boolean
If True save the transformation for each iteration of the
optimizer. Default is False. Supported only with Scipy >= 0.11.
num_threads : int, optional
Number of threads to be used for OpenMP parallelization. If None
(default) the value of OMP_NUM_THREADS environment variable is used
if it is set, otherwise all available threads are used. If < 0 the
maximal number of threads minus |num_threads + 1| is used (enter -1
to use as many threads as possible). 0 raises an error. Only
metrics using OpenMP will use this variable.
References
----------
.. [Garyfallidis15] Garyfallidis et al. "Robust and efficient linear
registration of white-matter fascicles in the space of streamlines",
NeuroImage, 117, 124--140, 2015
.. [Garyfallidis14] Garyfallidis et al., "Direct native-space fiber
bundle alignment for group comparisons", ISMRM, 2014.
.. [Garyfallidis17] Garyfallidis et al. Recognition of white matter
bundles using local and global streamline-based
registration and clustering, Neuroimage, 2017.
"""
self.x0 = self._set_x0(x0)
self.metric = metric
if self.metric is None:
self.metric = BundleMinDistanceMetric(num_threads=num_threads)
self.verbose = verbose
self.method = method
if self.method not in ['Powell', 'L-BFGS-B']:
raise ValueError('Only Powell and L-BFGS-B can be used')
self.bounds = bounds
self.options = options
self.evolution = evolution
def optimize(self, static, moving, mat=None):
""" Find the minimum of the provided metric.
Parameters
----------
static : streamlines
Reference or fixed set of streamlines.
moving : streamlines
Moving set of streamlines.
mat : array
Transformation (4, 4) matrix to start the registration. ``mat``
is applied to moving. Default value None which means that initial
transformation will be generated by shifting the centers of moving
and static sets of streamlines to the origin.
Returns
-------
map : StreamlineRegistrationMap
"""
msg = 'need to have the same number of points. Use '
msg += 'set_number_of_points from dipy.tracking.streamline'
if not np.all(np.array(list(map(len, static))) == static[0].shape[0]):
raise ValueError('Static streamlines ' + msg)
if not np.all(np.array(list(map(len, moving))) == moving[0].shape[0]):
raise ValueError('Moving streamlines ' + msg)
if not np.all(np.array(list(map(len, moving))) == static[0].shape[0]):
raise ValueError('Static and moving streamlines ' + msg)
if mat is None:
static_centered, static_shift = center_streamlines(static)
moving_centered, moving_shift = center_streamlines(moving)
static_mat = compose_matrix44([static_shift[0], static_shift[1],
static_shift[2], 0, 0, 0])
moving_mat = compose_matrix44([-moving_shift[0], -moving_shift[1],
-moving_shift[2], 0, 0, 0])
else:
static_centered = static
moving_centered = transform_streamlines(moving, mat)
static_mat = np.eye(4)
moving_mat = mat
self.metric.setup(static_centered, moving_centered)
distance = self.metric.distance
if self.method == 'Powell':
if self.options is None:
self.options = {'xtol': 1e-6, 'ftol': 1e-6, 'maxiter': 1e6}
opt = Optimizer(distance, self.x0.tolist(),
method=self.method, options=self.options,
evolution=self.evolution)
if self.method == 'L-BFGS-B':
if self.options is None:
self.options = {'maxcor': 10, 'ftol': 1e-7,
'gtol': 1e-5, 'eps': 1e-8,
'maxiter': 100}
opt = Optimizer(distance, self.x0.tolist(),
method=self.method,
bounds=self.bounds, options=self.options,
evolution=self.evolution)
if self.verbose:
opt.print_summary()
opt_mat = compose_matrix44(opt.xopt)
mat = compose_transformations(moving_mat, opt_mat, static_mat)
mat_history = []
if opt.evolution is not None:
for vecs in opt.evolution:
mat_history.append(
compose_transformations(moving_mat,
compose_matrix44(vecs),
static_mat))
# If we are running halfway streamline linear registration (for
# groupwise registration or atlasing) the registration map is different
if isinstance(self.metric, JointBundleMinDistanceMetric):
srm = JointStreamlineRegistrationMap(opt.xopt, opt.fopt,
mat_history, opt.nfev,
opt.nit)
else:
srm = StreamlineRegistrationMap(mat, opt.xopt, opt.fopt,
mat_history, opt.nfev, opt.nit)
del opt
return srm
def _set_x0(self, x0):
""" check if input is of correct type."""
if hasattr(x0, 'ndim'):
if len(x0) not in [3, 6, 7, 9, 12]:
m_ = 'Only 1D arrays of 3, 6, 7, 9 and 12 elements are allowed'
raise ValueError(m_)
if x0.ndim != 1:
raise ValueError("Array should have only one dimension")
return x0
if isinstance(x0, str):
if x0.lower() == 'translation':
return np.zeros(3)
if x0.lower() == 'rigid':
return np.zeros(6)
if x0.lower() == 'similarity':
return np.array([0, 0, 0, 0, 0, 0, 1.])
if x0.lower() == 'scaling':
return np.array([0, 0, 0, 0, 0, 0, 1., 1., 1.])
if x0.lower() == 'affine':
return np.array([0, 0, 0, 0, 0, 0, 1., 1., 1., 0, 0, 0])
if isinstance(x0, int):
if x0 not in [3, 6, 7, 9, 12]:
msg = 'Only 3, 6, 7, 9 and 12 are accepted as integers'
raise ValueError(msg)
else:
if x0 == 3:
return np.zeros(3)
if x0 == 6:
return np.zeros(6)
if x0 == 7:
return np.array([0, 0, 0, 0, 0, 0, 1.])
if x0 == 9:
return np.array([0, 0, 0, 0, 0, 0, 1., 1., 1.])
if x0 == 12:
return np.array([0, 0, 0, 0, 0, 0, 1., 1., 1., 0, 0, 0])
raise ValueError('Wrong input')
class StreamlineRegistrationMap:
def __init__(self, matopt, xopt, fopt, matopt_history, funcs, iterations):
r""" A map holding the optimum affine matrix and some other parameters
of the optimization
Parameters
----------
matrix : array,
4x4 affine matrix which transforms the moving to the static
streamlines
xopt : array,
1d array with the parameters of the transformation after centering
fopt : float,
final value of the metric
matrix_history : array
All transformation matrices created during the optimization
funcs : int,
Number of function evaluations of the optimizer
iterations : int
Number of iterations of the optimizer
"""
self.matrix = matopt
self.xopt = xopt
self.fopt = fopt
self.matrix_history = matopt_history
self.funcs = funcs
self.iterations = iterations
def transform(self, moving):
""" Transform moving streamlines to the static.
Parameters
----------
moving : streamlines
Returns
-------
moved : streamlines
Notes
-----
All this does is apply ``self.matrix`` to the input streamlines.
"""
return transform_streamlines(moving, self.matrix)
class JointStreamlineRegistrationMap():
def __init__(self, xopt, fopt, matopt_history, funcs, iterations):
""" A map holding the optimum affine matrices for halfway streamline
linear registration and some other parameters of the optimization.
xopt is optimized by StreamlineLinearRegistration using the
JointBundleMinDistanceMetric. In that case the mat argument of the
optimize method needs to be np.eye(4) to avoid streamline centering.
This constructor derives and stores the transformations to move both
static and moving bundles to the halfway space.
Parameters
----------
xopt : array
1d array with the parameters of the transformation.
fopt : float
Final value of the metric.
matopt_history : array
All transformation matrices created during the optimization.
funcs : int
Number of function evaluations of the optimizer.
iterations : int
Number of iterations of the optimizer.
"""
trans, angles, scale, shear = xopt[:3], xopt[3:6], xopt[6:9], xopt[9:]
self.x1 = np.concatenate((trans/2, angles/2, (1+scale)/2, shear/2))
self.x2 = np.concatenate((-trans/2, -angles/2, 2/(1+scale), -shear/2))
self.matrix1 = compose_matrix44(self.x1)
self.matrix2 = compose_matrix44(self.x2)
self.fopt = fopt
self.matrix_history = matopt_history
self.funcs = funcs
self.iterations = iterations
def transform(self, static, moving):
""" Transform both static and moving bundles to the halfway space.
All this does is apply ``self.matrix1`` and `self.matrix2`` to the
static and moving bundles, respectively.
Parameters
----------
static : streamlines
moving : streamlines
Returns
-------
static : streamlines
moving : streamlines
"""
static = transform_streamlines(static, self.matrix1)
moving = transform_streamlines(moving, self.matrix2)
return static, moving
def bundle_sum_distance(t, static, moving, num_threads=None):
""" MDF distance optimization function (SUM).
We minimize the distance between moving streamlines as they align
with the static streamlines.
Parameters
----------
t : ndarray
t is a vector of affine transformation parameters with
size at least 6.
If the size is 6, t is interpreted as translation + rotation.
If the size is 7, t is interpreted as translation + rotation +
isotropic scaling.
If size is 12, t is interpreted as translation + rotation +
scaling + shearing.
static : list
Static streamlines
moving : list
Moving streamlines. These will be transformed to align with
the static streamlines
num_threads : int, optional
Number of threads. If -1 then all available threads will be used.
Returns
-------
cost: float
"""
aff = compose_matrix44(t)
moving = transform_streamlines(moving, aff)
d01 = distance_matrix_mdf(static, moving)
return np.sum(d01)
def bundle_min_distance(t, static, moving):
""" MDF-based pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align
with the static streamlines.
Parameters
----------
t : ndarray
t is a vector of affine transformation parameters with
size at least 6.
If size is 6, t is interpreted as translation + rotation.
If size is 7, t is interpreted as translation + rotation +
isotropic scaling.
If size is 12, t is interpreted as translation + rotation +
scaling + shearing.
static : list
Static streamlines
moving : list
Moving streamlines.
Returns
-------
cost: float
"""
aff = compose_matrix44(t)
moving = transform_streamlines(moving, aff)
d01 = distance_matrix_mdf(static, moving)
rows, cols = d01.shape
return 0.25 * (np.sum(np.min(d01, axis=0)) / float(cols) +
np.sum(np.min(d01, axis=1)) / float(rows)) ** 2
def bundle_min_distance_fast(t, static, moving, block_size, num_threads=None):
""" MDF-based pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align
with the static streamlines.
Parameters
----------
t : array
1D array. t is a vector of affine transformation parameters with
size at least 6.
If the size is 6, t is interpreted as translation + rotation.
If the size is 7, t is interpreted as translation + rotation +
isotropic scaling.
If size is 12, t is interpreted as translation + rotation +
scaling + shearing.
static : array
N*M x 3 array. All the points of the static streamlines. With order of
streamlines intact. Where N is the number of streamlines and M
is the number of points per streamline.
moving : array
K*M x 3 array. All the points of the moving streamlines. With order of
streamlines intact. Where K is the number of streamlines and M
is the number of points per streamline.
block_size : int
Number of points per streamline. All streamlines in static and moving
should have the same number of points M.
num_threads : int, optional
Number of threads to be used for OpenMP parallelization. If None
(default) the value of OMP_NUM_THREADS environment variable is used
if it is set, otherwise all available threads are used. If < 0 the
maximal number of threads minus |num_threads + 1| is used (enter -1 to
use as many threads as possible). 0 raises an error.
Returns
-------
cost: float
Notes
-----
This is a faster implementation of ``bundle_min_distance``, which requires
that all the points of each streamline are allocated into an ndarray
(of shape N*M by 3, with N the number of points per streamline and M the
number of streamlines). This can be done by calling
`dipy.tracking.streamlines.unlist_streamlines`.
"""
aff = compose_matrix44(t)
moving = np.dot(aff[:3, :3], moving.T).T + aff[:3, 3]
moving = np.ascontiguousarray(moving, dtype=np.float64)
rows = static.shape[0] // block_size
cols = moving.shape[0] // block_size
return _bundle_minimum_distance(static, moving,
rows,
cols,
block_size,
num_threads)
def bundle_min_distance_asymmetric_fast(t, static, moving, block_size):
""" MDF-based pairwise distance optimization function (MIN).
We minimize the distance between moving streamlines as they align
with the static streamlines.
Parameters
----------
t : array
1D array. t is a vector of affine transformation parameters with
size at least 6.
If the size is 6, t is interpreted as translation + rotation.
If the size is 7, t is interpreted as translation + rotation +
isotropic scaling.
If size is 12, t is interpreted as translation + rotation +
scaling + shearing.
static : array
N*M x 3 array. All the points of the static streamlines. With order of
streamlines intact. Where N is the number of streamlines and M
is the number of points per streamline.
moving : array
K*M x 3 array. All the points of the moving streamlines. With order of
streamlines intact. Where K is the number of streamlines and M
is the number of points per streamline.
block_size : int
Number of points per streamline. All streamlines in static and moving
should have the same number of points M.
Returns
-------
cost: float
"""
aff = compose_matrix44(t)
moving = np.dot(aff[:3, :3], moving.T).T + aff[:3, 3]
moving = np.ascontiguousarray(moving, dtype=np.float64)
rows = static.shape[0] // block_size
cols = moving.shape[0] // block_size
return _bundle_minimum_distance_asymmetric(static, moving,
rows,
cols,
block_size)
def remove_clusters_by_size(clusters, min_size=0):
ob = filter(lambda c: len(c) >= min_size, clusters)
centroids = Streamlines()
for cluster in ob:
centroids.append(cluster.centroid)
return centroids
def progressive_slr(static, moving, metric, x0, bounds, method='L-BFGS-B',
verbose=False, num_threads=None):
""" Progressive SLR.
This is an utility function that allows for example to do affine
registration using Streamline-based Linear Registration (SLR)
[Garyfallidis15]_ by starting with translation first, then rigid,
then similarity, scaling and finally affine.
Similarly, if for example, you want to perform rigid then you start with
translation first. This progressive strategy can helps with finding the
optimal parameters of the final transformation.
Parameters
----------
static : Streamlines
moving : Streamlines
metric : StreamlineDistanceMetric
x0 : string
Could be any of 'translation', 'rigid', 'similarity', 'scaling',
'affine'
bounds : array
Boundaries of registration parameters. See variable `DEFAULT_BOUNDS`
for example.
method : string
L_BFGS_B' or 'Powell' optimizers can be used. Default is 'L_BFGS_B'.
verbose : bool, optional.
If True, log messages. Default:
num_threads : int, optional
Number of threads to be used for OpenMP parallelization. If None
(default) the value of OMP_NUM_THREADS environment variable is used
if it is set, otherwise all available threads are used. If < 0 the
maximal number of threads minus |num_threads + 1| is used (enter -1 to
use as many threads as possible). 0 raises an error. Only metrics
using OpenMP will use this variable.
References
----------
.. [Garyfallidis15] Garyfallidis et al. "Robust and efficient linear
registration of white-matter fascicles in the space of streamlines",
NeuroImage, 117, 124--140, 2015
"""
if verbose:
logger.info('Progressive Registration is Enabled')
if x0 in ('translation', 'rigid', 'similarity', 'scaling', 'affine'):
if verbose:
logger.info(' Translation (3 parameters)...')
slr_t = StreamlineLinearRegistration(metric=metric,
x0='translation',
bounds=bounds[:3],
method=method)
slm_t = slr_t.optimize(static, moving)
if x0 in ('rigid', 'similarity', 'scaling', 'affine'):
x_translation = slm_t.xopt
x = np.zeros(6)
x[:3] = x_translation
if verbose:
logger.info(' Rigid (6 parameters) ...')
slr_r = StreamlineLinearRegistration(metric=metric,
x0=x,
bounds=bounds[:6],
method=method)
slm_r = slr_r.optimize(static, moving)
if x0 in ('similarity', 'scaling', 'affine'):
x_rigid = slm_r.xopt
x = np.zeros(7)
x[:6] = x_rigid
x[6] = 1.
if verbose:
logger.info(' Similarity (7 parameters) ...')
slr_s = StreamlineLinearRegistration(metric=metric,
x0=x,
bounds=bounds[:7],
method=method)
slm_s = slr_s.optimize(static, moving)
if x0 in ('scaling', 'affine'):
x_similarity = slm_s.xopt
x = np.zeros(9)
x[:6] = x_similarity[:6]
x[6:] = np.array((x_similarity[6],) * 3)
if verbose:
logger.info(' Scaling (9 parameters) ...')
slr_c = StreamlineLinearRegistration(metric=metric,
x0=x,
bounds=bounds[:9],
method=method)
slm_c = slr_c.optimize(static, moving)
if x0 == 'affine':
x_scaling = slm_c.xopt
x = np.zeros(12)
x[:9] = x_scaling[:9]
x[9:] = np.zeros(3)
if verbose:
logger.info(' Affine (12 parameters) ...')
slr_a = StreamlineLinearRegistration(metric=metric,
x0=x,
bounds=bounds[:12],
method=method)
slm_a = slr_a.optimize(static, moving)
if x0 == 'translation':
slm = slm_t
elif x0 == 'rigid':
slm = slm_r
elif x0 == 'similarity':
slm = slm_s
elif x0 == 'scaling':
slm = slm_c
elif x0 == 'affine':
slm = slm_a
else:
raise ValueError('Incorrect SLR transform')
return slm
def slr_with_qbx(static, moving,
x0='affine',
rm_small_clusters=50,
maxiter=100,
select_random=None,
verbose=False,
greater_than=50,
less_than=250,
qbx_thr=(40, 30, 20, 15),