forked from moble/quaternion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumpy_quaternion.c
1739 lines (1592 loc) · 74 KB
/
numpy_quaternion.c
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
// Copyright (c) 2017, Michael Boyle
// See LICENSE file for details: <https://github.com/moble/quaternion/blob/master/LICENSE>
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#include <Python.h>
#include <numpy/arrayobject.h>
#include <numpy/npy_math.h>
#include <numpy/ufuncobject.h>
#include "structmember.h"
#include "quaternion.h"
// The following definitions, along with `#define NPY_PY3K 1`, can
// also be found in the header <numpy/npy_3kcompat.h>.
#if PY_MAJOR_VERSION >= 3
#define PyUString_FromString PyUnicode_FromString
static NPY_INLINE int PyInt_Check(PyObject *op) {
int overflow = 0;
if (!PyLong_Check(op)) {
return 0;
}
PyLong_AsLongAndOverflow(op, &overflow);
return (overflow == 0);
}
#define PyInt_AsLong PyLong_AsLong
#else
#define PyUString_FromString PyString_FromString
#endif
// The basic python object holding a quaternion
typedef struct {
PyObject_HEAD
quaternion obval;
} PyQuaternion;
static PyTypeObject PyQuaternion_Type;
// This is the crucial feature that will make a quaternion into a
// built-in numpy data type. We will describe its features below.
PyArray_Descr* quaternion_descr;
static NPY_INLINE int
PyQuaternion_Check(PyObject* object) {
return PyObject_IsInstance(object,(PyObject*)&PyQuaternion_Type);
}
static PyObject*
PyQuaternion_FromQuaternion(quaternion q) {
PyQuaternion* p = (PyQuaternion*)PyQuaternion_Type.tp_alloc(&PyQuaternion_Type,0);
if (p) { p->obval = q; }
return (PyObject*)p;
}
// TODO: Add list/tuple conversions
#define PyQuaternion_AsQuaternion(q, o) \
/* fprintf (stderr, "file %s, line %d., PyQuaternion_AsQuaternion\n", __FILE__, __LINE__); */ \
if(PyQuaternion_Check(o)) { \
q = ((PyQuaternion*)o)->obval; \
} else { \
PyErr_SetString(PyExc_TypeError, \
"Input object is not a quaternion."); \
return NULL; \
}
#define PyQuaternion_AsQuaternionPointer(q, o) \
/* fprintf (stderr, "file %s, line %d, PyQuaternion_AsQuaternionPointer.\n", __FILE__, __LINE__); */ \
if(PyQuaternion_Check(o)) { \
q = &((PyQuaternion*)o)->obval; \
} else { \
PyErr_SetString(PyExc_TypeError, \
"Input object is not a quaternion."); \
return NULL; \
}
static PyObject *
pyquaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyQuaternion* self;
self = (PyQuaternion *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
pyquaternion_init(PyObject *self, PyObject *args, PyObject *kwds)
{
// "A good rule of thumb is that for immutable types, all
// initialization should take place in `tp_new`, while for mutable
// types, most initialization should be deferred to `tp_init`."
// ---Python 2.7.8 docs
Py_ssize_t size = PyTuple_Size(args);
quaternion* q;
q = &(((PyQuaternion*)self)->obval);
if (kwds && PyDict_Size(kwds)) {
PyErr_SetString(PyExc_TypeError,
"quaternion constructor takes no keyword arguments");
return -1;
}
if (((size == 3) && (!PyArg_ParseTuple(args, "ddd", &q->x, &q->y, &q->z)))
|| ((size == 4) && (!PyArg_ParseTuple(args, "dddd", &q->w, &q->x, &q->y, &q->z)))) {
PyErr_SetString(PyExc_TypeError,
"quaternion constructor takes three or four float arguments");
return -1;
} else if(size == 3) {
q->w = 0.0;
}
return 0;
}
#define UNARY_BOOL_RETURNER(name) \
static PyObject* \
pyquaternion_##name(PyObject* a, PyObject* b) { \
quaternion q = {0}; \
PyQuaternion_AsQuaternion(q, a); \
return PyBool_FromLong(quaternion_##name(q)); \
}
UNARY_BOOL_RETURNER(nonzero)
UNARY_BOOL_RETURNER(isnan)
UNARY_BOOL_RETURNER(isinf)
UNARY_BOOL_RETURNER(isfinite)
#define BINARY_BOOL_RETURNER(name) \
static PyObject* \
pyquaternion_##name(PyObject* a, PyObject* b) { \
quaternion p = {0}; \
quaternion q = {0}; \
PyQuaternion_AsQuaternion(p, a); \
PyQuaternion_AsQuaternion(q, b); \
return PyBool_FromLong(quaternion_##name(p,q)); \
}
BINARY_BOOL_RETURNER(equal)
BINARY_BOOL_RETURNER(not_equal)
BINARY_BOOL_RETURNER(less)
BINARY_BOOL_RETURNER(greater)
BINARY_BOOL_RETURNER(less_equal)
BINARY_BOOL_RETURNER(greater_equal)
#define UNARY_FLOAT_RETURNER(name) \
static PyObject* \
pyquaternion_##name(PyObject* a, PyObject* b) { \
quaternion q = {0}; \
PyQuaternion_AsQuaternion(q, a); \
return PyFloat_FromDouble(quaternion_##name(q)); \
}
UNARY_FLOAT_RETURNER(absolute)
UNARY_FLOAT_RETURNER(norm)
UNARY_FLOAT_RETURNER(angle)
#define UNARY_QUATERNION_RETURNER(name) \
static PyObject* \
pyquaternion_##name(PyObject* a, PyObject* b) { \
quaternion q = {0}; \
PyQuaternion_AsQuaternion(q, a); \
return PyQuaternion_FromQuaternion(quaternion_##name(q)); \
}
UNARY_QUATERNION_RETURNER(negative)
UNARY_QUATERNION_RETURNER(conjugate)
UNARY_QUATERNION_RETURNER(inverse)
UNARY_QUATERNION_RETURNER(sqrt)
UNARY_QUATERNION_RETURNER(log)
UNARY_QUATERNION_RETURNER(exp)
UNARY_QUATERNION_RETURNER(normalized)
UNARY_QUATERNION_RETURNER(x_parity_conjugate)
UNARY_QUATERNION_RETURNER(x_parity_symmetric_part)
UNARY_QUATERNION_RETURNER(x_parity_antisymmetric_part)
UNARY_QUATERNION_RETURNER(y_parity_conjugate)
UNARY_QUATERNION_RETURNER(y_parity_symmetric_part)
UNARY_QUATERNION_RETURNER(y_parity_antisymmetric_part)
UNARY_QUATERNION_RETURNER(z_parity_conjugate)
UNARY_QUATERNION_RETURNER(z_parity_symmetric_part)
UNARY_QUATERNION_RETURNER(z_parity_antisymmetric_part)
UNARY_QUATERNION_RETURNER(parity_conjugate)
UNARY_QUATERNION_RETURNER(parity_symmetric_part)
UNARY_QUATERNION_RETURNER(parity_antisymmetric_part)
static PyObject*
pyquaternion_positive(PyObject* self, PyObject* b) {
Py_INCREF(self);
return self;
}
#define QQ_BINARY_QUATERNION_RETURNER(name) \
static PyObject* \
pyquaternion_##name(PyObject* a, PyObject* b) { \
quaternion p = {0}; \
quaternion q = {0}; \
if(PyArray_Check(b)) { fprintf (stderr, "\nfile %s, line %d, pyquaternion_%s(PyObject* a, PyObject* b).\n", __FILE__, __LINE__, #name); } /*return pyquaternion_##name##_array_operator(a, b); }*/ \
PyQuaternion_AsQuaternion(p, a); \
PyQuaternion_AsQuaternion(q, b); \
return PyQuaternion_FromQuaternion(quaternion_##name(p,q)); \
}
/* QQ_BINARY_QUATERNION_RETURNER(add) */
/* QQ_BINARY_QUATERNION_RETURNER(subtract) */
QQ_BINARY_QUATERNION_RETURNER(copysign)
#define QQ_QS_SQ_BINARY_QUATERNION_RETURNER_FULL(fake_name, name) \
static PyObject* \
pyquaternion_##fake_name##_array_operator(PyObject* a, PyObject* b) { \
/* fprintf (stderr, "\nfile %s, line %d, pyquaternion_%s_array_operator(PyObject* a, PyObject* b).\n", __FILE__, __LINE__, #fake_name); */ \
PyArrayObject *in_array = (PyArrayObject*) b; \
PyObject *out_array; \
NpyIter *in_iter; \
NpyIter *out_iter; \
NpyIter_IterNextFunc *in_iternext; \
NpyIter_IterNextFunc *out_iternext; \
quaternion p = {0}; \
quaternion ** out_dataptr; \
PyQuaternion_AsQuaternion(p, a); \
out_array = PyArray_NewLikeArray(in_array, NPY_ANYORDER, quaternion_descr, 0); \
if (out_array == NULL) return NULL; \
in_iter = NpyIter_New(in_array, NPY_ITER_READONLY, NPY_KEEPORDER, \
NPY_NO_CASTING, NULL); \
if (in_iter == NULL) goto fail; \
out_iter = NpyIter_New((PyArrayObject *)out_array, NPY_ITER_READWRITE, \
NPY_KEEPORDER, NPY_NO_CASTING, NULL); \
if (out_iter == NULL) { \
NpyIter_Deallocate(in_iter); \
goto fail; \
} \
in_iternext = NpyIter_GetIterNext(in_iter, NULL); \
out_iternext = NpyIter_GetIterNext(out_iter, NULL); \
if (in_iternext == NULL || out_iternext == NULL) { \
NpyIter_Deallocate(in_iter); \
NpyIter_Deallocate(out_iter); \
goto fail; \
} \
out_dataptr = (quaternion **) NpyIter_GetDataPtrArray(out_iter); \
if(PyArray_EquivTypes(PyArray_DESCR((PyArrayObject*) b), quaternion_descr)) { \
quaternion ** in_dataptr = (quaternion **) NpyIter_GetDataPtrArray(in_iter); \
do { \
**out_dataptr = quaternion_##name(p, **in_dataptr); \
} while(in_iternext(in_iter) && out_iternext(out_iter)); \
} else if(PyArray_ISFLOAT((PyArrayObject*) b)) { \
double ** in_dataptr = (double **) NpyIter_GetDataPtrArray(in_iter); \
do { \
**out_dataptr = quaternion_##name##_scalar(p, **in_dataptr); \
} while(in_iternext(in_iter) && out_iternext(out_iter)); \
} else if(PyArray_ISINTEGER((PyArrayObject*) b)) { \
int ** in_dataptr = (int **) NpyIter_GetDataPtrArray(in_iter); \
do { \
**out_dataptr = quaternion_##name##_scalar(p, **in_dataptr); \
} while(in_iternext(in_iter) && out_iternext(out_iter)); \
} else { \
NpyIter_Deallocate(in_iter); \
NpyIter_Deallocate(out_iter); \
goto fail; \
} \
NpyIter_Deallocate(in_iter); \
NpyIter_Deallocate(out_iter); \
Py_INCREF(out_array); \
return out_array; \
fail: \
Py_XDECREF(out_array); \
return NULL; \
} \
static PyObject* \
pyquaternion_##fake_name(PyObject* a, PyObject* b) { \
/* PyObject *a_type, *a_repr, *b_type, *b_repr, *a_repr2, *b_repr2; \ */ \
/* char* a_char, b_char, a_char2, b_char2; \ */ \
npy_int64 val64; \
npy_int32 val32; \
quaternion p = {0}; \
if(PyArray_Check(b)) { return pyquaternion_##fake_name##_array_operator(a, b); } \
if(PyFloat_Check(a) && PyQuaternion_Check(b)) { \
return PyQuaternion_FromQuaternion(quaternion_scalar_##name(PyFloat_AsDouble(a), ((PyQuaternion*)b)->obval)); \
} \
if(PyInt_Check(a) && PyQuaternion_Check(b)) { \
return PyQuaternion_FromQuaternion(quaternion_scalar_##name(PyInt_AsLong(a), ((PyQuaternion*)b)->obval)); \
} \
PyQuaternion_AsQuaternion(p, a); \
if(PyQuaternion_Check(b)) { \
return PyQuaternion_FromQuaternion(quaternion_##name(p,((PyQuaternion*)b)->obval)); \
} else if(PyFloat_Check(b)) { \
return PyQuaternion_FromQuaternion(quaternion_##name##_scalar(p,PyFloat_AsDouble(b))); \
} else if(PyInt_Check(b)) { \
return PyQuaternion_FromQuaternion(quaternion_##name##_scalar(p,PyInt_AsLong(b))); \
} else if(PyObject_TypeCheck(b, &PyInt64ArrType_Type)) { \
PyArray_ScalarAsCtype(b, &val64); \
return PyQuaternion_FromQuaternion(quaternion_##name##_scalar(p, val64)); \
} else if(PyObject_TypeCheck(b, &PyInt32ArrType_Type)) { \
PyArray_ScalarAsCtype(b, &val32); \
return PyQuaternion_FromQuaternion(quaternion_##name##_scalar(p, val32)); \
} \
/* a_type = PyObject_Type(a); \ */ \
/* a_repr = PyObject_Repr(a_type); \ */ \
/* a_char = PyString_AsString(a_repr); \ */ \
/* b_type = PyObject_Type(b); \ */ \
/* b_repr = PyObject_Repr(b_type); \ */ \
/* b_char = PyString_AsString(b_repr); \ */ \
/* a_repr2 = PyObject_Repr(a); \ */ \
/* a_char2 = PyString_AsString(a_repr2); \ */ \
/* b_repr2 = PyObject_Repr(b); \ */ \
/* b_char2 = PyString_AsString(b_repr2); \ */ \
/* fprintf (stderr, "\nfile %s, line %d, pyquaternion_%s(PyObject* a, PyObject* b).\n", __FILE__, __LINE__, #fake_name); \ */ \
/* fprintf (stderr, "\na: '%s'\tb: '%s'", a_char, b_char); \ */ \
/* fprintf (stderr, "\na: '%s'\tb: '%s'", a_char2, b_char2); \ */ \
/* Py_DECREF(a_type); \ */ \
/* Py_DECREF(a_repr); \ */ \
/* Py_DECREF(b_type); \ */ \
/* Py_DECREF(b_repr); \ */ \
/* Py_DECREF(a_repr2); \ */ \
/* Py_DECREF(b_repr2); \ */ \
PyErr_SetString(PyExc_TypeError, "Binary operation involving quaternion and \\neither float nor quaternion."); \
return NULL; \
}
#define QQ_QS_SQ_BINARY_QUATERNION_RETURNER(name) QQ_QS_SQ_BINARY_QUATERNION_RETURNER_FULL(name, name)
QQ_QS_SQ_BINARY_QUATERNION_RETURNER(add)
QQ_QS_SQ_BINARY_QUATERNION_RETURNER(subtract)
QQ_QS_SQ_BINARY_QUATERNION_RETURNER(multiply)
QQ_QS_SQ_BINARY_QUATERNION_RETURNER(divide)
/* QQ_QS_SQ_BINARY_QUATERNION_RETURNER_FULL(true_divide, divide) */
/* QQ_QS_SQ_BINARY_QUATERNION_RETURNER_FULL(floor_divide, divide) */
QQ_QS_SQ_BINARY_QUATERNION_RETURNER(power)
#define QQ_QS_SQ_BINARY_QUATERNION_INPLACE_FULL(fake_name, name) \
static PyObject* \
pyquaternion_inplace_##fake_name(PyObject* a, PyObject* b) { \
quaternion* p = {0}; \
/* fprintf (stderr, "file %s, line %d, pyquaternion_inplace_"#fake_name"(PyObject* a, PyObject* b).\n", __FILE__, __LINE__); \ */ \
if(PyFloat_Check(a) || PyInt_Check(a)) { \
PyErr_SetString(PyExc_TypeError, "Cannot in-place "#fake_name" a scalar by a quaternion; should be handled by python."); \
return NULL; \
} \
PyQuaternion_AsQuaternionPointer(p, a); \
if(PyQuaternion_Check(b)) { \
quaternion_inplace_##name(p,((PyQuaternion*)b)->obval); \
Py_INCREF(a); \
return a; \
} else if(PyFloat_Check(b)) { \
quaternion_inplace_##name##_scalar(p,PyFloat_AsDouble(b)); \
Py_INCREF(a); \
return a; \
} else if(PyInt_Check(b)) { \
quaternion_inplace_##name##_scalar(p,PyInt_AsLong(b)); \
Py_INCREF(a); \
return a; \
} \
PyErr_SetString(PyExc_TypeError, "Binary in-place operation involving quaternion and neither float nor quaternion."); \
return NULL; \
}
#define QQ_QS_SQ_BINARY_QUATERNION_INPLACE(name) QQ_QS_SQ_BINARY_QUATERNION_INPLACE_FULL(name, name)
QQ_QS_SQ_BINARY_QUATERNION_INPLACE(add)
QQ_QS_SQ_BINARY_QUATERNION_INPLACE(subtract)
QQ_QS_SQ_BINARY_QUATERNION_INPLACE(multiply)
QQ_QS_SQ_BINARY_QUATERNION_INPLACE(divide)
/* QQ_QS_SQ_BINARY_QUATERNION_INPLACE_FULL(true_divide, divide) */
/* QQ_QS_SQ_BINARY_QUATERNION_INPLACE_FULL(floor_divide, divide) */
QQ_QS_SQ_BINARY_QUATERNION_INPLACE(power)
static PyObject *
pyquaternion__reduce(PyQuaternion* self)
{
/* printf("\n\n\nI'm trying, most of all!\n\n\n"); */
return Py_BuildValue("O(OOOO)", Py_TYPE(self),
PyFloat_FromDouble(self->obval.w), PyFloat_FromDouble(self->obval.x),
PyFloat_FromDouble(self->obval.y), PyFloat_FromDouble(self->obval.z));
}
static PyObject *
pyquaternion_getstate(PyQuaternion* self, PyObject* args)
{
/* printf("\n\n\nI'm Trying, OKAY?\n\n\n"); */
if (!PyArg_ParseTuple(args, ":getstate"))
return NULL;
return Py_BuildValue("OOOO",
PyFloat_FromDouble(self->obval.w), PyFloat_FromDouble(self->obval.x),
PyFloat_FromDouble(self->obval.y), PyFloat_FromDouble(self->obval.z));
}
static PyObject *
pyquaternion_setstate(PyQuaternion* self, PyObject* args)
{
/* printf("\n\n\nI'm Trying, TOO!\n\n\n"); */
quaternion* q;
q = &(self->obval);
if (!PyArg_ParseTuple(args, "dddd:setstate", &q->w, &q->x, &q->y, &q->z)) {
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// This is an array of methods (member functions) that will be
// available to use on the quaternion objects in python. This is
// packaged up here, and will be used in the `tp_methods` field when
// definining the PyQuaternion_Type below.
PyMethodDef pyquaternion_methods[] = {
// Unary bool returners
{"nonzero", pyquaternion_nonzero, METH_NOARGS,
"True if the quaternion has all zero components"},
{"isnan", pyquaternion_isnan, METH_NOARGS,
"True if the quaternion has any NAN components"},
{"isinf", pyquaternion_isinf, METH_NOARGS,
"True if the quaternion has any INF components"},
{"isfinite", pyquaternion_isfinite, METH_NOARGS,
"True if the quaternion has all finite components"},
// Binary bool returners
{"equal", pyquaternion_equal, METH_O,
"True if the quaternions are PRECISELY equal"},
{"not_equal", pyquaternion_not_equal, METH_O,
"True if the quaternions are not PRECISELY equal"},
{"less", pyquaternion_less, METH_O,
"Strict dictionary ordering"},
{"greater", pyquaternion_greater, METH_O,
"Strict dictionary ordering"},
{"less_equal", pyquaternion_less_equal, METH_O,
"Dictionary ordering"},
{"greater_equal", pyquaternion_greater_equal, METH_O,
"Dictionary ordering"},
// Unary float returners
{"absolute", pyquaternion_absolute, METH_NOARGS,
"Absolute value of quaternion"},
{"abs", pyquaternion_absolute, METH_NOARGS,
"Absolute value of quaternion"},
{"norm", pyquaternion_norm, METH_NOARGS,
"Norm (square of the absolute value) of quaternion"},
{"angle", pyquaternion_angle, METH_NOARGS,
"Angle through which rotor rotates"},
// Unary quaternion returners
// {"negative", pyquaternion_negative, METH_NOARGS,
// "Return the negated quaternion"},
// {"positive", pyquaternion_positive, METH_NOARGS,
// "Return the quaternion itself"},
{"conjugate", pyquaternion_conjugate, METH_NOARGS,
"Return the complex conjugate of the quaternion"},
{"conj", pyquaternion_conjugate, METH_NOARGS,
"Return the complex conjugate of the quaternion"},
{"inverse", pyquaternion_inverse, METH_NOARGS,
"Return the inverse of the quaternion"},
{"sqrt", pyquaternion_sqrt, METH_NOARGS,
"Return the square-root of the quaternion"},
{"log", pyquaternion_log, METH_NOARGS,
"Return the logarithm (base e) of the quaternion"},
{"exp", pyquaternion_exp, METH_NOARGS,
"Return the exponential of the quaternion (e**q)"},
{"normalized", pyquaternion_normalized, METH_NOARGS,
"Return a normalized copy of the quaternion"},
{"x_parity_conjugate", pyquaternion_x_parity_conjugate, METH_NOARGS,
"Reflect across y-z plane (note spinorial character)"},
{"x_parity_symmetric_part", pyquaternion_x_parity_symmetric_part, METH_NOARGS,
"Part invariant under reflection across y-z plane (note spinorial character)"},
{"x_parity_antisymmetric_part", pyquaternion_x_parity_antisymmetric_part, METH_NOARGS,
"Part anti-invariant under reflection across y-z plane (note spinorial character)"},
{"y_parity_conjugate", pyquaternion_y_parity_conjugate, METH_NOARGS,
"Reflect across x-z plane (note spinorial character)"},
{"y_parity_symmetric_part", pyquaternion_y_parity_symmetric_part, METH_NOARGS,
"Part invariant under reflection across x-z plane (note spinorial character)"},
{"y_parity_antisymmetric_part", pyquaternion_y_parity_antisymmetric_part, METH_NOARGS,
"Part anti-invariant under reflection across x-z plane (note spinorial character)"},
{"z_parity_conjugate", pyquaternion_z_parity_conjugate, METH_NOARGS,
"Reflect across x-y plane (note spinorial character)"},
{"z_parity_symmetric_part", pyquaternion_z_parity_symmetric_part, METH_NOARGS,
"Part invariant under reflection across x-y plane (note spinorial character)"},
{"z_parity_antisymmetric_part", pyquaternion_z_parity_antisymmetric_part, METH_NOARGS,
"Part anti-invariant under reflection across x-y plane (note spinorial character)"},
{"parity_conjugate", pyquaternion_parity_conjugate, METH_NOARGS,
"Reflect all dimensions (note spinorial character)"},
{"parity_symmetric_part", pyquaternion_parity_symmetric_part, METH_NOARGS,
"Part invariant under negation of all vectors (note spinorial character)"},
{"parity_antisymmetric_part", pyquaternion_parity_antisymmetric_part, METH_NOARGS,
"Part anti-invariant under negation of all vectors (note spinorial character)"},
// Quaternion-quaternion binary quaternion returners
// {"add", pyquaternion_add, METH_O,
// "Componentwise addition"},
// {"subtract", pyquaternion_subtract, METH_O,
// "Componentwise subtraction"},
{"copysign", pyquaternion_copysign, METH_O,
"Componentwise copysign"},
// Quaternion-quaternion or quaternion-scalar binary quaternion returners
// {"multiply", pyquaternion_multiply, METH_O,
// "Standard (geometric) quaternion product"},
// {"divide", pyquaternion_divide, METH_O,
// "Standard (geometric) quaternion division"},
// {"power", pyquaternion_power, METH_O,
// "q.power(p) = (q.log() * p).exp()"},
{"__reduce__", (PyCFunction)pyquaternion__reduce, METH_NOARGS,
"Return state information for pickling."},
{"__getstate__", (PyCFunction)pyquaternion_getstate, METH_VARARGS,
"Return state information for pickling."},
{"__setstate__", (PyCFunction)pyquaternion_setstate, METH_VARARGS,
"Reconstruct state information from pickle."},
{NULL}
};
static PyObject* pyquaternion_num_power(PyObject* a, PyObject* b, PyObject *c) { return pyquaternion_power(a,b); }
static PyObject* pyquaternion_num_inplace_power(PyObject* a, PyObject* b, PyObject *c) { return pyquaternion_inplace_power(a,b); }
static PyObject* pyquaternion_num_negative(PyObject* a) { return pyquaternion_negative(a,NULL); }
static PyObject* pyquaternion_num_positive(PyObject* a) { return pyquaternion_positive(a,NULL); }
static PyObject* pyquaternion_num_absolute(PyObject* a) { return pyquaternion_absolute(a,NULL); }
static PyObject* pyquaternion_num_inverse(PyObject* a) { return pyquaternion_inverse(a,NULL); }
static int pyquaternion_num_nonzero(PyObject* a) {
quaternion q = ((PyQuaternion*)a)->obval;
return quaternion_nonzero(q);
}
static PyNumberMethods pyquaternion_as_number = {
pyquaternion_add, // nb_add
pyquaternion_subtract, // nb_subtract
pyquaternion_multiply, // nb_multiply
#if PY_MAJOR_VERSION < 3
pyquaternion_divide, // nb_divide
#endif
0, // nb_remainder
0, // nb_divmod
pyquaternion_num_power, // nb_power
pyquaternion_num_negative, // nb_negative
pyquaternion_num_positive, // nb_positive
pyquaternion_num_absolute, // nb_absolute
pyquaternion_num_nonzero, // nb_nonzero
pyquaternion_num_inverse, // nb_invert
0, // nb_lshift
0, // nb_rshift
0, // nb_and
0, // nb_xor
0, // nb_or
#if PY_MAJOR_VERSION < 3
0, // nb_coerce
#endif
0, // nb_int
#if PY_MAJOR_VERSION >= 3
0, // nb_reserved
#else
0, // nb_long
#endif
0, // nb_float
#if PY_MAJOR_VERSION < 3
0, // nb_oct
0, // nb_hex
#endif
pyquaternion_inplace_add, // nb_inplace_add
pyquaternion_inplace_subtract, // nb_inplace_subtract
pyquaternion_inplace_multiply, // nb_inplace_multiply
#if PY_MAJOR_VERSION < 3
pyquaternion_inplace_divide, // nb_inplace_divide
#endif
0, // nb_inplace_remainder
pyquaternion_num_inplace_power, // nb_inplace_power
0, // nb_inplace_lshift
0, // nb_inplace_rshift
0, // nb_inplace_and
0, // nb_inplace_xor
0, // nb_inplace_or
pyquaternion_divide, // nb_floor_divide
pyquaternion_divide, // nb_true_divide
pyquaternion_inplace_divide, // nb_inplace_floor_divide
pyquaternion_inplace_divide, // nb_inplace_true_divide
0, // nb_index
#if PY_MAJOR_VERSION >= 3
#if PY_MINOR_VERSION >= 5
0, // nb_matrix_multiply
0, // nb_inplace_matrix_multiply
#endif
#endif
};
// This is an array of members (member data) that will be available to
// use on the quaternion objects in python. This is packaged up here,
// and will be used in the `tp_members` field when definining the
// PyQuaternion_Type below.
PyMemberDef pyquaternion_members[] = {
{"real", T_DOUBLE, offsetof(PyQuaternion, obval.w), 0,
"The real component of the quaternion"},
{"w", T_DOUBLE, offsetof(PyQuaternion, obval.w), 0,
"The real component of the quaternion"},
{"x", T_DOUBLE, offsetof(PyQuaternion, obval.x), 0,
"The first imaginary component of the quaternion"},
{"y", T_DOUBLE, offsetof(PyQuaternion, obval.y), 0,
"The second imaginary component of the quaternion"},
{"z", T_DOUBLE, offsetof(PyQuaternion, obval.z), 0,
"The third imaginary component of the quaternion"},
{NULL}
};
// The quaternion can be conveniently separated into two complex
// numbers, which we call 'part a' and 'part b'. These are useful in
// writing Wigner's D matrices directly in terms of quaternions. This
// is essentially the column-vector presentation of spinors.
static PyObject *
pyquaternion_get_part_a(PyObject *self, void *closure)
{
return (PyObject*) PyComplex_FromDoubles(((PyQuaternion *)self)->obval.w, ((PyQuaternion *)self)->obval.z);
}
static PyObject *
pyquaternion_get_part_b(PyObject *self, void *closure)
{
return (PyObject*) PyComplex_FromDoubles(((PyQuaternion *)self)->obval.y, ((PyQuaternion *)self)->obval.x);
}
// This will be defined as a member function on the quaternion
// objects, so that calling "vec" will return a numpy array
// with the last three components of the quaternion.
static PyObject *
pyquaternion_get_vec(PyObject *self, void *closure)
{
quaternion *q = &((PyQuaternion *)self)->obval;
int nd = 1;
npy_intp dims[1] = { 3 };
int typenum = NPY_DOUBLE;
PyObject* components = PyArray_SimpleNewFromData(nd, dims, typenum, &(q->x));
Py_INCREF(self);
PyArray_SetBaseObject((PyArrayObject*)components, self);
return components;
}
// This will be defined as a member function on the quaternion
// objects, so that calling `q.vec = [1,2,3]`, for example,
// will set the vector components appropriately.
static int
pyquaternion_set_vec(PyObject *self, PyObject *value, void *closure)
{
PyObject *element;
quaternion *q = &((PyQuaternion *)self)->obval;
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot set quaternion to empty value");
return -1;
}
if (! (PySequence_Check(value) && PySequence_Size(value)==3) ) {
PyErr_SetString(PyExc_TypeError,
"A quaternion's vector components must be set to something of length 3");
return -1;
}
/* PySequence_GetItem INCREFs element. */
element = PySequence_GetItem(value, 0);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->x = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(value, 1);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->y = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(value, 2);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->z = PyFloat_AsDouble(element);
Py_DECREF(element);
return 0;
}
// This will be defined as a member function on the quaternion
// objects, so that calling "components" will return a numpy array
// with the components of the quaternion.
static PyObject *
pyquaternion_get_components(PyObject *self, void *closure)
{
quaternion *q = &((PyQuaternion *)self)->obval;
int nd = 1;
npy_intp dims[1] = { 4 };
int typenum = NPY_DOUBLE;
PyObject* components = PyArray_SimpleNewFromData(nd, dims, typenum, &(q->w));
Py_INCREF(self);
PyArray_SetBaseObject((PyArrayObject*)components, self);
return components;
}
// This will be defined as a member function on the quaternion
// objects, so that calling `q.components = [1,2,3,4]`, for example,
// will set the components appropriately.
static int
pyquaternion_set_components(PyObject *self, PyObject *value, void *closure)
{
PyObject *element;
quaternion *q = &((PyQuaternion *)self)->obval;
if (value == NULL) {
PyErr_SetString(PyExc_ValueError, "Cannot set quaternion to empty value");
return -1;
}
if (! (PySequence_Check(value) && PySequence_Size(value)==4) ) {
PyErr_SetString(PyExc_TypeError,
"A quaternion's components must be set to something of length 4");
return -1;
}
element = PySequence_GetItem(value, 0);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->w = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(value, 1);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->x = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(value, 2);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->y = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(value, 3);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q->z = PyFloat_AsDouble(element);
Py_DECREF(element);
return 0;
}
// This collects the methods for getting and setting elements of the
// quaternion. This is packaged up here, and will be used in the
// `tp_getset` field when definining the PyQuaternion_Type
// below.
PyGetSetDef pyquaternion_getset[] = {
{"a", pyquaternion_get_part_a, NULL,
"The complex number (w+i*z)", NULL},
{"b", pyquaternion_get_part_b, NULL,
"The complex number (y+i*x)", NULL},
{"imag", pyquaternion_get_vec, pyquaternion_set_vec,
"The vector part (x,y,z) of the quaternion as a numpy array", NULL},
{"vec", pyquaternion_get_vec, pyquaternion_set_vec,
"The vector part (x,y,z) of the quaternion as a numpy array", NULL},
{"components", pyquaternion_get_components, pyquaternion_set_components,
"The components (w,x,y,z) of the quaternion as a numpy array", NULL},
{NULL}
};
static PyObject*
pyquaternion_richcompare(PyObject* a, PyObject* b, int op)
{
quaternion x = {0};
quaternion y = {0};
int result = 0;
PyQuaternion_AsQuaternion(x,a);
PyQuaternion_AsQuaternion(y,b);
#define COMPARISONOP(py,op) case py: result = quaternion_##op(x,y); break;
switch (op) {
COMPARISONOP(Py_LT,less)
COMPARISONOP(Py_LE,less_equal)
COMPARISONOP(Py_EQ,equal)
COMPARISONOP(Py_NE,not_equal)
COMPARISONOP(Py_GT,greater)
COMPARISONOP(Py_GE,greater_equal)
};
#undef COMPARISONOP
return PyBool_FromLong(result);
}
static long
pyquaternion_hash(PyObject *o)
{
quaternion q = ((PyQuaternion *)o)->obval;
long value = 0x456789;
value = (10000004 * value) ^ _Py_HashDouble(q.w);
value = (10000004 * value) ^ _Py_HashDouble(q.x);
value = (10000004 * value) ^ _Py_HashDouble(q.y);
value = (10000004 * value) ^ _Py_HashDouble(q.z);
if (value == -1)
value = -2;
return value;
}
static PyObject *
pyquaternion_repr(PyObject *o)
{
char str[128];
quaternion q = ((PyQuaternion *)o)->obval;
sprintf(str, "quaternion(%.15g, %.15g, %.15g, %.15g)", q.w, q.x, q.y, q.z);
return PyUString_FromString(str);
}
static PyObject *
pyquaternion_str(PyObject *o)
{
char str[128];
quaternion q = ((PyQuaternion *)o)->obval;
sprintf(str, "quaternion(%.15g, %.15g, %.15g, %.15g)", q.w, q.x, q.y, q.z);
return PyUString_FromString(str);
}
// This establishes the quaternion as a python object (not yet a numpy
// scalar type). The name may be a little counterintuitive; the idea
// is that this will be a type that can be used as an array dtype.
// Note that many of the slots below will be filled later, after the
// corresponding functions are defined.
static PyTypeObject PyQuaternion_Type = {
#if PY_MAJOR_VERSION >= 3
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyObject_HEAD_INIT(NULL)
0, // ob_size
#endif
"quaternion", // tp_name
sizeof(PyQuaternion), // tp_basicsize
0, // tp_itemsize
0, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
#if PY_MAJOR_VERSION >= 3
0, // tp_reserved
#else
0, // tp_compare
#endif
pyquaternion_repr, // tp_repr
&pyquaternion_as_number, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
pyquaternion_hash, // tp_hash
0, // tp_call
pyquaternion_str, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
#if PY_MAJOR_VERSION >= 3
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
#else
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES, // tp_flags
#endif
0, // tp_doc
0, // tp_traverse
0, // tp_clear
pyquaternion_richcompare, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
pyquaternion_methods, // tp_methods
pyquaternion_members, // tp_members
pyquaternion_getset, // tp_getset
0, // tp_base; will be reset to &PyGenericArrType_Type after numpy import
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
pyquaternion_init, // tp_init
0, // tp_alloc
pyquaternion_new, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0, // tp_weaklist
0, // tp_del
#if PY_VERSION_HEX >= 0x02060000
0, // tp_version_tag
#endif
};
// Functions implementing internal features. Not all of these function
// pointers must be defined for a given type. The required members are
// nonzero, copyswap, copyswapn, setitem, getitem, and cast.
static PyArray_ArrFuncs _PyQuaternion_ArrFuncs;
static npy_bool
QUATERNION_nonzero (char *ip, PyArrayObject *ap)
{
quaternion q;
quaternion zero = {0,0,0,0};
if (ap == NULL || PyArray_ISBEHAVED_RO(ap)) {
q = *(quaternion *)ip;
}
else {
PyArray_Descr *descr;
descr = PyArray_DescrFromType(NPY_DOUBLE);
descr->f->copyswap(&q.w, ip, !PyArray_ISNOTSWAPPED(ap), NULL);
descr->f->copyswap(&q.x, ip+8, !PyArray_ISNOTSWAPPED(ap), NULL);
descr->f->copyswap(&q.y, ip+16, !PyArray_ISNOTSWAPPED(ap), NULL);
descr->f->copyswap(&q.z, ip+24, !PyArray_ISNOTSWAPPED(ap), NULL);
Py_DECREF(descr);
}
return (npy_bool) !quaternion_equal(q, zero);
}
static void
QUATERNION_copyswap(quaternion *dst, quaternion *src,
int swap, void *NPY_UNUSED(arr))
{
PyArray_Descr *descr;
descr = PyArray_DescrFromType(NPY_DOUBLE);
descr->f->copyswapn(dst, sizeof(double), src, sizeof(double), 4, swap, NULL);
Py_DECREF(descr);
}
static void
QUATERNION_copyswapn(quaternion *dst, npy_intp dstride,
quaternion *src, npy_intp sstride,
npy_intp n, int swap, void *NPY_UNUSED(arr))
{
PyArray_Descr *descr;
descr = PyArray_DescrFromType(NPY_DOUBLE);
descr->f->copyswapn(&dst->w, dstride, &src->w, sstride, n, swap, NULL);
descr->f->copyswapn(&dst->x, dstride, &src->x, sstride, n, swap, NULL);
descr->f->copyswapn(&dst->y, dstride, &src->y, sstride, n, swap, NULL);
descr->f->copyswapn(&dst->z, dstride, &src->z, sstride, n, swap, NULL);
Py_DECREF(descr);
}
static int QUATERNION_setitem(PyObject* item, void* data, void* ap)
{
PyObject *element;
quaternion q = {0};
if(PyQuaternion_Check(item)) {
memcpy(data,&(((PyQuaternion *)item)->obval),sizeof(quaternion));
} else if(PySequence_Check(item) && PySequence_Length(item)==4) {
element = PySequence_GetItem(item, 0);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q.w = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(item, 1);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q.x = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(item, 2);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q.y = PyFloat_AsDouble(element);
Py_DECREF(element);
element = PySequence_GetItem(item, 3);
if(element == NULL) { return -1; } /* Not a sequence, or other failure */
q.z = PyFloat_AsDouble(element);
Py_DECREF(element);
} else {
PyErr_SetString(PyExc_TypeError,
"Unknown input to QUATERNION_setitem");
return -1;
}
return 0;
}
// When a numpy array of dtype=quaternion is indexed, this function is
// called, returning a new quaternion object with a copy of the
// data... sometimes...
static PyObject *
QUATERNION_getitem(void* data, void* arr)
{
quaternion q;
memcpy(&q,data,sizeof(quaternion));
return PyQuaternion_FromQuaternion(q);
}
static int
QUATERNION_compare(quaternion *pa, quaternion *pb, PyArrayObject *NPY_UNUSED(ap))
{
quaternion a = *pa, b = *pb;
npy_bool anan, bnan;
int ret;
anan = quaternion_isnan(a);
bnan = quaternion_isnan(b);
if (anan) {
ret = bnan ? 0 : -1;
} else if (bnan) {
ret = 1;
} else if(quaternion_less(a, b)) {
ret = -1;
} else if(quaternion_less(b, a)) {
ret = 1;
} else {
ret = 0;
}
return ret;
}
static int
QUATERNION_argmax(quaternion *ip, npy_intp n, npy_intp *max_ind, PyArrayObject *NPY_UNUSED(aip))
{
npy_intp i;
quaternion mp = *ip;
*max_ind = 0;
if (quaternion_isnan(mp)) {
// nan encountered; it's maximal
return 0;
}
for (i = 1; i < n; i++) {
ip++;
//Propagate nans, similarly as max() and min()
if (!(quaternion_less_equal(*ip, mp))) { // negated, for correct nan handling
mp = *ip;
*max_ind = i;
if (quaternion_isnan(mp)) {
// nan encountered, it's maximal
break;
}
}
}
return 0;
}
static void
QUATERNION_fillwithscalar(quaternion *buffer, npy_intp length, quaternion *value, void *NPY_UNUSED(ignored))
{
npy_intp i;
quaternion val = *value;
for (i = 0; i < length; ++i) {