-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathquaternion.py
714 lines (556 loc) · 19.2 KB
/
quaternion.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
import torch
import numpy as np
import warnings
import functools
HANDLED_FUNCTIONS = {}
def implements(torch_function):
"""Register a torch function override for ScalarTensor"""
@functools.wraps(torch_function)
def decorator(func):
HANDLED_FUNCTIONS[torch_function] = func
return func
return decorator
# ----------------------------------- general ------------------------------------------------
@implements(torch.Tensor.chunk)
def chunk(input, *args, **kwargs):
return torch.chunk(input.q, chunks=4, *args, **kwargs)
# ----------------------------------- conj ---------------------------------------------------
@implements(torch.Tensor.conj)
def conj(self):
"""
Quaternion conjugate
"""
if len(self.shape) > 1:
con = torch.cat([self.a, -self.b, -self.c, -self.d], 1)
else:
con = [self.a, -self.b, -self.c, -self.d]
return self.__class__(con, False)
@implements(torch.conj)
def conj(input):
return input.conj()
# ----------------------------------- inverse ------------------------------------------------
@implements(torch.Tensor.inverse)
def inverse(self):
"""
Quaternion inverse
"""
if len(self.shape) > 1:
inverse = self.conj() / self.sq_norm()
else:
inverse = self.conj() / self.sq_norm()
return inverse
@implements(torch.inverse)
def inverse(input):
return input.inverse()
# ----------------------------------- norm ------------------------------------------------
@implements(torch.Tensor.norm)
def norm(self, *args, **kwargs):
"""
Quaternion (non-squared) norm.
"""
return torch.sqrt(self.a ** 2 + self.b ** 2 + self.c ** 2 + self.d ** 2)
@implements(torch.linalg.norm)
def norm(input, *args, **kwargs):
return input.norm(*args, **kwargs)
# ----------------------------------- add ------------------------------------------------
@implements(torch.Tensor.add)
def add(self, other):
"""
Standard addition but only adds the other tensor
to the real part if it has 1/4 of the channels.
"""
if np.prod(self.shape) != 4:
if isinstance(other, torch.Tensor):
if other.__class__.__name__ == "QuaternionTensor":
other = other.q
if other.dim() > 1 and self.dim() > 1:
if other.shape[1] * 4 == self.shape[1]:
out = torch.cat([self.a + other, self.b, self.c, self.d], 1)
if self.real_tensor:
out = real_repr(out)
else:
out = self.q + other
elif other.dim() <= 1 and self.dim() > 1:
out = torch.cat([self.a + other.unsqueeze(1), self.b, self.c, self.d], 1)
if self.real_tensor:
out = real_repr(out)
else:
out = self.q + other
else:
if other.__class__.__name__ == "QuaternionTensor":
out = self.q + other.q
elif isinstance(other, int):
out = [self.a + other, self.b, self.c, self.d]
elif len(other) == 1:
out = [self.a + other, self.b, self.c, self.d]
else:
out = self.q + other
return self.__class__(out)
@implements(torch.add)
def add(input1, input2):
return torch.Tensor.add(input1, input2)
@implements(torch.Tensor.__add__)
def add(input1, input2):
return torch.Tensor.add(input1, input2)
@implements(torch.Tensor.add_)
def add(input1, input2):
return torch.Tensor.add(input1, input2)
# ----------------------------------- mul ------------------------------------------------
@implements(torch.Tensor.mul)
def mul(self, other):
"""
Product of two quaternions, called "Hamilton product".
Using the basis product's rules and the distributive rule
for two quaternions q1 = a1 + b1*i + c1*j + d1*k and
q2 = a2 + b2*i + c2*j + d2*k we get:
anew = a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2
bnew = (a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2) i
cnew = (a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2) j
dnew = (a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2) k
It broadcastes the other C/4 tensor to C channels
to compute the standard Kronecker product.
"""
if isinstance(other, QuaternionTensor):
a2, b2, c2, d2 = other.chunk()
r = self.a * a2 - self.b * b2 - self.c * c2 - self.d * d2
i = self.a * b2 + self.b * a2 + self.c * d2 - self.d * c2
j = self.a * c2 - self.b * d2 + self.c * a2 + self.d * b2
k = self.a * d2 + self.b * c2 - self.c * b2 + self.d * a2
if self.dim() > 1 or other.dim() > 1:
out = torch.cat([r, i, j, k], 1)
else:
out = [r, i, j, k]
elif isinstance(other, torch.Tensor):
if other.dim() > 1 and other.dim() > 1:
if other.shape[1] * 4 == self.shape[1]:
out = self.q * torch.cat([other] * 4, 1)
else:
out = self.q * other
else:
if other.dim() == 1 and other.shape[0] == self.shape[0]:
out = self.q * torch.stack([other] * self.shape[1], 1)
else:
out = self.q * other
else:
out = self.q * other
return self.__class__(out)
@implements(torch.mul)
def mul(input1, input2):
return torch.Tensor.mul(input1, input2)
@implements(torch.Tensor.__mul__)
def mul(input1, input2):
return torch.Tensor.mul(input1, input2)
@implements(torch.Tensor.mul_)
def mul(input1, input2):
return torch.Tensor.mul(input1, input2)
# ----------------------------------- matmul ---------------------------------------------
@implements(torch.Tensor.matmul)
def matmul(self, other):
return torch.matmul(self.q, other)
@implements(torch.matmul)
def matmul(input1, input2):
return torch.Tensor.matmul(input1, input2)
@implements(torch.Tensor.__matmul__)
def matmul(input1, input2):
return torch.Tensor.matmul(input1, input2)
# ----------------------------------- div ------------------------------------------------
@implements(torch.Tensor.div)
def true_div(self, other):
"""
Quaternion division q1 * (q2)^-1.
It broadcastes the other C/4 tensor to C channels
to compute the standard elementwise division.
"""
real_tensor = False
if isinstance(other, QuaternionTensor):
out = self * other.inverse()
elif isinstance(other, torch.Tensor):
if other.dim() > 1 and self.dim() > 1:
if other.shape[1] * 4 == self.shape[1]:
out = self.q / torch.cat([other] * 4, 1)
else:
out = self.q / other
else:
if other.dim() == 1 and other.shape[0] == self.shape[0]:
out = self.q / torch.stack([other] * self.shape[1], 1)
else:
out = self.q / other
else:
out = self.q / other
return self.__class__(out)
@implements(torch.div)
def div(input1, input2):
return torch.Tensor.div(input1, input2)
@implements(torch.Tensor.__div__)
def div(input1, input2):
return torch.Tensor.div(input1, input2)
@implements(torch.Tensor.div_)
def div(input1, input2):
return torch.Tensor.div(input1, input2)
# ----------------------------------- pow ------------------------------------------------
@implements(torch.Tensor.pow)
def pow(self, n):
"""
Quaternion power.
"""
n = float(n)
if self.quat_ops:
v = self.v
if self.dim() > 1:
out = v / v.norm() * torch.sin(n * self.theta())
out += torch.cos(n * self.theta())
out *= (self.norm() ** n)
else:
out = v / v.norm() * torch.sin(n * self.theta())
out += torch.cos(n * self.theta())
out *= (self.norm() ** n)
return self.__class__(out)
else:
return torch.pow(self.q, n)
@implements(torch.pow)
def div(input1, input2):
return torch.Tensor.pow(input1, input2)
@implements(torch.Tensor.__pow__)
def div(input1, input2):
return torch.Tensor.pow(input1, input2)
@implements(torch.Tensor.pow_)
def div(input1, input2):
return torch.Tensor.pow(input1, input2)
# ----------------------------------- exp ------------------------------------------------
@implements(torch.Tensor.exp)
def exp(self):
"""
Quaternion exponential.
"""
if self.quat_ops:
v = self.v
a = self.a
v_norm = v.norm()
exp = torch.exp(a)
real = exp * torch.cos(v_norm)
if self.dim() > 1:
vector = exp * (v / v_norm) * torch.sin(v_norm)
out = real + vector
else:
vector = exp * (v / v_norm) * torch.sin(v_norm)
out = torch.cat([
real, vector[1].unsqueeze(0), vector[2].unsqueeze(0), vector[3].unsqueeze(0)
], 0)
return self.__class__(out)
else:
return torch.exp(self.q)
@implements(torch.exp)
def exp(input):
return input.exp()
# ----------------------------------- log ------------------------------------------------
@implements(torch.Tensor.log)
def log(self):
"""
Quaternion logarithm.
"""
if self.quat_ops:
v = self.v
a = self.a
v_norm = v.norm()
q_norm = self.q.norm()
real = torch.log(q_norm)
if self.dim() > 1:
vector = (v / v_norm) * self.theta()
out = real + vector
else:
vector = (v / v_norm) * self.theta()
out = [real.unsqueeze(0), vector[1].unsqueeze(0),
vector[2].unsqueeze(0), vector[3].unsqueeze(0)]
return self.__class__(out)
else:
return torch.log(self.q)
@implements(torch.log)
def log(input):
return input.log()
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# ---------------------------- QuaternionTensor ------------------------------------------
# ----------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
def get_parts(q):
"""
Divides input tensor in real and imaginary parts.
@type q: torch.Tensor
@type dim: int
"""
a, b, c, d = torch.chunk(q, 4, 1)
return a.transpose(1, 0), \
b.transpose(1, 0), \
c.transpose(1, 0), \
d.transpose(1, 0)
def check_q_type(q):
"""
Readies the tensor for the QuaternionTensor class
@type q: torch.Tensor/list/tuple
"""
if isinstance(q, (tuple, list)):
if all(isinstance(i, torch.Tensor) for i in q) == True and len(q) != 0:
assert len(q) == 4, "Quaternion must have 4 elements."
if all(i.dim() == 1 for i in q):
q = torch.cat(q, 0)
else:
q = torch.stack(q, 1)
else:
q = torch.Tensor(q)
return q
def real_repr(q):
"""
Gets the real representation of the tensor.
@type q: torch.Tensor
"""
a, b, c, d = get_parts(q)
if all((i.dim() == 1) for i in [a, b, c, d]) == True:
a = a.view(1, 1)
b = b.view(1, 1)
c = c.view(1, 1)
d = d.view(1, 1)
return torch.cat([torch.cat([a, -b, -c, -d], dim=1),
torch.cat([b, a, -d, c], dim=1),
torch.cat([c, d, a, -b], dim=1),
torch.cat([d, -c, b, a], dim=1)], dim=0)
def real_rot_repr(q):
"""
Gets the real rotation representation of the tensor.
@type q: torch.Tensor
"""
a, b, c, d = get_parts(q)
if all((i.dim() == 1) for i in [a, b, c, d]) == True:
a = a.view(1, 1)
b = b.view(1, 1)
c = c.view(1, 1)
d = d.view(1, 1)
row1 = torch.cat([torch.zeros_like(b)] * 4, dim=1)
row2 = torch.cat([torch.zeros_like(b),
1 - 2 * (c ** 2 + d ** 2),
2 * (b * c - d * a),
2 * (b * d + c * a)], dim=1)
row3 = torch.cat([torch.zeros_like(b),
2 * (b * c + d * a),
1 - 2 * (b ** 2 + d ** 2),
2 * (c * d - b * a)], dim=1)
row4 = torch.cat([torch.zeros_like(b),
2 * (b * d - c * a),
2 * (c * d + b * a),
1 - 2 * (b ** 2 + c ** 2)], dim=1)
return torch.cat([row1, row2, row3, row4], dim=0)
class QuaternionTensor(torch.Tensor):
"""
The class contains the common quaternion operations suited
for the Pytorch framework subclassing its
"torch.Tensor". Thus it can be fed in any
Pytorch function that accepts a torch.Tensor or can be
used independently for other, more general, applications.
"""
@staticmethod
def __new__(cls, q=[], real_tensor=False, quat_ops=True, *args, **kwargs):
q = check_q_type(q)
if real_tensor:
q = real_repr(q)
cls.q = q
cls.device = q.device
return super().__new__(cls, q.cpu(), *args, **kwargs)
def __init__(self, q=[], real_tensor=False, quat_ops=True):
super().__init__()
"""
Init accepts incoming quaternion and immediately
transforms it into its real represention when
"real_tensor" is set to True.
@type q: torch.Tensor/list/tuple
@type real_tensor: bool
"""
self.real_tensor = real_tensor
self.quat_ops = quat_ops
q = check_q_type(q)
if len(q) != 0:
if real_tensor:
q = real_repr(q)
self.q = q
self.q.grad = None
@property
def a(self):
if self.dim() == 1:
out = self.q[:self.shape[0] // 4]
else:
out = self.q[:, :self.shape[1] // 4]
out.quat_ops = False
return out
@property
def b(self):
if self.dim() == 1:
step = self.shape[0] // 4
out = self.q[step:step * 2]
else:
step = self.shape[1] // 4
out = self.q[:, step:step * 2]
out.quat_ops = False
return out
@property
def c(self):
if self.dim() == 1:
step = self.shape[0] // 4
out = self.q[step * 2:step * 3]
else:
step = self.shape[1] // 4
out = self.q[:, step * 2:step * 3]
out.quat_ops = False
return out
@property
def d(self):
if self.dim() == 1:
step = self.shape[0] // 4
out = self.q[step * 3:]
else:
step = self.shape[1] // 4
out = self.q[:, step * 3:]
out.quat_ops = False
return out
# overrides pytorch operations
def __torch_function__(self, func, types, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
if func not in HANDLED_FUNCTIONS or not all(
issubclass(t, QuaternionTensor)
for t in types
):
args = [a.q if isinstance(a, QuaternionTensor) else a for a in args]
return func(*args, **kwargs)
return HANDLED_FUNCTIONS[func](*args, **kwargs)
def torch(self):
"""
Casts to standard pytorch
"""
return self.q
def rand(self, size):
"""
Creates random QuaternionTensor
in the interval [0,1)
"""
return self.__class__(torch.rand(size))
def sq_norm(self):
"""
Quaternion squared norm.
"""
return self.q.norm() ** 2
@property
def _real_repr(self):
"""
Real representation of the quaternion.
"""
return real_repr(self.q)
@property
def _real_rot_repr(self):
"""
Real rotation representation.
"""
return real_rot_repr(self.q)
@property
def v(self):
"""
Vector part of the quaternion: 0 + b*i + c*j + d*k.
"""
if self.dim() > 1:
out = torch.cat([torch.zeros_like(self.b), self.b, self.c, self.d], 1)
else:
out = [torch.zeros_like(self.b), self.b, self.c, self.d]
return self.__class__(out)
def theta(self):
"""
Angle of the quaternion.
"""
return torch.acos(self.a / self.norm())
@property
def qshape(self):
"""
Quaternion shape
"""
if self.real_tensor:
return self.a.shape
else:
return self.shape
def clone(self):
"""
General Pytorch cloning.
"""
return self.__class__(self.q.clone())
def to(self, device):
"""
Sends tensor to CPU or GPU.
"""
new_obj = QuaternionTensor(self.q)
tempTensor = super().to(device)
new_obj.data = tempTensor.data
new_obj.device = device
new_obj.requires_grad = tempTensor.requires_grad
return new_obj
def chunk(self):
return self.a, self.b, self.c, self.d
def __add__(self, other):
return torch.Tensor.add(self, other)
def __radd__(self, other):
return self.__add__(other)
def __iadd_(self, other):
return self.__class__(self + other)
def __sub__(self, other):
return torch.add(self, -other)
def __rsub__(self, other):
return -self.__add__(-other)
def __isub__(self, other):
return self.__class__(self - other)
def __mul__(self, other):
return torch.mul(self, other)
def __rmul__(self, other):
if isinstance(other, torch.Tensor):
if other.dim() > 1 and self.dim() > 1:
if other.shape[1] * 4 == self.shape[1]:
out = torch.cat([other] * 4, 1) * self.q
else:
out = other * self.q
else:
if other.dim() == 1 and other.shape[0] == self.shape[0]:
out = other * self.q
else:
out = other * self.q
else:
out = other * self.q
return self.__class__(out)
def __imul__(self, other):
return self.__class__(self * other)
def __matmul__(self, other):
return torch.matmul(self, other)
def __rmatmul__(self, other):
return self.__matmul__(other)
def __truediv__(self, other):
return torch.div(self, other)
def __rtruediv__(self, other):
if isinstance(other, torch.Tensor):
if other.dim() > 1 and self.dim() > 1:
if other.shape[1] * 4 == self.shape[1]:
out = torch.cat([other] * 4, 1) / self.q
else:
out = other / self.q
else:
if other.dim() == 1 and other.shape[0] == self.shape[0]:
out = torch.stack([other] * self.shape[1], 1) / self.q
else:
out = other / self.q
else:
out = other / self.q
return self.__class__(out)
def __itruediv__(self, other):
return self.__class__(self / other)
def __pow__(self, n):
return torch.pow(self, n)
def __len__(self):
return len(self.q)
def __str__(self):
return self.__repr__()
def __repr__(self):
return f"real part: {self.a}\n" + \
f"imaginary part (i): {self.b}\n" + \
f"imaginary part (j): {self.c}\n" + \
f"imaginary part (k): {self.d}"