/
scalartypes.c.src
4250 lines (3726 loc) · 116 KB
/
scalartypes.c.src
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
/* -*- c -*- */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <structmember.h>
#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#ifndef _MULTIARRAYMODULE
#define _MULTIARRAYMODULE
#endif
#include "numpy/arrayobject.h"
#include "numpy/npy_math.h"
#include "numpy/halffloat.h"
#include "numpy/arrayscalars.h"
#include "npy_pycompat.h"
#include "npy_config.h"
#include "mapping.h"
#include "ctors.h"
#include "usertypes.h"
#include "numpyos.h"
#include "can_cast_table.h"
#include "common.h"
#include "scalartypes.h"
#include "_datetime.h"
#include "datetime_strings.h"
#include "alloc.h"
#include "npy_import.h"
#include "dragon4.h"
#include "npy_longdouble.h"
#include "npy_buffer.h"
#include <stdlib.h>
#include "binop_override.h"
/*
* used for allocating a single scalar, so use the default numpy
* memory allocators instead of the (maybe) user overrides
*/
NPY_NO_EXPORT void *
npy_alloc_cache_zero(size_t nmemb, size_t size);
NPY_NO_EXPORT void
npy_free_cache(void * p, npy_uintp sz);
NPY_NO_EXPORT PyBoolScalarObject _PyArrayScalar_BoolValues[] = {
{PyObject_HEAD_INIT(&PyBoolArrType_Type) 0},
{PyObject_HEAD_INIT(&PyBoolArrType_Type) 1},
};
/* TimeInteger is deleted, but still here to fill the API slot */
NPY_NO_EXPORT PyTypeObject PyTimeIntegerArrType_Type;
/*
* Inheritance is established later when tp_bases is set (or tp_base for
* single inheritance)
*/
/**begin repeat
* #name = number, integer, signedinteger, unsignedinteger, inexact,
* floating, complexfloating, flexible, character#
* #NAME = Number, Integer, SignedInteger, UnsignedInteger, Inexact,
* Floating, ComplexFloating, Flexible, Character#
*/
NPY_NO_EXPORT PyTypeObject Py@NAME@ArrType_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "numpy.@name@",
.tp_basicsize = sizeof(PyObject),
};
/**end repeat**/
static PyObject *
gentype_alloc(PyTypeObject *type, Py_ssize_t nitems)
{
PyObject *obj;
const size_t size = _PyObject_VAR_SIZE(type, nitems + 1);
obj = (PyObject *)PyObject_Malloc(size);
if (obj == NULL) {
PyErr_NoMemory();
return NULL;
}
/*
* If we don't need to zero memory, we could use
* PyObject_{New, NewVar} for this whole function.
*/
memset(obj, 0, size);
if (type->tp_itemsize == 0) {
PyObject_Init(obj, type);
}
else {
(void) PyObject_InitVar((PyVarObject *)obj, type, nitems);
}
return obj;
}
static void
gentype_dealloc(PyObject *v)
{
Py_TYPE(v)->tp_free(v);
}
static void
gentype_free(PyObject *v)
{
/*
* have an explicit tp_free to enforce inheritance from it.
* PyObject_Free is also the tp_free of PyBaseObject so python does not
* COPYSLOT it, instead it takes the next parent PyInt which has a
* different allocator
*/
PyObject_Free(v);
}
static PyObject *
gentype_power(PyObject *m1, PyObject *m2, PyObject *modulo)
{
if (modulo != Py_None) {
/* modular exponentiation is not implemented (gh-8804) */
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_power, gentype_power);
return PyArray_Type.tp_as_number->nb_power(m1, m2, Py_None);
}
static PyObject *
gentype_generic_method(PyObject *self, PyObject *args, PyObject *kwds,
char *str)
{
PyObject *arr, *meth, *ret;
arr = PyArray_FromScalar(self, NULL);
if (arr == NULL) {
return NULL;
}
meth = PyObject_GetAttrString(arr, str);
if (meth == NULL) {
Py_DECREF(arr);
return NULL;
}
if (kwds == NULL) {
ret = PyObject_CallObject(meth, args);
}
else {
ret = PyObject_Call(meth, args, kwds);
}
Py_DECREF(meth);
Py_DECREF(arr);
if (ret && PyArray_Check(ret)) {
return PyArray_Return((PyArrayObject *)ret);
}
else {
return ret;
}
}
static PyObject *
gentype_add(PyObject *m1, PyObject* m2)
{
/* special case str.__radd__, which should not call array_add */
if (PyBytes_Check(m1) || PyUnicode_Check(m1)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_add, gentype_add);
return PyArray_Type.tp_as_number->nb_add(m1, m2);
}
/**begin repeat
*
* #name = subtract, remainder, divmod, lshift, rshift,
* and, xor, or, floor_divide, true_divide#
*/
static PyObject *
gentype_@name@(PyObject *m1, PyObject *m2)
{
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_@name@, gentype_@name@);
return PyArray_Type.tp_as_number->nb_@name@(m1, m2);
}
/**end repeat**/
/* Get a nested slot, or NULL if absent */
#define GET_NESTED_SLOT(type, group, slot) \
((type)->group == NULL ? NULL : (type)->group->slot)
static PyObject *
gentype_multiply(PyObject *m1, PyObject *m2)
{
/*
* If the other object supports sequence repeat and not number multiply
* we fall back on the python builtin to invoke the sequence repeat, rather
* than promoting both arguments to ndarray.
* This covers a list repeat by numpy scalars.
* A python defined class will always only have the nb_multiply slot and
* some classes may have neither defined. For the latter we want need
* to give the normal case a chance to convert the object to ndarray.
* Probably no class has both defined, but if they do, prefer number.
*/
if (!PyArray_IsScalar(m1, Generic) &&
GET_NESTED_SLOT(Py_TYPE(m1), tp_as_sequence, sq_repeat) != NULL &&
GET_NESTED_SLOT(Py_TYPE(m1), tp_as_number, nb_multiply) == NULL) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
if (!PyArray_IsScalar(m2, Generic) &&
GET_NESTED_SLOT(Py_TYPE(m2), tp_as_sequence, sq_repeat) != NULL &&
GET_NESTED_SLOT(Py_TYPE(m2), tp_as_number, nb_multiply) == NULL) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
/* All normal cases are handled by PyArray's multiply */
BINOP_GIVE_UP_IF_NEEDED(m1, m2, nb_multiply, gentype_multiply);
return PyArray_Type.tp_as_number->nb_multiply(m1, m2);
}
/**begin repeat
* #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
* LONG, ULONG, LONGLONG, ULONGLONG#
* #type = npy_byte, npy_ubyte, npy_short, npy_ushort, npy_int, npy_uint,
* npy_long, npy_ulong, npy_longlong, npy_ulonglong#
* #c = hh, uhh, h, uh,, u, l, ul, ll, ull#
* #Name = Byte, UByte, Short, UShort, Int, UInt,
* Long, ULong, LongLong, ULongLong#
* #convert = Long*8, LongLong*2#
*/
static PyObject *
@type@_bit_count(PyObject *self, PyObject *NPY_UNUSED(args))
{
@type@ scalar = PyArrayScalar_VAL(self, @Name@);
uint8_t count = npy_popcount@c@(scalar);
PyObject *result = PyLong_From@convert@(count);
return result;
}
/**end repeat**/
/**begin repeat
*
* #name = positive, negative, absolute, invert, int, float#
*/
static PyObject *
gentype_@name@(PyObject *m1)
{
PyObject *arr, *ret;
arr = PyArray_FromScalar(m1, NULL);
if (arr == NULL) {
return NULL;
}
ret = Py_TYPE(arr)->tp_as_number->nb_@name@(arr);
Py_DECREF(arr);
return ret;
}
/**end repeat**/
static int
gentype_nonzero_number(PyObject *m1)
{
PyObject *arr;
int ret;
arr = PyArray_FromScalar(m1, NULL);
if (arr == NULL) {
return -1;
}
ret = Py_TYPE(arr)->tp_as_number->nb_bool(arr);
Py_DECREF(arr);
return ret;
}
static PyObject *
genint_type_str(PyObject *self)
{
PyObject *item, *item_str;
item = gentype_generic_method(self, NULL, NULL, "item");
if (item == NULL) {
return NULL;
}
item_str = PyObject_Str(item);
Py_DECREF(item);
return item_str;
}
/*
* The __format__ method for PEP 3101.
*/
static PyObject *
gentype_format(PyObject *self, PyObject *args)
{
PyObject *format_spec;
PyObject *obj, *ret;
if (!PyArg_ParseTuple(args, "U:__format__", &format_spec)) {
return NULL;
}
/*
* Convert to an appropriate Python type and call its format.
* TODO: For some types, like long double, this isn't right,
* because it throws away precision.
*/
if (Py_TYPE(self) == &PyBoolArrType_Type) {
obj = PyBool_FromLong(PyArrayScalar_VAL(self, Bool));
}
else if (PyArray_IsScalar(self, Integer)
&& !PyArray_IsScalar(self, Timedelta)) {
obj = Py_TYPE(self)->tp_as_number->nb_int(self);
}
else if (PyArray_IsScalar(self, Floating)) {
obj = Py_TYPE(self)->tp_as_number->nb_float(self);
}
else if (PyArray_IsScalar(self, ComplexFloating)) {
double val[2];
PyArray_Descr *dtype = PyArray_DescrFromScalar(self);
if (dtype == NULL) {
return NULL;
}
if (PyArray_CastScalarDirect(self, dtype, &val[0], NPY_CDOUBLE) < 0) {
Py_DECREF(dtype);
return NULL;
}
obj = PyComplex_FromDoubles(val[0], val[1]);
Py_DECREF(dtype);
}
else {
obj = PyObject_Str(self);
}
if (obj == NULL) {
return NULL;
}
ret = PyObject_Format(obj, format_spec);
Py_DECREF(obj);
return ret;
}
#ifdef FORCE_NO_LONG_DOUBLE_FORMATTING
#undef NPY_LONGDOUBLE_FMT
#define NPY_LONGDOUBLE_FMT NPY_DOUBLE_FMT
#endif
/**begin repeat
* #name = half, float, double, longdouble#
* #Name = Half, Float, Double, LongDouble#
* #NAME = HALF, FLOAT, DOUBLE, LONGDOUBLE#
* #type = npy_half, npy_float, npy_double, npy_longdouble#
* #suff = h, f, d, l#
*/
NPY_NO_EXPORT PyObject *
format_@name@(@type@ val, npy_bool scientific,
int precision, int sign, TrimMode trim,
int pad_left, int pad_right, int exp_digits)
{
if (scientific) {
return Dragon4_Scientific_@Name@(&val,
DigitMode_Unique, precision, -1,
sign, trim, pad_left, exp_digits);
}
else {
return Dragon4_Positional_@Name@(&val,
DigitMode_Unique, CutoffMode_TotalLength, precision,
-1, sign, trim, pad_left, pad_right);
}
}
/**end repeat**/
/*
* Over-ride repr and str of array-scalar byte strings to remove NULL bytes and
* then call the corresponding functions of PyBytes_Type to generate the string
*/
/**begin repeat
* #form = repr, str#
*/
static PyObject *
stringtype_@form@(PyObject *self)
{
const npy_char *dptr, *ip;
Py_ssize_t len;
PyObject *new;
PyObject *ret;
ip = PyBytes_AS_STRING(self);
len = PyBytes_GET_SIZE(self);
for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
new = PyBytes_FromStringAndSize(ip, len);
if (new == NULL) {
return NULL;
}
ret = PyBytes_Type.tp_@form@(new);
Py_DECREF(new);
return ret;
}
/**end repeat**/
/*
* Over-ride repr and str of array-scalar strings to remove NULL code points and
* then call the corresponding functions of PyUnicode_Type to generate the string
*/
/**begin repeat
* #form = repr, str#
*/
static PyObject *
unicodetype_@form@(PyObject *self)
{
Py_UCS4 *dptr, *ip;
Py_ssize_t len;
PyObject *new;
PyObject *ret;
/* PyUnicode_READY is called by PyUnicode_GetLength */
len = PyUnicode_GetLength(self);
ip = PyUnicode_AsUCS4Copy(self);
if (ip == NULL) {
return NULL;
}
for(dptr = ip + len - 1; len > 0 && *dptr == 0; len--, dptr--);
new = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, ip, len);
if (new == NULL) {
PyMem_Free(ip);
return NULL;
}
ret = PyUnicode_Type.tp_@form@(new);
Py_DECREF(new);
PyMem_Free(ip);
return ret;
}
/**end repeat**/
/*
* Convert array of bytes to a string representation much like bytes.__repr__,
* but convert all bytes (including ASCII) to the `\x00` notation with
* uppercase hex codes (FF not ff).
*
* Largely copied from _Py_strhex_impl in CPython implementation
*/
static NPY_INLINE PyObject *
_void_to_hex(const char* argbuf, const Py_ssize_t arglen,
const char *schars, const char *bprefix, const char *echars)
{
PyObject *retval;
int extrachars, slen;
char *retbuf;
Py_ssize_t i, j;
char const *hexdigits = "0123456789ABCDEF";
extrachars = strlen(schars) + strlen(echars);
slen = extrachars + arglen*(2 + strlen(bprefix));
if (arglen > (PY_SSIZE_T_MAX / 2) - extrachars) {
return PyErr_NoMemory();
}
retbuf = (char *)PyMem_Malloc(slen);
if (!retbuf) {
return PyErr_NoMemory();
}
memcpy(retbuf, schars, strlen(schars));
j = strlen(schars);
for (i = 0; i < arglen; i++) {
unsigned char c;
memcpy(&retbuf[j], bprefix, strlen(bprefix));
j += strlen(bprefix);
c = (argbuf[i] >> 4) & 0xf;
retbuf[j++] = hexdigits[c];
c = argbuf[i] & 0xf;
retbuf[j++] = hexdigits[c];
}
memcpy(&retbuf[j], echars, strlen(echars));
retval = PyUnicode_FromStringAndSize(retbuf, slen);
PyMem_Free(retbuf);
return retval;
}
static PyObject *
_void_scalar_repr(PyObject *obj) {
static PyObject *reprfunc = NULL;
npy_cache_import("numpy.core.arrayprint",
"_void_scalar_repr", &reprfunc);
if (reprfunc == NULL) {
return NULL;
}
return PyObject_CallFunction(reprfunc, "O", obj);
}
static PyObject *
voidtype_repr(PyObject *self)
{
PyVoidScalarObject *s = (PyVoidScalarObject*) self;
if (PyDataType_HASFIELDS(s->descr)) {
return _void_scalar_repr(self);
}
return _void_to_hex(s->obval, s->descr->elsize, "void(b'", "\\x", "')");
}
static PyObject *
voidtype_str(PyObject *self)
{
PyVoidScalarObject *s = (PyVoidScalarObject*) self;
if (PyDataType_HASFIELDS(s->descr)) {
return _void_scalar_repr(self);
}
return _void_to_hex(s->obval, s->descr->elsize, "b'", "\\x", "'");
}
static PyObject *
datetimetype_repr(PyObject *self)
{
PyDatetimeScalarObject *scal;
npy_datetimestruct dts;
PyObject *ret;
char iso[NPY_DATETIME_MAX_ISO8601_STRLEN];
NPY_DATETIMEUNIT unit;
if (!PyArray_IsScalar(self, Datetime)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy datetime repr on a non-datetime type");
return NULL;
}
scal = (PyDatetimeScalarObject *)self;
if (convert_datetime_to_datetimestruct(&scal->obmeta,
scal->obval, &dts) < 0) {
return NULL;
}
unit = scal->obmeta.base;
if (make_iso_8601_datetime(&dts, iso, sizeof(iso), 0, 0,
unit, -1, NPY_SAFE_CASTING) < 0) {
return NULL;
}
/*
* For straight units or generic units, the unit will be deduced
* from the string, so it's not necessary to specify it.
*/
if ((scal->obmeta.num == 1 && scal->obmeta.base != NPY_FR_h) ||
scal->obmeta.base == NPY_FR_GENERIC) {
ret = PyUnicode_FromFormat("numpy.datetime64('%s')", iso);
}
else {
PyObject *meta = metastr_to_unicode(&scal->obmeta, 1);
if (meta == NULL) {
return NULL;
}
ret = PyUnicode_FromFormat("numpy.datetime64('%s','%S')", iso, meta);
Py_DECREF(meta);
}
return ret;
}
static PyObject *
timedeltatype_repr(PyObject *self)
{
PyTimedeltaScalarObject *scal;
PyObject *val, *ret;
if (!PyArray_IsScalar(self, Timedelta)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy timedelta repr on a non-datetime type");
return NULL;
}
scal = (PyTimedeltaScalarObject *)self;
/* The value */
if (scal->obval == NPY_DATETIME_NAT) {
val = PyUnicode_FromString("'NaT'");
}
else {
/* Can't use "%lld" if HAVE_LONG_LONG is not defined */
#if defined(HAVE_LONG_LONG)
val = PyUnicode_FromFormat("%lld", (long long)scal->obval);
#else
val = PyUnicode_FromFormat("%ld", (long)scal->obval);
#endif
}
if (val == NULL) {
return NULL;
}
/* The metadata unit */
if (scal->obmeta.base == NPY_FR_GENERIC) {
ret = PyUnicode_FromFormat("numpy.timedelta64(%S)", val);
}
else {
PyObject *meta = metastr_to_unicode(&scal->obmeta, 1);
if (meta == NULL) {
Py_DECREF(val);
return NULL;
}
ret = PyUnicode_FromFormat("numpy.timedelta64(%S,'%S')", val, meta);
Py_DECREF(meta);
}
Py_DECREF(val);
return ret;
}
static PyObject *
datetimetype_str(PyObject *self)
{
PyDatetimeScalarObject *scal;
npy_datetimestruct dts;
char iso[NPY_DATETIME_MAX_ISO8601_STRLEN];
NPY_DATETIMEUNIT unit;
if (!PyArray_IsScalar(self, Datetime)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy datetime str on a non-datetime type");
return NULL;
}
scal = (PyDatetimeScalarObject *)self;
if (convert_datetime_to_datetimestruct(&scal->obmeta, scal->obval,
&dts) < 0) {
return NULL;
}
unit = scal->obmeta.base;
if (make_iso_8601_datetime(&dts, iso, sizeof(iso), 0, 0,
unit, -1, NPY_SAFE_CASTING) < 0) {
return NULL;
}
return PyUnicode_FromString(iso);
}
static char *_datetime_verbose_strings[NPY_DATETIME_NUMUNITS] = {
"years",
"months",
"weeks",
"<invalid>",
"days",
"hours",
"minutes",
"seconds",
"milliseconds",
"microseconds",
"nanoseconds",
"picoseconds",
"femtoseconds",
"attoseconds",
"generic time units"
};
static PyObject *
timedeltatype_str(PyObject *self)
{
PyTimedeltaScalarObject *scal;
PyObject *ret;
char *basestr = "invalid";
if (!PyArray_IsScalar(self, Timedelta)) {
PyErr_SetString(PyExc_RuntimeError,
"Called NumPy timedelta str on a non-datetime type");
return NULL;
}
scal = (PyTimedeltaScalarObject *)self;
if (scal->obmeta.base >= 0 && scal->obmeta.base < NPY_DATETIME_NUMUNITS) {
basestr = _datetime_verbose_strings[scal->obmeta.base];
}
else {
PyErr_SetString(PyExc_RuntimeError,
"NumPy datetime metadata is corrupted");
return NULL;
}
if (scal->obval == NPY_DATETIME_NAT) {
ret = PyUnicode_FromString("NaT");
}
else {
/*
* Can't use "%lld" if HAVE_LONG_LONG is not defined
*/
#if defined(HAVE_LONG_LONG)
ret = PyUnicode_FromFormat("%lld %s",
(long long)(scal->obval * scal->obmeta.num), basestr);
#else
ret = PyUnicode_FromFormat("%ld %s",
(long)(scal->obval * scal->obmeta.num), basestr);
#endif
}
return ret;
}
/*
* float type str and repr
*
* These functions will return NULL if PyString creation fails.
*/
/*
* *** BEGIN LEGACY PRINTING MODE CODE ***
*
* This code is legacy code needed to reproduce the printing behavior of
* scalars in numpy 1.13. One day we hope to remove it.
*/
/* determines if legacy mode is enabled, global set in multiarraymodule.c */
extern int npy_legacy_print_mode;
#define HALFPREC_REPR 5
#define HALFPREC_STR 5
#define FLOATPREC_REPR 8
#define FLOATPREC_STR 6
#define DOUBLEPREC_REPR 17
#define DOUBLEPREC_STR 12
#if NPY_SIZEOF_LONGDOUBLE == NPY_SIZEOF_DOUBLE
#define LONGDOUBLEPREC_REPR DOUBLEPREC_REPR
#define LONGDOUBLEPREC_STR DOUBLEPREC_STR
#else /* More than probably needed on Intel FP */
#define LONGDOUBLEPREC_REPR 20
#define LONGDOUBLEPREC_STR 12
#endif
/**begin repeat
* #kind = str, repr#
* #KIND = STR, REPR#
*/
/**begin repeat1
* #name = cfloat, cdouble, clongdouble#
* #NAME = FLOAT, DOUBLE, LONGDOUBLE#
* #type = npy_cfloat, npy_cdouble, npy_clongdouble#
* #suff = f, d, l#
*/
#define _FMT1 "%%.%i" NPY_@NAME@_FMT
#define _FMT2 "%%+.%i" NPY_@NAME@_FMT
static PyObject*
legacy_@name@_format@kind@(@type@ val)
{
/* XXX: Find a correct size here for format string */
char format[64], buf[100], *res;
/*
* Ideally, we should handle this nan/inf stuff in NumpyOS_ascii_format*
*/
if (val.real == 0.0 && npy_signbit(val.real) == 0) {
PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
res = NumPyOS_ascii_format@suff@(buf, sizeof(buf) - 1, format, val.imag, 0);
if (res == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
return NULL;
}
if (!npy_isfinite(val.imag)) {
strncat(buf, "*", sizeof(buf) - strlen(buf) - 1);
}
strncat(buf, "j", sizeof(buf) - strlen(buf) - 1);
}
else {
char re[64], im[64];
if (npy_isfinite(val.real)) {
PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
res = NumPyOS_ascii_format@suff@(re, sizeof(re), format,
val.real, 0);
if (res == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
return NULL;
}
}
else {
if (npy_isnan(val.real)) {
strcpy(re, "nan");
}
else if (val.real > 0){
strcpy(re, "inf");
}
else {
strcpy(re, "-inf");
}
}
if (npy_isfinite(val.imag)) {
PyOS_snprintf(format, sizeof(format), _FMT2, @NAME@PREC_@KIND@);
res = NumPyOS_ascii_format@suff@(im, sizeof(im), format,
val.imag, 0);
if (res == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
return NULL;
}
}
else {
if (npy_isnan(val.imag)) {
strcpy(im, "+nan");
}
else if (val.imag > 0){
strcpy(im, "+inf");
}
else {
strcpy(im, "-inf");
}
if (!npy_isfinite(val.imag)) {
strncat(im, "*", sizeof(im) - strlen(im) - 1);
}
}
PyOS_snprintf(buf, sizeof(buf), "(%s%sj)", re, im);
}
return PyUnicode_FromString(buf);
}
#undef _FMT1
#undef _FMT2
/**end repeat1**/
/**begin repeat1
* #name = float, double, longdouble#
* #Name = Float, Double, LongDouble#
* #NAME = FLOAT, DOUBLE, LONGDOUBLE#
* #suff = f, d, l#
*/
#define _FMT1 "%%.%i" NPY_@NAME@_FMT
static PyObject *
legacy_@name@_format@kind@(npy_@name@ val){
/* XXX: Find a correct size here for format string */
char format[64], buf[100], *res;
size_t i, cnt;
PyOS_snprintf(format, sizeof(format), _FMT1, @NAME@PREC_@KIND@);
res = NumPyOS_ascii_format@suff@(buf, sizeof(buf), format, val, 0);
if (res == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Error while formatting");
return NULL;
}
/* If nothing but digits after sign, append ".0" */
cnt = strlen(buf);
for (i = (buf[0] == '-') ? 1 : 0; i < cnt; ++i) {
if (!isdigit(Py_CHARMASK(buf[i]))) {
break;
}
}
if (i == cnt && sizeof(buf) >= cnt + 3) {
strcpy(&buf[cnt],".0");
}
return PyUnicode_FromString(buf);
}
#undef _FMT1
/**end repeat1**/
/**end repeat**/
/*
* *** END LEGACY PRINTING MODE CODE ***
*/
/**begin repeat
* #kind = str, repr#
*/
/**begin repeat1
* #name = float, double, longdouble#
* #Name = Float, Double, LongDouble#
* #NAME = FLOAT, DOUBLE, LONGDOUBLE#
*/
/* helper function choose scientific of fractional output, based on a cutoff */
static PyObject *
@name@type_@kind@_either(npy_@name@ val, TrimMode trim_pos, TrimMode trim_sci,
npy_bool sign)
{
if (npy_legacy_print_mode <= 113) {
return legacy_@name@_format@kind@(val);
}
int use_positional;
if (npy_isnan(val) || val == 0) {
use_positional = 1;
}
else {
npy_@name@ absval = val < 0 ? -val : val;
use_positional = absval < 1.e16L && absval >= 1.e-4L;
}
if (use_positional) {
return format_@name@(val, 0, -1, sign, trim_pos, -1, -1, -1);
}
return format_@name@(val, 1, -1, sign, trim_sci, -1, -1, -1);
}
static PyObject *
@name@type_@kind@(PyObject *self)
{
return @name@type_@kind@_either(PyArrayScalar_VAL(self, @Name@),
TrimMode_LeaveOneZero, TrimMode_DptZeros, 0);
}
static PyObject *
c@name@type_@kind@(PyObject *self)
{
PyObject *rstr, *istr;
npy_c@name@ val = PyArrayScalar_VAL(self, C@Name@);
TrimMode trim = TrimMode_DptZeros;
if (npy_legacy_print_mode <= 113) {
return legacy_c@name@_format@kind@(val);
}
if (val.real == 0.0 && npy_signbit(val.real) == 0) {
istr = @name@type_@kind@_either(val.imag, trim, trim, 0);
if (istr == NULL) {
return NULL;
}
PyObject *ret = PyUnicode_FromFormat("%Sj", istr);
Py_DECREF(istr);
return ret;
}
if (npy_isfinite(val.real)) {
rstr = @name@type_@kind@_either(val.real, trim, trim, 0);
}
else if (npy_isnan(val.real)) {
rstr = PyUnicode_FromString("nan");
}
else if (val.real > 0){
rstr = PyUnicode_FromString("inf");
}
else {
rstr = PyUnicode_FromString("-inf");
}
if (rstr == NULL) {
return NULL;
}
if (npy_isfinite(val.imag)) {
istr = @name@type_@kind@_either(val.imag, trim, trim, 1);
}
else if (npy_isnan(val.imag)) {
istr = PyUnicode_FromString("+nan");
}
else if (val.imag > 0){
istr = PyUnicode_FromString("+inf");
}
else {
istr = PyUnicode_FromString("-inf");
}
if (istr == NULL) {
Py_DECREF(rstr);
return NULL;
}
PyObject *ret = PyUnicode_FromFormat("(%S%Sj)", rstr, istr);
Py_DECREF(rstr);
Py_DECREF(istr);
return ret;
}
#undef PREC
/**end repeat1**/
static PyObject *
halftype_@kind@(PyObject *self)
{
npy_half val = PyArrayScalar_VAL(self, Half);
float floatval = npy_half_to_float(val);
float absval;
if (npy_legacy_print_mode <= 113) {
return legacy_float_format@kind@(floatval);
}