-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
convert_datatype.c
2265 lines (2098 loc) · 70.2 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 "npy_pycompat.h"
#include "numpy/npy_math.h"
#include "common.h"
#include "ctors.h"
#include "scalartypes.h"
#include "mapping.h"
#include "convert_datatype.h"
#include "_datetime.h"
#include "datetime_strings.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};
/*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;
/* If the requested dtype is flexible, adapt it */
dtype = PyArray_AdaptFlexibleDType((PyObject *)arr, PyArray_DESCR(arr), 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 = PyInt_FromLong(type_num);
cobj = PyDict_GetItem(obj, key);
Py_DECREF(key);
if (cobj && NpyCapsule_Check(cobj)) {
castfunc = NpyCapsule_AsVoidPtr(cobj);
}
}
}
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;
}
/*
* This function returns a dtype based on flex_dtype and the values in
* data_dtype and data_obj. It also calls Py_DECREF on the flex_dtype. If the
* flex_dtype is not flexible, it returns it as-is.
*
* Usually, if data_obj is not an array, dtype should be the result
* given by the PyArray_GetArrayParamsFromObject function.
*
* The data_obj may be NULL if just a dtype is known for the source.
*
* If *flex_dtype is NULL, returns immediately, without setting an
* exception, leaving any previous error handling intact.
*
* The current flexible dtypes include NPY_STRING, NPY_UNICODE, NPY_VOID,
* and NPY_DATETIME with generic units.
*/
NPY_NO_EXPORT PyArray_Descr *
PyArray_AdaptFlexibleDType(PyObject *data_obj, PyArray_Descr *data_dtype,
PyArray_Descr *flex_dtype)
{
PyArray_DatetimeMetaData *meta;
PyArray_Descr *retval = NULL;
int flex_type_num;
if (flex_dtype == NULL) {
return retval;
}
flex_type_num = flex_dtype->type_num;
/* Flexible types with expandable size */
if (PyDataType_ISUNSIZED(flex_dtype)) {
/* First replace the flex_dtype */
retval = PyArray_DescrNew(flex_dtype);
Py_DECREF(flex_dtype);
if (retval == NULL) {
return retval;
}
if (data_dtype->type_num == flex_type_num ||
flex_type_num == NPY_VOID) {
(retval)->elsize = data_dtype->elsize;
}
else if (flex_type_num == NPY_STRING || flex_type_num == NPY_UNICODE) {
npy_intp size = 8;
/*
* Get a string-size estimate of the input. These
* are generallly the size needed, rounded up to
* a multiple of eight.
*/
switch (data_dtype->type_num) {
case NPY_BOOL:
case NPY_UBYTE:
case NPY_BYTE:
case NPY_USHORT:
case NPY_SHORT:
case NPY_UINT:
case NPY_INT:
case NPY_ULONG:
case NPY_LONG:
case NPY_ULONGLONG:
case NPY_LONGLONG:
if (data_dtype->kind == 'b') {
/* 5 chars needed for cast to 'True' or 'False' */
size = 5;
}
else if (data_dtype->elsize > 8 ||
data_dtype->elsize < 0) {
/*
* Element size should never be greater than 8 or
* less than 0 for integer type, but just in case...
*/
break;
}
else if (data_dtype->kind == 'u') {
size = REQUIRED_STR_LEN[data_dtype->elsize];
}
else if (data_dtype->kind == 'i') {
/* Add character for sign symbol */
size = REQUIRED_STR_LEN[data_dtype->elsize] + 1;
}
break;
case NPY_HALF:
case NPY_FLOAT:
case NPY_DOUBLE:
size = 32;
break;
case NPY_LONGDOUBLE:
size = 48;
break;
case NPY_CFLOAT:
case NPY_CDOUBLE:
size = 2 * 32;
break;
case NPY_CLONGDOUBLE:
size = 2 * 48;
break;
case NPY_OBJECT:
size = 64;
if ((flex_type_num == NPY_STRING ||
flex_type_num == NPY_UNICODE) &&
data_obj != NULL) {
PyObject *list;
if (PyArray_CheckScalar(data_obj)) {
list = PyArray_ToList((PyArrayObject *)data_obj);
if (list != NULL) {
PyObject *s = PyObject_Str(list);
if (s == NULL) {
Py_DECREF(list);
Py_DECREF(retval);
return NULL;
}
else {
size = PyObject_Length(s);
Py_DECREF(s);
}
Py_DECREF(list);
}
}
else if (PyArray_Check(data_obj)) {
/*
* Convert data array to list of objects since
* GetArrayParamsFromObject won't iterate over
* array.
*/
PyArray_Descr *dtype = NULL;
PyArrayObject *arr = NULL;
int result;
int ndim = 0;
npy_intp dims[NPY_MAXDIMS];
list = PyArray_ToList((PyArrayObject *)data_obj);
result = PyArray_GetArrayParamsFromObject_int(
list,
retval,
0, &dtype,
&ndim, dims, &arr);
Py_DECREF(list);
Py_XDECREF(arr);
if (result < 0) {
Py_XDECREF(dtype);
Py_DECREF(retval);
return NULL;
}
if (result == 0 && dtype != NULL) {
if (flex_type_num == NPY_UNICODE) {
size = dtype->elsize / 4;
}
else {
size = dtype->elsize;
}
}
Py_XDECREF(dtype);
}
else if (PyArray_IsPythonScalar(data_obj)) {
PyObject *s = PyObject_Str(data_obj);
if (s == NULL) {
Py_DECREF(retval);
return NULL;
}
else {
size = PyObject_Length(s);
Py_DECREF(s);
}
}
}
break;
case NPY_STRING:
case NPY_VOID:
size = data_dtype->elsize;
break;
case NPY_UNICODE:
size = data_dtype->elsize / 4;
break;
case NPY_DATETIME:
meta = get_datetime_metadata_from_dtype(data_dtype);
if (meta == NULL) {
Py_DECREF(retval);
return NULL;
}
size = get_datetime_iso_8601_strlen(0, meta->base);
break;
case NPY_TIMEDELTA:
size = 21;
break;
}
if (flex_type_num == NPY_STRING) {
retval->elsize = size;
}
else if (flex_type_num == NPY_UNICODE) {
retval->elsize = size * 4;
}
}
else {
/*
* We should never get here, but just in case someone adds
* a new flex dtype...
*/
PyErr_SetString(PyExc_TypeError,
"don't know how to adapt flex dtype");
Py_DECREF(retval);
return NULL;
}
}
/* Flexible type with generic time unit that adapts */
else if (flex_type_num == NPY_DATETIME ||
flex_type_num == NPY_TIMEDELTA) {
meta = get_datetime_metadata_from_dtype(flex_dtype);
retval = flex_dtype;
if (meta == NULL) {
return NULL;
}
if (meta->base == NPY_FR_GENERIC) {
if (data_dtype->type_num == NPY_DATETIME ||
data_dtype->type_num == NPY_TIMEDELTA) {
meta = get_datetime_metadata_from_dtype(data_dtype);
if (meta == NULL) {
return NULL;
}
retval = create_datetime_dtype(flex_type_num, meta);
Py_DECREF(flex_dtype);
}
else if (data_obj != NULL) {
/* Detect the unit from the input's data */
retval = find_object_datetime_type(data_obj,
flex_type_num);
Py_DECREF(flex_dtype);
}
}
}
else {
retval = flex_dtype;
}
return retval;
}
/*
* 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);
}
/*NUMPY_API
*Check the type coercion rules.
*/
NPY_NO_EXPORT int
PyArray_CanCastSafely(int fromtype, int totype)
{
PyArray_Descr *from;
/* Fast table lookup for small type numbers */
if ((unsigned int)fromtype < NPY_NTYPES &&
(unsigned int)totype < NPY_NTYPES) {
return _npy_can_cast_safely_table[fromtype][totype];
}
/* Identity */
if (fromtype == totype) {
return 1;
}
/* Special-cases for some types */
switch (fromtype) {
case NPY_DATETIME:
case NPY_TIMEDELTA:
case NPY_OBJECT:
case NPY_VOID:
return 0;
case NPY_BOOL:
return 1;
}
switch (totype) {
case NPY_BOOL:
case NPY_DATETIME:
case NPY_TIMEDELTA:
return 0;
case NPY_OBJECT:
case NPY_VOID:
return 1;
}
from = PyArray_DescrFromType(fromtype);
/*
* cancastto is a NPY_NOTYPE terminated C-int-array of types that
* the data-type can be cast to safely.
*/
if (from->f->cancastto) {
int *curtype = from->f->cancastto;
while (*curtype != NPY_NOTYPE) {
if (*curtype++ == totype) {
return 1;
}
}
}
return 0;
}
/*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)
{
int from_type_num = from->type_num;
int to_type_num = to->type_num;
npy_bool ret;
ret = (npy_bool) PyArray_CanCastSafely(from_type_num, to_type_num);
if (ret) {
/* Check String and Unicode more closely */
if (from_type_num == NPY_STRING) {
if (to_type_num == NPY_STRING) {
ret = (from->elsize <= to->elsize);
}
else if (to_type_num == NPY_UNICODE) {
ret = (from->elsize << 2 <= to->elsize);
}
}
else if (from_type_num == NPY_UNICODE) {
if (to_type_num == NPY_UNICODE) {
ret = (from->elsize <= to->elsize);
}
}
/*
* For datetime/timedelta, only treat casts moving towards
* more precision as safe.
*/
else if (from_type_num == NPY_DATETIME && to_type_num == NPY_DATETIME) {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
return can_cast_datetime64_metadata(meta1, meta2,
NPY_SAFE_CASTING);
}
else if (from_type_num == NPY_TIMEDELTA &&
to_type_num == NPY_TIMEDELTA) {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
return can_cast_timedelta64_metadata(meta1, meta2,
NPY_SAFE_CASTING);
}
/*
* If to_type_num is STRING or unicode
* see if the length is long enough to hold the
* stringified value of the object.
*/
else if (to_type_num == NPY_STRING || to_type_num == NPY_UNICODE) {
/*
* Boolean value cast to string type is 5 characters max
* for string 'False'.
*/
int char_size = 1;
if (to_type_num == NPY_UNICODE) {
char_size = 4;
}
ret = 0;
if (PyDataType_ISUNSIZED(to)) {
ret = 1;
}
/*
* Need at least 5 characters to convert from boolean
* to 'True' or 'False'.
*/
else if (from->kind == 'b' && to->elsize >= 5 * char_size) {
ret = 1;
}
else if (from->kind == 'u') {
/* Guard against unexpected integer size */
if (from->elsize > 8 || from->elsize < 0) {
ret = 0;
}
else if (to->elsize >=
REQUIRED_STR_LEN[from->elsize] * char_size) {
ret = 1;
}
}
else if (from->kind == 'i') {
/* Guard against unexpected integer size */
if (from->elsize > 8 || from->elsize < 0) {
ret = 0;
}
/* Extra character needed for sign */
else if (to->elsize >=
(REQUIRED_STR_LEN[from->elsize] + 1) * char_size) {
ret = 1;
}
}
}
}
return ret;
}
/* Provides an ordering for the dtype 'kind' character codes */
static 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;
}
}
/*
* Compare two field dictionaries for castability.
*
* Return 1 if 'field1' can be cast to 'field2' according to the rule
* 'casting', 0 if not.
*
* Castabiliy of field dictionaries is defined recursively: 'field1' and
* 'field2' must have the same field names (possibly in different
* orders), and the corresponding field types must be castable according
* to the given casting rule.
*/
static int
can_cast_fields(PyObject *field1, PyObject *field2, NPY_CASTING casting)
{
Py_ssize_t ppos;
PyObject *key;
PyObject *tuple1, *tuple2;
if (field1 == field2) {
return 1;
}
if (field1 == NULL || field2 == NULL) {
return 0;
}
if (PyDict_Size(field1) != PyDict_Size(field2)) {
return 0;
}
/* Iterate over all the fields and compare for castability */
ppos = 0;
while (PyDict_Next(field1, &ppos, &key, &tuple1)) {
if ((tuple2 = PyDict_GetItem(field2, key)) == NULL) {
return 0;
}
/* Compare the dtype of the field for castability */
if (!PyArray_CanCastTypeTo(
(PyArray_Descr *)PyTuple_GET_ITEM(tuple1, 0),
(PyArray_Descr *)PyTuple_GET_ITEM(tuple2, 0),
casting)) {
return 0;
}
}
return 1;
}
/*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)
{
/*
* Fast paths for equality and for basic types.
*/
if (from == to ||
((NPY_LIKELY(PyDataType_ISNUMBER(from)) ||
PyDataType_ISOBJECT(from)) &&
NPY_LIKELY(from->type_num == to->type_num) &&
NPY_LIKELY(from->byteorder == to->byteorder))) {
return 1;
}
/*
* Cases with subarrays and fields need special treatment.
*/
if (PyDataType_HASFIELDS(from)) {
/*
* If from is a structured data type, then it can be cast to a simple
* non-object one only for unsafe casting *and* if it has a single
* field; recurse just in case the single field is itself structured.
*/
if (!PyDataType_HASFIELDS(to) && !PyDataType_ISOBJECT(to)) {
if (casting == NPY_UNSAFE_CASTING &&
PyDict_Size(from->fields) == 1) {
Py_ssize_t ppos = 0;
PyObject *tuple;
PyArray_Descr *field;
PyDict_Next(from->fields, &ppos, NULL, &tuple);
field = (PyArray_Descr *)PyTuple_GET_ITEM(tuple, 0);
/*
* For a subarray, we need to get the underlying type;
* since we already are casting unsafely, we can ignore
* the shape.
*/
if (PyDataType_HASSUBARRAY(field)) {
field = field->subarray->base;
}
return PyArray_CanCastTypeTo(field, to, casting);
}
else {
return 0;
}
}
/*
* Casting from one structured data type to another depends on the fields;
* we pass that case on to the EquivTypenums case below.
*
* TODO: move that part up here? Need to check whether equivalent type
* numbers is an addition constraint that is needed.
*
* TODO/FIXME: For now, always allow structured to structured for unsafe
* casting; this is not correct, but needed since the treatment in can_cast
* below got out of sync with astype; see gh-13667.
*/
if (casting == NPY_UNSAFE_CASTING) {
return 1;
}
}
else if (PyDataType_HASFIELDS(to)) {
/*
* If "from" is a simple data type and "to" has fields, then only
* unsafe casting works (and that works always, even to multiple fields).
*/
return casting == NPY_UNSAFE_CASTING;
}
/*
* Everything else we consider castable for unsafe for now.
* FIXME: ensure what we do here is consistent with "astype",
* i.e., deal more correctly with subarrays and user-defined dtype.
*/
else if (casting == NPY_UNSAFE_CASTING) {
return 1;
}
/*
* Equivalent simple types can be cast with any value of 'casting', but
* we need to be careful about structured to structured.
*/
if (PyArray_EquivTypenums(from->type_num, to->type_num)) {
/* For complicated case, use EquivTypes (for now) */
if (PyTypeNum_ISUSERDEF(from->type_num) ||
from->subarray != NULL) {
int ret;
/* Only NPY_NO_CASTING prevents byte order conversion */
if ((casting != NPY_NO_CASTING) &&
(!PyArray_ISNBO(from->byteorder) ||
!PyArray_ISNBO(to->byteorder))) {
PyArray_Descr *nbo_from, *nbo_to;
nbo_from = PyArray_DescrNewByteorder(from, NPY_NATIVE);
nbo_to = PyArray_DescrNewByteorder(to, NPY_NATIVE);
if (nbo_from == NULL || nbo_to == NULL) {
Py_XDECREF(nbo_from);
Py_XDECREF(nbo_to);
PyErr_Clear();
return 0;
}
ret = PyArray_EquivTypes(nbo_from, nbo_to);
Py_DECREF(nbo_from);
Py_DECREF(nbo_to);
}
else {
ret = PyArray_EquivTypes(from, to);
}
return ret;
}
if (PyDataType_HASFIELDS(from)) {
switch (casting) {
case NPY_EQUIV_CASTING:
case NPY_SAFE_CASTING:
case NPY_SAME_KIND_CASTING:
/*
* `from' and `to' must have the same fields, and
* corresponding fields must be (recursively) castable.
*/
return can_cast_fields(from->fields, to->fields, casting);
case NPY_NO_CASTING:
default:
return PyArray_EquivTypes(from, to);
}
}
switch (from->type_num) {
case NPY_DATETIME: {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
if (casting == NPY_NO_CASTING) {
return PyArray_ISNBO(from->byteorder) ==
PyArray_ISNBO(to->byteorder) &&
can_cast_datetime64_metadata(meta1, meta2, casting);
}
else {
return can_cast_datetime64_metadata(meta1, meta2, casting);
}
}
case NPY_TIMEDELTA: {
PyArray_DatetimeMetaData *meta1, *meta2;
meta1 = get_datetime_metadata_from_dtype(from);
if (meta1 == NULL) {
PyErr_Clear();
return 0;
}
meta2 = get_datetime_metadata_from_dtype(to);
if (meta2 == NULL) {
PyErr_Clear();
return 0;
}
if (casting == NPY_NO_CASTING) {
return PyArray_ISNBO(from->byteorder) ==
PyArray_ISNBO(to->byteorder) &&
can_cast_timedelta64_metadata(meta1, meta2, casting);
}
else {
return can_cast_timedelta64_metadata(meta1, meta2, casting);
}
}
default:
switch (casting) {
case NPY_NO_CASTING:
return PyArray_EquivTypes(from, to);
case NPY_EQUIV_CASTING:
return (from->elsize == to->elsize);
case NPY_SAFE_CASTING:
return (from->elsize <= to->elsize);
default:
return 1;
}
break;
}
}
/* If safe or same-kind casts are allowed */
else if (casting == NPY_SAFE_CASTING || casting == NPY_SAME_KIND_CASTING) {
if (PyArray_CanCastTo(from, to)) {
return 1;
}
else if(casting == NPY_SAME_KIND_CASTING) {
/*
* Also allow casting from lower to higher kinds, according
* to the ordering provided by dtype_kind_to_ordering.
* Some kinds, like datetime, don't fit in the hierarchy,
* and are special cased as -1.
*/
int from_order, to_order;
from_order = dtype_kind_to_ordering(from->kind);
to_order = dtype_kind_to_ordering(to->kind);
if (to->kind == 'm') {
/* both types being timedelta is already handled before. */
int integer_order = dtype_kind_to_ordering('i');
return (from_order != -1) && (from_order <= integer_order);
}
return (from_order != -1) && (from_order <= to_order);
}
else {
return 0;
}
}
/* NPY_NO_CASTING or NPY_EQUIV_CASTING was specified */
else {
return 0;
}
}
/* CanCastArrayTo needs this function */
static int min_scalar_type_num(char *valueptr, int type_num,
int *is_small_unsigned);
NPY_NO_EXPORT npy_bool
can_cast_scalar_to(PyArray_Descr *scal_type, char *scal_data,
PyArray_Descr *to, NPY_CASTING casting)
{
int swap;
int is_small_unsigned = 0, type_num;
npy_bool ret;
PyArray_Descr *dtype;
/* An aligned memory buffer large enough to hold any type */
npy_longlong value[4];
/*
* If the two dtypes are actually references to the same object
* or if casting type is forced unsafe then always OK.
*/
if (scal_type == to || casting == NPY_UNSAFE_CASTING ) {
return 1;
}
/*
* If the scalar isn't a number, or the rule is stricter than
* NPY_SAFE_CASTING, use the straight type-based rules
*/
if (!PyTypeNum_ISNUMBER(scal_type->type_num) ||
casting < NPY_SAFE_CASTING) {
return PyArray_CanCastTypeTo(scal_type, to, casting);
}
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
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);
/* If it's a scalar, check the value */
if (PyArray_NDIM(arr) == 0 && !PyArray_HASFIELDS(arr)) {
return can_cast_scalar_to(from, PyArray_DATA(arr), to, casting);
}
/* Otherwise, use the standard rules */
return PyArray_CanCastTypeTo(from, to, casting);
}
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'";