/
convert_datatype.c
3625 lines (3289 loc) · 110 KB
/
convert_datatype.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 PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include "numpy/arrayobject.h"
#include "numpy/arrayscalars.h"
#include "npy_config.h"
#include "lowlevel_strided_loops.h"
#include "npy_pycompat.h"
#include "numpy/npy_math.h"
#include "array_coercion.h"
#include "common.h"
#include "ctors.h"
#include "dtypemeta.h"
#include "common_dtype.h"
#include "scalartypes.h"
#include "mapping.h"
#include "legacy_dtype_implementation.h"
#include "abstractdtypes.h"
#include "convert_datatype.h"
#include "_datetime.h"
#include "datetime_strings.h"
#include "array_method.h"
#include "usertypes.h"
#include "dtype_transfer.h"
/*
* Required length of string when converting from unsigned integer type.
* Array index is integer size in bytes.
* - 3 chars needed for cast to max value of 255 or 127
* - 5 chars needed for cast to max value of 65535 or 32767
* - 10 chars needed for cast to max value of 4294967295 or 2147483647
* - 20 chars needed for cast to max value of 18446744073709551615
* or 9223372036854775807
*/
NPY_NO_EXPORT npy_intp REQUIRED_STR_LEN[] = {0, 3, 5, 10, 10, 20, 20, 20, 20};
static PyObject *
PyArray_GetGenericToVoidCastingImpl(void);
static PyObject *
PyArray_GetVoidToGenericCastingImpl(void);
static PyObject *
PyArray_GetGenericToObjectCastingImpl(void);
static PyObject *
PyArray_GetObjectToGenericCastingImpl(void);
/**
* Fetch the casting implementation from one DType to another.
*
* @params from
* @params to
*
* @returns A castingimpl (PyArrayDTypeMethod *), None or NULL with an
* error set.
*/
NPY_NO_EXPORT PyObject *
PyArray_GetCastingImpl(PyArray_DTypeMeta *from, PyArray_DTypeMeta *to)
{
PyObject *res;
if (from == to) {
res = from->within_dtype_castingimpl;
}
else {
res = PyDict_GetItemWithError(from->castingimpls, (PyObject *)to);
}
if (res != NULL || PyErr_Occurred()) {
Py_XINCREF(res);
return res;
}
/*
* The following code looks up CastingImpl based on the fact that anything
* can be cast to and from objects or structured (void) dtypes.
*
* The last part adds casts dynamically based on legacy definition
*/
if (from->type_num == NPY_OBJECT) {
res = PyArray_GetObjectToGenericCastingImpl();
}
else if (to->type_num == NPY_OBJECT) {
res = PyArray_GetGenericToObjectCastingImpl();
}
else if (from->type_num == NPY_VOID) {
res = PyArray_GetVoidToGenericCastingImpl();
}
else if (to->type_num == NPY_VOID) {
res = PyArray_GetGenericToVoidCastingImpl();
}
else if (from->type_num < NPY_NTYPES && to->type_num < NPY_NTYPES) {
/* All builtin dtypes have their casts explicitly defined. */
PyErr_Format(PyExc_RuntimeError,
"builtin cast from %S to %S not found, this should not "
"be possible.", from, to);
return NULL;
}
else {
if (from->parametric || to->parametric) {
Py_RETURN_NONE;
}
/* Reject non-legacy dtypes (they need to use the new API) */
if (!from->legacy || !to->legacy) {
Py_RETURN_NONE;
}
if (from != to) {
/* A cast function must have been registered */
PyArray_VectorUnaryFunc *castfunc = PyArray_GetCastFunc(
from->singleton, to->type_num);
if (castfunc == NULL) {
PyErr_Clear();
/* Remember that this cast is not possible */
if (PyDict_SetItem(from->castingimpls, (PyObject *) to, Py_None) < 0) {
return NULL;
}
Py_RETURN_NONE;
}
}
/* PyArray_AddLegacyWrapping_CastingImpl find the correct casting level: */
/*
* TODO: Possibly move this to the cast registration time. But if we do
* that, we have to also update the cast when the casting safety
* is registered.
*/
if (PyArray_AddLegacyWrapping_CastingImpl(from, to, -1) < 0) {
return NULL;
}
return PyArray_GetCastingImpl(from, to);
}
if (res == NULL) {
return NULL;
}
if (from == to) {
PyErr_Format(PyExc_RuntimeError,
"Internal NumPy error, within-DType cast missing for %S!", from);
Py_DECREF(res);
return NULL;
}
if (PyDict_SetItem(from->castingimpls, (PyObject *)to, res) < 0) {
Py_DECREF(res);
return NULL;
}
return res;
}
/**
* Fetch the (bound) casting implementation from one DType to another.
*
* @params from
* @params to
*
* @returns A bound casting implementation or None (or NULL for error).
*/
static PyObject *
PyArray_GetBoundCastingImpl(PyArray_DTypeMeta *from, PyArray_DTypeMeta *to)
{
PyObject *method = PyArray_GetCastingImpl(from, to);
if (method == NULL || method == Py_None) {
return method;
}
/* TODO: Create better way to wrap method into bound method */
PyBoundArrayMethodObject *res;
res = PyObject_New(PyBoundArrayMethodObject, &PyBoundArrayMethod_Type);
if (res == NULL) {
return NULL;
}
res->method = (PyArrayMethodObject *)method;
res->dtypes = PyMem_Malloc(2 * sizeof(PyArray_DTypeMeta *));
if (res->dtypes == NULL) {
Py_DECREF(res);
return NULL;
}
Py_INCREF(from);
res->dtypes[0] = from;
Py_INCREF(to);
res->dtypes[1] = to;
return (PyObject *)res;
}
NPY_NO_EXPORT PyObject *
_get_castingimpl(PyObject *NPY_UNUSED(module), PyObject *args)
{
PyArray_DTypeMeta *from, *to;
if (!PyArg_ParseTuple(args, "O!O!:_get_castingimpl",
&PyArrayDTypeMeta_Type, &from, &PyArrayDTypeMeta_Type, &to)) {
return NULL;
}
return PyArray_GetBoundCastingImpl(from, to);
}
/**
* Find the minimal cast safety level given two cast-levels as input.
* Supports the NPY_CAST_IS_VIEW check, and should be preferred to allow
* extending cast-levels if necessary.
* It is not valid for one of the arguments to be -1 to indicate an error.
*
* @param casting1
* @param casting2
* @return The minimal casting error (can be -1).
*/
NPY_NO_EXPORT NPY_CASTING
PyArray_MinCastSafety(NPY_CASTING casting1, NPY_CASTING casting2)
{
if (casting1 < 0 || casting2 < 0) {
return -1;
}
NPY_CASTING view = casting1 & casting2 & _NPY_CAST_IS_VIEW;
casting1 = casting1 & ~_NPY_CAST_IS_VIEW;
casting2 = casting2 & ~_NPY_CAST_IS_VIEW;
/* larger casting values are less safe */
if (casting1 > casting2) {
return casting1 | view;
}
return casting2 | view;
}
/*NUMPY_API
* For backward compatibility
*
* Cast an array using typecode structure.
* steals reference to dtype --- cannot be NULL
*
* This function always makes a copy of arr, even if the dtype
* doesn't change.
*/
NPY_NO_EXPORT PyObject *
PyArray_CastToType(PyArrayObject *arr, PyArray_Descr *dtype, int is_f_order)
{
PyObject *out;
Py_SETREF(dtype, PyArray_AdaptDescriptorToArray(arr, (PyObject *)dtype));
if (dtype == NULL) {
return NULL;
}
out = PyArray_NewFromDescr(Py_TYPE(arr), dtype,
PyArray_NDIM(arr),
PyArray_DIMS(arr),
NULL, NULL,
is_f_order,
(PyObject *)arr);
if (out == NULL) {
return NULL;
}
if (PyArray_CopyInto((PyArrayObject *)out, arr) < 0) {
Py_DECREF(out);
return NULL;
}
return out;
}
/*NUMPY_API
* Get a cast function to cast from the input descriptor to the
* output type_number (must be a registered data-type).
* Returns NULL if un-successful.
*/
NPY_NO_EXPORT PyArray_VectorUnaryFunc *
PyArray_GetCastFunc(PyArray_Descr *descr, int type_num)
{
PyArray_VectorUnaryFunc *castfunc = NULL;
if (type_num < NPY_NTYPES_ABI_COMPATIBLE) {
castfunc = descr->f->cast[type_num];
}
else {
PyObject *obj = descr->f->castdict;
if (obj && PyDict_Check(obj)) {
PyObject *key;
PyObject *cobj;
key = PyLong_FromLong(type_num);
cobj = PyDict_GetItem(obj, key);
Py_DECREF(key);
if (cobj && PyCapsule_CheckExact(cobj)) {
castfunc = PyCapsule_GetPointer(cobj, NULL);
if (castfunc == NULL) {
return NULL;
}
}
}
}
if (PyTypeNum_ISCOMPLEX(descr->type_num) &&
!PyTypeNum_ISCOMPLEX(type_num) &&
PyTypeNum_ISNUMBER(type_num) &&
!PyTypeNum_ISBOOL(type_num)) {
PyObject *cls = NULL, *obj = NULL;
int ret;
obj = PyImport_ImportModule("numpy.core");
if (obj) {
cls = PyObject_GetAttrString(obj, "ComplexWarning");
Py_DECREF(obj);
}
ret = PyErr_WarnEx(cls,
"Casting complex values to real discards "
"the imaginary part", 1);
Py_XDECREF(cls);
if (ret < 0) {
return NULL;
}
}
if (castfunc) {
return castfunc;
}
PyErr_SetString(PyExc_ValueError,
"No cast function available.");
return NULL;
}
/*
* Must be broadcastable.
* This code is very similar to PyArray_CopyInto/PyArray_MoveInto
* except casting is done --- NPY_BUFSIZE is used
* as the size of the casting buffer.
*/
/*NUMPY_API
* Cast to an already created array.
*/
NPY_NO_EXPORT int
PyArray_CastTo(PyArrayObject *out, PyArrayObject *mp)
{
/* CopyInto handles the casting now */
return PyArray_CopyInto(out, mp);
}
/*NUMPY_API
* Cast to an already created array. Arrays don't have to be "broadcastable"
* Only requirement is they have the same number of elements.
*/
NPY_NO_EXPORT int
PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp)
{
/* CopyAnyInto handles the casting now */
return PyArray_CopyAnyInto(out, mp);
}
static NPY_CASTING
_get_cast_safety_from_castingimpl(PyArrayMethodObject *castingimpl,
PyArray_DTypeMeta *dtypes[2], PyArray_Descr *from, PyArray_Descr *to)
{
PyArray_Descr *descrs[2] = {from, to};
PyArray_Descr *out_descrs[2];
NPY_CASTING casting = castingimpl->resolve_descriptors(
castingimpl, dtypes, descrs, out_descrs);
if (casting < 0) {
return -1;
}
/* The returned descriptors may not match, requiring a second check */
if (out_descrs[0] != descrs[0]) {
NPY_CASTING from_casting = PyArray_GetCastSafety(
descrs[0], out_descrs[0], NULL);
casting = PyArray_MinCastSafety(casting, from_casting);
if (casting < 0) {
goto finish;
}
}
if (descrs[1] != NULL && out_descrs[1] != descrs[1]) {
NPY_CASTING from_casting = PyArray_GetCastSafety(
descrs[1], out_descrs[1], NULL);
casting = PyArray_MinCastSafety(casting, from_casting);
if (casting < 0) {
goto finish;
}
}
finish:
Py_DECREF(out_descrs[0]);
Py_DECREF(out_descrs[1]);
/* NPY_NO_CASTING has to be used for (NPY_EQUIV_CASTING|_NPY_CAST_IS_VIEW) */
assert(casting != (NPY_EQUIV_CASTING|_NPY_CAST_IS_VIEW));
return casting;
}
/**
* Given two dtype instances, find the correct casting safety.
*
* Note that in many cases, it may be preferable to fetch the casting
* implementations fully to have them available for doing the actual cast
* later.
*
* @param from
* @param to The descriptor to cast to (may be NULL)
* @param to_dtype If `to` is NULL, must pass the to_dtype (otherwise this
* is ignored).
* @return NPY_CASTING or -1 on error or if the cast is not possible.
*/
NPY_NO_EXPORT NPY_CASTING
PyArray_GetCastSafety(
PyArray_Descr *from, PyArray_Descr *to, PyArray_DTypeMeta *to_dtype)
{
if (to != NULL) {
to_dtype = NPY_DTYPE(to);
}
PyObject *meth = PyArray_GetCastingImpl(NPY_DTYPE(from), to_dtype);
if (meth == NULL) {
return -1;
}
if (meth == Py_None) {
Py_DECREF(Py_None);
return -1;
}
PyArrayMethodObject *castingimpl = (PyArrayMethodObject *)meth;
PyArray_DTypeMeta *dtypes[2] = {NPY_DTYPE(from), to_dtype};
NPY_CASTING casting = _get_cast_safety_from_castingimpl(castingimpl,
dtypes, from, to);
Py_DECREF(meth);
return casting;
}
/**
* Check whether a cast is safe, see also `PyArray_GetCastSafety` for
* a similiar function. Unlike GetCastSafety, this function checks the
* `castingimpl->casting` when available. This allows for two things:
*
* 1. It avoids calling `resolve_descriptors` in some cases.
* 2. Strings need to discover the length, but in some cases we know that the
* cast is valid (assuming the string length is discovered first).
*
* The latter means that a `can_cast` could return True, but the cast fail
* because the parametric type cannot guess the correct output descriptor.
* (I.e. if `object_arr.astype("S")` did _not_ inspect the objects, and the
* user would have to guess the string length.)
*
* @param casting the requested casting safety.
* @param from
* @param to The descriptor to cast to (may be NULL)
* @param to_dtype If `to` is NULL, must pass the to_dtype (otherwise this
* is ignored).
* @return 0 for an invalid cast, 1 for a valid and -1 for an error.
*/
NPY_NO_EXPORT int
PyArray_CheckCastSafety(NPY_CASTING casting,
PyArray_Descr *from, PyArray_Descr *to, PyArray_DTypeMeta *to_dtype)
{
if (to != NULL) {
to_dtype = NPY_DTYPE(to);
}
PyObject *meth = PyArray_GetCastingImpl(NPY_DTYPE(from), to_dtype);
if (meth == NULL) {
return -1;
}
if (meth == Py_None) {
Py_DECREF(Py_None);
return -1;
}
PyArrayMethodObject *castingimpl = (PyArrayMethodObject *)meth;
if (PyArray_MinCastSafety(castingimpl->casting, casting) == casting) {
/* No need to check using `castingimpl.resolve_descriptors()` */
Py_DECREF(meth);
return 1;
}
PyArray_DTypeMeta *dtypes[2] = {NPY_DTYPE(from), to_dtype};
NPY_CASTING safety = _get_cast_safety_from_castingimpl(castingimpl,
dtypes, from, to);
Py_DECREF(meth);
/* If casting is the smaller (or equal) safety we match */
if (safety < 0) {
return -1;
}
return PyArray_MinCastSafety(safety, casting) == casting;
}
/*NUMPY_API
*Check the type coercion rules.
*/
NPY_NO_EXPORT int
PyArray_CanCastSafely(int fromtype, int totype)
{
/* Identity */
if (fromtype == totype) {
return 1;
}
/*
* As a micro-optimization, keep the cast table around. This can probably
* be removed as soon as the ufunc loop lookup is modified (presumably
* before the 1.21 release). It does no harm, but the main user of this
* function is the ufunc-loop lookup calling it until a loop matches!
*
* (The table extends further, but is not strictly correct for void).
* TODO: Check this!
*/
if ((unsigned int)fromtype <= NPY_CLONGDOUBLE &&
(unsigned int)totype <= NPY_CLONGDOUBLE) {
return _npy_can_cast_safely_table[fromtype][totype];
}
PyArray_DTypeMeta *from = PyArray_DTypeFromTypeNum(fromtype);
if (from == NULL) {
PyErr_WriteUnraisable(NULL);
return 0;
}
PyArray_DTypeMeta *to = PyArray_DTypeFromTypeNum(totype);
if (to == NULL) {
PyErr_WriteUnraisable(NULL);
return 0;
}
PyObject *castingimpl = PyArray_GetCastingImpl(from, to);
Py_DECREF(from);
Py_DECREF(to);
if (castingimpl == NULL) {
PyErr_WriteUnraisable(NULL);
return 0;
}
else if (castingimpl == Py_None) {
Py_DECREF(Py_None);
return 0;
}
NPY_CASTING safety = ((PyArrayMethodObject *)castingimpl)->casting;
int res = PyArray_MinCastSafety(safety, NPY_SAFE_CASTING) == NPY_SAFE_CASTING;
Py_DECREF(castingimpl);
return res;
}
/*NUMPY_API
* leaves reference count alone --- cannot be NULL
*
* PyArray_CanCastTypeTo is equivalent to this, but adds a 'casting'
* parameter.
*/
NPY_NO_EXPORT npy_bool
PyArray_CanCastTo(PyArray_Descr *from, PyArray_Descr *to)
{
return PyArray_CanCastTypeTo(from, to, NPY_SAFE_CASTING);
}
/* Provides an ordering for the dtype 'kind' character codes */
NPY_NO_EXPORT int
dtype_kind_to_ordering(char kind)
{
switch (kind) {
/* Boolean kind */
case 'b':
return 0;
/* Unsigned int kind */
case 'u':
return 1;
/* Signed int kind */
case 'i':
return 2;
/* Float kind */
case 'f':
return 4;
/* Complex kind */
case 'c':
return 5;
/* String kind */
case 'S':
case 'a':
return 6;
/* Unicode kind */
case 'U':
return 7;
/* Void kind */
case 'V':
return 8;
/* Object kind */
case 'O':
return 9;
/*
* Anything else, like datetime, is special cased to
* not fit in this hierarchy
*/
default:
return -1;
}
}
/* Converts a type number from unsigned to signed */
static int
type_num_unsigned_to_signed(int type_num)
{
switch (type_num) {
case NPY_UBYTE:
return NPY_BYTE;
case NPY_USHORT:
return NPY_SHORT;
case NPY_UINT:
return NPY_INT;
case NPY_ULONG:
return NPY_LONG;
case NPY_ULONGLONG:
return NPY_LONGLONG;
default:
return type_num;
}
}
/*NUMPY_API
* Returns true if data of type 'from' may be cast to data of type
* 'to' according to the rule 'casting'.
*/
NPY_NO_EXPORT npy_bool
PyArray_CanCastTypeTo(PyArray_Descr *from, PyArray_Descr *to,
NPY_CASTING casting)
{
PyArray_DTypeMeta *to_dtype = NPY_DTYPE(to);
/*
* NOTE: This code supports U and S, this is identical to the code
* in `ctors.c` which does not allow these dtypes to be attached
* to an array. Unlike the code for `np.array(..., dtype=)`
* which uses `PyArray_ExtractDTypeAndDescriptor` it rejects "m8"
* as a flexible dtype instance representing a DType.
*/
/*
* TODO: We should grow support for `np.can_cast("d", "S")` being
* different from `np.can_cast("d", "S0")` here, at least for
* the python side API.
* The `to = NULL` branch, which considers "S0" to be "flexible"
* should probably be deprecated.
* (This logic is duplicated in `PyArray_CanCastArrayTo`)
*/
if (PyDataType_ISUNSIZED(to) && to->subarray == NULL) {
to = NULL; /* consider mainly S0 and U0 as S and U */
}
int is_valid = PyArray_CheckCastSafety(casting, from, to, to_dtype);
/* Clear any errors and consider this unsafe (should likely be changed) */
if (is_valid < 0) {
PyErr_Clear();
return 0;
}
return is_valid;
}
/* CanCastArrayTo needs this function */
static int min_scalar_type_num(char *valueptr, int type_num,
int *is_small_unsigned);
/*
* NOTE: This function uses value based casting logic for scalars. It will
* require updates when we phase out value-based-casting.
*/
NPY_NO_EXPORT npy_bool
can_cast_scalar_to(PyArray_Descr *scal_type, char *scal_data,
PyArray_Descr *to, NPY_CASTING casting)
{
/*
* If the two dtypes are actually references to the same object
* or if casting type is forced unsafe then always OK.
*
* TODO: Assuming that unsafe casting always works is not actually correct
*/
if (scal_type == to || casting == NPY_UNSAFE_CASTING ) {
return 1;
}
int valid = PyArray_CheckCastSafety(casting, scal_type, to, NPY_DTYPE(to));
if (valid == 1) {
/* This is definitely a valid cast. */
return 1;
}
if (valid < 0) {
/* Probably must return 0, but just keep trying for now. */
PyErr_Clear();
}
/*
* If the scalar isn't a number, value-based casting cannot kick in and
* we must not attempt it.
* (Additional fast-checks would be possible, but probably unnecessary.)
*/
if (!PyTypeNum_ISNUMBER(scal_type->type_num)) {
return 0;
}
/*
* At this point we have to check value-based casting.
*/
PyArray_Descr *dtype;
int is_small_unsigned = 0, type_num;
/* An aligned memory buffer large enough to hold any builtin numeric type */
npy_longlong value[4];
int swap = !PyArray_ISNBO(scal_type->byteorder);
scal_type->f->copyswap(&value, scal_data, swap, NULL);
type_num = min_scalar_type_num((char *)&value, scal_type->type_num,
&is_small_unsigned);
/*
* If we've got a small unsigned scalar, and the 'to' type
* is not unsigned, then make it signed to allow the value
* to be cast more appropriately.
*/
if (is_small_unsigned && !(PyTypeNum_ISUNSIGNED(to->type_num))) {
type_num = type_num_unsigned_to_signed(type_num);
}
dtype = PyArray_DescrFromType(type_num);
if (dtype == NULL) {
return 0;
}
#if 0
printf("min scalar cast ");
PyObject_Print(dtype, stdout, 0);
printf(" to ");
PyObject_Print(to, stdout, 0);
printf("\n");
#endif
npy_bool ret = PyArray_CanCastTypeTo(dtype, to, casting);
Py_DECREF(dtype);
return ret;
}
/*NUMPY_API
* Returns 1 if the array object may be cast to the given data type using
* the casting rule, 0 otherwise. This differs from PyArray_CanCastTo in
* that it handles scalar arrays (0 dimensions) specially, by checking
* their value.
*/
NPY_NO_EXPORT npy_bool
PyArray_CanCastArrayTo(PyArrayObject *arr, PyArray_Descr *to,
NPY_CASTING casting)
{
PyArray_Descr *from = PyArray_DESCR(arr);
PyArray_DTypeMeta *to_dtype = NPY_DTYPE(to);
/* NOTE, TODO: The same logic as `PyArray_CanCastTypeTo`: */
if (PyDataType_ISUNSIZED(to) && to->subarray == NULL) {
to = NULL;
}
/*
* If it's a scalar, check the value. (This only currently matters for
* numeric types and for `to == NULL` it can't be numeric.)
*/
if (PyArray_NDIM(arr) == 0 && !PyArray_HASFIELDS(arr) && to != NULL) {
return can_cast_scalar_to(from, PyArray_DATA(arr), to, casting);
}
/* Otherwise, use the standard rules (same as `PyArray_CanCastTypeTo`) */
int is_valid = PyArray_CheckCastSafety(casting, from, to, to_dtype);
/* Clear any errors and consider this unsafe (should likely be changed) */
if (is_valid < 0) {
PyErr_Clear();
return 0;
}
return is_valid;
}
NPY_NO_EXPORT const char *
npy_casting_to_string(NPY_CASTING casting)
{
switch (casting) {
case NPY_NO_CASTING:
return "'no'";
case NPY_EQUIV_CASTING:
return "'equiv'";
case NPY_SAFE_CASTING:
return "'safe'";
case NPY_SAME_KIND_CASTING:
return "'same_kind'";
case NPY_UNSAFE_CASTING:
return "'unsafe'";
default:
return "<unknown>";
}
}
/**
* Helper function to set a useful error when casting is not possible.
*
* @param src_dtype
* @param dst_dtype
* @param casting
* @param scalar Whether this was a "scalar" cast (includes 0-D array with
* PyArray_CanCastArrayTo result).
*/
NPY_NO_EXPORT void
npy_set_invalid_cast_error(
PyArray_Descr *src_dtype, PyArray_Descr *dst_dtype,
NPY_CASTING casting, npy_bool scalar)
{
char *msg;
if (!scalar) {
msg = "Cannot cast array data from %R to %R according to the rule %s";
}
else {
msg = "Cannot cast scalar from %R to %R according to the rule %s";
}
PyErr_Format(PyExc_TypeError,
msg, src_dtype, dst_dtype, npy_casting_to_string(casting));
}
/*NUMPY_API
* See if array scalars can be cast.
*
* TODO: For NumPy 2.0, add a NPY_CASTING parameter.
*/
NPY_NO_EXPORT npy_bool
PyArray_CanCastScalar(PyTypeObject *from, PyTypeObject *to)
{
int fromtype;
int totype;
fromtype = _typenum_fromtypeobj((PyObject *)from, 0);
totype = _typenum_fromtypeobj((PyObject *)to, 0);
if (fromtype == NPY_NOTYPE || totype == NPY_NOTYPE) {
return NPY_FALSE;
}
return (npy_bool) PyArray_CanCastSafely(fromtype, totype);
}
/*
* Internal promote types function which handles unsigned integers which
* fit in same-sized signed integers specially.
*/
static PyArray_Descr *
promote_types(PyArray_Descr *type1, PyArray_Descr *type2,
int is_small_unsigned1, int is_small_unsigned2)
{
if (is_small_unsigned1) {
int type_num1 = type1->type_num;
int type_num2 = type2->type_num;
int ret_type_num;
if (type_num2 < NPY_NTYPES && !(PyTypeNum_ISBOOL(type_num2) ||
PyTypeNum_ISUNSIGNED(type_num2))) {
/* Convert to the equivalent-sized signed integer */
type_num1 = type_num_unsigned_to_signed(type_num1);
ret_type_num = _npy_type_promotion_table[type_num1][type_num2];
/* The table doesn't handle string/unicode/void, check the result */
if (ret_type_num >= 0) {
return PyArray_DescrFromType(ret_type_num);
}
}
return PyArray_PromoteTypes(type1, type2);
}
else if (is_small_unsigned2) {
int type_num1 = type1->type_num;
int type_num2 = type2->type_num;
int ret_type_num;
if (type_num1 < NPY_NTYPES && !(PyTypeNum_ISBOOL(type_num1) ||
PyTypeNum_ISUNSIGNED(type_num1))) {
/* Convert to the equivalent-sized signed integer */
type_num2 = type_num_unsigned_to_signed(type_num2);
ret_type_num = _npy_type_promotion_table[type_num1][type_num2];
/* The table doesn't handle string/unicode/void, check the result */
if (ret_type_num >= 0) {
return PyArray_DescrFromType(ret_type_num);
}
}
return PyArray_PromoteTypes(type1, type2);
}
else {
return PyArray_PromoteTypes(type1, type2);
}
}
/*
* Returns a new reference to type if it is already NBO, otherwise
* returns a copy converted to NBO.
*/
NPY_NO_EXPORT PyArray_Descr *
ensure_dtype_nbo(PyArray_Descr *type)
{
if (PyArray_ISNBO(type->byteorder)) {
Py_INCREF(type);
return type;
}
else {
return PyArray_DescrNewByteorder(type, NPY_NATIVE);
}
}
/**
* This function should possibly become public API eventually. At this
* time it is implemented by falling back to `PyArray_AdaptFlexibleDType`.
* We will use `CastingImpl[from, to].resolve_descriptors(...)` to implement
* this logic.
* Before that, the API needs to be reviewed though.
*
* WARNING: This function currently does not guarantee that `descr` can
* actually be cast to the given DType.
*
* @param descr The dtype instance to adapt "cast"
* @param given_DType The DType class for which we wish to find an instance able
* to represent `descr`.
* @returns Instance of `given_DType`. If `given_DType` is parametric the
* descr may be adapted to hold it.
*/
NPY_NO_EXPORT PyArray_Descr *
PyArray_CastDescrToDType(PyArray_Descr *descr, PyArray_DTypeMeta *given_DType)
{
if (NPY_DTYPE(descr) == given_DType) {
Py_INCREF(descr);
return descr;
}
if (!given_DType->parametric) {
/*
* Don't actually do anything, the default is always the result
* of any cast.
*/
return given_DType->default_descr(given_DType);
}
if (PyObject_TypeCheck((PyObject *)descr, (PyTypeObject *)given_DType)) {
Py_INCREF(descr);
return descr;
}
PyObject *tmp = PyArray_GetCastingImpl(NPY_DTYPE(descr), given_DType);
if (tmp == NULL || tmp == Py_None) {
Py_XDECREF(tmp);
goto error;
}
PyArray_DTypeMeta *dtypes[2] = {NPY_DTYPE(descr), given_DType};
PyArray_Descr *given_descrs[2] = {descr, NULL};
PyArray_Descr *loop_descrs[2];
PyArrayMethodObject *meth = (PyArrayMethodObject *)tmp;
NPY_CASTING casting = meth->resolve_descriptors(
meth, dtypes, given_descrs, loop_descrs);
Py_DECREF(tmp);
if (casting < 0) {
goto error;
}
Py_DECREF(loop_descrs[0]);
return loop_descrs[1];
error:; /* (; due to compiler limitations) */
PyObject *err_type = NULL, *err_value = NULL, *err_traceback = NULL;
PyErr_Fetch(&err_type, &err_value, &err_traceback);
PyErr_Format(PyExc_TypeError,
"cannot cast dtype %S to %S.", descr, given_DType);
npy_PyErr_ChainExceptionsCause(err_type, err_value, err_traceback);
return NULL;
}
/*
* Helper to find the target descriptor for multiple arrays given an input
* one that may be a DType class (e.g. "U" or "S").
* Works with arrays, since that is what `concatenate` works with. However,
* unlike `np.array(...)` or `arr.astype()` we will never inspect the array's
* content, which means that object arrays can only be cast to strings if a
* fixed width is provided (same for string -> generic datetime).
*
* As this function uses `PyArray_ExtractDTypeAndDescriptor`, it should
* eventually be refactored to move the step to an earlier point.
*/
NPY_NO_EXPORT PyArray_Descr *
PyArray_FindConcatenationDescriptor(
npy_intp n, PyArrayObject **arrays, PyObject *requested_dtype)
{
if (requested_dtype == NULL) {
return PyArray_LegacyResultType(n, arrays, 0, NULL);
}
PyArray_DTypeMeta *common_dtype;