/
ufunc_object.c
6602 lines (5942 loc) · 215 KB
/
ufunc_object.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
/*
* Python Universal Functions Object -- Math for all types, plus fast
* arrays math
*
* Full description
*
* This supports mathematical (and Boolean) functions on arrays and other python
* objects. Math on large arrays of basic C types is rather efficient.
*
* Travis E. Oliphant 2005, 2006 oliphant@ee.byu.edu (oliphant.travis@ieee.org)
* Brigham Young University
*
* based on the
*
* Original Implementation:
* Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
*
* with inspiration and code from
* Numarray
* Space Science Telescope Institute
* J. Todd Miller
* Perry Greenfield
* Rick White
*
*/
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#define _UMATHMODULE
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stddef.h>
#include "npy_config.h"
#include "npy_pycompat.h"
#include "npy_argparse.h"
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include "numpy/arrayscalars.h"
#include "lowlevel_strided_loops.h"
#include "ufunc_type_resolution.h"
#include "reduction.h"
#include "mem_overlap.h"
#include "npy_hashtable.h"
#include "conversion_utils.h"
#include "ufunc_object.h"
#include "override.h"
#include "npy_import.h"
#include "extobj.h"
#include "arrayobject.h"
#include "arraywrap.h"
#include "common.h"
#include "ctors.h"
#include "dtypemeta.h"
#include "numpyos.h"
#include "dispatching.h"
#include "convert_datatype.h"
#include "legacy_array_method.h"
#include "abstractdtypes.h"
#include "mapping.h"
/* TODO: Only for `NpyIter_GetTransferFlags` until it is public */
#define NPY_ITERATOR_IMPLEMENTATION_CODE
#include "nditer_impl.h"
/********** PRINTF DEBUG TRACING **************/
#define NPY_UF_DBG_TRACING 0
#if NPY_UF_DBG_TRACING
#define NPY_UF_DBG_PRINT(s) {printf("%s", s);fflush(stdout);}
#define NPY_UF_DBG_PRINT1(s, p1) {printf((s), (p1));fflush(stdout);}
#define NPY_UF_DBG_PRINT2(s, p1, p2) {printf(s, p1, p2);fflush(stdout);}
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3) {printf(s, p1, p2, p3);fflush(stdout);}
#else
#define NPY_UF_DBG_PRINT(s)
#define NPY_UF_DBG_PRINT1(s, p1)
#define NPY_UF_DBG_PRINT2(s, p1, p2)
#define NPY_UF_DBG_PRINT3(s, p1, p2, p3)
#endif
/**********************************************/
typedef struct {
PyObject *in; /* The input arguments to the ufunc, a tuple */
PyObject *out; /* The output arguments, a tuple. If no non-None outputs are
provided, then this is NULL. */
} ufunc_full_args;
/* ---------------------------------------------------------------- */
static PyObject *
prepare_input_arguments_for_outer(PyObject *args, PyUFuncObject *ufunc);
static int
resolve_descriptors(int nop,
PyUFuncObject *ufunc, PyArrayMethodObject *ufuncimpl,
PyArrayObject *operands[], PyArray_Descr *dtypes[],
PyArray_DTypeMeta *signature[], PyObject *inputs_tup,
NPY_CASTING casting);
/*UFUNC_API*/
NPY_NO_EXPORT int
PyUFunc_getfperr(void)
{
/*
* non-clearing get was only added in 1.9 so this function always cleared
* keep it so just in case third party code relied on the clearing
*/
char param = 0;
return npy_clear_floatstatus_barrier(¶m);
}
/* Checking the status flag clears it */
/*UFUNC_API*/
NPY_NO_EXPORT void
PyUFunc_clearfperr()
{
char param = 0;
npy_clear_floatstatus_barrier(¶m);
}
#define NPY_UFUNC_DEFAULT_INPUT_FLAGS \
NPY_ITER_READONLY | \
NPY_ITER_ALIGNED | \
NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
#define NPY_UFUNC_DEFAULT_OUTPUT_FLAGS \
NPY_ITER_ALIGNED | \
NPY_ITER_ALLOCATE | \
NPY_ITER_NO_BROADCAST | \
NPY_ITER_NO_SUBTYPE | \
NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
/* Called at module initialization to set the matmul ufunc output flags */
NPY_NO_EXPORT int
set_matmul_flags(PyObject *d)
{
PyObject *matmul = _PyDict_GetItemStringWithError(d, "matmul");
if (matmul == NULL) {
return -1;
}
/*
* The default output flag NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE allows
* perfectly overlapping input and output (in-place operations). While
* correct for the common mathematical operations, this assumption is
* incorrect in the general case and specifically in the case of matmul.
*
* NPY_ITER_UPDATEIFCOPY is added by default in
* PyUFunc_GeneralizedFunction, which is the variant called for gufuncs
* with a signature
*
* Enabling NPY_ITER_WRITEONLY can prevent a copy in some cases.
*/
((PyUFuncObject *)matmul)->op_flags[2] = (NPY_ITER_WRITEONLY |
NPY_ITER_UPDATEIFCOPY |
NPY_UFUNC_DEFAULT_OUTPUT_FLAGS) &
~NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE;
return 0;
}
/*
* Set per-operand flags according to desired input or output flags.
* op_flags[i] for i in input (as determined by ufunc->nin) will be
* merged with op_in_flags, perhaps overriding per-operand flags set
* in previous stages.
* op_flags[i] for i in output will be set to op_out_flags only if previously
* unset.
* The input flag behavior preserves backward compatibility, while the
* output flag behaviour is the "correct" one for maximum flexibility.
*/
NPY_NO_EXPORT void
_ufunc_setup_flags(PyUFuncObject *ufunc, npy_uint32 op_in_flags,
npy_uint32 op_out_flags, npy_uint32 *op_flags)
{
int nin = ufunc->nin;
int nout = ufunc->nout;
int nop = nin + nout, i;
/* Set up the flags */
for (i = 0; i < nin; ++i) {
op_flags[i] = ufunc->op_flags[i] | op_in_flags;
/*
* If READWRITE flag has been set for this operand,
* then clear default READONLY flag
*/
if (op_flags[i] & (NPY_ITER_READWRITE | NPY_ITER_WRITEONLY)) {
op_flags[i] &= ~NPY_ITER_READONLY;
}
}
for (i = nin; i < nop; ++i) {
op_flags[i] = ufunc->op_flags[i] ? ufunc->op_flags[i] : op_out_flags;
}
}
/* Return the position of next non-white-space char in the string */
static int
_next_non_white_space(const char* str, int offset)
{
int ret = offset;
while (str[ret] == ' ' || str[ret] == '\t') {
ret++;
}
return ret;
}
static int
_is_alpha_underscore(char ch)
{
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_';
}
static int
_is_alnum_underscore(char ch)
{
return _is_alpha_underscore(ch) || (ch >= '0' && ch <= '9');
}
/*
* Convert a string into a number
*/
static npy_intp
_get_size(const char* str)
{
char *stop;
npy_longlong size = NumPyOS_strtoll(str, &stop, 10);
if (stop == str || _is_alpha_underscore(*stop)) {
/* not a well formed number */
return -1;
}
if (size >= NPY_MAX_INTP || size <= NPY_MIN_INTP) {
/* len(str) too long */
return -1;
}
return size;
}
/*
* Return the ending position of a variable name including optional modifier
*/
static int
_get_end_of_name(const char* str, int offset)
{
int ret = offset;
while (_is_alnum_underscore(str[ret])) {
ret++;
}
if (str[ret] == '?') {
ret ++;
}
return ret;
}
/*
* Returns 1 if the dimension names pointed by s1 and s2 are the same,
* otherwise returns 0.
*/
static int
_is_same_name(const char* s1, const char* s2)
{
while (_is_alnum_underscore(*s1) && _is_alnum_underscore(*s2)) {
if (*s1 != *s2) {
return 0;
}
s1++;
s2++;
}
return !_is_alnum_underscore(*s1) && !_is_alnum_underscore(*s2);
}
/*
* Sets the following fields in the PyUFuncObject 'ufunc':
*
* Field Type Array Length
* core_enabled int (effectively bool) N/A
* core_num_dim_ix int N/A
* core_dim_flags npy_uint32 * core_num_dim_ix
* core_dim_sizes npy_intp * core_num_dim_ix
* core_num_dims int * nargs (i.e. nin+nout)
* core_offsets int * nargs
* core_dim_ixs int * sum(core_num_dims)
* core_signature char * strlen(signature) + 1
*
* The function assumes that the values that are arrays have not
* been set already, and sets these pointers to memory allocated
* with PyArray_malloc. These are freed when the ufunc dealloc
* method is called.
*
* Returns 0 unless an error occurred.
*/
static int
_parse_signature(PyUFuncObject *ufunc, const char *signature)
{
size_t len;
char const **var_names;
int nd = 0; /* number of dimension of the current argument */
int cur_arg = 0; /* index into core_num_dims&core_offsets */
int cur_core_dim = 0; /* index into core_dim_ixs */
int i = 0;
char *parse_error = NULL;
if (signature == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"_parse_signature with NULL signature");
return -1;
}
len = strlen(signature);
ufunc->core_signature = PyArray_malloc(sizeof(char) * (len+1));
if (ufunc->core_signature) {
strcpy(ufunc->core_signature, signature);
}
/* Allocate sufficient memory to store pointers to all dimension names */
var_names = PyArray_malloc(sizeof(char const*) * len);
if (var_names == NULL) {
PyErr_NoMemory();
return -1;
}
ufunc->core_enabled = 1;
ufunc->core_num_dim_ix = 0;
ufunc->core_num_dims = PyArray_malloc(sizeof(int) * ufunc->nargs);
ufunc->core_offsets = PyArray_malloc(sizeof(int) * ufunc->nargs);
/* The next three items will be shrunk later */
ufunc->core_dim_ixs = PyArray_malloc(sizeof(int) * len);
ufunc->core_dim_sizes = PyArray_malloc(sizeof(npy_intp) * len);
ufunc->core_dim_flags = PyArray_malloc(sizeof(npy_uint32) * len);
if (ufunc->core_num_dims == NULL || ufunc->core_dim_ixs == NULL ||
ufunc->core_offsets == NULL ||
ufunc->core_dim_sizes == NULL ||
ufunc->core_dim_flags == NULL) {
PyErr_NoMemory();
goto fail;
}
for (size_t j = 0; j < len; j++) {
ufunc->core_dim_flags[j] = 0;
}
i = _next_non_white_space(signature, 0);
while (signature[i] != '\0') {
/* loop over input/output arguments */
if (cur_arg == ufunc->nin) {
/* expect "->" */
if (signature[i] != '-' || signature[i+1] != '>') {
parse_error = "expect '->'";
goto fail;
}
i = _next_non_white_space(signature, i + 2);
}
/*
* parse core dimensions of one argument,
* e.g. "()", "(i)", or "(i,j)"
*/
if (signature[i] != '(') {
parse_error = "expect '('";
goto fail;
}
i = _next_non_white_space(signature, i + 1);
while (signature[i] != ')') {
/* loop over core dimensions */
int ix, i_end;
npy_intp frozen_size;
npy_bool can_ignore;
if (signature[i] == '\0') {
parse_error = "unexpected end of signature string";
goto fail;
}
/*
* Is this a variable or a fixed size dimension?
*/
if (_is_alpha_underscore(signature[i])) {
frozen_size = -1;
}
else {
frozen_size = (npy_intp)_get_size(signature + i);
if (frozen_size <= 0) {
parse_error = "expect dimension name or non-zero frozen size";
goto fail;
}
}
/* Is this dimension flexible? */
i_end = _get_end_of_name(signature, i);
can_ignore = (i_end > 0 && signature[i_end - 1] == '?');
/*
* Determine whether we already saw this dimension name,
* get its index, and set its properties
*/
for(ix = 0; ix < ufunc->core_num_dim_ix; ix++) {
if (frozen_size > 0 ?
frozen_size == ufunc->core_dim_sizes[ix] :
_is_same_name(signature + i, var_names[ix])) {
break;
}
}
/*
* If a new dimension, store its properties; if old, check consistency.
*/
if (ix == ufunc->core_num_dim_ix) {
ufunc->core_num_dim_ix++;
var_names[ix] = signature + i;
ufunc->core_dim_sizes[ix] = frozen_size;
if (frozen_size < 0) {
ufunc->core_dim_flags[ix] |= UFUNC_CORE_DIM_SIZE_INFERRED;
}
if (can_ignore) {
ufunc->core_dim_flags[ix] |= UFUNC_CORE_DIM_CAN_IGNORE;
}
} else {
if (can_ignore && !(ufunc->core_dim_flags[ix] &
UFUNC_CORE_DIM_CAN_IGNORE)) {
parse_error = "? cannot be used, name already seen without ?";
goto fail;
}
if (!can_ignore && (ufunc->core_dim_flags[ix] &
UFUNC_CORE_DIM_CAN_IGNORE)) {
parse_error = "? must be used, name already seen with ?";
goto fail;
}
}
ufunc->core_dim_ixs[cur_core_dim] = ix;
cur_core_dim++;
nd++;
i = _next_non_white_space(signature, i_end);
if (signature[i] != ',' && signature[i] != ')') {
parse_error = "expect ',' or ')'";
goto fail;
}
if (signature[i] == ',')
{
i = _next_non_white_space(signature, i + 1);
if (signature[i] == ')') {
parse_error = "',' must not be followed by ')'";
goto fail;
}
}
}
ufunc->core_num_dims[cur_arg] = nd;
ufunc->core_offsets[cur_arg] = cur_core_dim-nd;
cur_arg++;
nd = 0;
i = _next_non_white_space(signature, i + 1);
if (cur_arg != ufunc->nin && cur_arg != ufunc->nargs) {
/*
* The list of input arguments (or output arguments) was
* only read partially
*/
if (signature[i] != ',') {
parse_error = "expect ','";
goto fail;
}
i = _next_non_white_space(signature, i + 1);
}
}
if (cur_arg != ufunc->nargs) {
parse_error = "incomplete signature: not all arguments found";
goto fail;
}
ufunc->core_dim_ixs = PyArray_realloc(ufunc->core_dim_ixs,
sizeof(int) * cur_core_dim);
ufunc->core_dim_sizes = PyArray_realloc(
ufunc->core_dim_sizes,
sizeof(npy_intp) * ufunc->core_num_dim_ix);
ufunc->core_dim_flags = PyArray_realloc(
ufunc->core_dim_flags,
sizeof(npy_uint32) * ufunc->core_num_dim_ix);
/* check for trivial core-signature, e.g. "(),()->()" */
if (cur_core_dim == 0) {
ufunc->core_enabled = 0;
}
PyArray_free((void*)var_names);
return 0;
fail:
PyArray_free((void*)var_names);
if (parse_error) {
PyErr_Format(PyExc_ValueError,
"%s at position %d in \"%s\"",
parse_error, i, signature);
}
return -1;
}
/*
* Checks if 'obj' is a valid output array for a ufunc, i.e. it is
* either None or a writeable array, increments its reference count
* and stores a pointer to it in 'store'. Returns 0 on success, sets
* an exception and returns -1 on failure.
*/
static int
_set_out_array(PyObject *obj, PyArrayObject **store)
{
if (obj == Py_None) {
/* Translate None to NULL */
return 0;
}
if (PyArray_Check(obj)) {
/* If it's an array, store it */
if (PyArray_FailUnlessWriteable((PyArrayObject *)obj,
"output array") < 0) {
return -1;
}
Py_INCREF(obj);
*store = (PyArrayObject *)obj;
return 0;
}
PyErr_SetString(PyExc_TypeError, "return arrays must be of ArrayType");
return -1;
}
/********* GENERIC UFUNC USING ITERATOR *********/
/*
* Produce a name for the ufunc, if one is not already set
* This is used in the PyUFunc_handlefperr machinery, and in error messages
*/
NPY_NO_EXPORT const char*
ufunc_get_name_cstr(PyUFuncObject *ufunc) {
return ufunc->name ? ufunc->name : "<unnamed ufunc>";
}
/*
* Converters for use in parsing of keywords arguments.
*/
static int
_subok_converter(PyObject *obj, npy_bool *subok)
{
if (PyBool_Check(obj)) {
*subok = (obj == Py_True);
return NPY_SUCCEED;
}
else {
PyErr_SetString(PyExc_TypeError,
"'subok' must be a boolean");
return NPY_FAIL;
}
}
static int
_keepdims_converter(PyObject *obj, int *keepdims)
{
if (PyBool_Check(obj)) {
*keepdims = (obj == Py_True);
return NPY_SUCCEED;
}
else {
PyErr_SetString(PyExc_TypeError,
"'keepdims' must be a boolean");
return NPY_FAIL;
}
}
static int
_wheremask_converter(PyObject *obj, PyArrayObject **wheremask)
{
/*
* Optimization: where=True is the same as no where argument.
* This lets us document True as the default.
*/
if (obj == Py_True) {
return NPY_SUCCEED;
}
else {
PyArray_Descr *dtype = PyArray_DescrFromType(NPY_BOOL);
if (dtype == NULL) {
return NPY_FAIL;
}
/* PyArray_FromAny steals reference to dtype, even on failure */
*wheremask = (PyArrayObject *)PyArray_FromAny(obj, dtype, 0, 0, 0, NULL);
if ((*wheremask) == NULL) {
return NPY_FAIL;
}
return NPY_SUCCEED;
}
}
/*
* Due to the array override, do the actual parameter conversion
* only in this step. This function takes the reference objects and
* parses them into the desired values.
* This function cleans up after itself and NULLs references on error,
* however, the caller has to ensure that `out_op[0:nargs]` and `out_whermeask`
* are NULL initialized.
*/
static int
convert_ufunc_arguments(PyUFuncObject *ufunc,
ufunc_full_args full_args, PyArrayObject *out_op[],
PyArray_DTypeMeta *out_op_DTypes[],
npy_bool *force_legacy_promotion, npy_bool *allow_legacy_promotion,
npy_bool *promoting_pyscalars,
PyObject *order_obj, NPY_ORDER *out_order,
PyObject *casting_obj, NPY_CASTING *out_casting,
PyObject *subok_obj, npy_bool *out_subok,
PyObject *where_obj, PyArrayObject **out_wheremask, /* PyArray of bool */
PyObject *keepdims_obj, int *out_keepdims)
{
int nin = ufunc->nin;
int nout = ufunc->nout;
int nop = ufunc->nargs;
PyObject *obj;
/* Convert and fill in input arguments */
npy_bool all_scalar = NPY_TRUE;
npy_bool any_scalar = NPY_FALSE;
*allow_legacy_promotion = NPY_TRUE;
*force_legacy_promotion = NPY_FALSE;
*promoting_pyscalars = NPY_FALSE;
for (int i = 0; i < nin; i++) {
obj = PyTuple_GET_ITEM(full_args.in, i);
if (PyArray_Check(obj)) {
out_op[i] = (PyArrayObject *)obj;
Py_INCREF(out_op[i]);
}
else {
/* Convert the input to an array and check for special cases */
out_op[i] = (PyArrayObject *)PyArray_FromAny(obj, NULL, 0, 0, 0, NULL);
if (out_op[i] == NULL) {
goto fail;
}
}
out_op_DTypes[i] = NPY_DTYPE(PyArray_DESCR(out_op[i]));
Py_INCREF(out_op_DTypes[i]);
if (nin == 1) {
/*
* TODO: If nin == 1 we don't promote! This has exactly the effect
* that right now integers can still go to object/uint64 and
* their behavior is thus unchanged for unary ufuncs (like
* isnan). This is not ideal, but pragmatic...
* We should eventually have special loops for isnan and once
* we do, we may just deprecate all remaining ones (e.g.
* `negative(2**100)` not working as it is an object.)
*
* This is issue is part of the NEP 50 adoption.
*/
break;
}
if (!NPY_DT_is_legacy(out_op_DTypes[i])) {
*allow_legacy_promotion = NPY_FALSE;
// TODO: A subclass of int, float, complex could reach here and
// it should not be flagged as "weak" if it does.
}
if (PyArray_NDIM(out_op[i]) == 0) {
any_scalar = NPY_TRUE;
}
else {
all_scalar = NPY_FALSE;
continue;
}
// TODO: Is this equivalent/better by removing the logic which enforces
// that we always use weak promotion in the core?
if (npy_promotion_state == NPY_USE_LEGACY_PROMOTION) {
continue; /* Skip use of special dtypes */
}
/*
* Handle the "weak" Python scalars/literals. We use a special DType
* for these.
* Further, we mark the operation array with a special flag to indicate
* this. This is because the legacy dtype resolution makes use of
* `np.can_cast(operand, dtype)`. The flag is local to this use, but
* necessary to propagate the information to the legacy type resolution.
*/
if (npy_mark_tmp_array_if_pyscalar(obj, out_op[i], &out_op_DTypes[i])) {
if (PyArray_FLAGS(out_op[i]) & NPY_ARRAY_WAS_PYTHON_INT
&& PyArray_TYPE(out_op[i]) != NPY_LONG) {
/*
* When `np.array(integer)` is not the default integer (mainly
* object dtype), this confuses many type resolvers. Simply
* forcing a default integer array is unfortunately easiest.
* In this disables the optional NEP 50 warnings, but in
* practice when this happens we should _usually_ pick the
* default integer loop and that raises an error.
* (An exception is `float64(1.) + 10**100` which silently
* will give a float64 result rather than a Python float.)
*
* TODO: Just like the general dual NEP 50/legacy promotion
* support this is meant as a temporary hack for NumPy 1.25.
*/
static PyArrayObject *zero_arr = NULL;
if (NPY_UNLIKELY(zero_arr == NULL)) {
zero_arr = (PyArrayObject *)PyArray_ZEROS(
0, NULL, NPY_LONG, NPY_FALSE);
if (zero_arr == NULL) {
goto fail;
}
((PyArrayObject_fields *)zero_arr)->flags |= (
NPY_ARRAY_WAS_PYTHON_INT|NPY_ARRAY_WAS_INT_AND_REPLACED);
}
Py_INCREF(zero_arr);
Py_SETREF(out_op[i], zero_arr);
}
*promoting_pyscalars = NPY_TRUE;
}
}
if (*allow_legacy_promotion && (!all_scalar && any_scalar)) {
*force_legacy_promotion = should_use_min_scalar(nin, out_op, 0, NULL);
}
/* Convert and fill in output arguments */
memset(out_op_DTypes + nin, 0, nout * sizeof(*out_op_DTypes));
if (full_args.out != NULL) {
for (int i = 0; i < nout; i++) {
obj = PyTuple_GET_ITEM(full_args.out, i);
if (_set_out_array(obj, out_op + i + nin) < 0) {
goto fail;
}
if (out_op[i] != NULL) {
out_op_DTypes[i + nin] = NPY_DTYPE(PyArray_DESCR(out_op[i]));
Py_INCREF(out_op_DTypes[i + nin]);
}
}
}
/*
* Convert most arguments manually here, since it is easier to handle
* the ufunc override if we first parse only to objects.
*/
if (where_obj && !_wheremask_converter(where_obj, out_wheremask)) {
goto fail;
}
if (keepdims_obj && !_keepdims_converter(keepdims_obj, out_keepdims)) {
goto fail;
}
if (casting_obj && !PyArray_CastingConverter(casting_obj, out_casting)) {
goto fail;
}
if (order_obj && !PyArray_OrderConverter(order_obj, out_order)) {
goto fail;
}
if (subok_obj && !_subok_converter(subok_obj, out_subok)) {
goto fail;
}
return 0;
fail:
if (out_wheremask != NULL) {
Py_XSETREF(*out_wheremask, NULL);
}
for (int i = 0; i < nop; i++) {
Py_XSETREF(out_op[i], NULL);
}
return -1;
}
/*
* This checks whether a trivial loop is ok,
* making copies of scalar and one dimensional operands if that will
* help.
*
* Returns 1 if a trivial loop is ok, 0 if it is not, and
* -1 if there is an error.
*/
static int
check_for_trivial_loop(PyArrayMethodObject *ufuncimpl,
PyArrayObject **op, PyArray_Descr **dtypes,
NPY_CASTING casting, npy_intp buffersize)
{
int force_cast_input = ufuncimpl->flags & _NPY_METH_FORCE_CAST_INPUTS;
int i, nin = ufuncimpl->nin, nop = nin + ufuncimpl->nout;
for (i = 0; i < nop; ++i) {
/*
* If the dtype doesn't match, or the array isn't aligned,
* indicate that the trivial loop can't be done.
*/
if (op[i] == NULL) {
continue;
}
int must_copy = !PyArray_ISALIGNED(op[i]);
if (dtypes[i] != PyArray_DESCR(op[i])) {
npy_intp view_offset;
NPY_CASTING safety = PyArray_GetCastInfo(
PyArray_DESCR(op[i]), dtypes[i], NULL, &view_offset);
if (safety < 0 && PyErr_Occurred()) {
/* A proper error during a cast check, should be rare */
return -1;
}
if (view_offset != 0) {
/* NOTE: Could possibly implement non-zero view offsets */
must_copy = 1;
}
if (force_cast_input && i < nin) {
/*
* ArrayMethod flagged to ignore casting (logical funcs
* can force cast to bool)
*/
}
else if (PyArray_MinCastSafety(safety, casting) != casting) {
return 0; /* the cast is not safe enough */
}
}
if (must_copy) {
/*
* If op[j] is a scalar or small one dimensional
* array input, make a copy to keep the opportunity
* for a trivial loop. Outputs are not copied here.
*/
if (i < nin && (PyArray_NDIM(op[i]) == 0
|| (PyArray_NDIM(op[i]) == 1
&& PyArray_DIM(op[i], 0) <= buffersize))) {
PyArrayObject *tmp;
Py_INCREF(dtypes[i]);
tmp = (PyArrayObject *)PyArray_CastToType(op[i], dtypes[i], 0);
if (tmp == NULL) {
return -1;
}
Py_DECREF(op[i]);
op[i] = tmp;
}
else {
return 0;
}
}
}
return 1;
}
/*
* Check whether a trivial loop is possible and call the innerloop if it is.
* A trivial loop is defined as one where a single strided inner-loop call
* is possible.
*
* This function only supports a single output (due to the overlap check).
* It always accepts 0-D arrays and will broadcast them. The function
* cannot broadcast any other array (as it requires a single stride).
* The function accepts all 1-D arrays, and N-D arrays that are either all
* C- or all F-contiguous.
* NOTE: Broadcast outputs are implicitly rejected in the overlap detection.
*
* Returns -2 if a trivial loop is not possible, 0 on success and -1 on error.
*/
static int
try_trivial_single_output_loop(PyArrayMethod_Context *context,
PyArrayObject *op[], NPY_ORDER order,
int errormask)
{
int nin = context->method->nin;
int nop = nin + 1;
assert(context->method->nout == 1);
/* The order of all N-D contiguous operands, can be fixed by `order` */
int operation_order = 0;
if (order == NPY_CORDER) {
operation_order = NPY_ARRAY_C_CONTIGUOUS;
}
else if (order == NPY_FORTRANORDER) {
operation_order = NPY_ARRAY_F_CONTIGUOUS;
}
int operation_ndim = 0;
npy_intp *operation_shape = NULL;
npy_intp fixed_strides[NPY_MAXARGS];
for (int iop = 0; iop < nop; iop++) {
if (op[iop] == NULL) {
/* The out argument may be NULL (and only that one); fill later */
assert(iop == nin);
continue;
}
int op_ndim = PyArray_NDIM(op[iop]);
/* Special case 0-D since we can handle broadcasting using a 0-stride */
if (op_ndim == 0 && iop < nin) {
fixed_strides[iop] = 0;
continue;
}
/* First non 0-D op: fix dimensions, shape (order is fixed later) */
if (operation_ndim == 0) {
operation_ndim = op_ndim;
operation_shape = PyArray_SHAPE(op[iop]);
}
else if (op_ndim != operation_ndim) {
return -2; /* dimension mismatch (except 0-d input ops) */
}
else if (!PyArray_CompareLists(
operation_shape, PyArray_DIMS(op[iop]), op_ndim)) {
return -2; /* shape mismatch */
}
if (op_ndim == 1) {
fixed_strides[iop] = PyArray_STRIDES(op[iop])[0];
}
else {
fixed_strides[iop] = PyArray_ITEMSIZE(op[iop]); /* contiguous */
/* This op must match the operation order (and be contiguous) */
int op_order = (PyArray_FLAGS(op[iop]) &
(NPY_ARRAY_C_CONTIGUOUS|NPY_ARRAY_F_CONTIGUOUS));
if (op_order == 0) {
return -2; /* N-dimensional op must be contiguous */
}
else if (operation_order == 0) {
operation_order = op_order; /* op fixes order */
}
else if (operation_order != op_order) {
return -2;
}
}
}
if (op[nin] == NULL) {
Py_INCREF(context->descriptors[nin]);
op[nin] = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type,
context->descriptors[nin], operation_ndim, operation_shape,
NULL, NULL, operation_order==NPY_ARRAY_F_CONTIGUOUS, NULL);
if (op[nin] == NULL) {
return -1;
}
fixed_strides[nin] = context->descriptors[nin]->elsize;
}
else {
/* If any input overlaps with the output, we use the full path. */
for (int iop = 0; iop < nin; iop++) {
if (!PyArray_EQUIVALENTLY_ITERABLE_OVERLAP_OK(
op[iop], op[nin],
PyArray_TRIVIALLY_ITERABLE_OP_READ,
PyArray_TRIVIALLY_ITERABLE_OP_NOREAD)) {
return -2;
}
}
/* Check self-overlap (non 1-D are contiguous, perfect overlap is OK) */
if (operation_ndim == 1 &&
PyArray_STRIDES(op[nin])[0] < PyArray_ITEMSIZE(op[nin]) &&
PyArray_STRIDES(op[nin])[0] != 0) {
return -2;
}
}
/*
* We can use the trivial (single inner-loop call) optimization
* and `fixed_strides` holds the strides for that call.
*/
char *data[NPY_MAXARGS];
npy_intp count = PyArray_MultiplyList(operation_shape, operation_ndim);
if (count == 0) {
/* Nothing to do */
return 0;
}
NPY_BEGIN_THREADS_DEF;
PyArrayMethod_StridedLoop *strided_loop;
NpyAuxData *auxdata = NULL;
NPY_ARRAYMETHOD_FLAGS flags = 0;
if (context->method->get_strided_loop(context,
1, 0, fixed_strides,
&strided_loop, &auxdata, &flags) < 0) {
return -1;
}
for (int iop=0; iop < nop; iop++) {
data[iop] = PyArray_BYTES(op[iop]);
}
if (!(flags & NPY_METH_NO_FLOATINGPOINT_ERRORS)) {
npy_clear_floatstatus_barrier((char *)context);
}
if (!(flags & NPY_METH_REQUIRES_PYAPI)) {
NPY_BEGIN_THREADS_THRESHOLDED(count);
}
int res = strided_loop(context, data, &count, fixed_strides, auxdata);
NPY_END_THREADS;
NPY_AUXDATA_FREE(auxdata);
/*
* An error should only be possible if `res != 0` is already set.
* But this is not strictly correct for old-style ufuncs (e.g. `power`
* released the GIL but manually set an Exception).
*/
if (PyErr_Occurred()) {
res = -1;
}
if (res == 0 && !(flags & NPY_METH_NO_FLOATINGPOINT_ERRORS)) {
/* NOTE: We could check float errors even when `res < 0` */
const char *name = ufunc_get_name_cstr((PyUFuncObject *)context->caller);