-
Notifications
You must be signed in to change notification settings - Fork 5
/
util_affine.py
1898 lines (1596 loc) · 78.8 KB
/
util_affine.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.nn.functional as F
import torch, math, time, os
import numpy as np
import pandas as pd
from segmentation.config import Config
from read_csv_results import ModelCSVResults
from itertools import product
from types import SimpleNamespace
import torchio as tio
import SimpleITK as sitk
pi = torch.tensor(3.14159265358979323846)
import numpy.linalg as npl
try:
import quaternion as nq
except :
print('can not import quaternion package, ... not a big deal')
from dual_quaternions import DualQuaternion
import scipy.linalg as scl
def product_dict(**kwargs):
keys = kwargs.keys()
vals = kwargs.values()
#for instance in itertools.product(*vals):
# yield dict(zip(keys, instance))
#return (dict(zip(keys, values)) for values in product(*vals)) #this yield a generator, but easier with a list -> known size
return list(dict(zip(keys, values)) for values in product(*vals))
def apply_motion(sdata, tmot, fp, config_runner=None, df=pd.DataFrame(), extra_info=dict(), param=dict(),
root_out_dir=None, suj_name='NotSet', suj_orig_name=None,
do_coreg='Elastix', return_motion=False, save_fitpars=False,
compute_displacement=False):
if 'displacement_shift_strategy' not in param: param['displacement_shift_strategy']=None
if 'freq_encoding_dim' not in param: param['freq_encoding_dim']=0
''
# apply motion transform
start = time.time()
#tmot.metrics = None
if isinstance(tmot, tio.transforms.augmentation.intensity.RandomMotionFromTimeCourse):
tmot.nT = fp.shape[1]
tmot.simulate_displacement = False; #tmot.oversampling_pct = 1
tmot.displacement_shift_strategy = param['displacement_shift_strategy']
tmot.freq_encoding_dim = param['freq_encoding_dim'] #only use in the constructor to set
tmot.frequency_encoding_dim = param['freq_encoding_dim']
# if tmot.displacement_shift_strategy is None: #let's force demean for the first try to be not too far
# fp = fp - np.mean(fp, axis=1, keepdims=True)
# print('first motion is done with demean')
# #arg, may be not a good idea, for sigma motion
tmot.euler_motion_params = fp
smot = tmot(sdata)
#update fp, since it may have change is displacement_shift_strategy is used
for hh in smot.history:
if isinstance(hh, tio.transforms.augmentation.intensity.random_motion_from_time_course.MotionFromTimeCourse):
fp = hh.euler_motion_params['t1'] #fitpar is modifie in Motion transform not in tmot
print(f'max fp is {fp.max(axis=1)}')
batch_time = time.time() - start; start = time.time()
print(f'First motion in {batch_time} ')
df_before_coreg = pd.DataFrame()
df_before_coreg, report_time = config_runner.record_regression_batch(df_before_coreg, smot, torch.zeros(1).unsqueeze(0),
torch.zeros(1).unsqueeze(0), batch_time, save=False, extra_info=extra_info)
clean_output = param["clean_output"] if "clean_output" in param else 0
if do_coreg is not None:
if root_out_dir is None: raise ('error outut path (root_out_dir) must be se ')
if not os.path.isdir(root_out_dir): os.mkdir(root_out_dir)
if suj_orig_name is None:
orig_vol_name = f'vol_orig_I{param["suj_index"]}_C{param["suj_contrast"]}_N_{int(param["suj_noise"] * 100)}_D{param["suj_deform"]:d}.nii'
else:
orig_vol_name = f'{suj_orig_name}.nii'
# save orig data in the upper dir
# if not os.path.isfile(orig_vol):
# sdata.t1.save(orig_vol)
# bad idea with random contrast, since it can change with seeding ... and then wrong flirt
out_dir = root_out_dir + '/' + suj_name
if not os.path.isdir(out_dir): os.mkdir(out_dir)
os.chdir(out_dir)
orig_vol = f'{out_dir}/{orig_vol_name}'
sdata.t1.save(orig_vol)
out_vol = out_dir + '/vol_motion.nii'
smot.t1.save(out_vol)
out_affine = out_dir + '/coreg_affine.txt'
if do_coreg == 'Elastix':
out_aff, elastix_trf = ElastixRegister(sdata.t1, smot.t1)
trans_rot = get_euler_and_trans_from_matrix(out_aff) # RAS from center (zero) same convention as the input euler to mat
else:
import subprocess
import numpy.linalg as npl
# since (I guess motion do rotation relatif to volume center, shift the affine to have 0,0,0 at volume center)
notuse = False
if notuse: # not necessary for fsl affine, (since independant of nifti header)
aff = sdata.t1.affine
dim = sdata.t1.data[0].shape
aff[:, 3] = [dim[0] // 2, dim[1] // 2, dim[2] // 2, 1] # todo !! works becaus not rotation in nifti affinne
new_affine = npl.inv(aff)
sdata.t1.affine = new_affine
smot.t1.affine = new_affine
# arg when pure rotation I get the same fsl matrix even if I do not change the header origin
if np.allclose(sdata.t1.affine, smot.t1.affine) is False:
print(f'WWWWWWWWWWhat the fuck Afine orig is {sdata.t1.affine} but after motion {smot.t1.affine} ')
qsdf
#out_vol_nifti_reg = out_dir + '/r_vol_motion.nii'
# cmd = f'reg_aladin -rigOnly -ref {orig_vol} -flo {out_vol} -res {out_vol_nifti_reg} -aff {out_affine}'
# cmd = f'flirt -dof 6 -ref {out_vol} -in {orig_vol} -out {out_vol_nifti_reg} -omat {out_affine}'
cmd = f'flirt -dof 6 -ref {out_vol} -in {orig_vol} -omat {out_affine}'
outvalue = subprocess.run(cmd.split(' '))
if not outvalue == 0:
print(" ** Error in " + cmd + " satus is " + str(outvalue))
if clean_output>0:
os.remove(out_vol)
#### reading and transforming FSL flirt Affine to retriev trans and rot set with spm_matrix(order=0) (as used torchio motion)
out_aff = np.loadtxt(out_affine)
affine = smot.t1.affine
# fsl flirt rotation center is first voxel (0,0,0) image corner
shape = sdata.t1.data[0].shape;
pixdim = [1] #
center = np.array(shape) // 2
new_rotation_center = -center # I do not fully understand, it should be +center, but well ...
T = spm_matrix([new_rotation_center[0], new_rotation_center[1], new_rotation_center[2], 0, 0, 0, 1, 1, 1, 0, 0, 0],
order=4);
Ti = npl.inv(T)
out_aff = np.matmul(T, np.matmul(out_aff, Ti))
# convert to trans so that we get the same affine but from convention R*T
rot = out_aff.copy();
rot[:, 3] = [0, 0, 0, 1]
trans2 = out_aff.copy();
trans2[:3, :3] = np.eye(3)
trans1 = np.matmul(npl.inv(rot),
np.matmul(trans2, rot)) # trans1 = np.matmul(rot, np.matmul(trans2, npl.inv(rot)))
out_aff[:, 3] = trans1[:, 3]
if npl.det(affine) > 0: # ie canonical, then flip, (because flirt affine convention is with -x
shape = sdata.t1.data[0].shape;
pixdim = [1] #
x = (shape[0] - 1) * pixdim[0]
flip = np.eye(4);
flip[0, 0] = -1;
flip[0, 3] = 0 # x not sure why not translation shift ... ?
out_aff = np.matmul(flip, out_aff)
# out_aff = np.matmul(out_aff,flip)
trans_rot = spm_imatrix(out_aff)[:6]
np.savetxt(out_dir + '/coreg_affine_MotConv.txt', out_aff)
for i in range(6):
fp[i, :] = fp[i, :] - trans_rot[i]
if isinstance(tmot, tio.transforms.augmentation.intensity.RandomMotionFromTimeCourse):
tmot.euler_motion_params = fp
tmot.displacement_shift_strategy = None
else: #MotionFromTimeCourse
#argument are then in dict ... arg ...
for kkey in tmot.euler_motion_params.keys():
tmot.euler_motion_params[kkey] = fp
if not isinstance(tmot.frequency_encoding_dim ,dict):
print('arggg')
tmot.frequency_encoding_dim = dict(t1=tmot.frequency_encoding_dim)
smot_shift = tmot(sdata)
out_vol = out_dir + '/vol_motion_no_shift.nii'
if clean_output <2:
smot_shift.t1.save(out_vol)
batch_time = time.time() - start
print(f'coreg and second motion in {batch_time} ')
extra_info['flirt_coreg'] = 1
for i in range(6):
extra_info[f'shift_{i}'] = trans_rot[i]
df_after_coreg = pd.DataFrame()
# extra_info["shift_T1"] = trans_rot[0]; extra_info["shift_T2"] = trans_rot[1]; extra_info["shift_T3"] = trans_rot[2]
# extra_info["shift_R1"] = trans_rot[3]; extra_info["shift_R2"] = trans_rot[4]; extra_info["shift_R3"] = trans_rot[5]
df_after_coreg, report_time = config_runner.record_regression_batch(df_after_coreg, smot_shift, torch.zeros(1).unsqueeze(0),
torch.zeros(1).unsqueeze(0),
batch_time, save=False, extra_info=extra_info)
#concatenate metrics dataframe before and after coreg
df_keep1 = df_before_coreg[['transforms_metrics']]
mres = ModelCSVResults(df_data=df_keep1, out_tmp="/tmp/rrr")
keys_unpack = ['transforms_metrics', 'no_shift_t1'];
suffix = ['no_shift', 'no_shift']
df1 = mres.normalize_dict_to_df(keys_unpack, suffix=suffix);
df1.pop('transforms_metrics')
mres = ModelCSVResults(df_data=df_after_coreg, out_tmp="/tmp/rrr")
keys_unpack = ['transforms_metrics', 't1'];
suffix = ['', 'm']
df2 = mres.normalize_dict_to_df(keys_unpack, suffix=suffix);
df2.pop('transforms_metrics')
if compute_displacement:
start = time.time()
image, brain_mask = sdata.t1.data[0].numpy(), sdata.brain.data[0].numpy()
df_disp = get_displacement_field_metric(image, brain_mask, fp)
batch_time = time.time() - start
print(f'Displacement field metrics in {batch_time} ')
dfall = pd.concat([df_disp, df2, df1], sort=True, axis=1);
else:
print('Skiping displacement field computation')
dfall = pd.concat([df2, df1], sort=True, axis=1);
if out_dir is not None:
if not os.path.isdir(out_dir): os.mkdir(out_dir)
saved_filename = f'{out_dir}/metrics_fp_{suj_name}'
dfall.to_pickle(saved_filename + '.gz', protocol=3)
dfall["history"] = saved_filename + '.gz'
dfall.to_csv(saved_filename + ".csv")
if save_fitpars:
np.savetxt(out_dir + '/fitpars_shift.txt',fp)
fp_orig = fp.copy()
for i in range(6):
fp_orig[i, :] = fp_orig[i, :] + trans_rot[i]
np.savetxt(out_dir + '/fitpars_orig.txt',fp_orig)
if return_motion:
return df1, smot_shift
else:
return df1
if return_motion:
return df_before_coreg, smot
else:
return df_before_coreg
test_direct_problem = False
if test_direct_problem:
fp = np.ones_like(fp) * 6;
for iii, r in enumerate(fp):
fp[iii, :] = (6 - iii) * 3
# fp[:3,:]=0
out_dir = '/home/romain.valabregue/tmp/a'
# if nocanonical not necessary if flip matrix
# aff_direct = spm_matrix([fp[0, 0], fp[1, 0], fp[2, 0],fp[3, 0], -fp[4, 0], -fp[5, 0], 1, 1, 1, 0, 0, 0, ], order=0)
# if canonical
aff_direct = spm_matrix([fp[0, 0], fp[1, 0], fp[2, 0], fp[3, 0], fp[4, 0], fp[5, 0], 1, 1, 1, 0, 0, 0, ],
order=0)
nii_img0 = nb.load('/home/romain.valabregue/tmp/a/vol_orig_I0_C1_N_1_D0.nii')
nii_img = nb.load('/home/romain.valabregue/tmp/a/vol_orig_I0_C1_N_1_D0.nii')
out_p = '/home/romain.valabregue/tmp/a/lille_005011AAA_BL0/nii_dir.nii'
nii_aff = nii_img.get_affine()
# change aff_direct to have rotation expres at nifi origin
shape = sdata.t1.data[0].shape;
pixdim = [1];
center = np.array(shape) // 2
origin_vox = np.matmul(npl.inv(nii_aff), np.array([0, 0, 0, 1]))[:3]
voxel_shift = -origin_vox + center
T = spm_matrix([voxel_shift[0], voxel_shift[1], voxel_shift[2], 0, 0, 0, 1, 1, 1, 0, 0, 0], order=4);
Ti = npl.inv(T)
aff_direct = np.matmul(T, np.matmul(aff_direct, Ti))
if npl.det(nii_aff) < 0: # ie nocanonical, then flip, (inverse of fsl)
flip = np.eye(4);
flip[
0, 0] = -1; # #pixdim = [1] # x = (shape[0] - 1) * pixdim[0] flip[0, 3] = 0 # x not sure why not translation shift ... ?
aff_direct = np.matmul(flip, aff_direct)
nii_aff = np.matmul(flip, nii_aff)
# nii_img0.affine[:] = np.matmul(flip, nii_img0.affine)[:]
# # convert to trans so that we get the same affine but from convention R*T needed only if aff_direct is done with order>0
# rot = aff_direct.copy(); rot[:, 3] = [0, 0, 0, 1]
# trans2 = aff_direct.copy(); trans2[:3, :3] = np.eye(3)
# #trans1 = np.matmul(npl.inv(rot),np.matmul(trans2, rot)) # arg here it is the inverse compare to transformaing flirt matrix
# trans1 = np.matmul(rot, np.matmul(trans2, npl.inv(rot)))
# aff_direct[:, 3] = trans1[:, 3]
nii_img.affine[:] = np.matmul(aff_direct, nii_aff)[:]
# nii_img.affine[:] = np.matmul(npl.inv(aff_direct), nii_aff)[:] #nii_img.affine[:] = np.matmul( nii_aff, aff_direct)[:]
out_img = nbp.resample_from_to(nii_img, nii_img0, cval=0)
nb.save(out_img, out_p)
# fslpy
from fsl.transform.affine import decompose, compose
angle = np.deg2rad([fp[3, 0], fp[4, 0], fp[5, 0]])
aff_direct_fsl = compose((1, 1, 1), (fp[0, 0], fp[1, 0], fp[2, 0]), angle)
scale, trans, angles = decompose(aff_direct);
angles = np.rad2deg(angles)
spm_imatrix(aff_direct)[:6]
# argg other convention for angle ... I stop here
# image space motion
ta = tio.Compose([tio.ToCanonical(), tio.Affine(scales=1, degrees=[3, -6, -9], translation=0)])
ta = tio.Affine(scales=1, degrees=[-fp[3, 0], -fp[4, 0], -fp[5, 0]], translation=0)
ta = tio.Affine(scales=1, degrees=[-fp[3, 0], fp[4, 0], fp[5, 0]], translation=0)
smoti = ta(sdata)
smoti.t1.save(out_dir + '/tio_affma3.nii')
# rotation around point 50, 0, 0
rot = spm_matrix([0, 0, 0, 10, 11, 12, 1, 1, 1, 0, 0, 0], order=4)
T = spm_matrix([10, -18, -76, 0, 0, 0, 1, 1, 1, 0, 0, 0], order=4);
Ti = npl.inv(T)
new_affine = np.matmul(T, np.matmul(rot, Ti))
# new_affine.dot([0, 80,0, 1]) is the same point, it is the rotation center
# taking into account that motion is doing R*T (and not T*R), to get the translation :
trans2 = new_affine.copy();
trans2[:3, :3] = np.eye(3)
trans1 = np.matmul(npl.inv(rot), np.matmul(trans2, rot))
new_affine[:, 3] = trans1[:, 3]
fp = np.zeros_like(fp);
fp[0, :] = trans1[0, 3];
fp[1, :] = trans1[1, 3];
fp[2, :] = trans1[2, 3];
fp[3, :] = 10
# find fsl rotation center http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
from sympy import symbols, Eq, solve
rot = out_aff
x, y, z = symbols('x,y,z')
eq1 = Eq((x - rot[0, 0] * x - rot[0, 1] * y - rot[0, 2] * z), rot[0, 3])
eq2 = Eq((y - rot[1, 0] * x - rot[1, 1] * y - rot[1, 2] * z), rot[1, 3])
eq3 = Eq((z - rot[2, 0] * x - rot[2, 1] * y - rot[2, 2] * z), rot[2, 3])
print(solve((eq1, eq2, eq3), (x, y, z)))
# why is there several solutions .... (ie several fix point for the given affine)
# rotation axis
u = np.array([rot[2, 1] - rot[1, 2], rot[0, 2] - rot[2, 0], rot[1, 0] - rot[0, 1]])
def apply_motion_old_with_shift(sin, tmot, fp, df, res_fitpar, res, extra_info, config_runner,
displacement_shift_strategy='None', shifts=range(-15, 15, 1),
correct_disp=True):
start = time.time()
tmot.nT = fp.shape[1]
tmot.simulate_displacement = False
tmot.euler_motion_params = fp
tmot.displacement_shift_strategy = displacement_shift_strategy
sout = tmot(sin)
l1_loss = torch.nn.L1Loss()
# compute and record L1 shift
if correct_disp:
data_ref = sin.t1.data
data = sout.t1.data
dimy = data.shape[2]
l1dist = [];
res_extra_info = extra_info.copy()
for shift in shifts:
if shift < 0:
d1 = data[:, :, dimy + shift:, :]
d2 = torch.cat([d1, data[:, :, :dimy + shift, :]], dim=2)
else:
d1 = data[:, :, 0:shift, :]
d2 = torch.cat([data[:, :, shift:, :], d1], dim=2)
l1dist.append(float(l1_loss(data_ref, d2).numpy()))
res_extra_info['L1'], res_extra_info['vox_disp'] = l1dist[-1], shift
res = res.append(res_extra_info, ignore_index=True, sort=False)
disp = shifts[np.argmin(l1dist)]
extra_info['shift'] = disp
if disp > 0:
print(f' redoo motion disp is {disp}')
fp[1, :] = fp[1, :] - disp
tmot.euler_motion_params = fp
sout = tmot(sin)
batch_time = time.time() - start
df, report_time = config_runner.record_regression_batch(df, sout, torch.zeros(1).unsqueeze(0), torch.zeros(1).unsqueeze(0),
batch_time, save=False, extra_info=extra_info)
# record extra_info in df
#last_line = df.shape[0] - 1
#for k, v in extra_info.items():
# if k not in df:
# df[k] = v
# else:
# df.loc[last_line, k] = v
# record fitpar
res_extra_info = extra_info.copy()
fit_pars = tmot.euler_motion_params # - np.tile(tmot.to_substract[..., np.newaxis],(1,200))
dff = pd.DataFrame(fit_pars.T);
dff.columns = ['x', 'trans_y', 'z', 'r1', 'r2', 'r3'];
dff['nbt'] = range(0, tmot.nT)
for k, v in res_extra_info.items():
dff[k] = v
res_fitpar = res_fitpar.append(dff, sort=False)
return sout, df, res_fitpar, res
def select_data(json_file, param=None, to_canonical=True):
result_dir= os.path.dirname(json_file) +'/rrr' #/data/romain/PVsynth/motion_on_synth_data/test1/rrr/'
config = Config(json_file, result_dir, mode='eval', save_files=False) #since cluster read (and write) the same files, one need save_file false to avoid colusion
config.init()
mr = config.get_runner()
if param is not None:
suj_ind = param['suj_index']
if suj_ind==9999:
suj_ind = np.random.randint(0, len(config.train_subjects) )
if 'suj_seed' in param:
suj_seed = param['suj_seed']
if suj_seed is not None:
np.random.seed(suj_seed)
torch.manual_seed(suj_seed)
else:
suj_seed=-1
contrast = param['suj_contrast']
suj_deform = param['suj_deform']
suj_noise = param['suj_noise']
else:
suj_ind, contrast, suj_deform, suj_noise = 0, 1, False, 0
transfo_list = config.train_transfo_list
if suj_ind<0:
tmot = transfo_list[1]
if suj_ind<-9:
suj_ind = np.random.randint(0, len(config.train_subjects))
ssynth = config.train_subjects[suj_ind]
else:
ssynth = tio.Subject({'t1':tio.Image(path='/network/lustre/iss02/opendata/data/HCP/raw_data/nii/100307/T1w/T1_1mm/T1w_1mm.nii.gz',type=tio.INTENSITY),
'brain':tio.Image(path='/network/lustre/iss02/opendata/data/HCP/raw_data/nii/100307/T1w/T1_1mm/brain_T1w_1mm.nii.gz',type=tio.LabelMap),
'name':'s100307'})
trescale = tio.RescaleIntensity(out_min_max= [0, 1], percentiles=[1, 99])
ssynth = trescale(ssynth)
if to_canonical:
tcano = tio.ToCanonical(p=1)
ssynth = tcano(ssynth)
return ssynth, tmot, mr
s1 = config.train_subjects[suj_ind]
print(f'loading suj {s1.name} with contrast {contrast} deform is {suj_deform} sujseed {suj_seed} suj_noise {suj_noise}')
#same label, random motion
tsynth = transfo_list[0]
if contrast is None:
#first transfo is suposed to be rescale instensity
if isinstance(tsynth, tio.transforms.preprocessing.intensity.rescale.RescaleIntensity):
print(f'WARNING no contrast define and first transfo is {type(tsynth)}')
else:
if contrast==1:
tsynth.mean = [(0.6, 0.6), (0.1, 0.1), (1, 1), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6),
(0.9, 0.9), (0.6, 0.6), (1, 1), (0.2, 0.2), (0.4, 0.4), (0, 0)]
tsynth.mean = [(1, 1), (0.6, 0.6), (0.1, 0.1), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6), (0.6, 0.6),
(0.6, 0.6), (0.6, 0.6),
(0.6, 0.6), (0.2, 0.2), (0.4, 0.4), (0, 0)]
elif contrast ==2:
tsynth.mean = [(0.5, 0.6), (0.1, 0.2), (0.9, 1), (0.5, 0.6), (0.5, 0.6), (0.5, 0.6), (0.5, 0.6), (0.5, 0.6), (0.5, 0.6), (0.5, 0.6),
(0.8, 0.9), (0.5, 0.6), (0.9, 1), (0.2, 0.3), (0.3, 0.4), (0, 0)]
elif contrast ==3:
tsynth.mean = [(0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9),
(0.1, 0.9), (0.1, 0.9), (0.1, 0.9), (0, 0)]
else:
raise(f'error contrast not define {contrast}')
ssynth = tsynth(s1)
if to_canonical:
tcano = tio.ToCanonical(p=1)
ssynth = tcano(ssynth)
tmot = transfo_list[1]
if suj_deform:
taff_ela = transfo_list[2]
ssynth = taff_ela(ssynth)
if suj_noise:
tnoise = tio.RandomNoise(std = (suj_noise,suj_noise), abs_after_noise=True)
ssynth = tnoise(ssynth)
return ssynth, tmot, mr
def perform_motion_step_loop(json_file, params, out_path=None, out_name=None, resolution=512):
mvt_axe_str_list = ['transX', 'transY', 'transZ', 'rotX', 'rotY', 'rotZ','oy1','oy2']
nb_x0s = params[0]['nb_x0s']
nb_sim = len(params) * nb_x0s
print(f'performing loop of {nb_sim} iter 10s per iter is {nb_sim * 10 / 60 / 60} Hours {nb_sim * 10 / 60} mn ')
if out_name is not None:
print(f'save will be made in {out_path} with name {out_name}')
df, extra_info, i = pd.DataFrame(), dict(), 0
for param in params:
pp = SimpleNamespace(**param)
amplitude, sigma, sym, mvt_type, mvt_axe, nb_x0s, x0_min = pp.amplitude, pp.sigma, pp.sym, pp.mvt_type, pp.mvt_axe, pp.nb_x0s, pp.x0_min
xend_steps = pp.xend_steps #if 'xend_steps' in pp else None
ssynth, tmot, config_runner = select_data(json_file, param, to_canonical=True)
mvt_axe_str = ''
for ii in mvt_axe: mvt_axe_str += mvt_axe_str_list[ii]
if sym:
xcenter = resolution // 2 #- sigma // 2; #to have the same
#x0s = np.floor(np.linspace(xcenter - x0_min, xcenter, nb_x0s))
x0s = np.floor(np.linspace(x0_min, xcenter, nb_x0s))
x0s = x0s[x0s>=sigma//2] #remove first point to not reduce sigma
x0s = x0s[x0s<=(xcenter-sigma//2)] #remove last points to not reduce sigma because of sym
else:
xcenter = resolution // 2;
x0s = np.floor(np.linspace(x0_min, xcenter, nb_x0s))
x0s = x0s[x0s>=sigma//2] #remove first point to not reduce sigma
if xend_steps is not None:
#interprete as a list of xend
xend_steps = np.array(xend_steps)
if sym:
xend_steps = xend_steps[xend_steps<=xcenter]
x0s = xend_steps - sigma//2
x0s = x0s[x0s > sigma // 2]
print(f'preparing {len(x0s)} with Sigma {sigma} Sym {sym} and xend : {x0s + sigma//2}')
for x0 in x0s:
start = time.time()
sigma, x0, xend = int(sigma), int(x0), x0 + sigma // 2
# print(f'{amplitude} {sigma} {type(sigma)}')
fp = corrupt_data(x0, sigma=sigma, method=mvt_type, amplitude=amplitude, mvt_axes=mvt_axe,
center='none', return_all6=True, sym=sym, resolution=resolution)
# plt.figure();plt.plot(fp.T)
extra_info = param
extra_info['xend'], extra_info['x0'] = xend, x0
extra_info['mvt_type'] = mvt_type + '_sym' if sym else mvt_type
extra_info['mvt_axe'] = mvt_axe_str #change list of int, to str, easier for csv ...
extra_info['sujname'] = ssynth.name
#get a unique sujname to write resultt
suj_name = f'Suj_{ssynth.name}_I{param["suj_index"]}_C{param["suj_contrast"]}_N_{int(param["suj_noise"] * 100)}_D{param["suj_deform"]:d}_S{param["suj_seed"]}'
if 'displacement_shift_strategy' in param:
if param['displacement_shift_strategy'] is not None:
suj_name += f'Disp_{param["displacement_shift_strategy"]}'
if 'freq_encoding_dim' in param:
suj_name += f'_F{param["freq_encoding_dim"]}'
fp_name = f'fp_x{x0}_sig{sigma}_Amp{amplitude}_M{mvt_type}_A{mvt_axe_str}_sym{int(sym)}'
if xend_steps is not None:
fp_name = f'fp_x{xend}_sig{sigma}_Amp{amplitude}_M{mvt_type}_A{mvt_axe_str}_sym{int(sym)}'
suj_name += fp_name
extra_info['out_dir'] = suj_name
_ = apply_motion(ssynth, tmot, fp, config_runner, extra_info=extra_info, param=param,
root_out_dir=out_path, suj_name=suj_name, do_coreg='Elastix', save_fitpars=True)
i += 1
total_time = time.time() - start
print(f'{i} / {nb_sim} in {total_time} ')
#if out_name is not None:
# if not os.path.isdir(out_path): os.mkdir(out_path)
# if res.shape[0] > 0: # only if correct_disp is True
# res.to_csv(out_path + f'/res_shift{out_name}.csv')
# res_fitpar.to_csv(out_path + f'/res_fitpars{out_name}.csv')
# df1.to_csv(out_path + f'/res_metrics{out_name}.csv')
#return df1
def create_motion_job(params, split_length, fjson, out_path, res_name, type='motion_loop', fp_paths=None,
mem=6000, cpus_per_task=2, walltime='12:00:00', job_pack=1,
jobdir = '/network/lustre/iss01/cenir/analyse/irm/users/romain.valabregue/PVsynth/job/motion_elastix/' ):
nb_param = len(params)
nb_job = int(np.ceil(nb_param / split_length))
from script.create_jobs import create_jobs
if type=='motion_loop':
cmd_init = '\n'.join(['python -c "', "from util_affine import perform_motion_step_loop "])
jobs = []
for nj in range(nb_job):
ind_start = nj * split_length;
ind_end = np.min([(nj + 1) * split_length, nb_param])
print(f'{nj} {ind_start} {ind_end} ')
print(f'param = {params[ind_start:ind_end]}')
cmd = '\n'.join([cmd_init, f'params = {params[ind_start:ind_end]}',
f'out_name = \'{res_name}_split{nj}\'',
f'json_file = \'{fjson}\'',
f'out_path = \'{out_path}\'',
'_ = perform_motion_step_loop(json_file,params, out_path=out_path, out_name=out_name) "'])
jobs.append(cmd)
elif type=='one_motion':
nb_param = len(fp_paths)
nb_job = int(np.ceil(nb_param / split_length))
cmd_init = '\n'.join(['python -c "', "from util_affine import perform_one_motion "])
jobs = []
for nj in range(nb_job):
ind_start = nj * split_length;
ind_end = np.min([(nj + 1) * split_length, nb_param])
cmd = '\n'.join([cmd_init, f'params = {params}',
f'fp_path = {fp_paths[ind_start:ind_end]}',
f'out_path = \'{out_path}\'',
f'json_file = \'{fjson}\'',
'_ = perform_one_motion(fp_path,json_file, root_out_dir=out_path, param=params) "'])
jobs.append(cmd)
elif type=='one_motion_simulated':
cmd_init = '\n'.join(['python -c "', "from util_affine import perform_one_simulated_motion "])
jobs = []
for nj in range(nb_job):
ind_start = nj * split_length;
ind_end = np.min([(nj + 1) * split_length, nb_param])
cmd = '\n'.join([cmd_init, f'params = {params[ind_start:ind_end]}',
f'out_path = \'{out_path}\'',
f'json_file = \'{fjson}\'',
'_ = perform_one_simulated_motion(params,json_file, root_out_dir=out_path) "'])
jobs.append(cmd)
job_params = dict()
job_params[
'output_directory'] = jobdir + f'{res_name}_job'
job_params['jobs'] = jobs
job_params['job_name'] = 'motion'
job_params['cluster_queue'] = 'bigmem,normal'
job_params['cpus_per_task'] = cpus_per_task
job_params['mem'] = mem
job_params['walltime'] = walltime
job_params['job_pack'] = job_pack
create_jobs(job_params)
def get_default_param(param=None):
if param is None:
param = dict()
if not isinstance(param, list):
params = [param]
else:
params = param
for param in params:
if 'suj_contrast' not in param: param['suj_contrast'] = 1
if 'suj_noise' not in param: param['suj_noise'] = 0.01
if 'suj_index' not in param: param['suj_index'] = 0
if 'suj_deform' not in param: param['suj_deform'] = 0
if 'displacement_shift_strategy' not in param: param['displacement_shift_strategy']=None
return params
def perform_one_simulated_motion(params, fjson, root_out_dir=None,do_coreg='Elastix', return_motion=False):
df = pd.DataFrame()
params = get_default_param(params)
for param in params:
# get the data
sdata, tmot, config_runner = select_data(fjson, param, to_canonical=True)
# load mvt fitpars
suj_name0 = f'Suj_{sdata.name}_I{param["suj_index"]}_C{param["suj_contrast"]}_N_{int(param["suj_noise"] * 100)}_D{param["suj_deform"]:d}_S{param["suj_seed"]}'
if 'displacement_shift_strategy' in param:
if param['displacement_shift_strategy'] is not None:
suj_name0 += f'_Disp_{param["displacement_shift_strategy"]}'
for nbmot in range(param['nb_x0s']):
if 'new_suj' in param:
if param['new_suj']:
sdata, tmot, config_runner = select_data(fjson, param, to_canonical=True)
cmd = '\n'.join(['python -c "', "from util_affine import perform_one_simulated_motion ",
f'params = {param}',
f'out_path = \'{root_out_dir}\'',
f'json_file = \'{fjson}\'',
'_ = perform_one_simulated_motion(params,json_file, root_out_dir=out_path) "'
])
tmot.preserve_center_frequency_pct = 0;
tmot.nT = 218
amplitude = param['amplitude']
tmot.maxGlobalDisp, tmot.maxGlobalRot = (amplitude, amplitude), (amplitude, amplitude)
tmot._simulate_random_trajectory()
fp = tmot.euler_motion_params
fp_name = f'_fp_Amp{amplitude}_N{nbmot:02d}'
suj_name = suj_name0 + fp_name
extra_info = dict( suj_name_fp=suj_name, flirt_coreg=1)
extra_info = dict(param, **extra_info)
extra_info['out_dir'] = suj_name
extra_info['job_cmd'] = cmd
one_df = apply_motion(sdata, tmot, fp, config_runner, extra_info=extra_info, param=param,
root_out_dir=root_out_dir, suj_name=suj_name, suj_orig_name = suj_name0,
do_coreg=do_coreg, save_fitpars=True)
if len(df)==0:
df = one_df
else:
df = pd.concat([df, one_df], axis=0, sort=False)
return df
def perform_one_motion(fp_paths, fjson, param=None, root_out_dir=None,do_coreg='Elastix', return_motion=False):
def get_sujname_from_path(ff):
name = [];
dn = os.path.dirname(ff)
for k in range(3):
name.append(os.path.basename(dn))
dn = os.path.dirname(dn)
return '_'.join(reversed(name))
df = pd.DataFrame()
param = get_default_param(param)[0]
if isinstance(fp_paths, str):
fp_paths = [fp_paths]
for fp_path in fp_paths:
# get the data
sdata, tmot, config_runner = select_data(fjson, param, to_canonical=True) #why does it matter ? (check 05 2022 with cati fp
# load mvt fitpars
fp = np.loadtxt(fp_path)
suj_name = get_sujname_from_path(fp_path)
if 'amplitude' in param:
trans_diff = fp.T[:,None,:3] - fp.T[None,:,:3] #numpy broadcating rule !
dd = np.linalg.norm(trans_diff, axis=2)
ddrot = np.linalg.norm(fp.T[:, None, 3:] - fp.T[None, :, 3:], axis=-1)
trans_max = dd.max()
rot_max = ddrot.max()
fp[:3,:] = fp[:3,:] / trans_max * param['amplitude']
fp[3:,:] = fp[3:,:] / rot_max * param['amplitude']
#get a unique sujname to write resultt
suj_name = f'Suj_{suj_name}_I{param["suj_index"]}_A_{param["amplitude"]}_C{param["suj_contrast"]}_N_{int(param["suj_noise"] * 100)}_D{param["suj_deform"]:d}'
if 'displacement_shift_strategy' in param:
if param['displacement_shift_strategy'] is not None:
suj_name += f'Disp_{param["displacement_shift_strategy"]}'
if 'freq_encoding_dim' in param:
suj_name += f'_F{param["freq_encoding_dim"]}'
suj_name = f'{suj_name}_S_{sdata.name}'
extra_info = dict(fp= fp_path)
extra_info = dict(param, **extra_info)
# apply motion transform
if return_motion:
one_df, smot = apply_motion(sdata, tmot, fp, config_runner, extra_info=extra_info, param=param,
root_out_dir=root_out_dir, suj_name=suj_name, do_coreg=do_coreg, return_motion=return_motion)
else:
one_df = apply_motion(sdata, tmot, fp, config_runner, extra_info=extra_info, param=param,
root_out_dir=root_out_dir, suj_name=suj_name, do_coreg=do_coreg)
if len(df)==0:
df = one_df
else:
df = pd.concat([df, one_df], axis=0, sort=False)
if return_motion:
return df, smot
else:
return df
def corrupt_data( x0, sigma= 5, amplitude=20, method='gauss', mvt_axes=[1], center='zero', resolution=200, sym=False,
return_all6=False):
fp = np.zeros((6, resolution))
x = np.arange(0, resolution)
if method=='gauss':
y = np.exp(-(x - x0) ** 2 / float(2 * sigma ** 2))*amplitude
elif method == '2step':
y = np.hstack((np.zeros((1, (x0 - sigma[0]))),
np.linspace(0, amplitude[0], 2 * sigma[0] + 1).reshape(1, -1),
np.ones((1, sigma[1]-1)) * amplitude[0],
np.linspace(amplitude[0], amplitude[1], 2 * sigma[0] + 1).reshape(1, -1),
np.ones((1, sigma[2]-1)) * amplitude[1],
np.linspace(amplitude[1], 0 , 2 * sigma[0] + 1).reshape(1, -1)) )
remain = resolution - y.shape[1]
if remain<0:
y = y[:,:remain]
print(y.shape)
print("warning seconf step is too big taking cutting {}".format(remain))
else:
y = np.hstack([y, np.zeros((1,remain))])
y=y[0]
elif method == 'step':
y = np.hstack((np.zeros((1, (x0 - sigma))),
np.linspace(0, amplitude, 2 * sigma + 1).reshape(1, -1),
np.ones((1, ((resolution - x0) - sigma - 1))) * amplitude))
y = y[0]
elif method == 'Ustep':
y = np.zeros(resolution)
y[x0-(sigma//2):x0+(sigma//2)] = 1
y = y * amplitude
elif method == 'sin':
#fp = np.zeros((6, 182*218))
#x = np.arange(0,182*218)
y = np.sin(x/x0 * 2 * np.pi)
#plt.plot(x,y)
elif method == 'Const':
y = np.ones(resolution) * amplitude
if center=='zero':
y = y -y[resolution//2]
if sym:
fp_center = y.shape[0]//2
y = np.hstack([y[0:fp_center], np.flip(y[0:fp_center])])
if return_all6:
if mvt_axes[0] == 6: #oy1
orig_pos = [0, -80, 0] # np.array([90, 28, 90]) - np.array([90,108, 90])
l = [0, 0, 1]; m = np.cross(orig_pos, l);
theta = np.deg2rad(amplitude); disp = 0;
dq = DualQuaternion.from_screw(l, m, theta, disp)
fp = np.tile(spm_imatrix(dq.homogeneous_matrix(), order=0)[:6, np.newaxis], (1, resolution))
fp[:,y==0] = 0
elif mvt_axes[0] == 7: #oy2
orig_pos = [0, 80, 0] # np.array([90, 28, 90]) - np.array([90,108, 90])
l = [0, 0, 1];
m = np.cross(orig_pos, l);
theta = np.deg2rad(amplitude);
disp = 0;
dq = DualQuaternion.from_screw(l, m, theta, disp)
fp = np.tile(spm_imatrix(dq.homogeneous_matrix(), order=0)[:6, np.newaxis], (1, resolution))
fp[:, y == 0] = 0
else:
for xx in mvt_axes:
fp[xx, :] = y
if len(mvt_axes)>1:
if len(mvt_axes)==3:
max0 = np.max(fp)
fp = np.sqrt(fp**2 /3);
print(f'because of 3 ax reducing amplitude from {max0} to {np.max(fp)} of 0.86' )
else:
print('WARNING pb in amplitude norm')
y=fp
return y
def get_displacement_field_metric(image, brain_mask, fitpar):
#prepare weigths to check size
img_fft = (np.fft.fftshift(np.fft.fftn(np.fft.ifftshift(image)))).astype(np.complex128)
coef_TF = np.sum(abs(img_fft), axis=(0,2)) ;
coef_shaw = np.sqrt( np.sum(abs(img_fft**2), axis=(0,2)) ) ;
if fitpar.shape[1] != coef_TF.shape[0] :
#just interpolate end to end. at image slowest dimention size
fitpar = interpolate_fitpars(fitpar, len_output=coef_TF.shape[0])
print(f'displacement_field: interp fitpar for wcoef new shape {fitpar.shape}')
nbt = fitpar.shape[1]
brain_mask[brain_mask > 0] = 1 # need pure mask
mean_disp_mask = np.zeros(nbt); wimage_disp = np.zeros(nbt) #mean_disp = np.zeros(nbt);
max_disp = np.zeros(nbt); min_disp = np.zeros(nbt)
for i in range(nbt):
P = np.hstack((fitpar[:, i], np.array([1, 1, 1, 0, 0, 0])))
aff = spm_matrix(P, order=0)
disp_norm = get_dist_field(aff, list(image.shape))
# disp_norm_small = get_dist_field(aff, [22,26,22], scale=8)
disp_norm_mask = disp_norm * (brain_mask)
# mean_disp[i] = np.mean(disp_norm) #not usefull since take the all cube
max_disp[i], min_disp[i] = np.max(disp_norm_mask), np.min(disp_norm_mask[brain_mask > 0])
#compute the weighted displacement (weigths beeing the image intensity) but wihtin brain mask !
wimage_disp[i] = np.sum(disp_norm_mask * image) / np.sum(image)
mean_disp_mask[i] = np.sum(disp_norm_mask) / np.sum(brain_mask)
#compute weighted metrics
res = dict(
mean_disp_mask = mean_disp_mask,
max_disp = max_disp,
min_disp = min_disp,
MD_mask_mean = np.mean(mean_disp_mask),
MD_wimg_mean = np.mean(wimage_disp),
MD_mask_wTF = np.sum(mean_disp_mask * coef_TF) / np.sum(coef_TF),
MD_mask_wTF2 = np.sum(mean_disp_mask * coef_TF**2) / np.sum(coef_TF**2),
MD_mask_wSH = np.sum(mean_disp_mask * coef_shaw) / np.sum(coef_shaw),
MD_mask_wSH2 = np.sum(mean_disp_mask * coef_shaw**2) / np.sum(coef_shaw**2),
MD_wimg_wTF = np.sum(wimage_disp * coef_TF) / np.sum(coef_TF),
MD_wimg_wTF2 = np.sum(wimage_disp * coef_TF**2) / np.sum(coef_TF**2),
MD_wimg_wSH = np.sum(wimage_disp * coef_shaw) / np.sum(coef_shaw),
MD_wimg_wSH2 = np.sum(wimage_disp * coef_shaw**2) / np.sum(coef_shaw**2),
)
df = pd.DataFrame();
df = df.append(res, ignore_index=True)
return df
def torch_deg2rad(tensor: torch.Tensor) -> torch.Tensor:
r"""Function that converts angles from degrees to radians.
Args:
tensor (torch.Tensor): Tensor of arbitrary shape.
Returns:
torch.Tensor: tensor with same shape as input.
Examples::
>>> input = 360. * torch.rand(1, 3, 3)
>>> output = kornia.deg2rad(input)
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
type(tensor)))
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
def spm_imatrixOLD(M):
import nibabel as ni
import numpy.linalg as npl
#translation euler angle scaling shears % copy from from spm_imatrix
[rot,[tx,ty,tz]] = ni.affines.to_matvec(M)
# rrr C = np.transpose(npl.cholesky(np.transpose(rot).dot(rot)))
C = np.transpose(npl.cholesky(rot.dot(np.transpose(rot))))
[scalx, scaly, scalz] = np.diag(C)
if npl.det(rot)<0: # Fix for -ve determinants
scalx=-scalx
C = np.dot(npl.inv(np.diag(np.diag(C))),C)
[shearx, sheary, shearz] = [C[0,1], C[0,2], C[1,2]]
P=np.array([0,0,0,0,0,0,scalx, scaly, scalz,shearx, sheary, shearz])
R0=spm_matrix(P)
R0=R0[:3,:3]
#rrr R1 = rot.dot(npl.inv(R0))
R1 = (npl.inv(R0)).dot(rot)
[rz, ry, rx] = ni.eulerangles.mat2euler(R1)
[rz, ry, rx] = [rz*180/np.pi, ry*180/np.pi, rx*180/np.pi] #rad to degree
#rrr I do not know why I have to add - to make it coherent
P = np.array([tx,ty,tz,-rx,-ry,-rz,scalx, scaly, scalz,shearx, sheary, shearz])
return P
def spm_imatrix(M, order=1):
def rang(x):
return np.min([np.max([x,-1]), 1])
import nibabel as ni
import numpy.linalg as npl
if order==0: #change rotation Translation order ie: get same trans as those given by spm_matrix(order=0)
rot = M.copy(); rot[:, 3] = [0, 0, 0, 1]
trans2 = M.copy(); trans2[:3, :3] = np.eye(3)
trans1 = np.matmul(npl.inv(rot), np.matmul(trans2, rot))
M[:,3] = trans1[:,3]
#translation euler angle scaling shears % copy from from spm_imatrix
[rot,[tx,ty,tz]] = ni.affines.to_matvec(M)
C = npl.cholesky(np.transpose(rot).dot(rot)).T
#C = np.transpose(npl.cholesky(rot.dot(np.transpose(rot))))
[scalx, scaly, scalz] = np.diag(C)
if npl.det(rot)<0: # Fix for -ve determinants
scalx=-scalx
C = np.matmul(npl.inv(np.diag(np.diag(C))),C)
[shearx, sheary, shearz] = [C[0,1], C[0,2], C[1,2]]
P=np.array([0,0,0,0,0,0,scalx, scaly, scalz,shearx, sheary, shearz])
R0=spm_matrix(P,order=4)
R0=R0[:3,:3]
#rrr R1 = rot.dot(npl.inv(R0))
R1 = np.matmul(rot, npl.inv(R0)) #(npl.inv(R0)).dot(rot)
ry = np.arcsin(R1[0,2])
if (abs(ry) - np.pi / 2) ** 2 < 1e-9:
rx = 0;
rz = np.arctan2(-rang(R1[1, 0]), rang(-R1[2, 0] / R1[0, 2]));
else:
c = np.cos(ry);
rx = np.arctan2(rang(R1[1, 2] / c), rang(R1[2, 2] / c));
rz = np.arctan2(rang(R1[0, 1] / c), rang(R1[0, 0] / c));
#[rz, ry, rx] = ni.eulerangles.mat2euler(R1)
[rz, ry, rx] = [rz*180/np.pi, ry*180/np.pi, rx*180/np.pi] #rad to degree
#rrr I do not know why I have to add - to make it coherent
#P = np.array([tx,ty,tz,-rx,-ry,-rz,scalx, scaly, scalz,shearx, sheary, shearz])
P = np.array([tx, ty, tz, rx, ry, rz, scalx, scaly, scalz, shearx, sheary, shearz])
return P
def spm_matrix(P, order=1, set_ZXY=False, rotation_center=None):
"""
FORMAT [A] = spm_matrix(P )
P(0) - x translation
P(1) - y translation
P(2) - z translation
P(3) - x rotation around x in degree
P(4) - y rotation around y in degree
P(5) - z rotation around z in degree
P(6) - x scaling
P(7) - y scaling