/
ufunc_object.c
6338 lines (5683 loc) · 196 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 _UMATHMODULE
#define _MULTIARRAYMODULE
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#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 "ufunc_object.h"
#include "override.h"
#include "npy_import.h"
#include "extobj.h"
#include "common.h"
#include "dtypemeta.h"
#include "numpyos.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;
/* C representation of the context argument to __array_wrap__ */
typedef struct {
PyUFuncObject *ufunc;
ufunc_full_args args;
int out_i;
} _ufunc_context;
/* Get the arg tuple to pass in the context argument to __array_wrap__ and
* __array_prepare__.
*
* Output arguments are only passed if at least one is non-None.
*/
static PyObject *
_get_wrap_prepare_args(ufunc_full_args full_args) {
if (full_args.out == NULL) {
Py_INCREF(full_args.in);
return full_args.in;
}
else {
return PySequence_Concat(full_args.in, full_args.out);
}
}
/* ---------------------------------------------------------------- */
static PyObject *
prepare_input_arguments_for_outer(PyObject *args, PyUFuncObject *ufunc);
/*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);
}
#define HANDLEIT(NAME, str) {if (retstatus & NPY_FPE_##NAME) { \
handle = errmask & UFUNC_MASK_##NAME; \
if (handle && \
_error_handler(handle >> UFUNC_SHIFT_##NAME, \
errobj, str, retstatus, first) < 0) \
return -1; \
}}
/*UFUNC_API*/
NPY_NO_EXPORT int
PyUFunc_handlefperr(int errmask, PyObject *errobj, int retstatus, int *first)
{
int handle;
if (errmask && retstatus) {
HANDLEIT(DIVIDEBYZERO, "divide by zero");
HANDLEIT(OVERFLOW, "overflow");
HANDLEIT(UNDERFLOW, "underflow");
HANDLEIT(INVALID, "invalid value");
}
return 0;
}
#undef HANDLEIT
/*UFUNC_API*/
NPY_NO_EXPORT int
PyUFunc_checkfperr(int errmask, PyObject *errobj, int *first)
{
/* clearing is done for backward compatibility */
int retstatus;
retstatus = npy_clear_floatstatus_barrier((char*)&retstatus);
return PyUFunc_handlefperr(errmask, errobj, retstatus, first);
}
/* Checking the status flag clears it */
/*UFUNC_API*/
NPY_NO_EXPORT void
PyUFunc_clearfperr()
{
char param = 0;
npy_clear_floatstatus_barrier(¶m);
}
/*
* This function analyzes the input arguments and determines an appropriate
* method (__array_prepare__ or __array_wrap__) function to call, taking it
* from the input with the highest priority. Return NULL if no argument
* defines the method.
*/
static PyObject*
_find_array_method(PyObject *args, PyObject *method_name)
{
int i, n_methods;
PyObject *obj;
PyObject *with_method[NPY_MAXARGS], *methods[NPY_MAXARGS];
PyObject *method = NULL;
n_methods = 0;
for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
obj = PyTuple_GET_ITEM(args, i);
if (PyArray_CheckExact(obj) || PyArray_IsAnyScalar(obj)) {
continue;
}
method = PyObject_GetAttr(obj, method_name);
if (method) {
if (PyCallable_Check(method)) {
with_method[n_methods] = obj;
methods[n_methods] = method;
++n_methods;
}
else {
Py_DECREF(method);
method = NULL;
}
}
else {
PyErr_Clear();
}
}
if (n_methods > 0) {
/* If we have some methods defined, find the one of highest priority */
method = methods[0];
if (n_methods > 1) {
double maxpriority = PyArray_GetPriority(with_method[0],
NPY_PRIORITY);
for (i = 1; i < n_methods; ++i) {
double priority = PyArray_GetPriority(with_method[i],
NPY_PRIORITY);
if (priority > maxpriority) {
maxpriority = priority;
Py_DECREF(method);
method = methods[i];
}
else {
Py_DECREF(methods[i]);
}
}
}
}
return method;
}
/*
* Returns an incref'ed pointer to the proper __array_prepare__/__array_wrap__
* method for a ufunc output argument, given the output argument `obj`, and the
* method chosen from the inputs `input_method`.
*/
static PyObject *
_get_output_array_method(PyObject *obj, PyObject *method,
PyObject *input_method) {
if (obj != Py_None) {
PyObject *ometh;
if (PyArray_CheckExact(obj)) {
/*
* No need to wrap regular arrays - None signals to not call
* wrap/prepare at all
*/
Py_RETURN_NONE;
}
ometh = PyObject_GetAttr(obj, method);
if (ometh == NULL) {
PyErr_Clear();
}
else if (!PyCallable_Check(ometh)) {
Py_DECREF(ometh);
}
else {
/* Use the wrap/prepare method of the output if it's callable */
return ometh;
}
}
/* Fall back on the input's wrap/prepare */
Py_XINCREF(input_method);
return input_method;
}
/*
* This function analyzes the input arguments
* and determines an appropriate __array_prepare__ function to call
* for the outputs.
*
* If an output argument is provided, then it is prepped
* with its own __array_prepare__ not with the one determined by
* the input arguments.
*
* if the provided output argument is already an ndarray,
* the prepping function is None (which means no prepping will
* be done --- not even PyArray_Return).
*
* A NULL is placed in output_prep for outputs that
* should just have PyArray_Return called.
*/
static void
_find_array_prepare(ufunc_full_args args,
PyObject **output_prep, int nout)
{
int i;
PyObject *prep;
/*
* Determine the prepping function given by the input arrays
* (could be NULL).
*/
prep = _find_array_method(args.in, npy_um_str_array_prepare);
/*
* For all the output arrays decide what to do.
*
* 1) Use the prep function determined from the input arrays
* This is the default if the output array is not
* passed in.
*
* 2) Use the __array_prepare__ method of the output object.
* This is special cased for
* exact ndarray so that no PyArray_Return is
* done in that case.
*/
if (args.out == NULL) {
for (i = 0; i < nout; i++) {
Py_XINCREF(prep);
output_prep[i] = prep;
}
}
else {
for (i = 0; i < nout; i++) {
output_prep[i] = _get_output_array_method(
PyTuple_GET_ITEM(args.out, i), npy_um_str_array_prepare, prep);
}
}
Py_XDECREF(prep);
return;
}
#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;
}
}
/*
* This function analyzes the input arguments
* and determines an appropriate __array_wrap__ function to call
* for the outputs.
*
* If an output argument is provided, then it is wrapped
* with its own __array_wrap__ not with the one determined by
* the input arguments.
*
* if the provided output argument is already an array,
* the wrapping function is None (which means no wrapping will
* be done --- not even PyArray_Return).
*
* A NULL is placed in output_wrap for outputs that
* should just have PyArray_Return called.
*/
static void
_find_array_wrap(ufunc_full_args args, npy_bool subok,
PyObject **output_wrap, int nin, int nout)
{
int i;
PyObject *wrap = NULL;
/*
* If a 'subok' parameter is passed and isn't True, don't wrap but put None
* into slots with out arguments which means return the out argument
*/
if (!subok) {
goto handle_out;
}
/*
* Determine the wrapping function given by the input arrays
* (could be NULL).
*/
wrap = _find_array_method(args.in, npy_um_str_array_wrap);
/*
* For all the output arrays decide what to do.
*
* 1) Use the wrap function determined from the input arrays
* This is the default if the output array is not
* passed in.
*
* 2) Use the __array_wrap__ method of the output object
* passed in. -- this is special cased for
* exact ndarray so that no PyArray_Return is
* done in that case.
*/
handle_out:
if (args.out == NULL) {
for (i = 0; i < nout; i++) {
Py_XINCREF(wrap);
output_wrap[i] = wrap;
}
}
else {
for (i = 0; i < nout; i++) {
output_wrap[i] = _get_output_array_method(
PyTuple_GET_ITEM(args.out, i), npy_um_str_array_wrap, wrap);
}
}
Py_XDECREF(wrap);
}
/*
* Apply the __array_wrap__ function with the given array and content.
*
* Interprets wrap=None and wrap=NULL as intended by _find_array_wrap
*
* Steals a reference to obj and wrap.
* Pass context=NULL to indicate there is no context.
*/
static PyObject *
_apply_array_wrap(
PyObject *wrap, PyArrayObject *obj, _ufunc_context const *context) {
if (wrap == NULL) {
/* default behavior */
return PyArray_Return(obj);
}
else if (wrap == Py_None) {
Py_DECREF(wrap);
return (PyObject *)obj;
}
else {
PyObject *res;
PyObject *py_context = NULL;
/* Convert the context object to a tuple, if present */
if (context == NULL) {
py_context = Py_None;
Py_INCREF(py_context);
}
else {
PyObject *args_tup;
/* Call the method with appropriate context */
args_tup = _get_wrap_prepare_args(context->args);
if (args_tup == NULL) {
goto fail;
}
py_context = Py_BuildValue("OOi",
context->ufunc, args_tup, context->out_i);
Py_DECREF(args_tup);
if (py_context == NULL) {
goto fail;
}
}
/* try __array_wrap__(obj, context) */
res = PyObject_CallFunctionObjArgs(wrap, obj, py_context, NULL);
Py_DECREF(py_context);
/* try __array_wrap__(obj) if the context argument is not accepted */
if (res == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Clear();
res = PyObject_CallFunctionObjArgs(wrap, obj, NULL);
}
Py_DECREF(wrap);
Py_DECREF(obj);
return res;
fail:
Py_DECREF(wrap);
Py_DECREF(obj);
return NULL;
}
}
/*UFUNC_API
*
* On return, if errobj is populated with a non-NULL value, the caller
* owns a new reference to errobj.
*/
NPY_NO_EXPORT int
PyUFunc_GetPyValues(char *name, int *bufsize, int *errmask, PyObject **errobj)
{
PyObject *ref = get_global_ext_obj();
return _extract_pyvals(ref, name, bufsize, errmask, errobj);
}
/* 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 core_num_dim_ix, core_num_dims, core_dim_ixs, core_offsets,
* and core_signature in PyUFuncObject "ufunc". 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,
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 */
for (int i = 0; i < nin; i++) {
obj = PyTuple_GET_ITEM(full_args.in, i);
if (PyArray_Check(obj)) {
PyArrayObject *obj_a = (PyArrayObject *)obj;
out_op[i] = (PyArrayObject *)PyArray_FromArray(obj_a, NULL, 0);
}
else {
out_op[i] = (PyArrayObject *)PyArray_FromAny(obj,
NULL, 0, 0, 0, NULL);
}
if (out_op[i] == NULL) {
goto fail;
}
}
/* Convert and fill in output arguments */
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;
}
}
}
/*
* 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(PyUFuncObject *ufunc,
PyArrayObject **op,
PyArray_Descr **dtype,
npy_intp buffersize)
{
npy_intp i, nin = ufunc->nin, nop = nin + ufunc->nout;
for (i = 0; i < nop; ++i) {