-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
5799 lines (4698 loc) · 189 KB
/
utils.py
File metadata and controls
5799 lines (4698 loc) · 189 KB
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
"""
:Author: Zachary T. Varley
:Year: 2025
:License: MIT License
:Description: monofile of EBSD Logic
"""
"""
Unit normal quaternions (points that sit on the surface of the 3-sphere with
unit radius in 4D Euclidean space) are used to represent 3D rotations. This
module provides a set of operations for working with quaternions in general.
Often times only the angle of the rotation is needed for comparison amongst
quaternions, so separate functions are provided for accelerating this common
operation. The quaternion (w, x, y, z) is used to represent a rotation that is
indistinguishable from the quaternion (-w, x, y, z), so the standardization
function is provided to make the real part non-negative by conjugation, limiting
the hypervolume we work with to the positive w hemisphere of the 3-sphere.
For more information on quaternions, see:
https://en.wikipedia.org/wiki/Quaternion
Adopted from PyTorch3D
https://github.com/facebookresearch/pytorch3d
"""
import math
import torch
from torch import Tensor
import sys
import time
from typing import Optional, Tuple, List, Union
import random
from torch.nn import Linear, Module
from torch.ao.quantization import quantize_dynamic
@torch.jit.script
def qu_std(qu: Tensor) -> Tensor:
"""
Standardize unit quaternion to have non-negative real part.
Args:
qu: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
Standardized quaternions as tensor of shape (..., 4).
"""
return torch.where(qu[..., 0:1] >= 0, qu, -qu)
@torch.jit.script
def qu_norm(qu: Tensor) -> Tensor:
"""
Normalize quaternions to unit norm.
Args:
qu: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
Tensor of normalized quaternions.
"""
return qu / torch.norm(qu, dim=-1, keepdim=True)
@torch.jit.script
def qu_prod_raw(a: Tensor, b: Tensor) -> Tensor:
"""
Multiply two quaternions.
Usual torch rules for broadcasting apply.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
The product of a and b, a tensor of quaternions shape (..., 4).
"""
aw, ax, ay, az = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
bw, bx, by, bz = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
ow = aw * bw - ax * bx - ay * by - az * bz
ox = aw * bx + ax * bw + ay * bz - az * by
oy = aw * by - ax * bz + ay * bw + az * bx
oz = aw * bz + ax * by - ay * bx + az * bw
return torch.stack((ow, ox, oy, oz), -1)
@torch.jit.script
def qu_prod(a: Tensor, b: Tensor) -> Tensor:
"""
Quaternion multiplication, then make real part non-negative.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
a*b Tensor shape (..., 4) of the quaternion product.
"""
ab = qu_prod_raw(a, b)
return qu_std(ab)
@torch.jit.script
def qu_slerp(a: Tensor, b: Tensor, t: float) -> Tensor:
"""
Spherical linear interpolation between two quaternions.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
t: interpolation parameter between 0 and 1
Returns:
The interpolated quaternions, a tensor of shape (..., 4).
"""
a = qu_norm(a)
b = qu_norm(b)
cos_theta = torch.sum(a * b, dim=-1)
angle = torch.acos(cos_theta)
sin_theta = torch.sin(angle)
w1 = torch.sin((1 - t) * angle) / sin_theta
w2 = torch.sin(t * angle) / sin_theta
return (a.unsqueeze(-1) * w1 + b.unsqueeze(-1) * w2).squeeze(-1)
@torch.jit.script
def qu_prod_pos_real(a: Tensor, b: Tensor) -> Tensor:
"""
Return only the magnitude of the real part of the quaternion product.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
a*b Tensor shape (..., ) of quaternion product real part magnitudes.
"""
aw, ax, ay, az = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
bw, bx, by, bz = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
ow = aw * bw - ax * bx - ay * by - az * bz
return ow.abs()
@torch.jit.script
def qu_triple_prod_pos_real(a: Tensor, b: Tensor, c: Tensor) -> Tensor:
"""
Return only the magnitude of the real part of the quaternion triple product.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
c: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
a*b*c Tensor shape (..., ) of quaternion triple product real part magnitudes.
"""
return qu_prod_pos_real(a, qu_prod(b, c))
@torch.jit.script
def qu_prod_axis(a: Tensor, b: Tensor) -> Tensor:
"""
Return the axis of the quaternion product.
Args:
a: shape (..., 4) quaternions in form (w, x, y, z)
b: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
a*b Tensor shape (..., 3) of quaternion product axes.
"""
aw, ax, ay, az = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
bw, bx, by, bz = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
ox = aw * bx + ax * bw + ay * bz - az * by
oy = aw * by - ax * bz + ay * bw + az * bx
oz = aw * bz + ax * by - ay * bx + az * bw
return torch.stack((ox, oy, oz), -1)
@torch.jit.script
def qu_conj(qu: Tensor) -> Tensor:
"""
Get the unit quaternions for the inverse action.
Args:
qu: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
The inverse, a tensor of quaternions of shape (..., 4).
"""
scaling = torch.tensor([1, -1, -1, -1], device=qu.device, dtype=qu.dtype)
return qu * scaling
@torch.jit.script
def qu_apply(qu: Tensor, point: Tensor) -> Tensor:
"""
Rotate 3D points by unit quaternions.
Args:
qu: shape (..., 4) of quaternions in the form (w, x, y, z)
point: shape (..., 3) of 3D points.
Returns:
Tensor of rotated points of shape (..., 3).
"""
aw, ax, ay, az = qu[..., 0], qu[..., 1], qu[..., 2], qu[..., 3]
bx, by, bz = point[..., 0], point[..., 1], point[..., 2]
# need qu_prod_axis(qu_prod_raw(qu, point_as_quaternion), qu_conj(qu))
# do qu_prod_raw(qu, point_as_quaternion) first to get intermediate values
iw = aw - ax * bx - ay * by - az * bz
ix = aw * bx + ax + ay * bz - az * by
iy = aw * by - ax * bz + ay + az * bx
iz = aw * bz + ax * by - ay * bx + az
# next qu_prod_axis(qu_prod_raw(qu, point_as_quaternion), qu_conj(qu))
ox = -iw * ax + ix * aw - iy * az + iz * ay
oy = -iw * ay + ix * az + iy * aw - iz * ax
oz = -iw * az - ix * ay + iy * ax + iz * aw
return torch.stack((ox, oy, oz), -1)
@torch.jit.script
def qu_norm_std(qu: Tensor) -> Tensor:
"""
Normalize a quaternion to unit norm and make real part non-negative.
Args:
qu: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
Tensor of normalized and standardized quaternions.
"""
return qu_std(qu_norm(qu))
@torch.jit.script
def quaternion_rotate_sets_sphere(points_start: Tensor, points_finish) -> Tensor:
"""
Determine the quaternions that rotate the points_start to the points_finish.
All points are assumed to be on the unit sphere. The cross product is used
as the axis of rotation, but there are an infinite number of quaternions that
fulfill the requirement as the points can be rotated around their axis by
an arbitrary angle, and they will still have the same latitude and longitude.
Args:
points_start: Starting points as tensor of shape (..., 3).
points_finish: Ending points as tensor of shape (..., 3).
Returns:
The quaternions, as tensor of shape (..., 4).
"""
# determine mask for numerical stability
valid = torch.abs(torch.sum(points_start * points_finish, dim=-1)) < 0.999999
# get the cross product of the two sets of points
cross = torch.cross(points_start[valid], points_finish[valid], dim=-1)
# get the dot product of the two sets of points
dot = torch.sum(points_start[valid] * points_finish[valid], dim=-1)
# get the angle
angle = torch.atan2(torch.norm(cross, dim=-1), dot)
# add tau to the angle if the cross product is negative
angle[angle < 0] += 2 * torch.pi
# set the output
out = torch.empty(
(points_start.shape[0], 4), dtype=points_start.dtype, device=points_start.device
)
out[valid, 0] = torch.cos(angle / 2)
out[valid, 1:] = torch.sin(angle / 2).unsqueeze(-1) * (
cross / torch.norm(cross, dim=-1, keepdim=True)
)
out[~valid, 0] = 1
out[~valid, 1:] = 0
return out
@torch.jit.script
def qu_angle(qu: Tensor) -> Tensor:
"""
Compute angles of rotation for quaternions.
Args:
qu: shape (..., 4) quaternions in form (w, x, y, z)
Returns:
tensor of shape (..., ) of rotation angles.
"""
return 2 * torch.acos(qu[..., 0])
"""
Routines for orientation representations adopted from PyTorch3D and from EMsoft
https://github.com/facebookresearch/pytorch3d
https://github.com/marcdegraef/3Drotations
Abbreviations used in the code:
cu: cubochoric
ho: homochoric
ax: axis-angle
qu: quaternion
om: orientation matrix
bu: Bunge ZXZ Euler angles
cl: Clifford Torus
ro: Rodrigues-Frank vector
zh: 6D continuous representation of orientation
"""
@torch.jit.script
def qu2ho(qu: Tensor) -> Tensor:
"""
Convert rotations given as quaternions to homochoric coordinates.
Args:
quaternion: Quaternions as tensor of shape (..., 4).
Returns:
Homochoric coordinates as tensor of shape (..., 3).
"""
if qu.size(-1) != 4:
raise ValueError(f"Invalid quaternion shape {qu.shape}.")
ho = torch.empty_like(qu[..., :3])
# get the angle
angle = 2 * torch.acos(qu[..., 0:1].clamp_(min=-1.0, max=1.0))
# get the unit vector
unit = qu[..., 1:] / torch.norm(qu[..., 1:], dim=-1, keepdim=True)
ho = unit * (3.0 * (angle - torch.sin(angle)) / 4.0) ** (1 / 3)
# fix the case where the angle is zero
ho[(angle.squeeze(-1) < 1e-8)] = 0.0
return ho
@torch.jit.script
def om2qu(matrix: Tensor) -> Tensor:
"""
Convert rotations given as rotation matrices to quaternions.
Args:
matrix: Rotation matrices as tensor of shape (..., 3, 3).
Returns:
quaternions with real part first, as tensor of shape (..., 4).
Notes:
Farrell, J.A., 2015. Computation of the Quaternion from a Rotation Matrix.
University of California, 2.
"Converting a Rotation Matrix to a Quaternion" by Mike Day, Insomniac Games
"""
if matrix.size(-1) != 3 or matrix.size(-2) != 3:
raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
batch_dim = matrix.shape[:-2]
m00 = matrix[..., 0, 0]
m11 = matrix[..., 1, 1]
m22 = matrix[..., 2, 2]
m01 = matrix[..., 0, 1]
m02 = matrix[..., 0, 2]
m12 = matrix[..., 1, 2]
m20 = matrix[..., 2, 0]
m21 = matrix[..., 2, 1]
m10 = matrix[..., 1, 0]
mask_A = m22 < 0
mask_B = m00 > m11
mask_C = m00 < -m11
branch_1 = mask_A & mask_B
branch_2 = mask_A & ~mask_B
branch_3 = ~mask_A & mask_C
branch_4 = ~mask_A & ~mask_C
branch_1_t = 1 + m00[branch_1] - m11[branch_1] - m22[branch_1]
branch_1_t_rsqrt = 0.5 * torch.rsqrt(branch_1_t)
branch_2_t = 1 - m00[branch_2] + m11[branch_2] - m22[branch_2]
branch_2_t_rsqrt = 0.5 * torch.rsqrt(branch_2_t)
branch_3_t = 1 - m00[branch_3] - m11[branch_3] + m22[branch_3]
branch_3_t_rsqrt = 0.5 * torch.rsqrt(branch_3_t)
branch_4_t = 1 + m00[branch_4] + m11[branch_4] + m22[branch_4]
branch_4_t_rsqrt = 0.5 * torch.rsqrt(branch_4_t)
qu = torch.empty(batch_dim + (4,), dtype=matrix.dtype, device=matrix.device)
qu[branch_1, 1] = branch_1_t * branch_1_t_rsqrt
qu[branch_1, 2] = (m01[branch_1] + m10[branch_1]) * branch_1_t_rsqrt
qu[branch_1, 3] = (m20[branch_1] + m02[branch_1]) * branch_1_t_rsqrt
qu[branch_1, 0] = (m12[branch_1] - m21[branch_1]) * branch_1_t_rsqrt
qu[branch_2, 1] = (m01[branch_2] + m10[branch_2]) * branch_2_t_rsqrt
qu[branch_2, 2] = branch_2_t * branch_2_t_rsqrt
qu[branch_2, 3] = (m12[branch_2] + m21[branch_2]) * branch_2_t_rsqrt
qu[branch_2, 0] = (m20[branch_2] - m02[branch_2]) * branch_2_t_rsqrt
qu[branch_3, 1] = (m20[branch_3] + m02[branch_3]) * branch_3_t_rsqrt
qu[branch_3, 2] = (m12[branch_3] + m21[branch_3]) * branch_3_t_rsqrt
qu[branch_3, 3] = branch_3_t * branch_3_t_rsqrt
qu[branch_3, 0] = (m01[branch_3] - m10[branch_3]) * branch_3_t_rsqrt
qu[branch_4, 1] = (m12[branch_4] - m21[branch_4]) * branch_4_t_rsqrt
qu[branch_4, 2] = (m20[branch_4] - m02[branch_4]) * branch_4_t_rsqrt
qu[branch_4, 3] = (m01[branch_4] - m10[branch_4]) * branch_4_t_rsqrt
qu[branch_4, 0] = branch_4_t * branch_4_t_rsqrt
# guarantee the correct axis signs
qu[..., 0] = torch.abs(qu[..., 0])
qu[..., 1] = qu[..., 1].copysign((m21 - m12))
qu[..., 2] = qu[..., 2].copysign((m02 - m20))
qu[..., 3] = qu[..., 3].copysign((m10 - m01))
return qu
@torch.jit.script
def om2ax(matrix: Tensor) -> Tensor:
"""
Convert rotations given as rotation matrices to quaternions.
Args:
matrix: Rotation matrices as tensor of shape (..., 3, 3).
Returns:
axis-angle representation as tensor of shape (..., 4).
"""
if matrix.size(-1) != 3 or matrix.size(-2) != 3:
raise ValueError(f"Invalid rotation matrix shape {matrix.shape}.")
batch_dim = matrix.shape[:-2]
# set the output with the same batch dimensions as the input
axis = torch.empty(batch_dim + (4,), dtype=matrix.dtype, device=matrix.device)
# Get the trace of the matrix
trace = matrix[..., 0, 0] + matrix[..., 1, 1] + matrix[..., 2, 2]
# find the angles
acos_arg = 0.5 * (trace - 1.0)
acos_arg = torch.clamp(acos_arg, -1.0, 1.0)
theta = torch.acos(acos_arg)
# where the angle is small, treat theta/sin(theta) as 1
stable = theta > 0.001
axis[..., 0] = matrix[..., 2, 1] - matrix[..., 1, 2]
axis[..., 1] = matrix[..., 0, 2] - matrix[..., 2, 0]
axis[..., 2] = matrix[..., 1, 0] - matrix[..., 0, 1]
factor = torch.where(stable, 0.5 / torch.sin(theta), 0.5)
axis[..., :3] = factor[:, None] * axis[:, :3]
# normalize the axis
axis[..., :3] /= torch.norm(axis[:, :3], dim=-1, keepdim=True)
# set the angle
axis[..., 3] = theta
return axis.view(batch_dim + (4,))
@torch.jit.script
def ax2om(axis_angle: Tensor) -> Tensor:
"""
Convert axis-angle representation to rotation matrices.
Args:
axis_angle: Axis-angle representation as tensor of shape (..., 4).
Returns:
Rotation matrices as tensor of shape (..., 3, 3).
"""
if axis_angle.size(-1) != 4:
raise ValueError(f"Invalid axis-angle shape {axis_angle.shape}.")
batch_dim = axis_angle.shape[:-1]
data_n = int(torch.prod(torch.tensor(batch_dim)))
# set the output
matrices = torch.empty(
batch_dim + (3, 3), dtype=axis_angle.dtype, device=axis_angle.device
)
theta = axis_angle[..., 3:4]
omega = axis_angle[..., :3] * theta
matrices = torch.zeros((data_n, 3, 3), dtype=omega.dtype, device=omega.device)
matrices[..., 0, 1] = -omega[..., 2]
matrices[..., 0, 2] = omega[..., 1]
matrices[..., 1, 2] = -omega[..., 0]
matrices[..., 1, 0] = omega[..., 2]
matrices[..., 2, 0] = -omega[..., 1]
matrices[..., 2, 1] = omega[..., 0]
skew_sq = torch.matmul(matrices, matrices)
# Taylor expansion for small angles of each factor
stable = (theta > 0.05).squeeze()
theta_unstable = theta[~stable].unsqueeze(-1)
# This prefactor is only used for the calculation of exp(skew)
# sin(theta) / theta
# expression: 1 - theta^2 / 6 + theta^4 / 120 - theta^6 / 5040 ...
prefactor1 = 1 - theta_unstable**2 / 6
# This prefactor is shared between calculations of exp(skew) and v
# (1 - cos(theta)) / theta^2
# expression: 1/2 - theta^2 / 24 + theta^4 / 720 - theta^6 / 40320 ...
prefactor2 = 1 / 2 - theta_unstable**2 / 24
theta_stable = theta[stable].unsqueeze(-1)
matrices[stable] = (
torch.eye(3, dtype=matrices.dtype, device=matrices.device)
+ (torch.sin(theta_stable) / theta_stable) * matrices[stable]
+ (1 - torch.cos(theta_stable)) / theta_stable**2 * skew_sq[stable]
)
matrices[~stable] = (
torch.eye(3, dtype=matrices.dtype, device=matrices.device)
+ prefactor1 * matrices[~stable]
+ prefactor2 * skew_sq[~stable]
)
return matrices.view(batch_dim + (3, 3))
@torch.jit.script
def cu2ho(cu: torch.Tensor) -> torch.Tensor:
"""
Converts cubochoric vector representation to homochoric vector representation.
Args:
cu: Cubochoric vectors as tensor of shape (..., 3).
Returns:
Homochoric vectors as tensor of shape (..., 3).
"""
# Sort components
indices = torch.argsort(torch.abs(cu), dim=-1, descending=False)
sorted = torch.gather(cu, -1, indices)
s, m, b = sorted.unbind(dim=-1)
# Calculate trigonometric argument and avoid indeterminate forms
trig_arg_xy = s * torch.pi / (12.0 * m)
trig_arg_xy[torch.isnan(trig_arg_xy)] = 0
factor_xy = (
2 ** (1 / 12)
* 3 ** (1 / 3)
* m
* torch.sqrt(
(
4 * b**2 * (torch.cos(trig_arg_xy) - (2**0.5))
+ (2**0.5) * m**2 * (-2 * (2**0.5) * torch.cos(trig_arg_xy) + 3)
)
/ (torch.cos(trig_arg_xy) - (2**0.5))
)
/ (torch.pi ** (1 / 3) * b * torch.sqrt(-torch.cos(trig_arg_xy) + (2**0.5)))
)
# Compute x_s3, y_s3, and z_s3 using the provided equations
x_s3 = factor_xy * torch.sin(trig_arg_xy)
y_s3 = factor_xy * 2**-0.5 * ((2**0.5) * torch.cos(trig_arg_xy) - 1)
z_s3 = (
2 * 6 ** (1 / 3) * b**2 * (torch.cos(trig_arg_xy) - (2**0.5))
+ 2 ** (5 / 6)
* 3 ** (1 / 3)
* m**2
* (-2 * (2**0.5) * torch.cos(trig_arg_xy) + 3)
) / (2 * torch.pi ** (1 / 3) * b * (torch.cos(trig_arg_xy) - (2**0.5)))
# Reassemble the vector and undo the argsort
ho = torch.stack((x_s3, y_s3, z_s3), dim=-1)
ho = torch.scatter(ho, -1, indices, ho)
# replace any nans with 0
ho[torch.isnan(ho)] = 0
# copy the sign of the original cubochoric vector
ho.copysign_(cu)
return ho
@torch.jit.script
def ho2cu(ho: Tensor) -> Tensor:
"""
Converts homochoric vector representation to cubochoric vector representation.
Args:
homochoric_vectors: Homochoric vectors as tensor of shape (..., 3).
Returns:
Cubochoric vectors as tensor of shape (..., 3).
"""
# inverse steps in reverse order of cu2ho
# start with an argsort on the magnitudes
indices = torch.argsort(torch.abs(ho), dim=-1, descending=False)
sorted = torch.gather(ho, -1, indices)
x_s3, y_s3, z_s3 = torch.abs(sorted).unbind(dim=-1)
# step 3 inverse
r_s = torch.norm(ho, dim=-1, keepdim=False)
prefactor_xy_s3 = torch.sqrt(2 * r_s / (r_s + z_s3))
x_s2 = x_s3 * prefactor_xy_s3
y_s2 = y_s3 * prefactor_xy_s3
z_s2 = (torch.pi / 6) ** 0.5 * r_s
# # step 2 inverse from Appendix A eq (29)
# prefactor_xy_s2 = (torch.pi / 6)**0.5 * torch.sqrt((x_s2**2 + 2 * y_s2**2) * (x_s2**2 + y_s2**2)) / (
# (2 ** 0.5) * torch.sqrt(x_s2**2 + 2 * y_s2**2 - (torch.abs(y_s2) * torch.sqrt(x_s2**2 + 2 * y_s2**2)))
# )
# the above equation in the publication can be dramatically simplified if you assume x and y are positive:
# ((x^2 + 2 * y^2) * (x^2 + y^2)) / (x^2 + 2 * y^2 - |y| * sqrt(x^2 + 2*y^2)) is
# the same as:
# x^2 + y*(sqrt(x^2 + 2*y^2) + 2*y)
# for x and y positive
# these are the inverse squircle functions
# this also avoids an annoying 0/0 case that slows down the calculation
prefactor_xy_s2 = (
(torch.pi / 6) ** 0.5
* torch.sqrt(x_s2**2 + y_s2 * (torch.sqrt(x_s2**2 + 2 * y_s2**2) + 2 * y_s2))
/ (2**0.5)
)
# z_s1 is unchanged from z_s2 while x_s1 and y_s1 are found from inverse squircle function
x_s1 = (prefactor_xy_s2 * 12.0 * torch.sign(x_s2) / torch.pi) * (
torch.arccos(
(
(x_s2**2 + y_s2 * torch.sqrt(x_s2**2 + 2 * y_s2**2))
/ ((2**0.5) * (x_s2**2 + y_s2**2))
).clamp_(-1.0, 1.0)
)
)
y_s1 = prefactor_xy_s2 * torch.sign(y_s2)
# undo the argsort with an in-place scatter
cu = torch.empty_like(ho)
cu.scatter_(-1, indices, torch.stack((x_s1, y_s1, z_s2), dim=-1))
cu /= (torch.pi / 6) ** (1 / 6)
# copy the sign of the original homochoric vector
cu.copysign_(ho)
# replace any nans with 0
cu[torch.isnan(cu)] = 0
return cu
@torch.jit.script
def ho2ax(ho: Tensor, fast: bool = True) -> Tensor:
"""
Converts a set of homochoric vectors to axis-angle representation.
Args:
ho (Tensor): shape (..., 3) homochoric coordinates (x, y, z)
fast (bool): by default skip Newton iteration for FP64 only
Returns:
torch.Tensor: shape (..., 4) axis-angles (x, y, z, angle)
Notes:
These are Chebyshev fits on the modified homochoric inverse
fitted by Zachary Varley on 05/24/2024. The modified homochoric
inverse ties the square of the homochoric vector back to the
cosine of the half rotation angle.
"""
if ho.dtype == torch.float32 or ho.dtype == torch.float16:
fit_parameters = torch.tensor(
[
# 8 terms to reach FP32 machine eps
1.0000000000000009e00,
-4.9999943403867775e-01,
-2.5015165060149020e-02,
-3.8120131548551729e-03,
-1.2106188330642162e-03,
4.9329295993155416e-04,
-7.0089385526450620e-04,
3.0979774923589078e-04,
-7.3023474963298843e-05,
],
dtype=ho.dtype,
device=ho.device,
).to(ho.dtype)
else:
# 10 term loss mean abs error 5e-10 instead of 15 term's 1e-11
# 1 iteration of Newton's method is needed for double precision
# machine error... 20 terms somehow is stuck at 1e-11 error
fit_parameters = torch.tensor(
[
# 10 term polyfit
1.0000000000000000e00,
-4.9999997124013285e-01,
-2.5001181866044025e-02,
-3.9144209820521038e-03,
-8.9320268104539483e-04,
3.1181024286083695e-05,
-4.3961032788396477e-04,
3.9657471727506439e-04,
-2.6379945050586932e-04,
9.1185355979587159e-05,
-1.4875867805692529e-05,
],
dtype=ho.dtype,
device=ho.device,
).to(ho.dtype)
# ho_norm_sq = torch.sum(ho**2, dim=-1, keepdim=True)
# # makes out of memory error doing all at once
# s = torch.zeros_like(ho_norm_sq[..., 0])
# for i in range(len(fit_parameters)):
# s += fit_parameters[i] * ho_norm_sq[..., 0] ** i
ho_norm_sq = torch.sum(ho**2, dim=-1, keepdim=False)
# makes out of memory error doing all at once
s = torch.zeros_like(ho_norm_sq)
for i in range(len(fit_parameters)):
s += fit_parameters[i] * ho_norm_sq**i
if ho.dtype == torch.float64 and not fast:
w = 2 * torch.arccos(torch.clamp(s, -1.0, 1.0))
# do 1 iteration of Newton's method
f_w = ((3 / 4) * (w - torch.sin(w))) ** (1 / 3) - torch.sqrt(ho_norm_sq)
f_p_w = (1 - torch.cos(w)) / (6 ** (2 / 3) * (w - torch.sin(w)) ** (2 / 3))
update = f_w / f_p_w
# remove any nans
update[torch.isnan(update)] = 0
w -= update
else:
w = 2.0 * torch.arccos(torch.clamp(s, -1.0, 1.0))
ax = torch.concat(
[
ho * torch.rsqrt(ho_norm_sq).unsqueeze(-1),
w.unsqueeze(-1),
],
dim=-1,
)
rot_is_identity = torch.abs(ho_norm_sq) < 1e-6
# set the identity rotation
ax[rot_is_identity] = 0
ax[rot_is_identity, ..., 2] = 1.0
return ax
@torch.jit.script
def ho2ax_reference(ho: Tensor, coeffs: str = "kikuchipy") -> Tensor:
"""
Converts a set of homochoric vectors to axis-angle representation.
I have seen two polynomial fits for this conversion, one from EMsoft
and the other from Kikuchipy. The Kikuchipy one is used here.
Args:
ho (Tensor): shape (..., 3) homochoric coordinates (x, y, z)
Returns:
torch.Tensor: shape (..., 4) axis-angles (x, y, z, angle)
Notes:
f(w) = [(3/4) * (w - sin(w))]^(1/3) -> no inverse -> polynomial fit it
"""
if coeffs == "kikuchipy":
fit_parameters = torch.tensor(
[
# Kikuchipy polyfit coeffs
1.0000000000018852,
-0.5000000002194847,
-0.024999992127593126,
-0.003928701544781374,
-0.0008152701535450438,
-0.0002009500426119712,
-0.00002397986776071756,
-0.00008202868926605841,
0.00012448715042090092,
-0.0001749114214822577,
0.0001703481934140054,
-0.00012062065004116828,
0.000059719705868660826,
-0.00001980756723965647,
0.000003953714684212874,
-0.00000036555001439719544,
],
dtype=ho.dtype,
device=ho.device,
).to(ho.dtype)
elif coeffs == "EMsoft":
fit_parameters = torch.tensor(
[
# EMsoft polyfit coeffs
0.9999999999999968,
-0.49999999999986866,
-0.025000000000632055,
-0.003928571496460683,
-0.0008164666077062752,
-0.00019411896443261646,
-0.00004985822229871769,
-0.000014164962366386031,
-1.9000248160936107e-6,
-5.72184549898506e-6,
7.772149920658778e-6,
-0.00001053483452909705,
9.528014229335313e-6,
-5.660288876265125e-6,
1.2844901692764126e-6,
1.1255185726258763e-6,
-1.3834391419956455e-6,
7.513691751164847e-7,
-2.401996891720091e-7,
4.386887017466388e-8,
-3.5917775353564864e-9,
],
dtype=ho.dtype,
device=ho.device,
).to(ho.dtype)
else:
raise ValueError(f"Invalid fit parameters {coeffs}.")
ho_norm_sq = torch.sum(ho**2, dim=-1, keepdim=True)
# makes out of memory error doing all at once
s = torch.zeros_like(ho_norm_sq[..., 0])
for i in range(len(fit_parameters)):
s += fit_parameters[i] * ho_norm_sq[..., 0] ** i
ax = torch.empty(ho.shape[:-1] + (4,), dtype=ho.dtype, device=ho.device)
rot_is_identity = torch.abs(ho_norm_sq.squeeze(-1)) < 1e-8
ax[rot_is_identity, 0:1] = 0.0
ax[rot_is_identity, 1:2] = 0.0
ax[rot_is_identity, 2:3] = 1.0
ax[~rot_is_identity, :3] = ho[~rot_is_identity, :] * torch.rsqrt(
ho_norm_sq[~rot_is_identity]
)
ax[..., 3] = torch.where(
~rot_is_identity,
2.0 * torch.arccos(torch.clamp(s, -1.0, 1.0)),
0,
)
return ax
@torch.jit.script
def ho2ax_newton(ho: Tensor) -> Tensor:
"""
Converts homochoric coordinates to axis-angle representation.
Args:
ho (Tensor): shape (..., 3) homochoric coordinates (x, y, z)
Returns:
torch.Tensor: shape (..., 4) axis-angles (x, y, z, angle)
Notes:
Newton's method
"""
# initial guess for ang given h
h = torch.norm(ho, dim=-1)
# where zero return zero
mask_zero = h == 0
ax = torch.empty(ho.shape[:-1] + (4,), dtype=ho.dtype, device=ho.device)
ax[mask_zero, 0] = 0.0
ax[mask_zero, 1] = 0.0
ax[mask_zero, 2] = 1.0
ax[mask_zero, 3] = 0.0
# Newton's method
# initial guess for w given h is an inverted Pade approximation
w_newton = (15 - torch.sqrt(225 - 60 * h[~mask_zero] ** 2)) / h[~mask_zero]
# Newton's method
for _ in range(2 if h.dtype == torch.float32 else 3):
f_w = ((3 / 4) * (w_newton - torch.sin(w_newton))) ** (1 / 3) - h[~mask_zero]
f_p_w = (1 - torch.cos(w_newton)) / (
6 ** (2 / 3) * (w_newton - torch.sin(w_newton)) ** (2 / 3)
)
update = f_w / f_p_w
# remove any nans
update[torch.isnan(update)] = 0
w_newton -= update
ax[~mask_zero, 0:3] = ho[~mask_zero] * torch.rsqrt(h[~mask_zero].unsqueeze(-1))
ax[~mask_zero, 3] = w_newton
return ax
@torch.jit.script
def ax2ho(ax: Tensor) -> Tensor:
"""
Converts axis-angle representation to homochoric vector representation.
Args:
ax: Axis-angle representation as tensor of shape (..., 4).
Returns:
Homochoric vectors as tensor of shape (..., 3).
"""
return (0.75 * (ax[..., 3:4] - torch.sin(ax[..., 3:4]))) ** (1.0 / 3.0) * ax[
..., :3
]
@torch.jit.script
def ax2ro(ax: Tensor) -> Tensor:
"""
Converts axis-angle representation to Rodrigues vector representation.
Args:
ax (Tensor): shape (..., 4) axis-angle (x, y, z, angle)
Returns:
torch.Tensor: shape (..., 4) Rodrigues-Frank (x, y, z, tan(angle/2))
"""
ro = ax.clone()
ro[..., 3] = torch.tan(ax[..., 3] / 2)
return ro
@torch.jit.script
def ro2ax(ro: Tensor) -> Tensor:
"""
Converts a rotation vector to an axis-angle representation.
Args:
ro (Tensor): shape (..., 4) Rodrigues-Frank (x, y, z, tan(angle/2)).
Returns:
torch.Tensor: shape (..., 4) axis-angles (x, y, z, angle).
"""
ax = torch.empty_like(ro)
mask_zero_ro = torch.abs(ro[..., 3]) == 0
ax[mask_zero_ro] = torch.tensor([0, 0, 1, 0], dtype=ro.dtype, device=ro.device)
mask_inf_ro = torch.isinf(ro[..., 3])
ax[mask_inf_ro, :3] = ro[mask_inf_ro, :3]
ax[mask_inf_ro, 3] = torch.pi
mask_else = ~(mask_zero_ro | mask_inf_ro)
ax[mask_else, :3] = ro[mask_else, :3] / torch.norm(
ro[mask_else, :3], dim=-1, keepdim=True
)
ax[mask_else, 3] = 2 * torch.atan(ro[mask_else, 3])
return ax
@torch.jit.script
def ax2qu(ax: Tensor) -> Tensor:
"""
Converts axis-angle representation to quaternion representation.
Args:
ax (Tensor): shape (..., 4) axis-angle in the format (x, y, z, angle).
Returns:
torch.Tensor: shape (..., 4) quaternions in the format (w, x, y, z).
"""
qu = torch.empty_like(ax)
cos_half_ang = torch.cos(ax[..., 3] / 2.0)
sin_half_ang = torch.sin(ax[..., 3:4] / 2.0)
qu[..., 0] = cos_half_ang
qu[..., 1:] = ax[..., :3] * sin_half_ang
return qu
@torch.jit.script
def qu2ax(qu: Tensor) -> Tensor:
"""
Converts quaternion representation to axis-angle representation.
Args:
qu (Tensor): shape (..., 4) quaternions in the format (w, x, y, z).