/
ufunc_type_resolution.c
2320 lines (2112 loc) · 77.8 KB
/
ufunc_type_resolution.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
/*
* NOTE: The type resolution defined in this file is considered legacy.
*
* The new mechanism separates type resolution and promotion into two
* distinct steps, as per NEP 43.
* Further, the functions in this file rely on the operands rather than
* only the DTypes/descriptors. They are still called and at this point
* vital (NumPy ~1.21), but should hopefully become largely irrelevant very
* quickly.
*
* At that point, this file should be deletable in its entirety.
*
*
* This file implements type resolution for NumPy element-wise ufuncs.
* This mechanism is still backwards-compatible with the pre-existing
* legacy mechanism, so performs much slower than is necessary.
*
* Written by Mark Wiebe (mwwiebe@gmail.com)
* Copyright (c) 2011 by Enthought, Inc.
*
* See LICENSE.txt for the license.
*/
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#define _UMATHMODULE
#define PY_SSIZE_T_CLEAN
#include <Python.h>
// printif debug tracing
#ifndef NPY_UF_DBG_TRACING
#define NPY_UF_DBG_TRACING 0
#endif
#include "npy_config.h"
#include "npy_pycompat.h"
#include "npy_import.h"
#include "numpy/ufuncobject.h"
#include "ufunc_type_resolution.h"
#include "ufunc_object.h"
#include "common.h"
#include "convert_datatype.h"
#include "dtypemeta.h"
#include "mem_overlap.h"
#if defined(HAVE_CBLAS)
#include "cblasfuncs.h"
#endif
#include <stdbool.h>
#include <arrayobject.h>
static PyObject *
npy_casting_to_py_object(NPY_CASTING casting)
{
switch (casting) {
case NPY_NO_CASTING:
return PyUnicode_FromString("no");
case NPY_EQUIV_CASTING:
return PyUnicode_FromString("equiv");
case NPY_SAFE_CASTING:
return PyUnicode_FromString("safe");
case NPY_SAME_KIND_CASTING:
return PyUnicode_FromString("same_kind");
case NPY_UNSAFE_CASTING:
return PyUnicode_FromString("unsafe");
default:
return PyLong_FromLong(casting);
}
}
/**
* Always returns -1 to indicate the exception was raised, for convenience
*/
static int
raise_binary_type_reso_error(PyUFuncObject *ufunc, PyArrayObject **operands) {
static PyObject *exc_type = NULL;
PyObject *exc_value;
npy_cache_import(
"numpy._core._exceptions", "_UFuncBinaryResolutionError",
&exc_type);
if (exc_type == NULL) {
return -1;
}
/* produce an error object */
exc_value = Py_BuildValue(
"O(OO)", ufunc,
(PyObject *)PyArray_DESCR(operands[0]),
(PyObject *)PyArray_DESCR(operands[1])
);
if (exc_value == NULL){
return -1;
}
PyErr_SetObject(exc_type, exc_value);
Py_DECREF(exc_value);
return -1;
}
/** Helper function to raise UFuncNoLoopError
* Always returns -1 to indicate the exception was raised, for convenience
*/
NPY_NO_EXPORT int
raise_no_loop_found_error(
PyUFuncObject *ufunc, PyObject **dtypes, int ambiguous_promoter)
{
static PyObject *exc_type = NULL;
npy_cache_import(
"numpy._core._exceptions", "_UFuncNoLoopError",
&exc_type);
if (exc_type == NULL) {
return -1;
}
PyObject *dtypes_tup = PyArray_TupleFromItems(ufunc->nargs, dtypes, 1);
if (dtypes_tup == NULL) {
return -1;
}
/* produce an error object */
PyObject *exc_value = PyTuple_Pack(3, ufunc, dtypes_tup,
ambiguous_promoter ? Py_True : Py_False);
Py_DECREF(dtypes_tup);
if (exc_value == NULL) {
return -1;
}
PyErr_SetObject(exc_type, exc_value);
Py_DECREF(exc_value);
return -1;
}
static int
raise_casting_error(
PyObject *exc_type,
PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArray_Descr *from,
PyArray_Descr *to,
npy_intp i)
{
PyObject *exc_value;
PyObject *casting_value;
casting_value = npy_casting_to_py_object(casting);
if (casting_value == NULL) {
return -1;
}
exc_value = Py_BuildValue(
"ONOOi",
ufunc,
casting_value,
(PyObject *)from,
(PyObject *)to,
i
);
if (exc_value == NULL){
return -1;
}
PyErr_SetObject(exc_type, exc_value);
Py_DECREF(exc_value);
return -1;
}
/** Helper function to raise UFuncInputCastingError
* Always returns -1 to indicate the exception was raised, for convenience
*/
static int
raise_input_casting_error(
PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArray_Descr *from,
PyArray_Descr *to,
npy_intp i)
{
static PyObject *exc_type = NULL;
npy_cache_import(
"numpy._core._exceptions", "_UFuncInputCastingError",
&exc_type);
if (exc_type == NULL) {
return -1;
}
return raise_casting_error(exc_type, ufunc, casting, from, to, i);
}
/** Helper function to raise UFuncOutputCastingError
* Always returns -1 to indicate the exception was raised, for convenience
*/
static int
raise_output_casting_error(
PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArray_Descr *from,
PyArray_Descr *to,
npy_intp i)
{
static PyObject *exc_type = NULL;
npy_cache_import(
"numpy._core._exceptions", "_UFuncOutputCastingError",
&exc_type);
if (exc_type == NULL) {
return -1;
}
return raise_casting_error(exc_type, ufunc, casting, from, to, i);
}
/*UFUNC_API
*
* Validates that the input operands can be cast to
* the input types, and the output types can be cast to
* the output operands where provided.
*
* Returns 0 on success, -1 (with exception raised) on validation failure.
*/
NPY_NO_EXPORT int
PyUFunc_ValidateCasting(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyArray_Descr **dtypes)
{
int i, nin = ufunc->nin, nop = nin + ufunc->nout;
for (i = 0; i < nop; ++i) {
if (i < nin) {
if (!PyArray_CanCastArrayTo(operands[i], dtypes[i], casting)) {
return raise_input_casting_error(
ufunc, casting, PyArray_DESCR(operands[i]), dtypes[i], i);
}
} else if (operands[i] != NULL) {
if (!PyArray_CanCastTypeTo(dtypes[i],
PyArray_DESCR(operands[i]), casting)) {
return raise_output_casting_error(
ufunc, casting, dtypes[i], PyArray_DESCR(operands[i]), i);
}
}
}
return 0;
}
/*
* Same as `PyUFunc_ValidateCasting` but only checks output casting.
*/
NPY_NO_EXPORT int
PyUFunc_ValidateOutCasting(PyUFuncObject *ufunc,
NPY_CASTING casting, PyArrayObject **operands, PyArray_Descr **dtypes)
{
int i, nin = ufunc->nin, nop = nin + ufunc->nout;
for (i = nin; i < nop; ++i) {
if (operands[i] == NULL) {
continue;
}
if (!PyArray_CanCastTypeTo(dtypes[i],
PyArray_DESCR(operands[i]), casting)) {
return raise_output_casting_error(
ufunc, casting, dtypes[i], PyArray_DESCR(operands[i]), i);
}
}
return 0;
}
/*UFUNC_API
*
* This function applies the default type resolution rules
* for the provided ufunc.
*
* Returns 0 on success, -1 on error.
*/
NPY_NO_EXPORT int
PyUFunc_DefaultTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
int i, nop = ufunc->nin + ufunc->nout;
int retval = 0, any_object = 0;
NPY_CASTING input_casting;
for (i = 0; i < nop; ++i) {
if (operands[i] != NULL &&
PyTypeNum_ISOBJECT(PyArray_DESCR(operands[i])->type_num)) {
any_object = 1;
break;
}
}
/*
* Decide the casting rules for inputs and outputs. We want
* NPY_SAFE_CASTING or stricter, so that the loop selection code
* doesn't choose an integer loop for float inputs, or a float32
* loop for float64 inputs.
*/
input_casting = (casting > NPY_SAFE_CASTING) ? NPY_SAFE_CASTING : casting;
if (type_tup == NULL) {
/* Find the best ufunc inner loop, and fill in the dtypes */
retval = linear_search_type_resolver(ufunc, operands,
input_casting, casting, any_object,
out_dtypes);
} else {
/* Find the specified ufunc inner loop, and fill in the dtypes */
retval = type_tuple_type_resolver(ufunc, type_tup,
operands, input_casting, casting, any_object, out_dtypes);
}
return retval;
}
/*
* This function applies special type resolution rules for the case
* where all the functions have the pattern XX->bool, using
* PyArray_ResultType instead of a linear search to get the best
* loop.
*
* Returns 0 on success, -1 on error.
*/
NPY_NO_EXPORT int
PyUFunc_SimpleBinaryComparisonTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
int i, type_num1, type_num2;
const char *ufunc_name = ufunc_get_name_cstr(ufunc);
if (ufunc->nin != 2 || ufunc->nout != 1) {
PyErr_Format(PyExc_RuntimeError, "ufunc %s is configured "
"to use binary comparison type resolution but has "
"the wrong number of inputs or outputs",
ufunc_name);
return -1;
}
/*
* Use the default type resolution if there's a custom data type
* or object arrays.
*/
type_num1 = PyArray_DESCR(operands[0])->type_num;
type_num2 = PyArray_DESCR(operands[1])->type_num;
if (type_num1 >= NPY_NTYPES_LEGACY || type_num2 >= NPY_NTYPES_LEGACY ||
type_num1 == NPY_OBJECT || type_num2 == NPY_OBJECT) {
return PyUFunc_DefaultTypeResolver(ufunc, casting, operands,
type_tup, out_dtypes);
}
if (type_tup == NULL) {
if (PyArray_ISDATETIME(operands[0])
&& PyArray_ISDATETIME(operands[1])
&& type_num1 != type_num2) {
/*
* Reject mixed datetime and timedelta explicitly, this was always
* implicitly rejected because casting fails (except with
* `casting="unsafe"` admittedly).
* This is required to ensure that `==` and `!=` can correctly
* detect that they should return a result array of False/True.
*/
return raise_binary_type_reso_error(ufunc, operands);
}
/*
* This check is required to avoid a potential FutureWarning that
* ResultType would give for number->string promotions.
* (We never supported flexible dtypes here.)
*/
else if (!PyArray_ISFLEXIBLE(operands[0]) &&
!PyArray_ISFLEXIBLE(operands[1])) {
out_dtypes[0] = PyArray_ResultType(2, operands, 0, NULL);
if (out_dtypes[0] == NULL) {
return -1;
}
if (PyArray_ISINTEGER(operands[0])
&& PyArray_ISINTEGER(operands[1])
&& !PyDataType_ISINTEGER(out_dtypes[0])) {
/*
* NumPy promotion allows uint+int to go to float, avoid it
* (input must have been a mix of signed and unsigned)
*/
if (PyArray_ISSIGNED(operands[0])) {
Py_SETREF(out_dtypes[0], PyArray_DescrFromType(NPY_LONGLONG));
out_dtypes[1] = PyArray_DescrFromType(NPY_ULONGLONG);
Py_INCREF(out_dtypes[1]);
}
else {
Py_SETREF(out_dtypes[0], PyArray_DescrFromType(NPY_ULONGLONG));
out_dtypes[1] = PyArray_DescrFromType(NPY_LONGLONG);
Py_INCREF(out_dtypes[1]);
}
}
else {
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
}
}
else {
/* Not doing anything will lead to a loop no found error. */
out_dtypes[0] = PyArray_DESCR(operands[0]);
Py_INCREF(out_dtypes[0]);
out_dtypes[1] = PyArray_DESCR(operands[1]);
Py_INCREF(out_dtypes[1]);
}
}
else {
/* Usually a failure, but let the default version handle it */
return PyUFunc_DefaultTypeResolver(ufunc, casting,
operands, type_tup, out_dtypes);
}
/* Output type is always boolean (cannot fail for builtins) */
out_dtypes[2] = PyArray_DescrFromType(NPY_BOOL);
/* Check against the casting rules */
if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) {
for (i = 0; i < 3; ++i) {
Py_DECREF(out_dtypes[i]);
out_dtypes[i] = NULL;
}
return -1;
}
return 0;
}
NPY_NO_EXPORT int
PyUFunc_NegativeTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
int ret;
ret = PyUFunc_SimpleUniformOperationTypeResolver(ufunc, casting, operands,
type_tup, out_dtypes);
if (ret < 0) {
return ret;
}
/* The type resolver would have upcast already */
if (out_dtypes[0]->type_num == NPY_BOOL) {
PyErr_Format(PyExc_TypeError,
"The numpy boolean negative, the `-` operator, is not supported, "
"use the `~` operator or the logical_not function instead.");
return -1;
}
return ret;
}
/*
* The ones_like function shouldn't really be a ufunc, but while it
* still is, this provides type resolution that always forces UNSAFE
* casting.
*/
NPY_NO_EXPORT int
PyUFunc_OnesLikeTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING NPY_UNUSED(casting),
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
return PyUFunc_SimpleUniformOperationTypeResolver(ufunc,
NPY_UNSAFE_CASTING,
operands, type_tup, out_dtypes);
}
/*
* This function applies special type resolution rules for the case
* where all of the types in the signature are the same, eg XX->X or XX->XX.
* It uses PyArray_ResultType instead of a linear search to get the best
* loop.
*
* Note that a simpler linear search through the functions loop
* is still done, but switching to a simple array lookup for
* built-in types would be better at some point.
*
* Returns 0 on success, -1 on error.
*/
NPY_NO_EXPORT int
PyUFunc_SimpleUniformOperationTypeResolver(
PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
const char *ufunc_name = ufunc_get_name_cstr(ufunc);
if (ufunc->nin < 1) {
PyErr_Format(PyExc_RuntimeError, "ufunc %s is configured "
"to use uniform operation type resolution but has "
"no inputs",
ufunc_name);
return -1;
}
int nop = ufunc->nin + ufunc->nout;
/*
* There's a custom data type or an object array
*/
bool has_custom_or_object = false;
for (int iop = 0; iop < ufunc->nin; iop++) {
int type_num = PyArray_DESCR(operands[iop])->type_num;
if (type_num >= NPY_NTYPES_LEGACY || type_num == NPY_OBJECT) {
has_custom_or_object = true;
break;
}
}
if (has_custom_or_object) {
return PyUFunc_DefaultTypeResolver(ufunc, casting, operands,
type_tup, out_dtypes);
}
if (type_tup == NULL) {
/* PyArray_ResultType forgets to force a byte order when n == 1 */
if (ufunc->nin == 1){
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[0]));
}
else {
int iop;
npy_bool has_flexible = 0;
npy_bool has_object = 0;
for (iop = 0; iop < ufunc->nin; iop++) {
if (PyArray_ISOBJECT(operands[iop])) {
has_object = 1;
}
if (PyArray_ISFLEXIBLE(operands[iop])) {
has_flexible = 1;
}
}
if (NPY_UNLIKELY(has_flexible && !has_object)) {
/*
* DEPRECATED NumPy 1.20, 2020-12.
* This check is required to avoid the FutureWarning that
* ResultType will give for number->string promotions.
* (We never supported flexible dtypes here.)
*/
for (iop = 0; iop < ufunc->nin; iop++) {
out_dtypes[iop] = PyArray_DESCR(operands[iop]);
Py_INCREF(out_dtypes[iop]);
}
raise_no_loop_found_error(ufunc, (PyObject **)out_dtypes, 0);
for (iop = 0; iop < ufunc->nin; iop++) {
Py_DECREF(out_dtypes[iop]);
out_dtypes[iop] = NULL;
}
return -1;
}
out_dtypes[0] = PyArray_ResultType(ufunc->nin, operands, 0, NULL);
}
if (out_dtypes[0] == NULL) {
return -1;
}
}
else {
/*
* This is a fast-path, since all descriptors will be identical, mainly
* when only a single descriptor was passed (which would set the out
* one in the tuple), there is no need to check all loops.
* Note that this also allows (None, None, float64) to resolve to
* (float64, float64, float64), even when the inputs do not match,
* i.e. fixing the output part of the signature can fix all of them.
* This is necessary to support `nextafter(1., inf, dtype=float32)`,
* where it is "clear" we want to cast 1. and inf to float32.
*/
PyArray_Descr *descr = NULL;
if (PyTuple_CheckExact(type_tup) &&
PyTuple_GET_SIZE(type_tup) == nop) {
for (int i = 0; i < nop; i++) {
PyObject *item = PyTuple_GET_ITEM(type_tup, i);
if (item == Py_None) {
if (i < ufunc->nin) {
continue;
}
/* All outputs must be set (this could be relaxed) */
descr = NULL;
break;
}
if (!PyArray_DescrCheck(item)) {
/* Defer to default resolver (will raise an error there) */
descr = NULL;
break;
}
if (descr != NULL && descr != (PyArray_Descr *)item) {
/* Descriptor mismatch: try with default (probable error) */
descr = NULL;
break;
}
descr = (PyArray_Descr *)item;
}
}
if (descr == NULL) {
/* in all bad/unlikely cases, use the default type resolver: */
return PyUFunc_DefaultTypeResolver(ufunc, casting,
operands, type_tup, out_dtypes);
}
else if (descr->type_num == PyArray_DESCR(operands[0])->type_num) {
/* Prefer the input descriptor if it matches (preserve metadata) */
descr = PyArray_DESCR(operands[0]);
}
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(descr);
}
/* All types are the same - copy the first one to the rest */
for (int iop = 1; iop < nop; iop++) {
out_dtypes[iop] = out_dtypes[0];
Py_INCREF(out_dtypes[iop]);
}
/* Check against the casting rules */
if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) {
for (int iop = 0; iop < nop; iop++) {
Py_DECREF(out_dtypes[iop]);
out_dtypes[iop] = NULL;
}
return -1;
}
return 0;
}
/*
* This function applies special type resolution rules for the absolute
* ufunc. This ufunc converts complex -> float, so isn't covered
* by the simple unary type resolution.
*
* Returns 0 on success, -1 on error.
*/
NPY_NO_EXPORT int
PyUFunc_AbsoluteTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
/* Use the default for complex types, to find the loop producing float */
if (PyTypeNum_ISCOMPLEX(PyArray_DESCR(operands[0])->type_num)) {
return PyUFunc_DefaultTypeResolver(ufunc, casting, operands,
type_tup, out_dtypes);
}
else {
return PyUFunc_SimpleUniformOperationTypeResolver(ufunc, casting,
operands, type_tup, out_dtypes);
}
}
/*
* This function applies special type resolution rules for the isnat
* ufunc. This ufunc converts datetime/timedelta -> bool, and is not covered
* by the simple unary type resolution.
*
* Returns 0 on success, -1 on error.
*/
NPY_NO_EXPORT int
PyUFunc_IsNaTTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
if (!PyTypeNum_ISDATETIME(PyArray_DESCR(operands[0])->type_num)) {
PyErr_SetString(PyExc_TypeError,
"ufunc 'isnat' is only defined for np.datetime64 and np.timedelta64.");
return -1;
}
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(PyArray_DESCR(operands[0]));
out_dtypes[1] = PyArray_DescrFromType(NPY_BOOL);
return 0;
}
NPY_NO_EXPORT int
PyUFunc_IsFiniteTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
if (!PyTypeNum_ISDATETIME(PyArray_DESCR(operands[0])->type_num)) {
return PyUFunc_DefaultTypeResolver(ufunc, casting, operands,
type_tup, out_dtypes);
}
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(PyArray_DESCR(operands[0]));
out_dtypes[1] = PyArray_DescrFromType(NPY_BOOL);
return 0;
}
/*
* Creates a new NPY_TIMEDELTA dtype, copying the datetime metadata
* from the given dtype.
*
* NOTE: This function is copied from datetime.c in multiarray,
* because umath and multiarray are not linked together.
*/
static PyArray_Descr *
timedelta_dtype_with_copied_meta(PyArray_Descr *dtype)
{
PyArray_Descr *ret;
PyArray_DatetimeMetaData *dst, *src;
PyArray_DatetimeDTypeMetaData *dst_dtmd, *src_dtmd;
ret = PyArray_DescrNewFromType(NPY_TIMEDELTA);
if (ret == NULL) {
return NULL;
}
src_dtmd = (PyArray_DatetimeDTypeMetaData *)((_PyArray_LegacyDescr *)dtype)->c_metadata;
dst_dtmd = (PyArray_DatetimeDTypeMetaData *)((_PyArray_LegacyDescr *)ret)->c_metadata;
src = &(src_dtmd->meta);
dst = &(dst_dtmd->meta);
*dst = *src;
return ret;
}
/*
* This function applies the type resolution rules for addition.
* In particular, there's special cases for string and unicodes, as
* well as a number of special cases with datetime:
* m8[<A>] + m8[<B>] => m8[gcd(<A>,<B>)] + m8[gcd(<A>,<B>)]
* m8[<A>] + int => m8[<A>] + m8[<A>]
* int + m8[<A>] => m8[<A>] + m8[<A>]
* M8[<A>] + int => M8[<A>] + m8[<A>]
* int + M8[<A>] => m8[<A>] + M8[<A>]
* M8[<A>] + m8[<B>] => M8[gcd(<A>,<B>)] + m8[gcd(<A>,<B>)]
* m8[<A>] + M8[<B>] => m8[gcd(<A>,<B>)] + M8[gcd(<A>,<B>)]
* TODO: Non-linear time unit cases require highly special-cased loops
* M8[<A>] + m8[Y|M|B]
* m8[Y|M|B] + M8[<A>]
*/
NPY_NO_EXPORT int
PyUFunc_AdditionTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
int type_num1, type_num2;
int i;
type_num1 = PyArray_DESCR(operands[0])->type_num;
type_num2 = PyArray_DESCR(operands[1])->type_num;
/* Use the default when datetime, timedelta, string and unicode are not involved */
if (!PyTypeNum_ISDATETIME(type_num1) && !PyTypeNum_ISDATETIME(type_num2)
&& !(PyTypeNum_ISSTRING(type_num1) && PyTypeNum_ISSTRING(type_num2))) {
return PyUFunc_SimpleUniformOperationTypeResolver(ufunc, casting,
operands, type_tup, out_dtypes);
}
if ((type_num1 == NPY_STRING && type_num2 == NPY_STRING)
|| (type_num1 == NPY_UNICODE && type_num2 == NPY_UNICODE)) {
// This is wrong, but only the DType matters here (String or Unicode) and
// the loop has the correct implementation itself.
out_dtypes[0] = PyArray_DescrFromType(type_num1);
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
} else if (type_num1 == NPY_TIMEDELTA) {
/* m8[<A>] + m8[<B>] => m8[gcd(<A>,<B>)] + m8[gcd(<A>,<B>)] */
if (type_num2 == NPY_TIMEDELTA) {
out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]),
PyArray_DESCR(operands[1]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
}
/* m8[<A>] + M8[<B>] => m8[gcd(<A>,<B>)] + M8[gcd(<A>,<B>)] */
else if (type_num2 == NPY_DATETIME) {
out_dtypes[1] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]),
PyArray_DESCR(operands[1]));
if (out_dtypes[1] == NULL) {
return -1;
}
/* Make a new NPY_TIMEDELTA, and copy the datetime's metadata */
out_dtypes[0] = timedelta_dtype_with_copied_meta(out_dtypes[1]);
if (out_dtypes[0] == NULL) {
Py_DECREF(out_dtypes[1]);
out_dtypes[1] = NULL;
return -1;
}
out_dtypes[2] = out_dtypes[1];
Py_INCREF(out_dtypes[2]);
}
/* m8[<A>] + int => m8[<A>] + m8[<A>] */
else if (PyTypeNum_ISINTEGER(type_num2) ||
PyTypeNum_ISBOOL(type_num2)) {
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[0]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
type_num2 = NPY_TIMEDELTA;
}
else {
return raise_binary_type_reso_error(ufunc, operands);
}
}
else if (type_num1 == NPY_DATETIME) {
/* M8[<A>] + m8[<B>] => M8[gcd(<A>,<B>)] + m8[gcd(<A>,<B>)] */
if (type_num2 == NPY_TIMEDELTA) {
out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]),
PyArray_DESCR(operands[1]));
if (out_dtypes[0] == NULL) {
return -1;
}
/* Make a new NPY_TIMEDELTA, and copy the datetime's metadata */
out_dtypes[1] = timedelta_dtype_with_copied_meta(out_dtypes[0]);
if (out_dtypes[1] == NULL) {
Py_DECREF(out_dtypes[0]);
out_dtypes[0] = NULL;
return -1;
}
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
}
/* M8[<A>] + int => M8[<A>] + m8[<A>] */
else if (PyTypeNum_ISINTEGER(type_num2) ||
PyTypeNum_ISBOOL(type_num2)) {
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[0]));
if (out_dtypes[0] == NULL) {
return -1;
}
/* Make a new NPY_TIMEDELTA, and copy type1's metadata */
out_dtypes[1] = timedelta_dtype_with_copied_meta(
PyArray_DESCR(operands[0]));
if (out_dtypes[1] == NULL) {
Py_DECREF(out_dtypes[0]);
out_dtypes[0] = NULL;
return -1;
}
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
type_num2 = NPY_TIMEDELTA;
}
else {
return raise_binary_type_reso_error(ufunc, operands);
}
}
else if (PyTypeNum_ISINTEGER(type_num1) || PyTypeNum_ISBOOL(type_num1)) {
/* int + m8[<A>] => m8[<A>] + m8[<A>] */
if (type_num2 == NPY_TIMEDELTA) {
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[1]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
type_num1 = NPY_TIMEDELTA;
}
else if (type_num2 == NPY_DATETIME) {
/* Make a new NPY_TIMEDELTA, and copy type2's metadata */
out_dtypes[0] = timedelta_dtype_with_copied_meta(
PyArray_DESCR(operands[1]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[1]));
if (out_dtypes[1] == NULL) {
Py_DECREF(out_dtypes[0]);
out_dtypes[0] = NULL;
return -1;
}
out_dtypes[2] = out_dtypes[1];
Py_INCREF(out_dtypes[2]);
type_num1 = NPY_TIMEDELTA;
}
else {
return raise_binary_type_reso_error(ufunc, operands);
}
}
else {
return raise_binary_type_reso_error(ufunc, operands);
}
/* Check against the casting rules */
if (PyUFunc_ValidateCasting(ufunc, casting, operands, out_dtypes) < 0) {
for (i = 0; i < 3; ++i) {
Py_DECREF(out_dtypes[i]);
out_dtypes[i] = NULL;
}
return -1;
}
return 0;
}
/*
* This function applies the type resolution rules for subtraction.
* In particular, there are a number of special cases with datetime:
* m8[<A>] - m8[<B>] => m8[gcd(<A>,<B>)] - m8[gcd(<A>,<B>)]
* m8[<A>] - int => m8[<A>] - m8[<A>]
* int - m8[<A>] => m8[<A>] - m8[<A>]
* M8[<A>] - int => M8[<A>] - m8[<A>]
* M8[<A>] - m8[<B>] => M8[gcd(<A>,<B>)] - m8[gcd(<A>,<B>)]
* TODO: Non-linear time unit cases require highly special-cased loops
* M8[<A>] - m8[Y|M|B]
*/
NPY_NO_EXPORT int
PyUFunc_SubtractionTypeResolver(PyUFuncObject *ufunc,
NPY_CASTING casting,
PyArrayObject **operands,
PyObject *type_tup,
PyArray_Descr **out_dtypes)
{
int type_num1, type_num2;
int i;
type_num1 = PyArray_DESCR(operands[0])->type_num;
type_num2 = PyArray_DESCR(operands[1])->type_num;
/* Use the default when datetime and timedelta are not involved */
if (!PyTypeNum_ISDATETIME(type_num1) && !PyTypeNum_ISDATETIME(type_num2)) {
int ret;
ret = PyUFunc_SimpleUniformOperationTypeResolver(ufunc, casting,
operands, type_tup, out_dtypes);
if (ret < 0) {
return ret;
}
/* The type resolver would have upcast already */
if (out_dtypes[0]->type_num == NPY_BOOL) {
PyErr_Format(PyExc_TypeError,
"numpy boolean subtract, the `-` operator, is not supported, "
"use the bitwise_xor, the `^` operator, or the logical_xor "
"function instead.");
return -1;
}
return ret;
}
if (type_num1 == NPY_TIMEDELTA) {
/* m8[<A>] - m8[<B>] => m8[gcd(<A>,<B>)] - m8[gcd(<A>,<B>)] */
if (type_num2 == NPY_TIMEDELTA) {
out_dtypes[0] = PyArray_PromoteTypes(PyArray_DESCR(operands[0]),
PyArray_DESCR(operands[1]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
}
/* m8[<A>] - int => m8[<A>] - m8[<A>] */
else if (PyTypeNum_ISINTEGER(type_num2) ||
PyTypeNum_ISBOOL(type_num2)) {
out_dtypes[0] = NPY_DT_CALL_ensure_canonical(
PyArray_DESCR(operands[0]));
if (out_dtypes[0] == NULL) {
return -1;
}
out_dtypes[1] = out_dtypes[0];
Py_INCREF(out_dtypes[1]);
out_dtypes[2] = out_dtypes[0];
Py_INCREF(out_dtypes[2]);
type_num2 = NPY_TIMEDELTA;
}
else {
return raise_binary_type_reso_error(ufunc, operands);