-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtorch_lddmm.py
3124 lines (2791 loc) · 246 KB
/
torch_lddmm.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 torch
import numpy as np
import scipy.linalg
import time
import sys
import os
import distutils.version
import nibabel as nib
def mygaussian(sigma=1,size=5):
ind = np.linspace(-np.floor(size/2.0),np.floor(size/2.0),size)
X,Y = np.meshgrid(ind,ind,indexing='xy')
out_mat = np.exp(-(X**2 + Y**2) / (2*sigma**2))
out_mat = out_mat / np.sum(out_mat)
return out_mat
def mygaussian_torch_selectcenter(sigma=1,center_x=0,center_y=0,size_x=100,size_y=100):
ind_x = torch.linspace(0,size_x-1,size_x)
ind_y = torch.linspace(0,size_y-1,size_y)
X,Y = torch.meshgrid(ind_x,ind_y)
out_mat = torch.exp(-((X-center_x)**2 + (Y-center_y)**2) / (2*sigma**2))
#out_mat = out_mat / torch.sum(out_mat)
return out_mat
def mygaussian_torch_selectcenter_meshgrid(X,Y,sigma=1,center_x=0,center_y=0):
out_mat = torch.exp(-((X-center_x)**2 + (Y-center_y)**2) / (2*sigma**2))
#out_mat = out_mat / torch.sum(out_mat)
return out_mat
def mygaussian3d(sigma=1,size=5):
ind = np.linspace(-np.floor(size/2.0),np.floor(size/2.0),size)
X,Y,Z = np.meshgrid(ind,ind,ind,indexing='xy')
out_mat = np.exp(-(X**2 + Y**2 + Z**2) / (2*sigma**2))
out_mat = out_mat / np.sum(out_mat)
return out_mat
def mygaussian_3d_torch_selectcenter_meshgrid(X,Y,Z,sigma=1,center_x=0,center_y=0,center_z=0):
out_mat = torch.exp(-((X-center_x)**2 + (Y-center_y)**2 + (Z-center_z)**2) / (2*sigma**2))
#out_mat = out_mat / torch.sum(out_mat)
return out_mat
def grid_sample(*args,**kwargs):
if distutils.version.LooseVersion(torch.__version__) < distutils.version.LooseVersion("1.3.0"):
return torch.nn.functional.grid_sample(*args,**kwargs)
else:
return torch.nn.functional.grid_sample(*args,**kwargs,align_corners=True)
def irfft(mat,dim,onesided=False):
if distutils.version.LooseVersion(torch.__version__) < distutils.version.LooseVersion("1.8.0"):
return torch.irfft(mat,dim,onesided=onesided)
else:
return torch.fft.irfftn(mat,s=mat.shape)
def rfft(mat,dim,onesided=False):
if distutils.version.LooseVersion(torch.__version__) < distutils.version.LooseVersion("1.8.0"):
return torch.rfft(mat,dim,onesided=onesided)
else:
return torch.fft.fftn(mat)
class LDDMM:
def __init__(self,template=None,target=None,costmask=None,outdir='./',gpu_number=0,a=5.0,p=2,niter=100,epsilon=5e-3,epsilonL=1.0e-7,epsilonT=2.0e-5,sigma=2.0,sigmaR=1.0,nt=5,do_lddmm=1,do_affine=0,checkaffinestep=0,optimizer='gd',sg_mask_mode='ones',sg_rand_scale=1.0,sg_sigma=1.0,sg_climbcount=1,sg_holdcount=1,sg_gamma=0.9,adam_alpha=0.1,adam_beta1=0.9,adam_beta2=0.999,adam_epsilon=1e-8,ada_rho=0.95,ada_epsilon=1e-6,rms_rho=0.9,rms_epsilon=1e-8,rms_alpha=0.001,maxclimbcount=3,savebestv=False,minenergychange = 0.000001,minbeta=1e-4,dtype='float',im_norm_ms=0,slice_alignment=0,energy_fraction=0.02,energy_fraction_from=0,cc=0,cc_channels=[],we=0,we_channels=[],sigmaW=1.0,nMstep=5,dx=None,low_memory=0,update_epsilon=0,verbose=1,v_scale=1.0,v_scale_smoothing=0):
self.params = {}
self.params['gpu_number'] = gpu_number
self.params['a'] = float(a)
self.params['p'] = float(p)
self.params['niter'] = niter
self.params['epsilon'] = float(epsilon)
self.params['epsilonL'] = float(epsilonL)
self.params['epsilonT'] = float(epsilonT)
if isinstance(sigma,(int,float)):
self.params['sigma'] = float(sigma)
else:
self.params['sigma'] = [float(x) for x in sigma]
self.params['sigmaR'] = float(sigmaR)
self.params['nt'] = nt
self.params['orig_nt'] = nt
self.params['template'] = template
self.params['target'] = target
self.params['costmask'] = costmask
self.params['outdir'] = outdir
self.params['do_lddmm'] = do_lddmm
self.params['do_affine'] = do_affine
self.params['checkaffinestep'] = checkaffinestep
self.params['optimizer'] = optimizer
self.params['sg_sigma'] = float(sg_sigma)
self.params['sg_mask_mode'] = sg_mask_mode
self.params['sg_rand_scale'] = float(sg_rand_scale)
self.params['sg_climbcount'] = int(sg_climbcount)
self.params['sg_holdcount'] = int(sg_holdcount)
self.params['sg_gamma'] = float(sg_gamma)
self.params['adam_alpha'] = float(adam_alpha)
self.params['adam_beta1'] = float(adam_beta1)
self.params['adam_beta2'] = float(adam_beta2)
self.params['adam_epsilon'] = float(adam_epsilon)
self.params['ada_rho'] = float(ada_rho)
self.params['ada_epsilon'] = float(ada_epsilon)
self.params['rms_rho'] = float(rms_rho)
self.params['rms_epsilon'] = float(rms_epsilon)
self.params['rms_alpha'] = float(rms_alpha)
self.params['maxclimbcount'] = maxclimbcount
self.params['savebestv'] = savebestv
self.params['minbeta'] = minbeta
self.params['minenergychange'] = minenergychange
self.params['im_norm_ms'] = im_norm_ms
self.params['slice_alignment'] = slice_alignment
self.params['energy_fraction'] = energy_fraction
self.params['energy_fraction_from'] = energy_fraction_from
self.params['cc'] = cc
self.params['cc_channels'] = cc_channels
self.params['we'] = we
self.params['we_channels'] = we_channels
self.params['sigmaW'] = sigmaW
self.params['nMstep'] = nMstep
self.params['v_scale'] = float(v_scale)
self.params['v_scale_smoothing'] = int(v_scale_smoothing)
self.params['dx'] = dx
dtype_dict = {}
dtype_dict['float'] = 'torch.FloatTensor'
dtype_dict['double'] = 'torch.DoubleTensor'
self.params['dtype'] = dtype_dict[dtype]
self.params['low_memory'] = low_memory
self.params['update_epsilon'] = float(update_epsilon)
self.params['verbose'] = float(verbose)
optimizer_dict = {}
optimizer_dict['gd'] = 'gradient descent'
optimizer_dict['gdr'] = 'gradient descent with reducing epsilon'
optimizer_dict['gdw'] = 'gradient descent with delayed reducing epsilon'
optimizer_dict['adam'] = 'adaptive moment estimation (UNDER CONSTRUCTION)'
optimizer_dict['adadelta'] = 'adadelta (UNDER CONSTRUCTION)'
optimizer_dict['rmsprop'] = 'root mean square propagation (UNDER CONSTRUCTION)'
optimizer_dict['sgd'] = 'stochastic gradient descent'
optimizer_dict['sgdm'] = 'stochastic gradient descent with momentum (UNDER CONSTRUCTION)'
print('\nCurrent parameters:')
print('> a = ' + str(a) + ' (smoothing kernel, a*(pixel_size))')
print('> p = ' + str(p) + ' (smoothing kernel power, p*2)')
print('> niter = ' + str(niter) + ' (number of iterations)')
print('> epsilon = ' + str(epsilon) + ' (gradient descent step size)')
print('> epsilonL = ' + str(epsilonL) + ' (gradient descent step size, affine)')
print('> epsilonT = ' + str(epsilonT) + ' (gradient descent step size, translation)')
print('> minbeta = ' + str(minbeta) + ' (smallest multiple of epsilon)')
print('> sigma = ' + str(sigma) + ' (matching term coefficient (0.5/sigma**2))')
print('> sigmaR = ' + str(sigmaR)+ ' (regularization term coefficient (0.5/sigmaR**2))')
print('> nt = ' + str(nt) + ' (number of time steps in velocity field)')
print('> do_lddmm = ' + str(do_lddmm) + ' (perform LDDMM step, 0 = no, 1 = yes)')
print('> do_affine = ' + str(do_affine) + ' (interleave linear registration: 0 = no, 1 = affine, 2 = rigid, 3 = rigid + scale)')
print('> checkaffinestep = ' + str(checkaffinestep) + ' (evaluate linear matching energy: 0 = no, 1 = yes)')
print('> im_norm_ms = ' + str(im_norm_ms) + ' (normalize image by mean and std: 0 = no, 1 = yes)')
print('> gpu_number = ' + str(gpu_number) + ' (index of CUDA_VISIBLE_DEVICES to use)')
print('> dtype = ' + str(dtype) + ' (bit depth, \'float\' or \'double\')')
print('> energy_fraction = ' + str(energy_fraction) + ' (fraction of initial energy at which to stop)')
print('> cc = ' + str(cc) + ' (contrast correction: 0 = no, 1 = yes)')
print('> cc_channels = ' + str(cc_channels) + ' (image channels to run contrast correction (0-indexed))')
print('> we = ' + str(we) + ' (weight estimation: 0 = no, 2+ = yes)')
print('> we_channels = ' + str(we_channels) + ' (image channels to run weight estimation (0-indexed))')
print('> sigmaW = ' + str(sigmaW) + ' (coefficient for each weight estimation class)')
print('> nMstep = ' + str(nMstep) + ' (update weight estimation every nMstep steps)')
print('> v_scale = ' + str(v_scale) + ' (parameter scaling factor)')
if v_scale < 1.0:
print('> v_scale_smooth = ' + str(v_scale_smoothing) + ' (smoothing before interpolation for v-scaling: 0 = no, 1 = yes)')
print('> low_memory = ' + str(low_memory) + ' (low memory mode: 0 = no, 1 = yes)')
print('> update_epsilon = ' + str(update_epsilon) + ' (update optimization step size between runs: 0 = no, 1 = yes)')
print('> outdir = ' + str(outdir) + ' (output directory name)')
if optimizer in optimizer_dict:
print('> optimizer = ' + str(optimizer_dict[optimizer]) + ' (optimizer type)')
if optimizer == 'adam':
print('> +adam_alpha = ' + str(adam_alpha) + ' (learning rate)')
print('> +adam_beta1 = ' + str(adam_beta1) + ' (decay rate 1)')
print('> +adam_beta2 = ' + str(adam_beta2) + ' (decay rate 2)')
print('> +adam_epsilon = ' + str(adam_epsilon) + ' (epsilon)')
print('> +sg_sigma = ' + str(sg_sigma) + ' (subsampler sigma (for gaussian mode))')
print('> +sg_mask_mode = ' + str(sg_mask_mode) + ' (subsampler scheme)')
print('> +sg_climbcount = ' + str(sg_climbcount) + ' (# of times energy is allowed to increase)')
print('> +sg_holdcount = ' + str(sg_holdcount) + ' (# of iterations per random mask)')
print('> +sg_rand_scale = ' + str(sg_rand_scale) + ' (scale for non-gauss sg masking)')
elif optimizer == "adadelta":
print('> +ada_rho = ' + str(ada_rho) + ' (decay rate)')
print('> +ada_epsilon = ' + str(ada_epsilon) + ' (epsilon)')
elif optimizer == "rmsprop":
print('> +rms_rho = ' + str(rms_rho) + ' (decay rate)')
print('> +rms_epsilon = ' + str(rms_epsilon) + ' (epsilon)')
print('> +rms_alpha = ' + str(rms_alpha) + ' (learning rate)')
print('> +sg_sigma = ' + str(sg_sigma) + ' (subsampler sigma (for gaussian mode))')
print('> +sg_mask_mode = ' + str(sg_mask_mode) + ' (subsampler scheme)')
print('> +sg_climbcount = ' + str(sg_climbcount) + ' (# of times energy is allowed to increase)')
print('> +sg_holdcount = ' + str(sg_holdcount) + ' (# of iterations per random mask)')
print('> +sg_rand_scale = ' + str(sg_rand_scale) + ' (scale for non-gauss sg masking)')
elif optimizer == 'sgd' or optimizer == 'sgdm':
print('> +sg_sigma = ' + str(sg_sigma) + ' (subsampler sigma (for gaussian mode))')
print('> +sg_mask_mode = ' + str(sg_mask_mode) + ' (subsampler scheme)')
print('> +sg_climbcount = ' + str(sg_climbcount) + ' (# of times energy is allowed to increase)')
print('> +sg_holdcount = ' + str(sg_holdcount) + ' (# of iterations per random mask)')
print('> +sg_rand_scale = ' + str(sg_rand_scale) + ' (scale for non-gauss sg masking)')
if optimizer == 'sgdm':
print('> +sg_gamma = ' + str(sg_gamma) + ' (fraction of paste updates)')
else:
print('WARNING: optimizer \'' + str(optimizer) + '\' not recognized. Setting to basic gradient descent with reducing step size.')
self.params['optimizer'] = 'gdr'
print('\n')
if template is None:
print('WARNING: template file name is not set. Use LDDMM.setParams(\'template\',filename\/array).\n')
elif isinstance(template,np.ndarray):
print('> template = numpy.ndarray\n')
elif isinstance(template,list) and isinstance(template[0],np.ndarray):
myprintstring = '> template = [numpy.ndarray'
for i in range(len(template)-1):
myprintstring = myprintstring + ', numpy.ndarray'
myprintstring = myprintstring + ']\n'
print(myprintstring)
else:
print('> template = ' + str(template) + '\n')
if target is None:
print('WARNING: target file name is not set. Use LDDMM.setParams(\'target\',filename\/array).\n')
elif isinstance(target,np.ndarray):
print('> target = numpy.ndarray\n')
elif isinstance(target,list) and isinstance(target[0],np.ndarray):
myprintstring = '> target = [numpy.ndarray'
for i in range(len(target)-1):
myprintstring = myprintstring + ', numpy.ndarray'
myprintstring = myprintstring + ']\n'
print(myprintstring)
else:
print('> target = ' + str(target) + '\n')
if isinstance(costmask,np.ndarray):
print('> costmask = numpy.ndarray (costmask file name or numpy.ndarray)')
else:
print('> costmask = ' + str(costmask) + ' (costmask file name or numpy.ndarray)')
self.initializer_flags = {}
self.initializer_flags['load'] = 1
self.initializer_flags['v_scale'] = 0
if self.params['do_lddmm'] == 1:
self.initializer_flags['lddmm'] = 1
else:
self.initializer_flags['lddmm'] = 0
if self.params['do_affine'] > 0:
self.initializer_flags['affine'] = 1
else:
self.initializer_flags['affine'] = 0
if self.params['cc'] != 0:
self.initializer_flags['cc'] = 1
else:
self.initializer_flags['cc'] = 0
if self.params['we'] >= 2:
self.initializer_flags['we'] = 1
else:
self.initializer_flags['we'] = 0
# manual edit parameter
def setParams(self,parameter_name,parameter_value):
if parameter_name in self.params:
print('Parameter \'' + str(parameter_name) + '\' changed to \'' + str(parameter_value) + '\'.')
if parameter_name == 'template' or parameter_name == 'target' or parameter_name == 'costmask':
self.initializer_flags['load'] = 1
elif parameter_name == 'do_lddmm' and parameter_value == 1 and self.params['do_lddmm'] == 0:
self.initializer_flags['lddmm'] = 1
print('WARNING: LDDMM state has changed. Variables will be initialized.')
elif parameter_name == 'do_affine' and parameter_value > 0 and self.params['do_affine'] != parameter_value:
self.initializer_flags['affine'] = 1
print('WARNING: Affine state has changed. Variables will be initialized.')
elif (parameter_name == 'cc' and parameter_value != 0 and self.params['cc'] != parameter_value) or (parameter_name == 'cc_channels' and parameter_value != self.params['cc_channels']):
self.initializer_flags['cc'] = 1
print('WARNING: Contrast correction state has changed. Variables will be initialized.')
elif parameter_name == 'we' and parameter_value >= 2 and self.params['we'] != parameter_value or (parameter_name == 'we_channels' and parameter_value != self.params['we_channels']):
self.initializer_flags['we'] = 1
print('WARNING: Weight estimation state has changed. Variables will be initialized.')
elif parameter_name == 'v_scale' and self.params['do_lddmm'] == 1 and hasattr(self,'vt0'):
self.initializer_flags['v_scale'] = 1
print('WARNING: Parameter sparsity has changed. Variables will be initialized.')
self.params[parameter_name] = parameter_value
else:
print('Parameter \'' + str(parameter_name) + '\' is not a valid parameter.')
return
# image loader
def loadImage(self, filename,im_norm_ms=0):
fname, fext = os.path.splitext(filename)
if fext == '.img' or fext == '.hdr':
img_struct = nib.load(fname + '.img')
spacing = img_struct.header['pixdim'][1:4]
size = img_struct.header['dim'][1:4]
image = np.squeeze(img_struct.get_data().astype(np.float32))
if im_norm_ms == 1:
if np.std(image) != 0:
image = torch.tensor((image - np.mean(image)) / np.std(image)).type(self.params['dtype']).to(device=self.params['cuda'])
else:
image = torch.tensor((image - np.mean(image)) ).type(self.params['dtype']).to(device=self.params['cuda'])
print('WARNING: stdev of image is zero, not rescaling.')
else:
image = torch.tensor(image).type(self.params['dtype']).to(device=self.params['cuda'])
return (image, spacing, size)
elif fext == '.nii':
img_struct = nib.load(fname + '.nii')
spacing = img_struct.header['pixdim'][1:4]
size = img_struct.header['dim'][1:4]
image = np.squeeze(img_struct.get_data().astype(np.float32))
if im_norm_ms == 1:
if np.std(image) != 0:
image = torch.tensor((image - np.mean(image)) / np.std(image)).type(self.params['dtype']).to(device=self.params['cuda'])
else:
image = torch.tensor((image - np.mean(image)) ).type(self.params['dtype']).to(device=self.params['cuda'])
print('WARNING: stdev of image is zero, not rescaling.')
else:
image = torch.tensor(image).type(self.params['dtype']).to(device=self.params['cuda'])
return (image, spacing, size)
else:
print('File format not supported.\n')
return (-1,-1,-1)
# helper function to check parameters before running registration
def _checkParameters(self):
flag = 1
if self.params['gpu_number'] is not None and not isinstance(self.params['gpu_number'], (int, float)):
flag = -1
print('ERROR: gpu_number must be None or a number.')
else:
if self.params['gpu_number'] is None:
self.params['cuda'] = 'cpu'
else:
self.params['cuda'] = 'cuda:' + str(self.params['gpu_number'])
number_list = ['a','p','niter','epsilon','sigmaR','nt','do_lddmm','do_affine','epsilonL','epsilonT','im_norm_ms','slice_alignment','energy_fraction','energy_fraction_from','cc','we','nMstep','low_memory','update_epsilon','v_scale','adam_alpha','adam_beta1','adam_beta2','adam_epsilon','ada_rho','ada_epsilon','rms_rho','rms_alpha','rms_epsilon','sg_sigma','sg_climbcount','sg_rand_scale','sg_holdcount','sg_gamma','v_scale_smoothing','verbose']
string_list = ['outdir','optimizer']
stringornone_list = ['costmask'] # or array, actually
stringorlist_list = ['template','target'] # or array, actually
numberorlist_list = ['sigma','cc_channels','we_channels','sigmaW']
noneorarrayorlist_list = ['dx']
for i in range(len(number_list)):
if not isinstance(self.params[number_list[i]], (int, float)):
flag = -1
print('ERROR: ' + number_list[i] + ' must be a number.')
for i in range(len(string_list)):
if not isinstance(self.params[string_list[i]], str):
flag = -1
print('ERROR: ' + string_list[i] + ' must be a string.')
for i in range(len(stringornone_list)):
if not isinstance(self.params[stringornone_list[i]], (str,np.ndarray)) and self.params[stringornone_list[i]] is not None:
flag = -1
print('ERROR: ' + stringornone_list[i] + ' must be a string or None.')
for i in range(len(stringorlist_list)):
if not isinstance(self.params[stringorlist_list[i]], str) and not isinstance(self.params[stringorlist_list[i]], list) and not isinstance(self.params[stringorlist_list[i]], np.ndarray):
flag = -1
print('ERROR: ' + stringorlist_list[i] + ' must be a string or an np.ndarray or a list of these.')
elif isinstance(self.params[stringorlist_list[i]], (str,np.ndarray)):
self.params[stringorlist_list[i]] = [self.params[stringorlist_list[i]]]
for i in range(len(numberorlist_list)):
if not isinstance(self.params[numberorlist_list[i]], (int,float)) and not isinstance(self.params[numberorlist_list[i]], list):
flag = -1
print('ERROR: ' + numberorlist_list[i] + ' must be a number or a list of numbers.')
elif isinstance(self.params[numberorlist_list[i]], (int,float)):
self.params[numberorlist_list[i]] = [self.params[numberorlist_list[i]]]
for i in range(len(noneorarrayorlist_list)):
if self.params[noneorarrayorlist_list[i]] is not None and not isinstance(self.params[noneorarrayorlist_list[i]], list) and not isinstance(self.params[noneorarrayorlist_list[i]], np.ndarray):
flag = -1
print('ERROR: ' + noneorarrayorlist_list[i] + ' must be None or a list or a np.ndarray.')
elif isinstance(self.params[noneorarrayorlist_list[i]], str):
self.params[noneorarrayorlist_list[i]] = [self.params[noneorarrayorlist_list[i]]]
elif isinstance(self.params[noneorarrayorlist_list[i]], np.ndarray):
self.params[noneorarrayorlist_list[i]] = np.ndarray.tolist(self.params[noneorarrayorlist_list[i]])
# check channel length
channel_check_list = ['sigma','template','target']
channels = [len(self.params[x]) for x in channel_check_list]
channel_set = list(set(channels))
if len(channel_set) > 2 or (len(channel_set) == 2 and 1 not in channel_set):
print('ERROR: number of channels is not the same between sigma, template, and target.')
flag = -1
elif len(self.params['template']) != len(self.params['target']):
print('ERROR: number of channels is not the same between template and target.')
flag = -1
elif len(self.params['sigma']) > 1 and len(self.params['sigma']) != len(self.params['template']):
print('ERROR: sigma does not have channels of size 1 or # of template channels.')
flag = -1
elif (len(channel_set) == 2 and 1 in channel_set):
channel_set.remove(1)
for i in range(len(channel_check_list)):
if channels[i] == 1:
self.params[channel_check_list[i]] = self.params[channel_check_list[i]]*channel_set[0]
print('WARNING: one or more of sigma, template, and target has length 1 while another does not.')
# check contrast correction channels
if isinstance(self.params['cc_channels'],(int,float)):
self.params['cc_channels'] = [int(self.params['cc_channels'])]
elif isinstance(self.params['cc_channels'],list):
if len(self.params['cc_channels']) == 0:
self.params['cc_channels'] = list(range(max(channel_set)))
if max(self.params['cc_channels']) > max(channel_set):
print('ERROR: one or more of the contrast correction channels is greater than the number of image channels.')
flag = -1
# check weight estimation channels
if isinstance(self.params['we_channels'],(int,float)):
self.params['we_channels'] = [int(self.params['we_channels'])]
elif isinstance(self.params['we_channels'],list):
if len(self.params['we_channels']) == 0:
self.params['we_channels'] = list(range(max(channel_set)))
if max(self.params['we_channels']) > max(channel_set):
print('ERROR: one or more of the weight estimation channels is greater than the number of image channels.')
flag = -1
# check weight estimation sigmas
if len(self.params['sigmaW']) == 1:
self.params['sigmaW'] = self.params['sigmaW']*int(self.params['we'])
elif len(self.params['sigmaW']) != int(self.params['we']):
print('ERROR: length of weight estimation sigma list must be either 1 or equal to parameter \'we\'.')
flag = -1
# optimizer flags
if self.params['optimizer'] == 'gdw':
self.params['savebestv'] = True
# set timesteps to 1 if doing affine only
if self.params['do_affine'] > 0 and self.params['do_lddmm'] == 0 and not hasattr(self,'vt0'):
if self.params['nt'] != 1:
print('WARNING: nt set to 1 because settings indicate affine registration only.')
self.params['nt'] = 1
elif self.params['do_affine'] == 0 and self.params['do_lddmm'] == 0:
flag = -1
print('ERROR: both linear and LDDMM registration are turned off. Exiting.')
elif self.params['do_lddmm'] == 1:
if self.params['nt'] == 1 and self.params['orig_nt'] == 1:
print('WARNING: parameter \'nt\' is currently set to 1. You might have just finished linear registration. For LDDMM, set to a higher value.')
elif self.params['nt'] == 1 and self.params['orig_nt'] != 1:
self.params['nt'] = self.params['orig_nt']
print('WARNING: parameter \'nt\' was set to 1 and has been automatically reverted to your initial value of ' + str(self.params['orig_nt']) + '.')
return flag
# helper function to load images
def _load(self, template, target, costmask):
if isinstance(template, str):
I = [None]
Ispacing = [None]
Isize = [None]
I[0],Ispacing[0],Isize[0] = self.loadImage(template,im_norm_ms=self.params['im_norm_ms'])
elif isinstance(template, np.ndarray):
I = [None]
Ispacing = [None]
Isize = [None]
if self.params['im_norm_ms'] == 1:
I[0] = torch.tensor((template - np.mean(template)) / np.std(template)).type(self.params['dtype']).to(device=self.params['cuda'])
else:
I[0] = torch.tensor(template).type(self.params['dtype']).to(device=self.params['cuda'])
Isize[0] = list(template.shape)
if self.params['dx'] == None:
Ispacing[0] = np.ones((3,)).astype(np.float32)
else:
Ispacing[0] = self.params['dx']
elif isinstance(template, list):
if isinstance(template[0],str):
I = [None]*len(template)
Ispacing = [None]*len(template)
Isize = [None]*len(template)
for i in range(len(template)):
I[i],Ispacing[i],Isize[i] = self.loadImage(template[i],im_norm_ms=self.params['im_norm_ms'])
# assumes images are the same spacing
elif isinstance(template[0],np.ndarray):
I = [None]*len(template)
Ispacing = [None]*len(template)
Isize = [None]*len(template)
for i in range(len(template)):
if self.params['im_norm_ms'] == 1:
I[i] = torch.tensor((template[i] - np.mean(template[i])) / np.std(template[i])).type(self.params['dtype']).to(device=self.params['cuda'])
else:
I[i] = torch.tensor(template[i]).type(self.params['dtype']).to(device=self.params['cuda'])
Isize[i] = template[i].shape
if self.params['dx'] == None:
Ispacing[i] = np.ones((3,)).astype(np.float32)
else:
Ispacing[i] = self.params['dx']
else:
print('ERROR: received list of unhandled type for template image.')
return -1
if isinstance(target, str):
J = [None]
Jspacing = [None]
Jsize = [None]
J[0],Jspacing[0],Jsize[0] = self.loadImage(target,im_norm_ms=self.params['im_norm_ms'])
elif isinstance(target, np.ndarray):
J = [None]
Jspacing = [None]
Jsize = [None]
if self.params['im_norm_ms'] == 1:
J[0] = torch.tensor((target - np.mean(target)) / np.std(target)).type(self.params['dtype']).to(device=self.params['cuda'])
else:
J[0] = torch.tensor(target).type(self.params['dtype']).to(device=self.params['cuda'])
Jsize[0] = list(target.shape)
if self.params['dx'] == None:
Jspacing[0] = np.ones((3,)).astype(np.float32)
else:
Jspacing[0] = self.params['dx']
elif isinstance(target, list):
if isinstance(target[0],str):
J = [None]*len(target)
Jspacing = [None]*len(target)
Jsize = [None]*len(target)
for i in range(len(target)):
J[i],Jspacing[i],Jsize[i] = self.loadImage(target[i],im_norm_ms=self.params['im_norm_ms'])
# assumes images are the same spacing
elif isinstance(target[0],np.ndarray):
J = [None]*len(target)
Jspacing = [None]*len(target)
Jsize = [None]*len(target)
for i in range(len(target)):
if self.params['im_norm_ms'] == 1:
J[i] = torch.tensor((target[i] - np.mean(target[i])) / np.std(target[i])).type(self.params['dtype']).to(device=self.params['cuda'])
else:
J[i] = torch.tensor(target[i]).type(self.params['dtype']).to(device=self.params['cuda'])
Jsize[i] = target[i].shape
if self.params['dx'] == None:
Jspacing[i] = np.ones((3,)).astype(np.float32)
else:
Jspacing[i] = self.params['dx']
else:
print('ERROR: received list of unhandled type for target image.')
return -1
# load costmask if the variable exists
# TODO: make this multichannel
if isinstance(costmask, str):
K = [None]
Kspacing = [None]
Ksize = [None]
# never normalize cost mask
K[0],Kspacing[0],Ksize[0] = self.loadImage(costmask,im_norm_ms=0)
elif isinstance(costmask,np.ndarray):
K = [None]
Kspacing = [None]
Ksize = [None]
K[0] = torch.tensor(costmask).type(self.params['dtype']).to(device=self.params['cuda'])
Ksize[0] = costmask.shape
if self.params['dx'] == None:
Kspacing[0] = np.ones((3,)).astype(np.float32)
else:
Kspacing[0] = self.params['dx']
else:
K = []
Kspacing = []
Ksize = []
if len(J) != len(I):
print('ERROR: images must have the same number of channels.')
return -1
#if I.shape[0] != J.shape[0] or I.shape[1] != J.shape[1] or I.shape[2] != J.shape[2]:
#if I.shape != J.shape:
if not all([x.shape == I[0].shape for x in I+J+K]):
print('ERROR: the image sizes are not the same.\n')
return -1
#elif Ispacing[0] != Jspacing[0] or Ispacing[1] != Jspacing[1] or Ispacing[2] != Jspacing[2]
#elif np.sum(Ispacing==Jspacing) < len(I.shape):
elif self.params['dx'] is None and not all([list(x == Ispacing[0]) for x in Ispacing+Jspacing+Kspacing]):
print('ERROR: the image pixel spacings are not the same.\n')
return -1
else:
self.I = I
self.J = J
if costmask is not None:
self.M = K[0]
else:
self.M = torch.tensor(np.ones(I[0].shape)).type(self.params['dtype']).to(device=self.params['cuda']) # this could be initialized to a scalar 1.0 to save memory, if you do this make sure you check computeLinearContrastCorrection to see whether or not you are using torch.sum(w*self.M)
self.dx = list(Ispacing[0])
self.dx = [float(x) for x in self.dx]
self.nx = I[0].shape
return 1
# initialize lddmm kernels
def initializeKernels(self):
# make smoothing kernel on CPU
f0 = np.linspace(0,self.nx[0]-1,int(np.round(self.nx[0]*self.params['v_scale'])))/(self.dx[0]*self.nx[0])
f1 = np.linspace(0,self.nx[1]-1,int(np.round(self.nx[1]*self.params['v_scale'])))/(self.dx[1]*self.nx[1])
f2 = np.linspace(0,self.nx[2]-1,int(np.round(self.nx[2]*self.params['v_scale'])))/(self.dx[2]*self.nx[2])
F0,F1,F2 = np.meshgrid(f0,f1,f2,indexing='ij')
#a = 3.0*self.dx[0] # a scale in mm
#p = 2
self.Ahat = (1.0 - 2.0*(self.params['a']*self.dx[0])**2*((np.cos(2.0*np.pi*self.dx[0]*F0) - 1.0)/self.dx[0]**2
+ (np.cos(2.0*np.pi*self.dx[1]*F1) - 1.0)/self.dx[1]**2
+ (np.cos(2.0*np.pi*self.dx[2]*F2) - 1.0)/self.dx[2]**2))**(2.0*self.params['p'])
self.Khat = 1.0/self.Ahat
# only move one kernel for now
# TODO: try broadcasting this instead
if distutils.version.LooseVersion(torch.__version__) < distutils.version.LooseVersion("1.8.0"): # this is because pytorch fft functions have changed in input and output after 1.8. No longer outputs a two-channel matrix
self.Khat = torch.tensor(np.tile(np.reshape(self.Khat,(self.Khat.shape[0],self.Khat.shape[1],self.Khat.shape[2],1)),(1,1,1,2))).type(self.params['dtype']).to(device=self.params['cuda'])
else:
self.Khat = torch.tensor(np.reshape(self.Khat,(self.Khat.shape[0],self.Khat.shape[1],self.Khat.shape[2]))).type(self.params['dtype']).to(device=self.params['cuda'])
# optimization multipliers (putting this in here because I want to reset this if I change the smoothing kernel)
self.GDBeta = torch.tensor(1.0).type(self.params['dtype']).to(device=self.params['cuda'])
#self.GDBetaAffineR = float(1.0)
#self.GDBetaAffineT = float(1.0)
self.climbcount = 0
if self.params['savebestv']:
self.best = {}
# initialize lddmm kernels
def initializeKernels2d(self):
# make smoothing kernel on CPU
f0 = np.arange(self.nx[0])/(self.dx[0]*self.nx[0])
f1 = np.arange(self.nx[1])/(self.dx[1]*self.nx[1])
F0,F1 = np.meshgrid(f0,f1,indexing='ij')
#a = 3.0*self.dx[0] # a scale in mm
#p = 2
self.Ahat = (1.0 - 2.0*(self.params['a']*self.dx[0])**2*((np.cos(2.0*np.pi*self.dx[0]*F0) - 1.0)/self.dx[0]**2
+ (np.cos(2.0*np.pi*self.dx[1]*F1) - 1.0)/self.dx[1]**2))**(2.0*self.params['p'])
self.Khat = 1.0/self.Ahat
# only move one kernel for now
# TODO: try broadcasting this instead
if distutils.version.LooseVersion(torch.__version__) < distutils.version.LooseVersion("1.8.0"): # this is because pytorch fft functions have changed in input and output after 1.8. No longer outputs a two-channel matrix
self.Khat = torch.tensor(np.tile(np.reshape(self.Khat,(self.Khat.shape[0],self.Khat.shape[1],1)),(1,1,2))).type(self.params['dtype']).to(device=self.params['cuda'])
else:
self.Khat = torch.tensor(np.reshape(self.Khat,(self.Khat.shape[0],self.Khat.shape[1]))).type(self.params['dtype']).to(device=self.params['cuda'])
# optimization multipliers (putting this in here because I want to reset this if I change the smoothing kernel)
self.GDBeta = torch.tensor(1.0).type(self.params['dtype']).to(device=self.params['cuda'])
#self.GDBetaAffineR = float(1.0)
#self.GDBetaAffineT = float(1.0)
self.climbcount = 0
if self.params['savebestv']:
self.best = {}
# initialize lddmm variables
def initializeVariables(self):
# TODO: handle 2D and 3D versions
# helper variables
self.dt = 1.0/self.params['nt']
# loss values
if not hasattr(self,'EMAll'):
self.EMAll = []
if not hasattr(self,'ERAll'):
self.ERAll = []
if not hasattr(self,'EAll'):
self.EAll = []
if self.params['checkaffinestep'] == 1:
if not hasattr(self,'EMAffineR'):
self.EMAffineR = []
if not hasattr(self,'EMAffineT'):
self.EMAffineT = []
if not hasattr(self,'EMDiffeo'):
self.EMDiffeo = []
# save X if v_scale changed
#if hasattr(self, 'vt0') and self.initializer_flags['v_scale'] == 1:
# old_X0 = self.X0.clone()
# old_X1 = self.X0.clone()
# old_X2 = self.X0.clone()
# image sampling domain
x0 = np.linspace(0,self.nx[0]-1,int(np.round(self.nx[0]*self.params['v_scale'])))*self.dx[0]
x1 = np.linspace(0,self.nx[1]-1,int(np.round(self.nx[1]*self.params['v_scale'])))*self.dx[1]
x2 = np.linspace(0,self.nx[2]-1,int(np.round(self.nx[2]*self.params['v_scale'])))*self.dx[2]
#x0 = np.arange(self.nx[0])*self.dx[0]
#x1 = np.arange(self.nx[1])*self.dx[1]
#x2 = np.arange(self.nx[2])*self.dx[2]
X0,X1,X2 = np.meshgrid(x0,x1,x2,indexing='ij')
self.X0 = torch.tensor(X0-np.mean(X0)).type(self.params['dtype']).to(device=self.params['cuda'])
self.X1 = torch.tensor(X1-np.mean(X1)).type(self.params['dtype']).to(device=self.params['cuda'])
self.X2 = torch.tensor(X2-np.mean(X2)).type(self.params['dtype']).to(device=self.params['cuda'])
# 2D sampling domain for slice alignment
#if self.params['slice_alignment'] == 1:
# load a gaussian filter if v_scale is less than 1
if self.params['v_scale'] < 1.0:
size = int(np.ceil(1.0/self.params['v_scale']*5))
if np.mod(size,2) == 0:
size += 1
self.gaussian_filter = torch.tensor(mygaussian3d(sigma=1.0/self.params['v_scale'],size=size)).type(self.params['dtype']).to(device=self.params['cuda'])
# v and I
if self.params['gpu_number'] is not None:
if not hasattr(self, 'vt0') and self.initializer_flags['lddmm'] == 1: # we never reset lddmm variables
self.vt0 = []
self.vt1 = []
self.vt2 = []
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.vt1.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.vt2.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
if (self.initializer_flags['load'] == 1 or self.initializer_flags['lddmm'] == 1) and self.params['low_memory'] < 1:
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
# NOTE: you cannot use pointers / list multiplication for cuda tensors if you want actual copies
#self.It.append(torch.tensor(self.I[:,:,:]).type(self.params['dtype']).cuda())
for i in range(self.params['nt']+1):
if i == 0:
self.It[ii][i] = self.I[ii]
else:
if isinstance(self.I[ii],torch.Tensor):
self.It[ii][i] = self.I[ii][:,:,:].clone().type(self.params['dtype']).to(device=self.params['cuda'])
else:
self.It[ii][i] = torch.tensor(self.I[ii][:,:,:]).type(self.params['dtype']).to(device=self.params['cuda'])
else:
if not hasattr(self,'vt0') and self.initializer_flags['lddmm'] == 1:
self.vt0 = []
self.vt1 = []
self.vt2 = []
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']))
self.vt1.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']))
self.vt2.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']))
#self.It = [[None]]*len(self.I)
#for i in range(len(self.I)):
# self.It[i] = [torch.tensor(self.I[i][:,:,:]).type(self.params['dtype'])]*(self.params['nt']+1)
if self.initializer_flags['load'] == 1 or self.initializer_flags['lddmm'] == 1:
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
# NOTE: you cannot use pointers / list multiplication for cuda tensors if you want actual copies
#self.It.append(torch.tensor(self.I[:,:,:]).type(self.params['dtype']).cuda())
#for i in range(self.params['nt']+1):
# self.It[ii][i] = torch.tensor(self.I[ii][:,:,:]).type(self.params['dtype'])
for i in range(self.params['nt']+1):
if i == 0:
self.It[ii][i] = self.I[ii]
else:
if isinstance(self.I[ii],torch.Tensor):
self.It[ii][i] = self.I[ii][:,:,:].clone().type(self.params['dtype'])
else:
self.It[ii][i] = torch.tensor(self.I[ii][:,:,:]).type(self.params['dtype'])
# check if v_scale has changed
if hasattr(self, 'vt0') and self.initializer_flags['v_scale'] == 1:
# resample the current v fields
for i in range(self.params['nt']):
self.vt0[i] = torch.squeeze(grid_sample((self.vt0[i]).unsqueeze(0).unsqueeze(0),torch.stack(((self.X2)/(self.nx[2]*self.dx[2]-self.dx[2])*2,(self.X1)/(self.nx[1]*self.dx[1]-self.dx[1])*2,(self.X0)/(self.nx[0]*self.dx[0]-self.dx[0])*2),dim=3).unsqueeze(0),padding_mode='border'))
self.vt1[i] = torch.squeeze(grid_sample((self.vt1[i]).unsqueeze(0).unsqueeze(0),torch.stack(((self.X2)/(self.nx[2]*self.dx[2]-self.dx[2])*2,(self.X1)/(self.nx[1]*self.dx[1]-self.dx[1])*2,(self.X0)/(self.nx[0]*self.dx[0]-self.dx[0])*2),dim=3).unsqueeze(0),padding_mode='border'))
self.vt2[i] = torch.squeeze(grid_sample((self.vt2[i]).unsqueeze(0).unsqueeze(0),torch.stack(((self.X2)/(self.nx[2]*self.dx[2]-self.dx[2])*2,(self.X1)/(self.nx[1]*self.dx[1]-self.dx[1])*2,(self.X0)/(self.nx[0]*self.dx[0]-self.dx[0])*2),dim=3).unsqueeze(0),padding_mode='border'))
# affine parameters
if not hasattr(self,'affineA') and self.initializer_flags['affine'] == 1: # we never automatically reset affine variables
self.affineA = torch.tensor(np.eye(4)).type(self.params['dtype']).to(device=self.params['cuda'])
self.lastaffineA = torch.tensor(np.eye(4)).type(self.params['dtype']).to(device=self.params['cuda'])
self.gradA = torch.tensor(np.zeros((4,4))).type(self.params['dtype']).to(device=self.params['cuda'])
# contrast correction variables
if not hasattr(self,'ccIbar') or self.initializer_flags['cc'] == 1: # we never reset cc variables
self.ccIbar = []
self.ccJbar = []
self.ccVarI = []
self.ccCovIJ = []
for i in range(len(self.I)):
self.ccIbar.append(0.0)
self.ccJbar.append(0.0)
self.ccVarI.append(1.0)
self.ccCovIJ.append(1.0)
# contrast correction variables
if not hasattr(self,'ccCoeff') or self.initializer_flags['cc'] == 1: # we never reset cc variables
self.ccIbar = []
self.ccJbar = []
self.ccVarI = []
self.ccCovIJ = []
for i in range(len(self.I)):
self.ccIbar.append(0.0)
self.ccJbar.append(0.0)
self.ccVarI.append(1.0)
self.ccCovIJ.append(1.0)
# weight estimation variables
if self.initializer_flags['we'] == 1: # if number of channels changed, reset everything
self.W = [[] for i in range(len(self.I))]
self.we_C = [[] for i in range(len(self.I))]
for i in range(self.params['we']):
if i == 0: # first index is the matching channel, the rest is artifacts
for ii in self.params['we_channels']: # allocate space only for the desired channels
self.W[ii].append(torch.tensor(0.9*np.ones((self.nx[0],self.nx[1],self.nx[2]))).type(self.params['dtype']).to(device=self.params['cuda']))
self.we_C[ii].append(torch.tensor(1.0).type(self.params['dtype']).to(device=self.params['cuda']))
else:
for ii in self.params['we_channels']:
self.W[ii].append(torch.tensor(0.1*np.ones((self.nx[0],self.nx[1],self.nx[2]))).type(self.params['dtype']).to(device=self.params['cuda']))
self.we_C[ii].append(torch.tensor(1.0).type(self.params['dtype']).to(device=self.params['cuda']))
# optimizer update variables
self.GDBeta = torch.tensor(1.0).type(self.params['dtype']).to(device=self.params['cuda'])
self.GDBetaAffineR = float(1.0)
self.GDBetaAffineT = float(1.0)
# adam optimizer variables
if self.params['optimizer'] == "adam":
self.sgd_M = torch.ones(self.M.shape).type(self.params['dtype']).to(device=self.params['cuda'])
self.sgd_maskiter = 0
#self.params['adam_alpha'] = torch.Tensor(self.params['adam_alpha']).type(self.params['dtype']).to(device=self.params['cuda'])
#self.params['adam_beta1'] = torch.Tensor(self.params['adam_beta1']).type(self.params['dtype']).to(device=self.params['cuda'])
#self.params['adam_beta2'] = torch.Tensor(self.params['adam_beta2']).type(self.params['dtype']).to(device=self.params['cuda'])
#self.params['adam_epsilon'] = torch.Tensor(self.params['adam_epsilon']).type(self.params['dtype']).to(device=self.params['cuda'])
self.adam = {}
self.adam['m0'] = []
self.adam['m1'] = []
self.adam['m2'] = []
self.adam['v0'] = []
self.adam['v1'] = []
self.adam['v2'] = []
for i in range(self.params['nt']):
self.adam['m0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adam['m1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adam['m2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adam['v0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adam['v1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adam['v2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
# adadelta optimizer variables
if self.params['optimizer'] == 'adadelta':
self.adadelta = {}
# here we call m0 the accumulator for the gradients and v0 the accumulator for the parameter itself
self.adadelta['m0'] = []
self.adadelta['m1'] = []
self.adadelta['m2'] = []
self.adadelta['v0'] = []
self.adadelta['v1'] = []
self.adadelta['v2'] = []
for i in range(self.params['nt']):
self.adadelta['m0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adadelta['m1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adadelta['m2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adadelta['v0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adadelta['v1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.adadelta['v2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
# rmsprop optimizer variables
if self.params['optimizer'] == 'rmsprop':
self.sgd_M = torch.ones(self.M.shape).type(self.params['dtype']).to(device=self.params['cuda'])
self.sgd_maskiter = 0
self.rmsprop = {}
# here we call m0 the accumulator for the gradients and v0 the accumulator for the parameter itself
self.rmsprop['m0'] = []
self.rmsprop['m1'] = []
self.rmsprop['m2'] = []
for i in range(self.params['nt']):
self.rmsprop['m0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.rmsprop['m1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.rmsprop['m2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
# SGD mask initialization
if self.params['optimizer'] == 'sgd':
self.sgd_M = torch.ones(self.M.shape).type(self.params['dtype']).to(device=self.params['cuda'])
self.sgd_maskiter = 0
# SGDM initialization
if self.params['optimizer'] == 'sgdm':
self.sgd_M = torch.ones(self.M.shape).type(self.params['dtype']).to(device=self.params['cuda'])
# here we call m0 the accumulator for the gradients and v0 the accumulator for the parameter itself
self.sgdm = {}
self.sgdm['m0'] = []
self.sgdm['m1'] = []
self.sgdm['m2'] = []
for i in range(self.params['nt']):
self.sgdm['m0'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.sgdm['m1'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.sgdm['m2'].append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale'])),int(np.round(self.nx[2]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.sgd_maskiter = 0
# reset initializer flags
self.initializer_flags['load'] = 0
self.initializer_flags['lddmm'] = 0
self.initializer_flags['affine'] = 0
self.initializer_flags['cc'] = 0
self.initializer_flags['we'] = 0
self.initializer_flags['v_scale'] = 0
# initialize lddmm variables
def initializeVariables2d(self):
# TODO: handle 2D and 3D versions
# helper variables
self.dt = 1.0/self.params['nt']
# loss values
if not hasattr(self,'EMAll'):
self.EMAll = []
if not hasattr(self,'ERAll'):
self.ERAll = []
if not hasattr(self,'EAll'):
self.EAll = []
if self.params['checkaffinestep'] == 1:
if not hasattr(self,'EMAffineR'):
self.EMAffineR = []
if not hasattr(self,'EMAffineT'):
self.EMAffineT = []
if not hasattr(self,'EMDiffeo'):
self.EMDiffeo = []
# load a gaussian filter if v_scale is less than 1
if self.params['v_scale'] < 1.0:
size = int(np.ceil(1.0/self.params['v_scale']*5))
if np.mod(size,2) == 0:
size += 1
self.gaussian_filter = torch.tensor(mygaussian(sigma=1.0/self.params['v_scale'],size=size)).type(self.params['dtype']).to(device=self.params['cuda'])
# image sampling domain
x0 = np.arange(self.nx[0])*self.dx[0]
x1 = np.arange(self.nx[1])*self.dx[1]
X0,X1 = np.meshgrid(x0,x1,indexing='ij')
self.X0 = torch.tensor(X0-np.mean(X0)).type(self.params['dtype']).to(device=self.params['cuda'])
self.X1 = torch.tensor(X1-np.mean(X1)).type(self.params['dtype']).to(device=self.params['cuda'])
'''
# v and I
if self.params['gpu_number'] is not None:
self.vt0 = []
self.vt1 = []
self.detjac = []
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
for i in range(self.params['nt']+1):
self.It[ii][i] = torch.tensor(self.I[ii][:,:]).type(self.params['dtype']).cuda()
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']).cuda())
self.vt1.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']).cuda())
self.detjac.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']).cuda())
else:
self.vt0 = []
self.vt1 = []
self.detjac = []
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
for i in range(self.params['nt']+1):
self.It[ii][i] = torch.tensor(self.I[ii][:,:]).type(self.params['dtype'])
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']))
self.vt1.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']))
self.detjac.append(torch.tensor(np.zeros((self.nx[0],self.nx[1]))).type(self.params['dtype']))
'''
# v and I
if self.params['gpu_number'] is not None:
if not hasattr(self, 'vt0') and self.initializer_flags['lddmm'] == 1: # we never reset lddmm variables
self.vt0 = []
self.vt1 = []
self.detjac = []
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.vt1.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
self.detjac.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']).to(device=self.params['cuda']))
if (self.initializer_flags['load'] == 1 or self.initializer_flags['lddmm'] == 1) and self.params['low_memory'] < 1:
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
# NOTE: you cannot use pointers / list multiplication for cuda tensors if you want actual copies
#self.It.append(torch.tensor(self.I[:,:,:]).type(self.params['dtype']).cuda())
for i in range(self.params['nt']+1):
if i == 0:
self.It[ii][i] = self.I[ii]
else:
if isinstance(self.I[ii],torch.Tensor):
self.It[ii][i] = self.I[ii][:,:].clone().type(self.params['dtype']).to(device=self.params['cuda'])
else:
self.It[ii][i] = torch.tensor(self.I[ii][:,:]).type(self.params['dtype']).to(device=self.params['cuda'])
else:
if not hasattr(self,'vt0') and self.initializer_flags['lddmm'] == 1:
self.vt0 = []
self.vt1 = []
self.detjac = []
for i in range(self.params['nt']):
self.vt0.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']))
self.vt1.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']))
self.detjac.append(torch.tensor(np.zeros((int(np.round(self.nx[0]*self.params['v_scale'])),int(np.round(self.nx[1]*self.params['v_scale']))))).type(self.params['dtype']))
#self.It = [[None]]*len(self.I)
#for i in range(len(self.I)):
# self.It[i] = [torch.tensor(self.I[i][:,:,:]).type(self.params['dtype'])]*(self.params['nt']+1)
if self.initializer_flags['load'] == 1 or self.initializer_flags['lddmm'] == 1:
self.It = [ [None]*(self.params['nt']+1) for i in range(len(self.I)) ]
for ii in range(len(self.I)):
# NOTE: you cannot use pointers / list multiplication for cuda tensors if you want actual copies
#self.It.append(torch.tensor(self.I[:,:,:]).type(self.params['dtype']).cuda())
for i in range(self.params['nt']+1):
self.It[ii][i] = torch.tensor(self.I[ii][:,:]).type(self.params['dtype'])
# affine parameters
if not hasattr(self,'affineA') and self.initializer_flags['affine'] == 1: # we never automatically reset affine variables
self.affineA = torch.tensor(np.eye(3)).type(self.params['dtype']).to(device=self.params['cuda'])
self.lastaffineA = torch.tensor(np.eye(3)).type(self.params['dtype']).to(device=self.params['cuda'])
self.gradA = torch.tensor(np.zeros((3,3))).type(self.params['dtype']).to(device=self.params['cuda'])