-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
array_coercion.c
1463 lines (1356 loc) · 51.1 KB
/
array_coercion.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
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _UMATHMODULE
#define _MULTIARRAYMODULE
#include "Python.h"
#include "numpy/npy_3kcompat.h"
#include "lowlevel_strided_loops.h"
#include "numpy/arrayobject.h"
#include "descriptor.h"
#include "convert_datatype.h"
#include "dtypemeta.h"
#include "array_coercion.h"
#include "ctors.h"
#include "common.h"
#include "_datetime.h"
#include "npy_import.h"
/*
* This file defines helpers for some of the ctors.c functions which
* create an array from Python sequences and types.
* When creating an array with ``np.array(...)`` we have to do two main things:
*
* 1. Find the exact shape of the resulting array
* 2. Find the correct dtype of the resulting array.
*
* In most cases these two things are can be done in a single processing step.
* There are in principle three different calls that should be distinguished:
*
* 1. The user calls ``np.array(..., dtype=np.dtype("<f8"))``
* 2. The user calls ``np.array(..., dtype="S")``
* 3. The user calls ``np.array(...)``
*
* In the first case, in principle only the shape needs to be found. In the
* second case, the DType class (e.g. string) is already known but the DType
* instance (e.g. length of the string) has to be found.
* In the last case the DType class needs to be found as well. Note that
* it is not necessary to find the DType class of the entire array, but
* the DType class needs to be found for each element before the actual
* dtype instance can be found.
*
* Further, there are a few other things to keep in mind when coercing arrays:
*
* * For UFunc promotion, Python scalars need to be handled specially to
* allow value based casting. This requires python complex/float to
* have their own DTypes.
* * It is necessary to decide whether or not a sequence is an element.
* For example tuples are considered elements for structured dtypes, but
* otherwise are considered sequences.
* This means that if a dtype is given (either as a class or instance),
* it can effect the dimension discovery part.
* For the "special" NumPy types structured void and "c" (single character)
* this is special cased. For future user-types, this is currently
* handled by providing calling an `is_known_scalar` method. This method
* currently ensures that Python numerical types are handled quickly.
*
* In the initial version of this implementation, it is assumed that dtype
* discovery can be implemented sufficiently fast. That is, it is not
* necessary to create fast paths that only find the correct shape e.g. when
* ``dtype=np.dtype("f8")`` is given.
*
* The code here avoid multiple conversion of array-like objects (including
* sequences). These objects are cached after conversion, which will require
* additional memory, but can drastically speed up coercion from from array
* like objects.
*/
/*
* For finding a DType quickly from a type, it is easiest to have a
* a mapping of pytype -> DType.
* TODO: This mapping means that it is currently impossible to delete a
* pair of pytype <-> DType. To resolve this, it is necessary to
* weakly reference the pytype. As long as the pytype is alive, we
* want to be able to use `np.array([pytype()])`.
* It should be possible to retrofit this without too much trouble
* (all type objects support weak references).
*/
PyObject *_global_pytype_to_type_dict = NULL;
/* Enum to track or signal some things during dtype and shape discovery */
enum _dtype_discovery_flags {
FOUND_RAGGED_ARRAY = 1 << 0,
GAVE_SUBCLASS_WARNING = 1 << 1,
PROMOTION_FAILED = 1 << 2,
DISCOVER_STRINGS_AS_SEQUENCES = 1 << 3,
DISCOVER_TUPLES_AS_ELEMENTS = 1 << 4,
MAX_DIMS_WAS_REACHED = 1 << 5,
DESCRIPTOR_WAS_SET = 1 << 6,
};
/**
* Adds known sequence types to the global type dictionary, note that when
* a DType is passed in, this lookup may be ignored.
*
* @return -1 on error 0 on success
*/
static int
_prime_global_pytype_to_type_dict(void)
{
int res;
/* Add the basic Python sequence types */
res = PyDict_SetItem(_global_pytype_to_type_dict,
(PyObject *)&PyList_Type, Py_None);
if (res < 0) {
return -1;
}
res = PyDict_SetItem(_global_pytype_to_type_dict,
(PyObject *)&PyTuple_Type, Py_None);
if (res < 0) {
return -1;
}
/* NumPy Arrays are not handled as scalars */
res = PyDict_SetItem(_global_pytype_to_type_dict,
(PyObject *)&PyArray_Type, Py_None);
if (res < 0) {
return -1;
}
return 0;
}
/**
* Add a new mapping from a python type to the DType class. For a user
* defined legacy dtype, this function does nothing unless the pytype
* subclass from `np.generic`.
*
* This assumes that the DType class is guaranteed to hold on the
* python type (this assumption is guaranteed).
* This functionality supercedes ``_typenum_fromtypeobj``.
*
* @param DType DType to map the python type to
* @param pytype Python type to map from
* @param userdef Whether or not it is user defined. We ensure that user
* defined scalars subclass from our scalars (for now).
*/
NPY_NO_EXPORT int
_PyArray_MapPyTypeToDType(
PyArray_DTypeMeta *DType, PyTypeObject *pytype, npy_bool userdef)
{
PyObject *Dtype_obj = (PyObject *)DType;
if (userdef && !PyObject_IsSubclass(
(PyObject *)pytype, (PyObject *)&PyGenericArrType_Type)) {
/*
* We expect that user dtypes (for now) will subclass some numpy
* scalar class to allow automatic discovery.
*/
if (DType->legacy) {
/*
* For legacy user dtypes, discovery relied on subclassing, but
* arbitrary type objects are supported, so do nothing.
*/
return 0;
}
/*
* We currently enforce that user DTypes subclass from `np.generic`
* (this should become a `np.generic` base class and may be lifted
* entirely).
*/
PyErr_Format(PyExc_RuntimeError,
"currently it is only possible to register a DType "
"for scalars deriving from `np.generic`, got '%S'.",
(PyObject *)pytype);
return -1;
}
/* Create the global dictionary if it does not exist */
if (NPY_UNLIKELY(_global_pytype_to_type_dict == NULL)) {
_global_pytype_to_type_dict = PyDict_New();
if (_global_pytype_to_type_dict == NULL) {
return -1;
}
if (_prime_global_pytype_to_type_dict() < 0) {
return -1;
}
}
int res = PyDict_Contains(_global_pytype_to_type_dict, (PyObject *)pytype);
if (res < 0) {
return -1;
}
else if (res) {
PyErr_SetString(PyExc_RuntimeError,
"Can only map one python type to DType.");
return -1;
}
return PyDict_SetItem(_global_pytype_to_type_dict,
(PyObject *)pytype, Dtype_obj);
}
/**
* Lookup the DType for a registered known python scalar type.
*
* @param pytype Python Type to look up
* @return DType, None if it a known non-scalar, or NULL if an unknown object.
*/
static NPY_INLINE PyArray_DTypeMeta *
discover_dtype_from_pytype(PyTypeObject *pytype)
{
PyObject *DType;
if (pytype == &PyArray_Type) {
Py_INCREF(Py_None);
return (PyArray_DTypeMeta *)Py_None;
}
DType = PyDict_GetItem(_global_pytype_to_type_dict, (PyObject *)pytype);
if (DType == NULL) {
/* the python type is not known */
return NULL;
}
Py_INCREF(DType);
if (DType == Py_None) {
return (PyArray_DTypeMeta *)Py_None;
}
assert(PyObject_TypeCheck(DType, (PyTypeObject *)&PyArrayDTypeMeta_Type));
return (PyArray_DTypeMeta *)DType;
}
/**
* Find the correct DType class for the given python type. If flags is NULL
* this is not used to discover a dtype, but only for conversion to an
* existing dtype. In that case the Python (not NumPy) scalar subclass
* checks are skipped.
*
* @param obj The python object, mainly type(pyobj) is used, the object
* is passed to reuse existing code at this time only.
* @param flags Flags used to know if warnings were already given. If
* flags is NULL, this is not
* @param fixed_DType if not NULL, will be checked first for whether or not
* it can/wants to handle the (possible) scalar value.
* @return New reference to either a DType class, Py_None, or NULL on error.
*/
static NPY_INLINE PyArray_DTypeMeta *
discover_dtype_from_pyobject(
PyObject *obj, enum _dtype_discovery_flags *flags,
PyArray_DTypeMeta *fixed_DType)
{
if (fixed_DType != NULL) {
/*
* Let the given DType handle the discovery. This is when the
* scalar-type matches exactly, or the DType signals that it can
* handle the scalar-type. (Even if it cannot handle here it may be
* asked to attempt to do so later, if no other matching DType exists.)
*/
if ((Py_TYPE(obj) == fixed_DType->scalar_type) ||
(fixed_DType->is_known_scalar_type != NULL &&
fixed_DType->is_known_scalar_type(fixed_DType, Py_TYPE(obj)))) {
Py_INCREF(fixed_DType);
return fixed_DType;
}
}
PyArray_DTypeMeta *DType = discover_dtype_from_pytype(Py_TYPE(obj));
if (DType != NULL) {
return DType;
}
/*
* At this point we have not found a clear mapping, but mainly for
* backward compatibility we have to make some further attempts at
* interpreting the input as a known scalar type.
*/
PyArray_Descr *legacy_descr;
if (PyArray_IsScalar(obj, Generic)) {
legacy_descr = PyArray_DescrFromScalar(obj);
if (legacy_descr == NULL) {
return NULL;
}
}
else if (flags == NULL) {
Py_INCREF(Py_None);
return (PyArray_DTypeMeta *)Py_None;
}
else if (PyBytes_Check(obj)) {
legacy_descr = PyArray_DescrFromType(NPY_BYTE);
}
else if (PyUnicode_Check(obj)) {
legacy_descr = PyArray_DescrFromType(NPY_UNICODE);
}
else {
legacy_descr = _array_find_python_scalar_type(obj);
}
if (legacy_descr != NULL) {
DType = NPY_DTYPE(legacy_descr);
Py_INCREF(DType);
Py_DECREF(legacy_descr);
/* TODO: Enable warning about subclass handling */
if ((0) && !((*flags) & GAVE_SUBCLASS_WARNING)) {
if (DEPRECATE_FUTUREWARNING(
"in the future NumPy will not automatically find the "
"dtype for subclasses of scalars known to NumPy (i.e. "
"python types). Use the appropriate `dtype=...` to create "
"this array. This will use the `object` dtype or raise "
"an error in the future.") < 0) {
return NULL;
}
*flags |= GAVE_SUBCLASS_WARNING;
}
return DType;
}
Py_INCREF(Py_None);
return (PyArray_DTypeMeta *)Py_None;
}
/**
* Discover the correct descriptor from a known DType class and scalar.
* If the fixed DType can discover a dtype instance/descr all is fine,
* if it cannot and DType is used instead, a cast will have to be tried.
*
* @param fixed_DType A user provided fixed DType, can be NULL
* @param DType A discovered DType (by discover_dtype_from_pyobject);
* this can be identical to `fixed_DType`, if it obj is a
* known scalar. Can be `NULL` indicating no known type.
* @param obj The Python scalar object. At the time of calling this function
* it must be known that `obj` should represent a scalar.
*/
static NPY_INLINE PyArray_Descr *
find_scalar_descriptor(
PyArray_DTypeMeta *fixed_DType, PyArray_DTypeMeta *DType,
PyObject *obj)
{
PyArray_Descr *descr;
if (DType == NULL && fixed_DType == NULL) {
/* No known DType and no fixed one means we go to object. */
return PyArray_DescrFromType(NPY_OBJECT);
}
else if (DType == NULL) {
/*
* If no DType is known/found, give the fixed give one a second
* chance. This allows for example string, to call `str(obj)` to
* figure out the length for arbitrary objects.
*/
descr = fixed_DType->discover_descr_from_pyobject(fixed_DType, obj);
}
else {
descr = DType->discover_descr_from_pyobject(DType, obj);
}
if (descr == NULL) {
return NULL;
}
if (fixed_DType == NULL) {
return descr;
}
Py_SETREF(descr, PyArray_CastDescrToDType(descr, fixed_DType));
return descr;
}
/**
* Assign a single element in an array from a python value.
*
* The dtypes SETITEM should only be trusted to generally do the right
* thing if something is known to be a scalar *and* is of a python type known
* to the DType (which should include all basic Python math types), but in
* general a cast may be necessary.
* This function handles the cast, which is for example hit when assigning
* a float128 to complex128.
*
* At this time, this function does not support arrays (historically we
* mainly supported arrays through `__float__()`, etc.). Such support should
* possibly be added (although when called from `PyArray_AssignFromCache`
* the input cannot be an array).
* Note that this is also problematic for some array-likes, such as
* `astropy.units.Quantity` and `np.ma.masked`. These are used to us calling
* `__float__`/`__int__` for 0-D instances in many cases.
* Eventually, we may want to define this as wrong: They must use DTypes
* instead of (only) subclasses. Until then, here as well as in
* `PyArray_AssignFromCache` (which already does this), we need to special
* case 0-D array-likes to behave like arbitrary (unknown!) Python objects.
*
* @param descr
* @param item
* @param value
* @return 0 on success -1 on failure.
*/
/*
* TODO: This function should possibly be public API.
*/
NPY_NO_EXPORT int
PyArray_Pack(PyArray_Descr *descr, char *item, PyObject *value)
{
PyArrayObject_fields arr_fields = {
.flags = NPY_ARRAY_WRITEABLE, /* assume array is not behaved. */
};
Py_SET_TYPE(&arr_fields, &PyArray_Type);
Py_SET_REFCNT(&arr_fields, 1);
if (NPY_UNLIKELY(descr->type_num == NPY_OBJECT)) {
/*
* We always have store objects directly, casting will lose some
* type information. Any other dtype discards the type information.
* TODO: For a Categorical[object] this path may be necessary?
*/
arr_fields.descr = descr;
return descr->f->setitem(value, item, &arr_fields);
}
/* discover_dtype_from_pyobject includes a check for is_known_scalar_type */
PyArray_DTypeMeta *DType = discover_dtype_from_pyobject(
value, NULL, NPY_DTYPE(descr));
if (DType == NULL) {
return -1;
}
if (DType == NPY_DTYPE(descr) || DType == (PyArray_DTypeMeta *)Py_None) {
/* We can set the element directly (or at least will try to) */
Py_XDECREF(DType);
arr_fields.descr = descr;
return descr->f->setitem(value, item, &arr_fields);
}
PyArray_Descr *tmp_descr;
tmp_descr = DType->discover_descr_from_pyobject(DType, value);
Py_DECREF(DType);
if (tmp_descr == NULL) {
return -1;
}
char *data = PyObject_Malloc(tmp_descr->elsize);
if (data == NULL) {
PyErr_NoMemory();
Py_DECREF(tmp_descr);
return -1;
}
if (PyDataType_FLAGCHK(tmp_descr, NPY_NEEDS_INIT)) {
memset(data, 0, tmp_descr->elsize);
}
arr_fields.descr = tmp_descr;
if (tmp_descr->f->setitem(value, data, &arr_fields) < 0) {
PyObject_Free(data);
Py_DECREF(tmp_descr);
return -1;
}
if (PyDataType_REFCHK(tmp_descr)) {
/* We could probably use move-references above */
PyArray_Item_INCREF(data, tmp_descr);
}
int res = 0;
int needs_api = 0;
PyArray_StridedUnaryOp *stransfer;
NpyAuxData *transferdata;
if (PyArray_GetDTypeTransferFunction(
0, 0, 0, tmp_descr, descr, 0, &stransfer, &transferdata,
&needs_api) == NPY_FAIL) {
res = -1;
goto finish;
}
if (stransfer(item, 0, data, 0, 1, tmp_descr->elsize, transferdata) < 0) {
res = -1;
}
NPY_AUXDATA_FREE(transferdata);
finish:
if (PyDataType_REFCHK(tmp_descr)) {
/* We could probably use move-references above */
PyArray_Item_XDECREF(data, tmp_descr);
}
PyObject_Free(data);
Py_DECREF(tmp_descr);
return res;
}
static int
update_shape(int curr_ndim, int *max_ndim,
npy_intp out_shape[NPY_MAXDIMS], int new_ndim,
const npy_intp new_shape[NPY_MAXDIMS], npy_bool sequence,
enum _dtype_discovery_flags *flags)
{
int success = 0; /* unsuccessful if array is ragged */
const npy_bool max_dims_reached = *flags & MAX_DIMS_WAS_REACHED;
if (curr_ndim + new_ndim > *max_ndim) {
success = -1;
/* Only update/check as many dims as possible, max_ndim is unchanged */
new_ndim = *max_ndim - curr_ndim;
}
else if (!sequence && (*max_ndim != curr_ndim + new_ndim)) {
/*
* Sequences do not update max_ndim, otherwise shrink and check.
* This is depth first, so if it is already set, `out_shape` is filled.
*/
*max_ndim = curr_ndim + new_ndim;
/* If a shape was already set, this is also ragged */
if (max_dims_reached) {
success = -1;
}
}
for (int i = 0; i < new_ndim; i++) {
npy_intp curr_dim = out_shape[curr_ndim + i];
npy_intp new_dim = new_shape[i];
if (!max_dims_reached) {
out_shape[curr_ndim + i] = new_dim;
}
else if (new_dim != curr_dim) {
/* The array is ragged, and this dimension is unusable already */
success = -1;
if (!sequence) {
/* Remove dimensions that we cannot use: */
*max_ndim -= new_ndim - i;
}
else {
assert(i == 0);
/* max_ndim is usually not updated for sequences, so set now: */
*max_ndim = curr_ndim;
}
break;
}
}
if (!sequence) {
*flags |= MAX_DIMS_WAS_REACHED;
}
return success;
}
#define COERCION_CACHE_CACHE_SIZE 5
static int _coercion_cache_num = 0;
static coercion_cache_obj *_coercion_cache_cache[COERCION_CACHE_CACHE_SIZE];
/*
* Steals a reference to the object.
*/
static NPY_INLINE int
npy_new_coercion_cache(
PyObject *converted_obj, PyObject *arr_or_sequence, npy_bool sequence,
coercion_cache_obj ***next_ptr, int ndim)
{
coercion_cache_obj *cache;
if (_coercion_cache_num > 0) {
_coercion_cache_num--;
cache = _coercion_cache_cache[_coercion_cache_num];
}
else {
cache = PyMem_Malloc(sizeof(coercion_cache_obj));
}
if (cache == NULL) {
PyErr_NoMemory();
return -1;
}
cache->converted_obj = converted_obj;
cache->arr_or_sequence = arr_or_sequence;
cache->sequence = sequence;
cache->depth = ndim;
cache->next = NULL;
**next_ptr = cache;
*next_ptr = &(cache->next);
return 0;
}
/**
* Unlink coercion cache item.
*
* @param current
* @return next coercion cache object (or NULL)
*/
NPY_NO_EXPORT NPY_INLINE coercion_cache_obj *
npy_unlink_coercion_cache(coercion_cache_obj *current)
{
coercion_cache_obj *next = current->next;
Py_DECREF(current->arr_or_sequence);
if (_coercion_cache_num < COERCION_CACHE_CACHE_SIZE) {
_coercion_cache_cache[_coercion_cache_num] = current;
_coercion_cache_num++;
}
else {
PyMem_Free(current);
}
return next;
}
NPY_NO_EXPORT NPY_INLINE void
npy_free_coercion_cache(coercion_cache_obj *next) {
/* We only need to check from the last used cache pos */
while (next != NULL) {
next = npy_unlink_coercion_cache(next);
}
}
#undef COERCION_CACHE_CACHE_SIZE
/**
* Do the promotion step and possible casting. This function should
* never be called if a descriptor was requested. In that case the output
* dtype is not of importance, so we must not risk promotion errors.
*
* @param out_descr The current descriptor.
* @param descr The newly found descriptor to promote with
* @param fixed_DType The user provided (fixed) DType or NULL
* @param flags dtype discover flags to signal failed promotion.
* @return -1 on error, 0 on success.
*/
static NPY_INLINE int
handle_promotion(PyArray_Descr **out_descr, PyArray_Descr *descr,
PyArray_DTypeMeta *fixed_DType, enum _dtype_discovery_flags *flags)
{
assert(!(*flags & DESCRIPTOR_WAS_SET));
if (*out_descr == NULL) {
Py_INCREF(descr);
*out_descr = descr;
return 0;
}
PyArray_Descr *new_descr = PyArray_PromoteTypes(descr, *out_descr);
if (NPY_UNLIKELY(new_descr == NULL)) {
if (fixed_DType != NULL) {
/* If a DType is fixed, promotion must not fail. */
return -1;
}
PyErr_Clear();
*flags |= PROMOTION_FAILED;
/* Continue with object, since we may need the dimensionality */
new_descr = PyArray_DescrFromType(NPY_OBJECT);
}
Py_SETREF(*out_descr, new_descr);
return 0;
}
/**
* Handle a leave node (known scalar) during dtype and shape discovery.
*
* @param obj The python object or nested sequence to convert
* @param curr_dims The current number of dimensions (depth in the recursion)
* @param max_dims The maximum number of dimensions.
* @param out_shape The discovered output shape, will be filled
* @param fixed_DType The user provided (fixed) DType or NULL
* @param flags used signal that this is a ragged array, used internally and
* can be expanded if necessary.
* @param DType the DType class that should be used, or NULL, if not provided.
*
* @return 0 on success -1 on error
*/
static NPY_INLINE int
handle_scalar(
PyObject *obj, int curr_dims, int *max_dims,
PyArray_Descr **out_descr, npy_intp *out_shape,
PyArray_DTypeMeta *fixed_DType,
enum _dtype_discovery_flags *flags, PyArray_DTypeMeta *DType)
{
PyArray_Descr *descr;
if (update_shape(curr_dims, max_dims, out_shape,
0, NULL, NPY_FALSE, flags) < 0) {
*flags |= FOUND_RAGGED_ARRAY;
return *max_dims;
}
if (*flags & DESCRIPTOR_WAS_SET) {
/* no need to do any promotion */
return *max_dims;
}
/* This is a scalar, so find the descriptor */
descr = find_scalar_descriptor(fixed_DType, DType, obj);
if (descr == NULL) {
return -1;
}
if (handle_promotion(out_descr, descr, fixed_DType, flags) < 0) {
Py_DECREF(descr);
return -1;
}
Py_DECREF(descr);
return *max_dims;
}
/**
* Return the correct descriptor given an array object and a DType class.
*
* This is identical to casting the arrays descriptor/dtype to the new
* DType class
*
* @param arr The array object.
* @param DType The DType class to cast to (or NULL for convenience)
* @param out_descr The output descriptor will set. The result can be NULL
* when the array is of object dtype and has no elements.
*
* @return -1 on failure, 0 on success.
*/
static int
find_descriptor_from_array(
PyArrayObject *arr, PyArray_DTypeMeta *DType, PyArray_Descr **out_descr)
{
enum _dtype_discovery_flags flags = 0;
*out_descr = NULL;
if (DType == NULL) {
*out_descr = PyArray_DESCR(arr);
Py_INCREF(*out_descr);
return 0;
}
if (NPY_UNLIKELY(DType->parametric && PyArray_ISOBJECT(arr))) {
/*
* We have one special case, if (and only if) the input array is of
* object DType and the dtype is not fixed already but parametric.
* Then, we allow inspection of all elements, treating them as
* elements. We do this recursively, so nested 0-D arrays can work,
* but nested higher dimensional arrays will lead to an error.
*/
assert(DType->type_num != NPY_OBJECT); /* not parametric */
PyArrayIterObject *iter;
iter = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr);
if (iter == NULL) {
return -1;
}
while (iter->index < iter->size) {
PyArray_DTypeMeta *item_DType;
/*
* Note: If the array contains typed objects we may need to use
* the dtype to use casting for finding the correct instance.
*/
PyObject *elem = PyArray_GETITEM(arr, iter->dataptr);
if (elem == NULL) {
Py_DECREF(iter);
return -1;
}
item_DType = discover_dtype_from_pyobject(elem, &flags, DType);
if (item_DType == NULL) {
Py_DECREF(iter);
Py_DECREF(elem);
return -1;
}
if (item_DType == (PyArray_DTypeMeta *)Py_None) {
Py_SETREF(item_DType, NULL);
}
int flat_max_dims = 0;
if (handle_scalar(elem, 0, &flat_max_dims, out_descr,
NULL, DType, &flags, item_DType) < 0) {
Py_DECREF(iter);
Py_DECREF(elem);
Py_XDECREF(item_DType);
return -1;
}
Py_XDECREF(item_DType);
Py_DECREF(elem);
PyArray_ITER_NEXT(iter);
}
Py_DECREF(iter);
}
else if (NPY_UNLIKELY(DType->type_num == NPY_DATETIME) &&
PyArray_ISSTRING(arr)) {
/*
* TODO: This branch should be deprecated IMO, the workaround is
* to cast to the object to a string array. Although a specific
* function (if there is even any need) would be better.
* This is value based casting!
* Unless of course we actually want to support this kind of thing
* in general (not just for object dtype)...
*/
PyArray_DatetimeMetaData meta;
meta.base = NPY_FR_GENERIC;
meta.num = 1;
if (find_string_array_datetime64_type(arr, &meta) < 0) {
return -1;
}
else {
*out_descr = create_datetime_dtype(NPY_DATETIME, &meta);
if (*out_descr == NULL) {
return -1;
}
}
}
else {
/*
* If this is not an object array figure out the dtype cast,
* or simply use the returned DType.
*/
*out_descr = PyArray_CastDescrToDType(PyArray_DESCR(arr), DType);
if (*out_descr == NULL) {
return -1;
}
}
return 0;
}
/**
* Given a dtype or DType object, find the correct descriptor to cast the
* array to.
*
* This function is identical to normal casting using only the dtype, however,
* it supports inspecting the elements when the array has object dtype
* (and the given datatype describes a parametric DType class).
*
* @param arr
* @param dtype A dtype instance or class.
* @return A concrete dtype instance or NULL
*/
NPY_NO_EXPORT PyArray_Descr *
PyArray_AdaptDescriptorToArray(PyArrayObject *arr, PyObject *dtype)
{
/* If the requested dtype is flexible, adapt it */
PyArray_Descr *new_dtype;
PyArray_DTypeMeta *new_DType;
int res;
res = PyArray_ExtractDTypeAndDescriptor((PyObject *)dtype,
&new_dtype, &new_DType);
if (res < 0) {
return NULL;
}
if (new_dtype == NULL) {
res = find_descriptor_from_array(arr, new_DType, &new_dtype);
if (res < 0) {
Py_DECREF(new_DType);
return NULL;
}
if (new_dtype == NULL) {
/* This is an object array but contained no elements, use default */
new_dtype = new_DType->default_descr(new_DType);
}
}
Py_DECREF(new_DType);
return new_dtype;
}
/**
* Recursion helper for `PyArray_DiscoverDTypeAndShape`. See its
* documentation for additional details.
*
* @param obj The current (possibly nested) object
* @param curr_dims The current depth, i.e. initially 0 and increasing.
* @param max_dims Maximum number of dimensions, modified during discovery.
* @param out_descr dtype instance (or NULL) to promoted and update.
* @param out_shape The current shape (updated)
* @param coercion_cache_tail_ptr The tail of the linked list of coercion
* cache objects, which hold on to converted sequences and arrays.
* This is a pointer to the `->next` slot of the previous cache so
* that we can append a new cache object (and update this pointer).
* (Initially it is a pointer to the user-provided head pointer).
* @param fixed_DType User provided fixed DType class
* @param flags Discovery flags (reporting and behaviour flags, see def.)
* @return The updated number of maximum dimensions (i.e. scalars will set
* this to the current dimensions).
*/
NPY_NO_EXPORT int
PyArray_DiscoverDTypeAndShape_Recursive(
PyObject *obj, int curr_dims, int max_dims, PyArray_Descr**out_descr,
npy_intp out_shape[NPY_MAXDIMS],
coercion_cache_obj ***coercion_cache_tail_ptr,
PyArray_DTypeMeta *fixed_DType, enum _dtype_discovery_flags *flags)
{
PyArrayObject *arr = NULL;
PyObject *seq;
/*
* The first step is to find the DType class if it was not provided,
* alternatively we have to find out that this is not a scalar at all
* (which could fail and lead us to `object` dtype).
*/
PyArray_DTypeMeta *DType = NULL;
if (NPY_UNLIKELY(*flags & DISCOVER_STRINGS_AS_SEQUENCES)) {
/*
* We currently support that bytes/strings are considered sequences,
* if the dtype is np.dtype('c'), this should be deprecated probably,
* but requires hacks right now.
*/
if (PyBytes_Check(obj) && PyBytes_Size(obj) != 1) {
goto force_sequence_due_to_char_dtype;
}
else if (PyUnicode_Check(obj) && PyUnicode_GetLength(obj) != 1) {
goto force_sequence_due_to_char_dtype;
}
}
/* If this is a known scalar, find the corresponding DType class */
DType = discover_dtype_from_pyobject(obj, flags, fixed_DType);
if (DType == NULL) {
return -1;
}
else if (DType == (PyArray_DTypeMeta *)Py_None) {
Py_DECREF(Py_None);
}
else {
max_dims = handle_scalar(
obj, curr_dims, &max_dims, out_descr, out_shape, fixed_DType,
flags, DType);
Py_DECREF(DType);
return max_dims;
}
/*
* At this point we expect to find either a sequence, or an array-like.
* Although it is still possible that this fails and we have to use
* `object`.
*/
if (PyArray_Check(obj)) {
arr = (PyArrayObject *)obj;
Py_INCREF(arr);
}
else {
PyArray_Descr *requested_descr = NULL;
if (*flags & DESCRIPTOR_WAS_SET) {
/* __array__ may be passed the requested descriptor if provided */
requested_descr = *out_descr;
}
arr = (PyArrayObject *)_array_from_array_like(obj,
requested_descr, 0, NULL);
if (arr == NULL) {
return -1;
}
else if (arr == (PyArrayObject *)Py_NotImplemented) {
Py_DECREF(arr);
arr = NULL;
}
}
if (arr != NULL) {
/*
* This is an array object which will be added to the cache, keeps
* the reference to the array alive (takes ownership).
*/
if (npy_new_coercion_cache(obj, (PyObject *)arr,
0, coercion_cache_tail_ptr, curr_dims) < 0) {
return -1;
}
if (curr_dims == 0) {
/*
* Special case for reverse broadcasting, ignore max_dims if this
* is a single array-like object; needed for PyArray_CopyObject.
*/
memcpy(out_shape, PyArray_SHAPE(arr),
PyArray_NDIM(arr) * sizeof(npy_intp));
max_dims = PyArray_NDIM(arr);
}
else if (update_shape(curr_dims, &max_dims, out_shape,
PyArray_NDIM(arr), PyArray_SHAPE(arr), NPY_FALSE, flags) < 0) {
*flags |= FOUND_RAGGED_ARRAY;
return max_dims;
}
if (*flags & DESCRIPTOR_WAS_SET) {
return max_dims;
}
/*
* For arrays we may not just need to cast the dtype to the user
* provided fixed_DType. If this is an object array, the elements
* may need to be inspected individually.
* Note, this finds the descriptor of the array first and only then
* promotes here (different associativity).
*/
PyArray_Descr *cast_descr;
if (find_descriptor_from_array(arr, fixed_DType, &cast_descr) < 0) {
return -1;
}
if (cast_descr == NULL) {
/* object array with no elements, no need to promote/adjust. */
return max_dims;
}
if (handle_promotion(out_descr, cast_descr, fixed_DType, flags) < 0) {
Py_DECREF(cast_descr);
return -1;
}
Py_DECREF(cast_descr);
return max_dims;
}
/*
* The last step is to assume the input should be handled as a sequence
* and to handle it recursively. That is, unless we have hit the
* dimension limit.
*/
npy_bool is_sequence = PySequence_Check(obj);
if (is_sequence) {
is_sequence = PySequence_Size(obj) >= 0;
if (NPY_UNLIKELY(!is_sequence)) {
/* NOTE: This should likely just raise all errors */
if (PyErr_ExceptionMatches(PyExc_RecursionError) ||
PyErr_ExceptionMatches(PyExc_MemoryError)) {
/*
* Consider these unrecoverable errors, continuing execution
* might crash the interpreter.
*/
return -1;
}
PyErr_Clear();
}
}
if (NPY_UNLIKELY(*flags & DISCOVER_TUPLES_AS_ELEMENTS) &&
PyTuple_Check(obj)) {
is_sequence = NPY_FALSE;