3
2
Provide multidimensional arrays as a basic object type in python.
5
Based on Original Numeric implementation
6
Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
8
with contributions from many Numeric Python developers 1995-2004
10
Heavily modified in 2005 with inspiration from Numarray
14
Travis Oliphant, oliphant@ee.byu.edu
15
Brigham Young Univeristy
17
maintainer email: oliphant.travis@ieee.org
19
Numarray design (which provided guidance) by
20
Space Science Telescope Institute
4
Based on Original Numeric implementation
5
Copyright (c) 1995, 1996, 1997 Jim Hugunin, hugunin@mit.edu
7
with contributions from many Numeric Python developers 1995-2004
9
Heavily modified in 2005 with inspiration from Numarray
13
Travis Oliphant, oliphant@ee.byu.edu
14
Brigham Young Univeristy
16
maintainer email: oliphant.travis@ieee.org
18
Numarray design (which provided guidance) by
19
Space Science Telescope Institute
21
20
(J. Todd Miller, Perry Greenfield, Rick White)
22
/*#include <stdio.h>*/
25
Get Priority from object
25
* Get Priority from object
28
28
PyArray_GetPriority(PyObject *obj, double default_)
31
double priority=PyArray_PRIORITY;
33
if (PyArray_CheckExact(obj))
36
ret = PyObject_GetAttrString(obj, "__array_priority__");
37
if (ret != NULL) priority = PyFloat_AsDouble(ret);
38
if (PyErr_Occurred()) {
31
double priority=PyArray_PRIORITY;
33
if (PyArray_CheckExact(obj))
36
ret = PyObject_GetAttrString(obj, "__array_priority__");
37
if (ret != NULL) priority = PyFloat_AsDouble(ret);
38
if (PyErr_Occurred()) {
47
47
_check_object_rec(PyArray_Descr *descr)
49
if (PyDataType_HASFIELDS(descr) && PyDataType_REFCHK(descr)) {
50
PyErr_SetString(PyExc_TypeError, "Not supported for this data-type.");
49
if (PyDataType_HASFIELDS(descr) && PyDataType_REFCHK(descr)) {
50
PyErr_SetString(PyExc_TypeError, "Not supported for this data-type.");
56
56
/* Backward compatibility only */
57
57
/* In both Zero and One
59
***You must free the memory once you are done with it
60
using PyDataMem_FREE(ptr) or you create a memory leak***
62
If arr is an Object array you are getting a
63
BORROWED reference to Zero or One.
65
Please INCREF if you will be hanging on to it.
67
The memory for the ptr still must be freed in any case;
59
***You must free the memory once you are done with it
60
using PyDataMem_FREE(ptr) or you create a memory leak***
62
If arr is an Object array you are getting a
63
BORROWED reference to Zero or One.
65
Please INCREF if you will be hanging on to it.
67
The memory for the ptr still must be freed in any case;
72
Get pointer to zero of correct type for array.
72
Get pointer to zero of correct type for array.
75
75
PyArray_Zero(PyArrayObject *arr)
81
if (_check_object_rec(arr->descr) < 0) return NULL;
82
zeroval = PyDataMem_NEW(arr->descr->elsize);
83
if (zeroval == NULL) {
84
PyErr_SetNone(PyExc_MemoryError);
88
obj=PyInt_FromLong((long) 0);
89
if (PyArray_ISOBJECT(arr)) {
90
memcpy(zeroval, &obj, sizeof(PyObject *));
94
storeflags = arr->flags;
95
arr->flags |= BEHAVED;
96
ret = arr->descr->f->setitem(obj, zeroval, arr);
97
arr->flags = storeflags;
81
if (_check_object_rec(arr->descr) < 0) return NULL;
82
zeroval = PyDataMem_NEW(arr->descr->elsize);
83
if (zeroval == NULL) {
84
PyErr_SetNone(PyExc_MemoryError);
88
obj=PyInt_FromLong((long) 0);
89
if (PyArray_ISOBJECT(arr)) {
90
memcpy(zeroval, &obj, sizeof(PyObject *));
100
PyDataMem_FREE(zeroval);
94
storeflags = arr->flags;
95
arr->flags |= BEHAVED;
96
ret = arr->descr->f->setitem(obj, zeroval, arr);
97
arr->flags = storeflags;
100
PyDataMem_FREE(zeroval);
107
Get pointer to one of correct type for array
107
Get pointer to one of correct type for array
110
110
PyArray_One(PyArrayObject *arr)
116
if (_check_object_rec(arr->descr) < 0) return NULL;
117
oneval = PyDataMem_NEW(arr->descr->elsize);
118
if (oneval == NULL) {
119
PyErr_SetNone(PyExc_MemoryError);
123
obj = PyInt_FromLong((long) 1);
124
if (PyArray_ISOBJECT(arr)) {
125
memcpy(oneval, &obj, sizeof(PyObject *));
130
storeflags = arr->flags;
131
arr->flags |= BEHAVED;
132
ret = arr->descr->f->setitem(obj, oneval, arr);
133
arr->flags = storeflags;
116
if (_check_object_rec(arr->descr) < 0) {
119
oneval = PyDataMem_NEW(arr->descr->elsize);
120
if (oneval == NULL) {
121
PyErr_SetNone(PyExc_MemoryError);
125
obj = PyInt_FromLong((long) 1);
126
if (PyArray_ISOBJECT(arr)) {
127
memcpy(oneval, &obj, sizeof(PyObject *));
136
PyDataMem_FREE(oneval);
132
storeflags = arr->flags;
133
arr->flags |= BEHAVED;
134
ret = arr->descr->f->setitem(obj, oneval, arr);
135
arr->flags = storeflags;
138
PyDataMem_FREE(oneval);
142
144
/* End deprecated */
207
217
/* Used for arrays of python objects to increment the reference count of */
208
218
/* every python object in the array. */
210
For object arrays, increment all internal references.
220
For object arrays, increment all internal references.
213
223
PyArray_INCREF(PyArrayObject *mp)
216
PyObject **data, **temp;
217
PyArrayIterObject *it;
219
if (!PyDataType_REFCHK(mp->descr)) return 0;
221
if (mp->descr->type_num != PyArray_OBJECT) {
222
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
223
if (it == NULL) return -1;
224
while(it->index < it->size) {
225
PyArray_Item_INCREF(it->dataptr, mp->descr);
226
PyArray_ITER_NEXT(it);
232
if (PyArray_ISONESEGMENT(mp)) {
233
data = (PyObject **)mp->data;
234
n = PyArray_SIZE(mp);
235
if (PyArray_ISALIGNED(mp)) {
236
for(i=0; i<n; i++, data++) Py_XINCREF(*data);
239
for (i=0; i<n; i++, data++) {
245
else { /* handles misaligned data too */
246
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
247
if (it == NULL) return -1;
248
while(it->index < it->size) {
249
temp = (PyObject **)it->dataptr;
251
PyArray_ITER_NEXT(it);
226
PyObject **data, **temp;
227
PyArrayIterObject *it;
229
if (!PyDataType_REFCHK(mp->descr)) {
232
if (mp->descr->type_num != PyArray_OBJECT) {
233
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
237
while(it->index < it->size) {
238
PyArray_Item_INCREF(it->dataptr, mp->descr);
239
PyArray_ITER_NEXT(it);
245
if (PyArray_ISONESEGMENT(mp)) {
246
data = (PyObject **)mp->data;
247
n = PyArray_SIZE(mp);
248
if (PyArray_ISALIGNED(mp)) {
249
for(i = 0; i < n; i++, data++) {
254
for(i=0; i<n; i++, data++) {
260
else { /* handles misaligned data too */
261
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
265
while(it->index < it->size) {
266
temp = (PyObject **)it->dataptr;
268
PyArray_ITER_NEXT(it);
259
Decrement all internal references for object arrays.
260
(or arrays with object fields)
276
Decrement all internal references for object arrays.
277
(or arrays with object fields)
263
280
PyArray_XDECREF(PyArrayObject *mp)
268
PyArrayIterObject *it;
270
if (!PyDataType_REFCHK(mp->descr)) return 0;
272
if (mp->descr->type_num != PyArray_OBJECT) {
273
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
274
if (it == NULL) return -1;
275
while(it->index < it->size) {
276
PyArray_Item_XDECREF(it->dataptr, mp->descr);
277
PyArray_ITER_NEXT(it);
283
if (PyArray_ISONESEGMENT(mp)) {
284
data = (PyObject **)mp->data;
285
n = PyArray_SIZE(mp);
286
if (PyArray_ISALIGNED(mp)) {
287
for(i=0; i<n; i++, data++) Py_XDECREF(*data);
290
for (i=0; i<n; i++, data++) {
296
else { /* handles misaligned data too */
297
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
298
if (it == NULL) return -1;
299
while(it->index < it->size) {
300
temp = (PyObject **)it->dataptr;
302
PyArray_ITER_NEXT(it);
285
PyArrayIterObject *it;
287
if (!PyDataType_REFCHK(mp->descr)) {
290
if (mp->descr->type_num != PyArray_OBJECT) {
291
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
295
while(it->index < it->size) {
296
PyArray_Item_XDECREF(it->dataptr, mp->descr);
297
PyArray_ITER_NEXT(it);
303
if (PyArray_ISONESEGMENT(mp)) {
304
data = (PyObject **)mp->data;
305
n = PyArray_SIZE(mp);
306
if (PyArray_ISALIGNED(mp)) {
307
for(i = 0; i < n; i++, data++) Py_XDECREF(*data);
310
for(i = 0; i < n; i++, data++) {
316
else { /* handles misaligned data too */
317
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)mp);
321
while(it->index < it->size) {
322
temp = (PyObject **)it->dataptr;
324
PyArray_ITER_NEXT(it);
310
332
_strided_byte_copy(char *dst, intp outstrides, char *src, intp instrides,
311
333
intp N, int elsize)
317
#define _FAST_MOVE(_type_) \
318
for (i=0; i<N; i++) { \
319
((_type_ *)tout)[0] = ((_type_ *)tin)[0]; \
321
tout += outstrides; \
335
for (i=0; i<N; i++) {
336
((Float64 *)tout)[0] = ((Float64 *)tin)[0];
337
((Float64 *)tout)[1] = ((Float64 *)tin)[1];
343
for (i=0; i<N; i++) {
344
for (j=0; j<elsize; j++) {
347
tin = tin + instrides - elsize;
348
tout = tout + outstrides - elsize;
339
#define _FAST_MOVE(_type_) \
340
for(i=0; i<N; i++) { \
341
((_type_ *)tout)[0] = ((_type_ *)tin)[0]; \
343
tout += outstrides; \
358
((Int64 *)tout)[0] = ((Int64 *)tin)[0];
359
((Int64 *)tout)[1] = ((Int64 *)tin)[1];
366
for(j=0; j<elsize; j++) {
369
tin = tin + instrides - elsize;
370
tout = tout + outstrides - elsize;
351
373
#undef _FAST_MOVE
618
640
PyArray_PyIntAsInt(PyObject *o)
620
long long_value = -1;
622
static char *msg = "an integer is required";
624
PyArray_Descr *descr;
629
PyErr_SetString(PyExc_TypeError, msg);
633
if (PyInt_Check(o)) {
634
long_value = (long) PyInt_AS_LONG(o);
636
} else if (PyLong_Check(o)) {
637
long_value = (long) PyLong_AsLong(o);
643
if (PyArray_Check(o)) {
644
if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
645
PyErr_SetString(PyExc_TypeError, msg);
649
arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
651
if (PyArray_IsScalar(o, Integer)) {
653
arr = PyArray_FromScalar(o, descr);
656
ret = *((int *)PyArray_DATA(arr));
642
long long_value = -1;
644
static char *msg = "an integer is required";
646
PyArray_Descr *descr;
651
PyErr_SetString(PyExc_TypeError, msg);
655
if (PyInt_Check(o)) {
656
long_value = (long) PyInt_AS_LONG(o);
658
} else if (PyLong_Check(o)) {
659
long_value = (long) PyLong_AsLong(o);
665
if (PyArray_Check(o)) {
666
if (PyArray_SIZE(o)!=1 || !PyArray_ISINTEGER(o)) {
667
PyErr_SetString(PyExc_TypeError, msg);
671
arr = PyArray_CastToType((PyArrayObject *)o, descr, 0);
673
if (PyArray_IsScalar(o, Integer)) {
675
arr = PyArray_FromScalar(o, descr);
678
ret = *((int *)PyArray_DATA(arr));
660
682
#if (PY_VERSION_HEX >= 0x02050000)
661
if (PyIndex_Check(o)) {
662
PyObject* value = PyNumber_Index(o);
663
long_value = (longlong) PyInt_AsSsize_t(value);
683
if (PyIndex_Check(o)) {
684
PyObject* value = PyNumber_Index(o);
685
long_value = (longlong) PyInt_AsSsize_t(value);
667
if (o->ob_type->tp_as_number != NULL && \
668
o->ob_type->tp_as_number->nb_int != NULL) {
669
obj = o->ob_type->tp_as_number->nb_int(o);
670
if (obj == NULL) return -1;
671
long_value = (long) PyLong_AsLong(obj);
674
else if (o->ob_type->tp_as_number != NULL && \
675
o->ob_type->tp_as_number->nb_long != NULL) {
676
obj = o->ob_type->tp_as_number->nb_long(o);
677
if (obj == NULL) return -1;
678
long_value = (long) PyLong_AsLong(obj);
682
PyErr_SetString(PyExc_NotImplementedError,"");
689
if (o->ob_type->tp_as_number != NULL && \
690
o->ob_type->tp_as_number->nb_int != NULL) {
691
obj = o->ob_type->tp_as_number->nb_int(o);
695
long_value = (long) PyLong_AsLong(obj);
698
else if (o->ob_type->tp_as_number != NULL && \
699
o->ob_type->tp_as_number->nb_long != NULL) {
700
obj = o->ob_type->tp_as_number->nb_long(o);
704
long_value = (long) PyLong_AsLong(obj);
708
PyErr_SetString(PyExc_NotImplementedError,"");
686
if error_converting(long_value) {
687
PyErr_SetString(PyExc_TypeError, msg);
712
if error_converting(long_value) {
713
PyErr_SetString(PyExc_TypeError, msg);
691
717
#if (SIZEOF_LONG > SIZEOF_INT)
692
if ((long_value < INT_MIN) || (long_value > INT_MAX)) {
693
PyErr_SetString(PyExc_ValueError,
694
"integer won't fit into a C int");
718
if ((long_value < INT_MIN) || (long_value > INT_MAX)) {
719
PyErr_SetString(PyExc_ValueError,
720
"integer won't fit into a C int");
698
return (int) long_value;
724
return (int) long_value;
702
728
index2ptr(PyArrayObject *mp, intp i)
706
PyErr_SetString(PyExc_IndexError,
707
"0-d arrays can't be indexed");
710
dim0 = mp->dimensions[0];
712
if (i==0 && dim0 > 0)
715
if (i>0 && i < dim0) {
716
return mp->data+i*mp->strides[0];
718
PyErr_SetString(PyExc_IndexError,"index out of bounds");
732
PyErr_SetString(PyExc_IndexError,
733
"0-d arrays can't be indexed");
736
dim0 = mp->dimensions[0];
738
if (i==0 && dim0 > 0)
741
if (i>0 && i < dim0) {
742
return mp->data+i*mp->strides[0];
744
PyErr_SetString(PyExc_IndexError,"index out of bounds");
723
Compute the size of an array (in number of items)
749
Compute the size of an array (in number of items)
726
752
PyArray_Size(PyObject *op)
728
if (PyArray_Check(op)) {
729
return PyArray_SIZE((PyArrayObject *)op);
754
if (PyArray_Check(op)) {
755
return PyArray_SIZE((PyArrayObject *)op);
737
763
_copy_from0d(PyArrayObject *dest, PyArrayObject *src, int usecopy, int swap)
741
int numcopies, nbytes;
742
void (*myfunc)(char *, intp, char *, intp, intp, int);
745
NPY_BEGIN_THREADS_DEF
747
numcopies = PyArray_SIZE(dest);
748
if (numcopies < 1) return 0;
749
nbytes = PyArray_ITEMSIZE(src);
751
if (!PyArray_ISALIGNED(src)) {
752
aligned = malloc((size_t)nbytes);
753
if (aligned == NULL) {
757
memcpy(aligned, src->data, (size_t) nbytes);
761
else sptr = src->data;
762
if (PyArray_ISALIGNED(dest)) {
763
myfunc = _strided_byte_copy;
766
myfunc = _unaligned_strided_byte_copy;
769
myfunc = _unaligned_strided_byte_move;
772
if ((dest->nd < 2) || PyArray_ISONESEGMENT(dest)) {
778
dstride = dest->strides[0];
781
PyArray_XDECREF(dest);
785
myfunc(dptr, dstride, sptr, 0, numcopies, (int) nbytes);
787
_strided_byte_swap(dptr, dstride, numcopies, (int) nbytes);
791
PyArray_INCREF(dest);
794
PyArrayIterObject *dit;
796
dit = (PyArrayIterObject *)\
797
PyArray_IterAllButAxis((PyObject *)dest, &axis);
798
if (dit == NULL) goto finish;
799
PyArray_XDECREF(dest);
801
while(dit->index < dit->size) {
802
myfunc(dit->dataptr, PyArray_STRIDE(dest, axis),
804
PyArray_DIM(dest, axis), nbytes);
806
_strided_byte_swap(dit->dataptr,
807
PyArray_STRIDE(dest, axis),
808
PyArray_DIM(dest, axis), nbytes);
809
PyArray_ITER_NEXT(dit);
812
PyArray_INCREF(dest);
817
if (aligned != NULL) free(aligned);
767
int numcopies, nbytes;
768
void (*myfunc)(char *, intp, char *, intp, intp, int);
770
NPY_BEGIN_THREADS_DEF;
772
numcopies = PyArray_SIZE(dest);
776
nbytes = PyArray_ITEMSIZE(src);
778
if (!PyArray_ISALIGNED(src)) {
779
aligned = malloc((size_t)nbytes);
780
if (aligned == NULL) {
784
memcpy(aligned, src->data, (size_t) nbytes);
791
if (PyArray_SAFEALIGNEDCOPY(dest)) {
792
myfunc = _strided_byte_copy;
795
myfunc = _unaligned_strided_byte_copy;
798
myfunc = _unaligned_strided_byte_move;
801
if ((dest->nd < 2) || PyArray_ISONESEGMENT(dest)) {
807
dstride = dest->strides[0];
811
/* Refcount note: src and dest may have different sizes */
813
PyArray_XDECREF(dest);
815
myfunc(dptr, dstride, sptr, 0, numcopies, (int) nbytes);
817
_strided_byte_swap(dptr, dstride, numcopies, (int) nbytes);
820
PyArray_INCREF(dest);
821
PyArray_XDECREF(src);
824
PyArrayIterObject *dit;
826
dit = (PyArrayIterObject *)\
827
PyArray_IterAllButAxis((PyObject *)dest, &axis);
831
/* Refcount note: src and dest may have different sizes */
833
PyArray_XDECREF(dest);
835
while(dit->index < dit->size) {
836
myfunc(dit->dataptr, PyArray_STRIDE(dest, axis),
838
PyArray_DIM(dest, axis), nbytes);
840
_strided_byte_swap(dit->dataptr,
841
PyArray_STRIDE(dest, axis),
842
PyArray_DIM(dest, axis), nbytes);
844
PyArray_ITER_NEXT(dit);
847
PyArray_INCREF(dest);
848
PyArray_XDECREF(src);
854
if (aligned != NULL) {
821
/* Special-case of PyArray_CopyInto when dst is 1-d
822
and contiguous (and aligned).
823
PyArray_CopyInto requires broadcastable arrays while
824
this one is a flattening operation...
861
* Special-case of PyArray_CopyInto when dst is 1-d
862
* and contiguous (and aligned).
863
* PyArray_CopyInto requires broadcastable arrays while
864
* this one is a flattening operation...
826
int _flat_copyinto(PyObject *dst, PyObject *src, NPY_ORDER order) {
827
PyArrayIterObject *it;
828
void (*myfunc)(char *, intp, char *, intp, intp, int);
833
NPY_BEGIN_THREADS_DEF
836
if (PyArray_NDIM(src) == 0) {
837
PyArray_XDECREF((PyArrayObject *)dst);
839
memcpy(PyArray_BYTES(dst), PyArray_BYTES(src),
840
PyArray_ITEMSIZE(src));
842
PyArray_INCREF((PyArrayObject *)dst);
846
if (order == PyArray_FORTRANORDER) {
850
axis = PyArray_NDIM(src)-1;
853
it = (PyArrayIterObject *)PyArray_IterAllButAxis(src, &axis);
854
if (it == NULL) return -1;
856
if (PyArray_ISALIGNED(src)) {
857
myfunc = _strided_byte_copy;
860
myfunc = _unaligned_strided_byte_copy;
863
dptr = PyArray_BYTES(dst);
864
elsize = PyArray_ITEMSIZE(dst);
865
nbytes = elsize * PyArray_DIM(src, axis);
867
_flat_copyinto(PyObject *dst, PyObject *src, NPY_ORDER order)
869
PyArrayIterObject *it;
871
void (*myfunc)(char *, intp, char *, intp, intp, int);
876
NPY_BEGIN_THREADS_DEF;
880
if (PyArray_NDIM(src) == 0) {
881
/* Refcount note: src and dst have the same size */
882
PyArray_INCREF((PyArrayObject *)src);
866
883
PyArray_XDECREF((PyArrayObject *)dst);
868
while(it->index < it->size) {
869
myfunc(dptr, elsize, it->dataptr,
870
PyArray_STRIDE(src,axis),
871
PyArray_DIM(src,axis), elsize);
873
PyArray_ITER_NEXT(it);
876
PyArray_INCREF((PyArrayObject *)dst);
885
memcpy(PyArray_BYTES(dst), PyArray_BYTES(src),
886
PyArray_ITEMSIZE(src));
891
axis = PyArray_NDIM(src)-1;
893
if (order == PyArray_FORTRANORDER) {
894
if (PyArray_NDIM(src) <= 2) {
897
/* fall back to a more general method */
899
src = PyArray_Transpose((PyArrayObject *)orig_src, NULL);
903
it = (PyArrayIterObject *)PyArray_IterAllButAxis(src, &axis);
905
if (src != orig_src) {
911
if (PyArray_SAFEALIGNEDCOPY(src)) {
912
myfunc = _strided_byte_copy;
915
myfunc = _unaligned_strided_byte_copy;
918
dptr = PyArray_BYTES(dst);
919
elsize = PyArray_ITEMSIZE(dst);
920
nbytes = elsize * PyArray_DIM(src, axis);
922
/* Refcount note: src and dst have the same size */
923
PyArray_INCREF((PyArrayObject *)src);
924
PyArray_XDECREF((PyArrayObject *)dst);
926
while(it->index < it->size) {
927
myfunc(dptr, elsize, it->dataptr,
928
PyArray_STRIDE(src,axis),
929
PyArray_DIM(src,axis), elsize);
931
PyArray_ITER_NEXT(it);
935
if (src != orig_src) {
999
1077
_array_copy_into(PyArrayObject *dest, PyArrayObject *src, int usecopy)
1080
void (*myfunc)(char *, intp, char *, intp, intp, int);
1083
NPY_BEGIN_THREADS_DEF;
1086
if (!PyArray_EquivArrTypes(dest, src)) {
1087
return PyArray_CastTo(dest, src);
1089
if (!PyArray_ISWRITEABLE(dest)) {
1090
PyErr_SetString(PyExc_RuntimeError,
1091
"cannot write to array");
1094
same = PyArray_SAMESHAPE(dest, src);
1095
simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
1096
(PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
1099
/* Refcount note: src and dest have the same size */
1100
PyArray_INCREF(src);
1101
PyArray_XDECREF(dest);
1104
memcpy(dest->data, src->data, PyArray_NBYTES(dest));
1107
memmove(dest->data, src->data, PyArray_NBYTES(dest));
1113
swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
1116
return _copy_from0d(dest, src, usecopy, swap);
1119
if (PyArray_SAFEALIGNEDCOPY(dest) && PyArray_SAFEALIGNEDCOPY(src)) {
1120
myfunc = _strided_byte_copy;
1123
myfunc = _unaligned_strided_byte_copy;
1126
myfunc = _unaligned_strided_byte_move;
1129
* Could combine these because _broadcasted_copy would work as well.
1130
* But, same-shape copying is so common we want to speed it up.
1133
return _copy_from_same_shape(dest, src, myfunc, swap);
1136
return _broadcast_copy(dest, src, myfunc, swap);
1141
* Copy an Array into another array -- memory must not overlap
1142
* Does not require src and dest to have "broadcastable" shapes
1143
* (only the same number of elements).
1146
PyArray_CopyAnyInto(PyArrayObject *dest, PyArrayObject *src)
1149
PyArrayIterObject *idest, *isrc;
1150
void (*myfunc)(char *, intp, char *, intp, intp, int);
1151
NPY_BEGIN_THREADS_DEF;
1153
if (!PyArray_EquivArrTypes(dest, src)) {
1154
return PyArray_CastAnyTo(dest, src);
1156
if (!PyArray_ISWRITEABLE(dest)) {
1157
PyErr_SetString(PyExc_RuntimeError,
1158
"cannot write to array");
1161
if (PyArray_SIZE(dest) != PyArray_SIZE(src)) {
1162
PyErr_SetString(PyExc_ValueError,
1163
"arrays must have the same number of elements"
1168
simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
1169
(PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
1171
/* Refcount note: src and dest have the same size */
1172
PyArray_INCREF(src);
1173
PyArray_XDECREF(dest);
1175
memcpy(dest->data, src->data, PyArray_NBYTES(dest));
1180
if (PyArray_SAMESHAPE(dest, src)) {
1002
void (*myfunc)(char *, intp, char *, intp, intp, int);
1005
NPY_BEGIN_THREADS_DEF
1008
if (!PyArray_EquivArrTypes(dest, src)) {
1009
return PyArray_CastTo(dest, src);
1012
if (!PyArray_ISWRITEABLE(dest)) {
1013
PyErr_SetString(PyExc_RuntimeError,
1014
"cannot write to array");
1018
same = PyArray_SAMESHAPE(dest, src);
1019
simple = same && ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
1020
(PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
1023
PyArray_XDECREF(dest);
1026
memcpy(dest->data, src->data, PyArray_NBYTES(dest));
1028
memmove(dest->data, src->data, PyArray_NBYTES(dest));
1030
PyArray_INCREF(dest);
1183
if (PyArray_SAFEALIGNEDCOPY(dest) && PyArray_SAFEALIGNEDCOPY(src)) {
1184
myfunc = _strided_byte_copy;
1187
myfunc = _unaligned_strided_byte_copy;
1034
1189
swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
1037
return _copy_from0d(dest, src, usecopy, swap);
1040
if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
1041
myfunc = _strided_byte_copy;
1044
myfunc = _unaligned_strided_byte_copy;
1047
myfunc = _unaligned_strided_byte_move;
1050
/* Could combine these because _broadcasted_copy would work as well.
1051
But, same-shape copying is so common we want to speed it up.
1054
return _copy_from_same_shape(dest, src, myfunc, swap);
1057
return _broadcast_copy(dest, src, myfunc, swap);
1062
Copy an Array into another array -- memory must not overlap
1063
Does not require src and dest to have "broadcastable" shapes
1064
(only the same number of elements).
1067
PyArray_CopyAnyInto(PyArrayObject *dest, PyArrayObject *src)
1070
PyArrayIterObject *idest, *isrc;
1071
void (*myfunc)(char *, intp, char *, intp, intp, int);
1072
NPY_BEGIN_THREADS_DEF
1074
if (!PyArray_EquivArrTypes(dest, src)) {
1075
return PyArray_CastAnyTo(dest, src);
1078
if (!PyArray_ISWRITEABLE(dest)) {
1079
PyErr_SetString(PyExc_RuntimeError,
1080
"cannot write to array");
1084
if (PyArray_SIZE(dest) != PyArray_SIZE(src)) {
1085
PyErr_SetString(PyExc_ValueError,
1086
"arrays must have the same number of elements"
1091
simple = ((PyArray_ISCARRAY_RO(src) && PyArray_ISCARRAY(dest)) ||
1092
(PyArray_ISFARRAY_RO(src) && PyArray_ISFARRAY(dest)));
1095
PyArray_XDECREF(dest);
1097
memcpy(dest->data, src->data, PyArray_NBYTES(dest));
1099
PyArray_INCREF(dest);
1103
if (PyArray_SAMESHAPE(dest, src)) {
1105
if (PyArray_ISALIGNED(dest) && PyArray_ISALIGNED(src)) {
1106
myfunc = _strided_byte_copy;
1109
myfunc = _unaligned_strided_byte_copy;
1111
swap = PyArray_ISNOTSWAPPED(dest) != PyArray_ISNOTSWAPPED(src);
1112
return _copy_from_same_shape(dest, src, myfunc, swap);
1115
/* Otherwise we have to do an iterator-based copy */
1116
idest = (PyArrayIterObject *)PyArray_IterNew((PyObject *)dest);
1117
if (idest == NULL) return -1;
1118
isrc = (PyArrayIterObject *)PyArray_IterNew((PyObject *)src);
1119
if (isrc == NULL) {Py_DECREF(idest); return -1;}
1120
elsize = dest->descr->elsize;
1121
PyArray_XDECREF(dest);
1123
while(idest->index < idest->size) {
1124
memcpy(idest->dataptr, isrc->dataptr, elsize);
1125
PyArray_ITER_NEXT(idest);
1126
PyArray_ITER_NEXT(isrc);
1129
PyArray_INCREF(dest);
1190
return _copy_from_same_shape(dest, src, myfunc, swap);
1193
/* Otherwise we have to do an iterator-based copy */
1194
idest = (PyArrayIterObject *)PyArray_IterNew((PyObject *)dest);
1195
if (idest == NULL) {
1198
isrc = (PyArrayIterObject *)PyArray_IterNew((PyObject *)src);
1130
1200
Py_DECREF(idest);
1203
elsize = dest->descr->elsize;
1204
/* Refcount note: src and dest have the same size */
1205
PyArray_INCREF(src);
1206
PyArray_XDECREF(dest);
1208
while(idest->index < idest->size) {
1209
memcpy(idest->dataptr, isrc->dataptr, elsize);
1210
PyArray_ITER_NEXT(idest);
1211
PyArray_ITER_NEXT(isrc);
1136
Copy an Array into another array -- memory must not overlap.
1220
* Copy an Array into another array -- memory must not overlap.
1139
1223
PyArray_CopyInto(PyArrayObject *dest, PyArrayObject *src)
1141
return _array_copy_into(dest, src, 1);
1225
return _array_copy_into(dest, src, 1);
1146
Move the memory of one array into another.
1230
* Move the memory of one array into another.
1149
1233
PyArray_MoveInto(PyArrayObject *dest, PyArrayObject *src)
1151
return _array_copy_into(dest, src, 0);
1235
return _array_copy_into(dest, src, 0);
1214
1302
/* steals reference to descr -- and enforces native byteorder on it.*/
1216
Like FromDimsAndData but uses the Descr structure instead of typecode
1304
Like FromDimsAndData but uses the Descr structure instead of typecode
1219
1307
static PyObject *
1220
1308
PyArray_FromDimsAndDataAndDescr(int nd, int *d,
1221
1309
PyArray_Descr *descr,
1225
1313
#if SIZEOF_INTP != SIZEOF_INT
1227
intp newd[MAX_DIMS];
1315
intp newd[MAX_DIMS];
1230
if (!PyArray_ISNBO(descr->byteorder))
1231
descr->byteorder = '=';
1318
if (!PyArray_ISNBO(descr->byteorder))
1319
descr->byteorder = '=';
1233
1321
#if SIZEOF_INTP != SIZEOF_INT
1234
for (i=0; i<nd; i++) newd[i] = (intp) d[i];
1235
ret = PyArray_NewFromDescr(&PyArray_Type, descr,
1238
(data ? CARRAY : 0), NULL);
1322
for(i=0; i<nd; i++) newd[i] = (intp) d[i];
1323
ret = PyArray_NewFromDescr(&PyArray_Type, descr,
1326
(data ? CARRAY : 0), NULL);
1240
ret = PyArray_NewFromDescr(&PyArray_Type, descr,
1243
(data ? CARRAY : 0), NULL);
1328
ret = PyArray_NewFromDescr(&PyArray_Type, descr,
1331
(data ? CARRAY : 0), NULL);
1249
Construct an empty array from dimensions and typenum
1337
Construct an empty array from dimensions and typenum
1251
1339
static PyObject *
1252
1340
PyArray_FromDims(int nd, int *d, int type)
1255
ret = PyArray_FromDimsAndDataAndDescr(nd, d,
1256
PyArray_DescrFromType(type),
1258
/* Old FromDims set memory to zero --- some algorithms
1259
relied on that. Better keep it the same. If
1260
Object type, then it's already been set to zero, though.
1262
if (ret && (PyArray_DESCR(ret)->type_num != PyArray_OBJECT)) {
1263
memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
1343
ret = PyArray_FromDimsAndDataAndDescr(nd, d,
1344
PyArray_DescrFromType(type),
1346
/* Old FromDims set memory to zero --- some algorithms
1347
relied on that. Better keep it the same. If
1348
Object type, then it's already been set to zero, though.
1350
if (ret && (PyArray_DESCR(ret)->type_num != PyArray_OBJECT)) {
1351
memset(PyArray_DATA(ret), 0, PyArray_NBYTES(ret));
1268
1356
/* end old calls */
1274
1362
static PyObject *
1275
1363
PyArray_NewCopy(PyArrayObject *m1, NPY_ORDER fortran)
1278
if (fortran == PyArray_ANYORDER)
1279
fortran = PyArray_ISFORTRAN(m1);
1281
Py_INCREF(m1->descr);
1282
ret = (PyArrayObject *)PyArray_NewFromDescr(m1->ob_type,
1289
if (ret == NULL) return NULL;
1290
if (PyArray_CopyInto(ret, m1) == -1) {
1295
return (PyObject *)ret;
1366
if (fortran == PyArray_ANYORDER)
1367
fortran = PyArray_ISFORTRAN(m1);
1369
Py_INCREF(m1->descr);
1370
ret = (PyArrayObject *)PyArray_NewFromDescr(m1->ob_type,
1380
if (PyArray_CopyInto(ret, m1) == -1) {
1385
return (PyObject *)ret;
1298
1388
static PyObject *array_big_item(PyArrayObject *, intp);
1300
1390
/* Does nothing with descr (cannot be NULL) */
1302
Get scalar-equivalent to a region of memory described by a descriptor.
1392
Get scalar-equivalent to a region of memory described by a descriptor.
1304
1394
static PyObject *
1305
1395
PyArray_Scalar(void *data, PyArray_Descr *descr, PyObject *base)
1310
PyArray_CopySwapFunc *copyswap;
1400
PyArray_CopySwapFunc *copyswap;
1315
type_num = descr->type_num;
1316
if (type_num == PyArray_BOOL)
1317
PyArrayScalar_RETURN_BOOL_FROM_LONG(*(Bool*)data);
1318
else if (PyDataType_FLAGCHK(descr, NPY_USE_GETITEM)) {
1319
return descr->f->getitem(data, base);
1321
itemsize = descr->elsize;
1322
copyswap = descr->f->copyswap;
1323
type = descr->typeobj;
1324
swap = !PyArray_ISNBO(descr->byteorder);
1325
if PyTypeNum_ISSTRING(type_num) { /* Eliminate NULL bytes */
1328
while(itemsize && *dptr-- == 0) itemsize--;
1329
if (type_num == PyArray_UNICODE && itemsize) {
1330
/* make sure itemsize is a multiple of 4 */
1331
/* so round up to nearest multiple */
1332
itemsize = (((itemsize-1) >> 2) + 1) << 2;
1335
if (type->tp_itemsize != 0) /* String type */
1336
obj = type->tp_alloc(type, itemsize);
1338
obj = type->tp_alloc(type, 0);
1339
if (obj == NULL) return NULL;
1340
if PyTypeNum_ISFLEXIBLE(type_num) {
1341
if (type_num == PyArray_STRING) {
1342
destptr = PyString_AS_STRING(obj);
1343
((PyStringObject *)obj)->ob_shash = -1;
1344
((PyStringObject *)obj)->ob_sstate = \
1345
SSTATE_NOT_INTERNED;
1346
memcpy(destptr, data, itemsize);
1349
else if (type_num == PyArray_UNICODE) {
1350
PyUnicodeObject *uni = (PyUnicodeObject*)obj;
1351
int length = itemsize >> 2;
1405
type_num = descr->type_num;
1406
if (type_num == PyArray_BOOL)
1407
PyArrayScalar_RETURN_BOOL_FROM_LONG(*(Bool*)data);
1408
else if (PyDataType_FLAGCHK(descr, NPY_USE_GETITEM)) {
1409
return descr->f->getitem(data, base);
1411
itemsize = descr->elsize;
1412
copyswap = descr->f->copyswap;
1413
type = descr->typeobj;
1414
swap = !PyArray_ISNBO(descr->byteorder);
1415
if PyTypeNum_ISSTRING(type_num) { /* Eliminate NULL bytes */
1418
while(itemsize && *dptr-- == 0) itemsize--;
1419
if (type_num == PyArray_UNICODE && itemsize) {
1420
/* make sure itemsize is a multiple of 4 */
1421
/* so round up to nearest multiple */
1422
itemsize = (((itemsize-1) >> 2) + 1) << 2;
1425
if (type->tp_itemsize != 0) /* String type */
1426
obj = type->tp_alloc(type, itemsize);
1428
obj = type->tp_alloc(type, 0);
1432
if PyTypeNum_ISFLEXIBLE(type_num) {
1433
if (type_num == PyArray_STRING) {
1434
destptr = PyString_AS_STRING(obj);
1435
((PyStringObject *)obj)->ob_shash = -1;
1436
((PyStringObject *)obj)->ob_sstate = \
1437
SSTATE_NOT_INTERNED;
1438
memcpy(destptr, data, itemsize);
1441
else if (type_num == PyArray_UNICODE) {
1442
PyUnicodeObject *uni = (PyUnicodeObject*)obj;
1443
int length = itemsize >> 2;
1352
1444
#ifndef Py_UNICODE_WIDE
1357
/* Need an extra slot and need to use
1358
Python memory manager */
1360
destptr = PyMem_NEW(Py_UNICODE,length+1);
1361
if (destptr == NULL) {
1363
return PyErr_NoMemory();
1365
uni->str = (Py_UNICODE *)destptr;
1367
uni->str[length] = 0;
1368
uni->length = length;
1449
/* Need an extra slot and need to use
1450
Python memory manager */
1452
destptr = PyMem_NEW(Py_UNICODE,length+1);
1453
if (destptr == NULL) {
1455
return PyErr_NoMemory();
1457
uni->str = (Py_UNICODE *)destptr;
1459
uni->str[length] = 0;
1460
uni->length = length;
1371
1463
#ifdef Py_UNICODE_WIDE
1372
memcpy(destptr, data, itemsize);
1374
byte_swap_vector(destptr, length, 4);
1464
memcpy(destptr, data, itemsize);
1466
byte_swap_vector(destptr, length, 4);
1376
/* need aligned data buffer */
1377
if (!PyArray_ISBEHAVED(base)) {
1378
buffer = _pya_malloc(itemsize);
1380
return PyErr_NoMemory();
1382
memcpy(buffer, data, itemsize);
1383
if (!PyArray_ISNOTSWAPPED(base)) {
1384
byte_swap_vector(buffer,
1468
/* need aligned data buffer */
1469
if ((swap) || ((((intp)data) % descr->alignment) != 0)) {
1470
buffer = _pya_malloc(itemsize);
1472
return PyErr_NoMemory();
1474
memcpy(buffer, data, itemsize);
1476
byte_swap_vector(buffer,
1390
/* Allocated enough for 2-characters per itemsize.
1391
Now convert from the data-buffer
1393
length = PyUCS2Buffer_FromUCS4(uni->str,
1394
(PyArray_UCS4 *)buffer,
1396
if (alloc) _pya_free(buffer);
1397
/* Resize the unicode result */
1398
if (MyPyUnicode_Resize(uni, length) < 0) {
1482
/* Allocated enough for 2-characters per itemsize.
1483
Now convert from the data-buffer
1485
length = PyUCS2Buffer_FromUCS4(uni->str,
1486
(PyArray_UCS4 *)buffer,
1488
if (alloc) _pya_free(buffer);
1489
/* Resize the unicode result */
1490
if (MyPyUnicode_Resize(uni, length) < 0) {
1498
PyVoidScalarObject *vobj = (PyVoidScalarObject *)obj;
1500
vobj->descr = descr;
1503
vobj->ob_size = itemsize;
1504
vobj->flags = BEHAVED | OWNDATA;
1510
vobj->flags = PyArray_FLAGS(base);
1511
vobj->flags &= ~OWNDATA;
1406
PyVoidScalarObject *vobj = (PyVoidScalarObject *)obj;
1408
vobj->descr = descr;
1411
vobj->ob_size = itemsize;
1412
vobj->flags = BEHAVED | OWNDATA;
1418
vobj->flags = PyArray_FLAGS(base);
1419
vobj->flags &= ~OWNDATA;
1424
destptr = PyDataMem_NEW(itemsize);
1425
if (destptr == NULL) {
1427
return PyErr_NoMemory();
1429
vobj->obval = destptr;
1433
destptr = scalar_value(obj, descr);
1435
/* copyswap for OBJECT increments the reference count */
1436
copyswap(destptr, data, swap, base);
1516
destptr = PyDataMem_NEW(itemsize);
1517
if (destptr == NULL) {
1519
return PyErr_NoMemory();
1521
vobj->obval = destptr;
1525
destptr = scalar_value(obj, descr);
1527
/* copyswap for OBJECT increments the reference count */
1528
copyswap(destptr, data, swap, base);
1440
1532
/* returns an Array-Scalar Object of the type of arr
1653
1770
PyArray_RegisterCanCast(PyArray_Descr *descr, int totype,
1654
1771
NPY_SCALARKIND scalar)
1656
if (scalar == PyArray_NOSCALAR) {
1657
/* register with cancastto */
1658
/* These lists won't be freed once created
1659
-- they become part of the data-type */
1660
if (descr->f->cancastto == NULL) {
1661
descr->f->cancastto = (int *)malloc(1*sizeof(int));
1662
descr->f->cancastto[0] = PyArray_NOTYPE;
1664
descr->f->cancastto = _append_new(descr->f->cancastto,
1668
/* register with cancastscalarkindto */
1669
if (descr->f->cancastscalarkindto == NULL) {
1671
descr->f->cancastscalarkindto = \
1672
(int **)malloc(PyArray_NSCALARKINDS* \
1674
for (i=0; i<PyArray_NSCALARKINDS; i++) {
1675
descr->f->cancastscalarkindto[i] = NULL;
1678
if (descr->f->cancastscalarkindto[scalar] == NULL) {
1679
descr->f->cancastscalarkindto[scalar] = \
1680
(int *)malloc(1*sizeof(int));
1681
descr->f->cancastscalarkindto[scalar][0] = \
1684
descr->f->cancastscalarkindto[scalar] = \
1685
_append_new(descr->f->cancastscalarkindto[scalar],
1773
if (scalar == PyArray_NOSCALAR) {
1774
/* register with cancastto */
1775
/* These lists won't be freed once created
1776
-- they become part of the data-type */
1777
if (descr->f->cancastto == NULL) {
1778
descr->f->cancastto = (int *)malloc(1*sizeof(int));
1779
descr->f->cancastto[0] = PyArray_NOTYPE;
1781
descr->f->cancastto = _append_new(descr->f->cancastto,
1785
/* register with cancastscalarkindto */
1786
if (descr->f->cancastscalarkindto == NULL) {
1788
descr->f->cancastscalarkindto = \
1789
(int **)malloc(PyArray_NSCALARKINDS* \
1791
for(i=0; i<PyArray_NSCALARKINDS; i++) {
1792
descr->f->cancastscalarkindto[i] = NULL;
1795
if (descr->f->cancastscalarkindto[scalar] == NULL) {
1796
descr->f->cancastscalarkindto[scalar] = \
1797
(int *)malloc(1*sizeof(int));
1798
descr->f->cancastscalarkindto[scalar][0] = \
1801
descr->f->cancastscalarkindto[scalar] = \
1802
_append_new(descr->f->cancastscalarkindto[scalar],
1809
/* XXX: FIXME --- add ordering argument to
1810
Allow Fortran ordering on write
1811
This will need the addition of a Fortran-order iterator.
1695
1818
PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format)
1700
PyArrayIterObject *it;
1701
PyObject *obj, *strobj, *tupobj;
1703
n3 = (sep ? strlen((const char *)sep) : 0);
1704
if (n3 == 0) { /* binary data */
1705
if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
1706
PyErr_SetString(PyExc_ValueError, "cannot write " \
1707
"object arrays to a file in " \
1712
if (PyArray_ISCONTIGUOUS(self)) {
1713
size = PyArray_SIZE(self);
1714
NPY_BEGIN_ALLOW_THREADS
1715
n=fwrite((const void *)self->data,
1716
(size_t) self->descr->elsize,
1718
NPY_END_ALLOW_THREADS
1720
PyErr_Format(PyExc_ValueError,
1721
"%ld requested and %ld written",
1722
(long) size, (long) n);
1727
NPY_BEGIN_THREADS_DEF
1729
it=(PyArrayIterObject *) \
1730
PyArray_IterNew((PyObject *)self);
1732
while(it->index < it->size) {
1733
if (fwrite((const void *)it->dataptr,
1734
(size_t) self->descr->elsize,
1737
PyErr_Format(PyExc_IOError,
1738
"problem writing element"\
1744
PyArray_ITER_NEXT(it);
1750
else { /* text data */
1752
it=(PyArrayIterObject *) \
1753
PyArray_IterNew((PyObject *)self);
1754
n4 = (format ? strlen((const char *)format) : 0);
1755
while(it->index < it->size) {
1756
obj = self->descr->f->getitem(it->dataptr, self);
1757
if (obj == NULL) {Py_DECREF(it); return -1;}
1758
if (n4 == 0) { /* standard writing */
1759
strobj = PyObject_Str(obj);
1761
if (strobj == NULL) {Py_DECREF(it); return -1;}
1763
else { /* use format string */
1764
tupobj = PyTuple_New(1);
1765
if (tupobj == NULL) {Py_DECREF(it); return -1;}
1766
PyTuple_SET_ITEM(tupobj,0,obj);
1767
obj = PyString_FromString((const char *)format);
1768
if (obj == NULL) {Py_DECREF(tupobj);
1769
Py_DECREF(it); return -1;}
1770
strobj = PyString_Format(obj, tupobj);
1773
if (strobj == NULL) {Py_DECREF(it); return -1;}
1775
NPY_BEGIN_ALLOW_THREADS
1776
n=fwrite(PyString_AS_STRING(strobj), 1,
1777
n2=PyString_GET_SIZE(strobj), fp);
1778
NPY_END_ALLOW_THREADS
1780
PyErr_Format(PyExc_IOError,
1781
"problem writing element %d"\
1788
/* write separator for all but last one */
1789
if (it->index != it->size-1)
1790
if (fwrite(sep, 1, n3, fp) < n3) {
1791
PyErr_Format(PyExc_IOError,
1793
"separator to file");
1799
PyArray_ITER_NEXT(it);
1823
PyArrayIterObject *it;
1824
PyObject *obj, *strobj, *tupobj;
1826
n3 = (sep ? strlen((const char *)sep) : 0);
1829
if (PyDataType_FLAGCHK(self->descr, NPY_LIST_PICKLE)) {
1830
PyErr_SetString(PyExc_ValueError, "cannot write " \
1831
"object arrays to a file in " \
1836
if (PyArray_ISCONTIGUOUS(self)) {
1837
size = PyArray_SIZE(self);
1838
NPY_BEGIN_ALLOW_THREADS;
1839
n = fwrite((const void *)self->data,
1840
(size_t) self->descr->elsize,
1842
NPY_END_ALLOW_THREADS;
1844
PyErr_Format(PyExc_ValueError,
1845
"%ld requested and %ld written",
1846
(long) size, (long) n);
1851
NPY_BEGIN_THREADS_DEF;
1853
it = (PyArrayIterObject *)
1854
PyArray_IterNew((PyObject *)self);
1856
while(it->index < it->size) {
1857
if (fwrite((const void *)it->dataptr,
1858
(size_t) self->descr->elsize,
1861
PyErr_Format(PyExc_IOError,
1862
"problem writing element"\
1868
PyArray_ITER_NEXT(it);
1879
it = (PyArrayIterObject *)
1880
PyArray_IterNew((PyObject *)self);
1881
n4 = (format ? strlen((const char *)format) : 0);
1882
while(it->index < it->size) {
1883
obj = self->descr->f->getitem(it->dataptr, self);
1892
strobj = PyObject_Str(obj);
1894
if (strobj == NULL) {
1903
tupobj = PyTuple_New(1);
1904
if (tupobj == NULL) {
1908
PyTuple_SET_ITEM(tupobj,0,obj);
1909
obj = PyString_FromString((const char *)format);
1915
strobj = PyString_Format(obj, tupobj);
1918
if (strobj == NULL) {
1923
NPY_BEGIN_ALLOW_THREADS;
1924
n = fwrite(PyString_AS_STRING(strobj), 1,
1925
n2=PyString_GET_SIZE(strobj), fp);
1926
NPY_END_ALLOW_THREADS;
1928
PyErr_Format(PyExc_IOError,
1929
"problem writing element %d"\
1936
/* write separator for all but last one */
1937
if (it->index != it->size-1) {
1938
if (fwrite(sep, 1, n3, fp) < n3) {
1939
PyErr_Format(PyExc_IOError,
1941
"separator to file");
1948
PyArray_ITER_NEXT(it);
1809
1958
static PyObject *
1810
1959
PyArray_ToList(PyArrayObject *self)
1816
if (!PyArray_Check(self)) return (PyObject *)self;
1819
return self->descr->f->getitem(self->data,self);
1821
sz = self->dimensions[0];
1822
lp = PyList_New(sz);
1824
for (i=0; i<sz; i++) {
1825
v=(PyArrayObject *)array_big_item(self, i);
1826
if (v->nd >= self->nd) {
1827
PyErr_SetString(PyExc_RuntimeError,
1828
"array_item not returning smaller-" \
1829
"dimensional array");
1834
PyList_SetItem(lp, i, PyArray_ToList(v));
1965
if (!PyArray_Check(self)) {
1966
return (PyObject *)self;
1968
if (self->nd == 0) {
1969
return self->descr->f->getitem(self->data,self);
1972
sz = self->dimensions[0];
1973
lp = PyList_New(sz);
1974
for(i = 0; i < sz; i++) {
1975
v = (PyArrayObject *)array_big_item(self, i);
1976
if (PyArray_Check(v) && (v->nd >= self->nd)) {
1977
PyErr_SetString(PyExc_RuntimeError,
1978
"array_item not returning smaller-" \
1979
"dimensional array");
1984
PyList_SetItem(lp, i, PyArray_ToList(v));
1842
1991
static PyObject *
1843
1992
PyArray_ToString(PyArrayObject *self, NPY_ORDER order)
1850
PyArrayIterObject *it;
1852
if (order == NPY_ANYORDER)
1853
order = PyArray_ISFORTRAN(self);
1855
/* if (PyArray_TYPE(self) == PyArray_OBJECT) {
1856
PyErr_SetString(PyExc_ValueError, "a string for the data" \
1857
"in an object array is not appropriate");
1862
numbytes = PyArray_NBYTES(self);
1863
if ((PyArray_ISCONTIGUOUS(self) && (order == NPY_CORDER)) || \
1864
(PyArray_ISFORTRAN(self) && (order == NPY_FORTRANORDER))) {
1865
ret = PyString_FromStringAndSize(self->data, (int) numbytes);
1999
PyArrayIterObject *it;
2001
if (order == NPY_ANYORDER)
2002
order = PyArray_ISFORTRAN(self);
2004
/* if (PyArray_TYPE(self) == PyArray_OBJECT) {
2005
PyErr_SetString(PyExc_ValueError, "a string for the data" \
2006
"in an object array is not appropriate");
2011
numbytes = PyArray_NBYTES(self);
2012
if ((PyArray_ISCONTIGUOUS(self) && (order == NPY_CORDER)) || \
2013
(PyArray_ISFORTRAN(self) && (order == NPY_FORTRANORDER))) {
2014
ret = PyString_FromStringAndSize(self->data, (int) numbytes);
2018
if (order == NPY_FORTRANORDER) {
2019
/* iterators are always in C-order */
2020
new = PyArray_Transpose(self, NULL);
2021
if (new == NULL) return NULL;
1869
if (order == NPY_FORTRANORDER) {
1870
/* iterators are always in C-order */
1871
new = PyArray_Transpose(self, NULL);
1872
if (new == NULL) return NULL;
1876
new = (PyObject *)self;
1878
it = (PyArrayIterObject *)PyArray_IterNew(new);
1880
if (it==NULL) return NULL;
1881
ret = PyString_FromStringAndSize(NULL, (int) numbytes);
1882
if (ret == NULL) {Py_DECREF(it); return NULL;}
1883
dptr = PyString_AS_STRING(ret);
1885
elsize = self->descr->elsize;
1887
memcpy(dptr, it->dataptr, elsize);
1889
PyArray_ITER_NEXT(it);
2025
new = (PyObject *)self;
2027
it = (PyArrayIterObject *)PyArray_IterNew(new);
2029
if (it==NULL) return NULL;
2030
ret = PyString_FromStringAndSize(NULL, (int) numbytes);
2031
if (ret == NULL) {Py_DECREF(it); return NULL;}
2032
dptr = PyString_AS_STRING(ret);
2034
elsize = self->descr->elsize;
2036
memcpy(dptr, it->dataptr, elsize);
2038
PyArray_ITER_NEXT(it);
1954
2103
static Py_ssize_t
1955
2104
array_length(PyArrayObject *self)
1957
if (self->nd != 0) {
1958
return self->dimensions[0];
1960
PyErr_SetString(PyExc_TypeError, "len() of unsized object");
2106
if (self->nd != 0) {
2107
return self->dimensions[0];
2109
PyErr_SetString(PyExc_TypeError, "len() of unsized object");
1965
2114
static PyObject *
1966
2115
array_big_item(PyArrayObject *self, intp i)
1972
PyErr_SetString(PyExc_IndexError,
1973
"0-d arrays can't be indexed");
1976
if ((item = index2ptr(self, i)) == NULL) return NULL;
1978
Py_INCREF(self->descr);
1979
r = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
1983
self->strides+1, item,
1986
if (r == NULL) return NULL;
1988
r->base = (PyObject *)self;
1989
PyArray_UpdateFlags(r, CONTIGUOUS | FORTRAN);
1990
return (PyObject *)r;
2121
PyErr_SetString(PyExc_IndexError,
2122
"0-d arrays can't be indexed");
2125
if ((item = index2ptr(self, i)) == NULL) return NULL;
2127
Py_INCREF(self->descr);
2128
r = (PyArrayObject *)PyArray_NewFromDescr(self->ob_type,
2132
self->strides+1, item,
2135
if (r == NULL) return NULL;
2137
r->base = (PyObject *)self;
2138
PyArray_UpdateFlags(r, CONTIGUOUS | FORTRAN);
2139
return (PyObject *)r;
1993
2142
/* contains optimization for 1-d arrays */
1994
2143
static PyObject *
1995
2144
array_item_nice(PyArrayObject *self, Py_ssize_t i)
1997
if (self->nd == 1) {
1999
if ((item = index2ptr(self, i)) == NULL) return NULL;
2000
return PyArray_Scalar(item, self->descr, (PyObject *)self);
2003
return PyArray_Return((PyArrayObject *)\
2004
array_big_item(self, (intp) i));
2146
if (self->nd == 1) {
2148
if ((item = index2ptr(self, i)) == NULL) return NULL;
2149
return PyArray_Scalar(item, self->descr, (PyObject *)self);
2152
return PyArray_Return((PyArrayObject *)\
2153
array_big_item(self, (intp) i));
2009
2158
array_ass_big_item(PyArrayObject *self, intp i, PyObject *v)
2016
PyErr_SetString(PyExc_ValueError,
2017
"can't delete array elements");
2020
if (!PyArray_ISWRITEABLE(self)) {
2021
PyErr_SetString(PyExc_RuntimeError,
2022
"array is not writeable");
2025
if (self->nd == 0) {
2026
PyErr_SetString(PyExc_IndexError,
2027
"0-d arrays can't be indexed.");
2033
if((tmp = (PyArrayObject *)array_big_item(self, i)) == NULL)
2035
ret = PyArray_CopyObject(tmp, v);
2040
if ((item = index2ptr(self, i)) == NULL) return -1;
2041
if (self->descr->f->setitem(v, item, self) == -1) return -1;
2165
PyErr_SetString(PyExc_ValueError,
2166
"can't delete array elements");
2169
if (!PyArray_ISWRITEABLE(self)) {
2170
PyErr_SetString(PyExc_RuntimeError,
2171
"array is not writeable");
2174
if (self->nd == 0) {
2175
PyErr_SetString(PyExc_IndexError,
2176
"0-d arrays can't be indexed.");
2182
if((tmp = (PyArrayObject *)array_big_item(self, i)) == NULL)
2184
ret = PyArray_CopyObject(tmp, v);
2189
if ((item = index2ptr(self, i)) == NULL) return -1;
2190
if (self->descr->f->setitem(v, item, self) == -1) return -1;
2045
2194
#if PY_VERSION_HEX < 0x02050000
2046
#if SIZEOF_INT == SIZEOF_INTP
2047
#define array_ass_item array_ass_big_item
2195
#if SIZEOF_INT == SIZEOF_INTP
2196
#define array_ass_item array_ass_big_item
2050
#if SIZEOF_SIZE_T == SIZEOF_INTP
2051
#define array_ass_item array_ass_big_item
2199
#if SIZEOF_SIZE_T == SIZEOF_INTP
2200
#define array_ass_item array_ass_big_item
2054
2203
#ifndef array_ass_item
2056
2205
array_ass_item(PyArrayObject *self, Py_ssize_t i, PyObject *v)
2058
return array_ass_big_item(self, (intp) i, v);
2207
return array_ass_big_item(self, (intp) i, v);
2185
2334
parse_index(PyArrayObject *self, PyObject *op,
2186
2335
intp *dimensions, intp *strides, intp *offset_ptr)
2189
int nd_old, nd_new, n_add, n_pseudo;
2190
intp n_steps, start, offset, step_size;
2194
if (PySlice_Check(op) || op == Py_Ellipsis || op == Py_None) {
2198
/* this relies on the fact that n==1 for loop below */
2202
if (!PySequence_Check(op)) {
2203
PyErr_SetString(PyExc_IndexError,
2204
"index must be either an int "\
2208
n = PySequence_Length(op);
2212
nd_old = nd_new = 0;
2215
for(i=0; i<n; i++) {
2217
if (!(op1=PySequence_GetItem(op, i))) {
2218
PyErr_SetString(PyExc_IndexError,
2224
start = parse_subindex(op1, &step_size, &n_steps,
2225
nd_old < self->nd ? \
2226
self->dimensions[nd_old] : 0);
2228
if (start == -1) break;
2230
if (n_steps == PseudoIndex) {
2231
dimensions[nd_new] = 1; strides[nd_new] = 0;
2234
if (n_steps == RubberIndex) {
2235
for(j=i+1, n_pseudo=0; j<n; j++) {
2236
op1 = PySequence_GetItem(op, j);
2237
if (op1 == Py_None) n_pseudo++;
2240
n_add = self->nd-(n-i-n_pseudo-1+nd_old);
2242
PyErr_SetString(PyExc_IndexError,
2243
"too many indices");
2246
for(j=0; j<n_add; j++) {
2247
dimensions[nd_new] = \
2248
self->dimensions[nd_old];
2250
self->strides[nd_old];
2254
if (nd_old >= self->nd) {
2255
PyErr_SetString(PyExc_IndexError,
2256
"too many indices");
2259
offset += self->strides[nd_old]*start;
2261
if (n_steps != SingleIndex) {
2262
dimensions[nd_new] = n_steps;
2263
strides[nd_new] = step_size * \
2264
self->strides[nd_old-1];
2270
if (i < n) return -1;
2271
n_add = self->nd-nd_old;
2272
for(j=0; j<n_add; j++) {
2273
dimensions[nd_new] = self->dimensions[nd_old];
2274
strides[nd_new] = self->strides[nd_old];
2277
*offset_ptr = offset;
2338
int nd_old, nd_new, n_add, n_pseudo;
2339
intp n_steps, start, offset, step_size;
2343
if (PySlice_Check(op) || op == Py_Ellipsis || op == Py_None) {
2347
/* this relies on the fact that n==1 for loop below */
2351
if (!PySequence_Check(op)) {
2352
PyErr_SetString(PyExc_IndexError,
2353
"index must be either an int "\
2357
n = PySequence_Length(op);
2361
nd_old = nd_new = 0;
2364
for(i=0; i<n; i++) {
2366
if (!(op1=PySequence_GetItem(op, i))) {
2367
PyErr_SetString(PyExc_IndexError,
2373
start = parse_subindex(op1, &step_size, &n_steps,
2374
nd_old < self->nd ? \
2375
self->dimensions[nd_old] : 0);
2377
if (start == -1) break;
2379
if (n_steps == PseudoIndex) {
2380
dimensions[nd_new] = 1; strides[nd_new] = 0;
2383
if (n_steps == RubberIndex) {
2384
for(j=i+1, n_pseudo=0; j<n; j++) {
2385
op1 = PySequence_GetItem(op, j);
2386
if (op1 == Py_None) n_pseudo++;
2389
n_add = self->nd-(n-i-n_pseudo-1+nd_old);
2391
PyErr_SetString(PyExc_IndexError,
2392
"too many indices");
2395
for(j=0; j<n_add; j++) {
2396
dimensions[nd_new] = \
2397
self->dimensions[nd_old];
2399
self->strides[nd_old];
2403
if (nd_old >= self->nd) {
2404
PyErr_SetString(PyExc_IndexError,
2405
"too many indices");
2408
offset += self->strides[nd_old]*start;
2410
if (n_steps != SingleIndex) {
2411
dimensions[nd_new] = n_steps;
2412
strides[nd_new] = step_size * \
2413
self->strides[nd_old-1];
2419
if (i < n) return -1;
2420
n_add = self->nd-nd_old;
2421
for(j=0; j<n_add; j++) {
2422
dimensions[nd_new] = self->dimensions[nd_old];
2423
strides[nd_new] = self->strides[nd_old];
2426
*offset_ptr = offset;
2282
2431
_swap_axes(PyArrayMapIterObject *mit, PyArrayObject **ret, int getmap)
2285
int n1, n2, n3, val, bnd;
2287
PyArray_Dims permute;
2292
permute.len = mit->nd;
2294
/* arr might not have the right number of dimensions
2295
and need to be reshaped first by pre-pending ones */
2297
if (arr->nd != mit->nd) {
2298
for (i=1; i<=arr->nd; i++) {
2299
permute.ptr[mit->nd-i] = arr->dimensions[arr->nd-i];
2301
for (i=0; i<mit->nd-arr->nd; i++) {
2304
new = PyArray_Newshape(arr, &permute, PyArray_ANYORDER);
2306
*ret = (PyArrayObject *)new;
2307
if (new == NULL) return;
2310
/* Setting and getting need to have different permutations.
2311
On the get we are permuting the returned object, but on
2312
setting we are permuting the object-to-be-set.
2313
The set permutation is the inverse of the get permutation.
2316
/* For getting the array the tuple for transpose is
2317
(n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1)
2318
n1 is the number of dimensions of
2319
the broadcasted index array
2320
n2 is the number of dimensions skipped at the
2322
n3 is the number of dimensions of the
2326
/* For setting the array the tuple for transpose is
2327
(n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1)
2329
n1 = mit->iters[0]->nd_m1 + 1;
2330
n2 = mit->iteraxes[0];
2333
bnd = (getmap ? n1 : n2); /* use n1 as the boundary if getting
2334
but n2 if setting */
2339
permute.ptr[i++] = val++;
2342
permute.ptr[i++] = val++;
2345
permute.ptr[i++] = val++;
2347
new = PyArray_Transpose(*ret, &permute);
2434
int n1, n2, n3, val, bnd;
2436
PyArray_Dims permute;
2441
permute.len = mit->nd;
2443
/* arr might not have the right number of dimensions
2444
and need to be reshaped first by pre-pending ones */
2446
if (arr->nd != mit->nd) {
2447
for(i=1; i<=arr->nd; i++) {
2448
permute.ptr[mit->nd-i] = arr->dimensions[arr->nd-i];
2450
for(i=0; i<mit->nd-arr->nd; i++) {
2453
new = PyArray_Newshape(arr, &permute, PyArray_ANYORDER);
2349
2455
*ret = (PyArrayObject *)new;
2456
if (new == NULL) return;
2459
/* Setting and getting need to have different permutations.
2460
On the get we are permuting the returned object, but on
2461
setting we are permuting the object-to-be-set.
2462
The set permutation is the inverse of the get permutation.
2465
/* For getting the array the tuple for transpose is
2466
(n1,...,n1+n2-1,0,...,n1-1,n1+n2,...,n3-1)
2467
n1 is the number of dimensions of
2468
the broadcasted index array
2469
n2 is the number of dimensions skipped at the
2471
n3 is the number of dimensions of the
2475
/* For setting the array the tuple for transpose is
2476
(n2,...,n1+n2-1,0,...,n2-1,n1+n2,...n3-1)
2478
n1 = mit->iters[0]->nd_m1 + 1;
2479
n2 = mit->iteraxes[0];
2482
bnd = (getmap ? n1 : n2); /* use n1 as the boundary if getting
2483
but n2 if setting */
2488
permute.ptr[i++] = val++;
2491
permute.ptr[i++] = val++;
2494
permute.ptr[i++] = val++;
2496
new = PyArray_Transpose(*ret, &permute);
2498
*ret = (PyArrayObject *)new;
2352
2501
/* Prototypes for Mapping calls --- not part of the C-API
2362
2511
PyArray_GetMap(PyArrayMapIterObject *mit)
2365
PyArrayObject *ret, *temp;
2366
PyArrayIterObject *it;
2369
PyArray_CopySwapFunc *copyswap;
2371
/* Unbound map iterator --- Bind should have been called */
2372
if (mit->ait == NULL) return NULL;
2374
/* This relies on the map iterator object telling us the shape
2375
of the new array in nd and dimensions.
2377
temp = mit->ait->ao;
2378
Py_INCREF(temp->descr);
2379
ret = (PyArrayObject *)\
2380
PyArray_NewFromDescr(temp->ob_type,
2382
mit->nd, mit->dimensions,
2384
PyArray_ISFORTRAN(temp),
2386
if (ret == NULL) return NULL;
2388
/* Now just iterate through the new array filling it in
2389
with the next object from the original array as
2390
defined by the mapping iterator */
2392
if ((it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ret))
2398
swap = (PyArray_ISNOTSWAPPED(temp) != PyArray_ISNOTSWAPPED(ret));
2399
copyswap = ret->descr->f->copyswap;
2400
PyArray_MapIterReset(mit);
2514
PyArrayObject *ret, *temp;
2515
PyArrayIterObject *it;
2518
PyArray_CopySwapFunc *copyswap;
2520
/* Unbound map iterator --- Bind should have been called */
2521
if (mit->ait == NULL) return NULL;
2523
/* This relies on the map iterator object telling us the shape
2524
of the new array in nd and dimensions.
2526
temp = mit->ait->ao;
2527
Py_INCREF(temp->descr);
2528
ret = (PyArrayObject *)\
2529
PyArray_NewFromDescr(temp->ob_type,
2531
mit->nd, mit->dimensions,
2533
PyArray_ISFORTRAN(temp),
2535
if (ret == NULL) return NULL;
2537
/* Now just iterate through the new array filling it in
2538
with the next object from the original array as
2539
defined by the mapping iterator */
2541
if ((it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ret))
2547
swap = (PyArray_ISNOTSWAPPED(temp) != PyArray_ISNOTSWAPPED(ret));
2548
copyswap = ret->descr->f->copyswap;
2549
PyArray_MapIterReset(mit);
2551
copyswap(it->dataptr, mit->dataptr, swap, ret);
2552
PyArray_MapIterNext(mit);
2553
PyArray_ITER_NEXT(it);
2557
/* check for consecutive axes */
2558
if ((mit->subspace != NULL) && (mit->consec)) {
2559
if (mit->iteraxes[0] > 0) { /* then we need to swap */
2560
_swap_axes(mit, &ret, 1);
2563
return (PyObject *)ret;
2567
PyArray_SetMap(PyArrayMapIterObject *mit, PyObject *op)
2570
PyArrayIterObject *it;
2573
PyArray_CopySwapFunc *copyswap;
2574
PyArray_Descr *descr;
2576
/* Unbound Map Iterator */
2577
if (mit->ait == NULL) return -1;
2579
descr = mit->ait->ao->descr;
2581
arr = PyArray_FromAny(op, descr, 0, 0, FORCECAST, NULL);
2582
if (arr == NULL) return -1;
2584
if ((mit->subspace != NULL) && (mit->consec)) {
2585
if (mit->iteraxes[0] > 0) { /* then we need to swap */
2586
_swap_axes(mit, (PyArrayObject **)&arr, 0);
2587
if (arr == NULL) return -1;
2591
/* Be sure values array is "broadcastable"
2592
to shape of mit->dimensions, mit->nd */
2594
if ((it = (PyArrayIterObject *)\
2595
PyArray_BroadcastToShape(arr, mit->dimensions, mit->nd))==NULL) {
2601
swap = (PyArray_ISNOTSWAPPED(mit->ait->ao) != \
2602
(PyArray_ISNOTSWAPPED(arr)));
2603
copyswap = PyArray_DESCR(arr)->f->copyswap;
2604
PyArray_MapIterReset(mit);
2605
/* Need to decref hasobject arrays */
2606
if (PyDataType_FLAGCHK(descr, NPY_ITEM_REFCOUNT)) {
2401
2607
while (index--) {
2402
copyswap(it->dataptr, mit->dataptr, swap, ret);
2403
PyArray_MapIterNext(mit);
2404
PyArray_ITER_NEXT(it);
2408
/* check for consecutive axes */
2409
if ((mit->subspace != NULL) && (mit->consec)) {
2410
if (mit->iteraxes[0] > 0) { /* then we need to swap */
2411
_swap_axes(mit, &ret, 1);
2414
return (PyObject *)ret;
2418
PyArray_SetMap(PyArrayMapIterObject *mit, PyObject *op)
2421
PyArrayIterObject *it;
2424
PyArray_CopySwapFunc *copyswap;
2425
PyArray_Descr *descr;
2427
/* Unbound Map Iterator */
2428
if (mit->ait == NULL) return -1;
2430
descr = mit->ait->ao->descr;
2432
arr = PyArray_FromAny(op, descr, 0, 0, FORCECAST, NULL);
2433
if (arr == NULL) return -1;
2435
if ((mit->subspace != NULL) && (mit->consec)) {
2436
if (mit->iteraxes[0] > 0) { /* then we need to swap */
2437
_swap_axes(mit, (PyArrayObject **)&arr, 0);
2438
if (arr == NULL) return -1;
2442
/* Be sure values array is "broadcastable"
2443
to shape of mit->dimensions, mit->nd */
2445
if ((it = (PyArrayIterObject *)\
2446
PyArray_BroadcastToShape(arr, mit->dimensions, mit->nd))==NULL) {
2452
swap = (PyArray_ISNOTSWAPPED(mit->ait->ao) != \
2453
(PyArray_ISNOTSWAPPED(arr)));
2454
copyswap = PyArray_DESCR(arr)->f->copyswap;
2455
PyArray_MapIterReset(mit);
2456
/* Need to decref hasobject arrays */
2457
if (PyDataType_FLAGCHK(descr, NPY_ITEM_REFCOUNT)) {
2459
PyArray_Item_XDECREF(mit->dataptr, PyArray_DESCR(arr));
2460
PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(arr));
2461
memmove(mit->dataptr, it->dataptr, sizeof(PyObject *));
2462
/* ignored unless VOID array with object's */
2464
copyswap(mit->dataptr, NULL, swap, arr);
2465
PyArray_MapIterNext(mit);
2466
PyArray_ITER_NEXT(it);
2473
memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr));
2475
copyswap(mit->dataptr, NULL, swap, arr);
2476
PyArray_MapIterNext(mit);
2477
PyArray_ITER_NEXT(it);
2608
PyArray_Item_XDECREF(mit->dataptr, PyArray_DESCR(arr));
2609
PyArray_Item_INCREF(it->dataptr, PyArray_DESCR(arr));
2610
memmove(mit->dataptr, it->dataptr, sizeof(PyObject *));
2611
/* ignored unless VOID array with object's */
2613
copyswap(mit->dataptr, NULL, swap, arr);
2614
PyArray_MapIterNext(mit);
2615
PyArray_ITER_NEXT(it);
2479
2617
Py_DECREF(arr);
2622
memmove(mit->dataptr, it->dataptr, PyArray_ITEMSIZE(arr));
2624
copyswap(mit->dataptr, NULL, swap, arr);
2625
PyArray_MapIterNext(mit);
2626
PyArray_ITER_NEXT(it);
2485
2634
count_new_axes_0d(PyObject *tuple)
2487
int i, argument_count;
2488
int ellipsis_count = 0;
2489
int newaxis_count = 0;
2491
argument_count = PyTuple_GET_SIZE(tuple);
2493
for (i = 0; i < argument_count; ++i) {
2494
PyObject *arg = PyTuple_GET_ITEM(tuple, i);
2495
if (arg == Py_Ellipsis && !ellipsis_count) ellipsis_count++;
2496
else if (arg == Py_None) newaxis_count++;
2499
if (i < argument_count) {
2500
PyErr_SetString(PyExc_IndexError,
2501
"0-d arrays can only use a single ()"
2502
" or a list of newaxes (and a single ...)"
2506
if (newaxis_count > MAX_DIMS) {
2507
PyErr_SetString(PyExc_IndexError,
2508
"too many dimensions");
2511
return newaxis_count;
2636
int i, argument_count;
2637
int ellipsis_count = 0;
2638
int newaxis_count = 0;
2640
argument_count = PyTuple_GET_SIZE(tuple);
2642
for(i = 0; i < argument_count; ++i) {
2643
PyObject *arg = PyTuple_GET_ITEM(tuple, i);
2644
if (arg == Py_Ellipsis && !ellipsis_count) ellipsis_count++;
2645
else if (arg == Py_None) newaxis_count++;
2648
if (i < argument_count) {
2649
PyErr_SetString(PyExc_IndexError,
2650
"0-d arrays can only use a single ()"
2651
" or a list of newaxes (and a single ...)"
2655
if (newaxis_count > MAX_DIMS) {
2656
PyErr_SetString(PyExc_IndexError,
2657
"too many dimensions");
2660
return newaxis_count;
2514
2663
static PyObject *
2515
2664
add_new_axes_0d(PyArrayObject *arr, int newaxis_count)
2517
PyArrayObject *other;
2518
intp dimensions[MAX_DIMS];
2520
for (i = 0; i < newaxis_count; ++i) {
2523
Py_INCREF(arr->descr);
2524
if ((other = (PyArrayObject *)
2525
PyArray_NewFromDescr(arr->ob_type, arr->descr,
2526
newaxis_count, dimensions,
2529
(PyObject *)arr)) == NULL)
2531
other->base = (PyObject *)arr;
2533
return (PyObject *)other;
2666
PyArrayObject *other;
2667
intp dimensions[MAX_DIMS];
2669
for(i = 0; i < newaxis_count; ++i) {
2672
Py_INCREF(arr->descr);
2673
if ((other = (PyArrayObject *)
2674
PyArray_NewFromDescr(arr->ob_type, arr->descr,
2675
newaxis_count, dimensions,
2678
(PyObject *)arr)) == NULL)
2680
other->base = (PyObject *)arr;
2682
return (PyObject *)other;
2632
2781
static PyObject *
2633
2782
array_subscript_simple(PyArrayObject *self, PyObject *op)
2635
intp dimensions[MAX_DIMS], strides[MAX_DIMS];
2638
PyArrayObject *other;
2641
value = PyArray_PyIntAsIntp(op);
2642
if (!PyErr_Occurred()) {
2643
return array_big_item(self, value);
2647
/* Standard (view-based) Indexing */
2648
if ((nd = parse_index(self, op, dimensions, strides, &offset))
2651
/* This will only work if new array will be a view */
2652
Py_INCREF(self->descr);
2653
if ((other = (PyArrayObject *) \
2654
PyArray_NewFromDescr(self->ob_type, self->descr,
2656
strides, self->data+offset,
2658
(PyObject *)self)) == NULL)
2661
other->base = (PyObject *)self;
2664
PyArray_UpdateFlags(other, UPDATE_ALL);
2666
return (PyObject *)other;
2784
intp dimensions[MAX_DIMS], strides[MAX_DIMS];
2787
PyArrayObject *other;
2790
value = PyArray_PyIntAsIntp(op);
2791
if (!PyErr_Occurred()) {
2792
return array_big_item(self, value);
2796
/* Standard (view-based) Indexing */
2797
if ((nd = parse_index(self, op, dimensions, strides, &offset))
2800
/* This will only work if new array will be a view */
2801
Py_INCREF(self->descr);
2802
if ((other = (PyArrayObject *) \
2803
PyArray_NewFromDescr(self->ob_type, self->descr,
2805
strides, self->data+offset,
2807
(PyObject *)self)) == NULL)
2810
other->base = (PyObject *)self;
2813
PyArray_UpdateFlags(other, UPDATE_ALL);
2815
return (PyObject *)other;
2669
2818
static PyObject *
2670
2819
array_subscript(PyArrayObject *self, PyObject *op)
2672
int nd, oned, fancy;
2673
PyArrayObject *other;
2674
PyArrayMapIterObject *mit;
2676
if (PyString_Check(op) || PyUnicode_Check(op)) {
2677
if (self->descr->names) {
2679
obj = PyDict_GetItem(self->descr->fields, op);
2681
PyArray_Descr *descr;
2685
if (PyArg_ParseTuple(obj, "Oi|O",
2686
&descr, &offset, &title)) {
2688
return PyArray_GetField(self, descr,
2694
PyErr_Format(PyExc_ValueError,
2695
"field named %s not found.",
2696
PyString_AsString(op));
2700
if (self->nd == 0) {
2701
if (op == Py_Ellipsis) {
2702
/* XXX: This leads to a small inconsistency
2703
XXX: with the nd>0 case where (x[...] is x)
2704
XXX: is false for nd>0 case. */
2706
return (PyObject *)self;
2709
return add_new_axes_0d(self, 1);
2710
if (PyTuple_Check(op)) {
2711
if (0 == PyTuple_GET_SIZE(op)) {
2713
return (PyObject *)self;
2715
if ((nd = count_new_axes_0d(op)) == -1)
2717
return add_new_axes_0d(self, nd);
2719
PyErr_SetString(PyExc_IndexError,
2720
"0-d arrays can't be indexed.");
2724
fancy = fancy_indexing_check(op);
2726
if (fancy != SOBJ_NOTFANCY) {
2727
oned = ((self->nd == 1) &&
2728
!(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1));
2730
/* wrap arguments into a mapiter object */
2731
mit = (PyArrayMapIterObject *)\
2732
PyArray_MapIterNew(op, oned, fancy);
2733
if (mit == NULL) return NULL;
2735
PyArrayIterObject *it;
2737
it = (PyArrayIterObject *)\
2738
PyArray_IterNew((PyObject *)self);
2739
if (it == NULL) {Py_DECREF(mit); return NULL;}
2740
rval = iter_subscript(it, mit->indexobj);
2745
PyArray_MapIterBind(mit, self);
2746
other = (PyArrayObject *)PyArray_GetMap(mit);
2748
return (PyObject *)other;
2751
return array_subscript_simple(self, op);
2822
PyArrayObject *other;
2823
PyArrayMapIterObject *mit;
2825
if (PyString_Check(op) || PyUnicode_Check(op)) {
2826
if (self->descr->names) {
2828
obj = PyDict_GetItem(self->descr->fields, op);
2830
PyArray_Descr *descr;
2834
if (PyArg_ParseTuple(obj, "Oi|O",
2835
&descr, &offset, &title)) {
2837
return PyArray_GetField(self, descr,
2843
PyErr_Format(PyExc_ValueError,
2844
"field named %s not found.",
2845
PyString_AsString(op));
2849
if (op == Py_Ellipsis) {
2851
return (PyObject *)self;
2854
if (self->nd == 0) {
2856
return add_new_axes_0d(self, 1);
2857
if (PyTuple_Check(op)) {
2858
if (0 == PyTuple_GET_SIZE(op)) {
2860
return (PyObject *)self;
2862
if ((nd = count_new_axes_0d(op)) == -1)
2864
return add_new_axes_0d(self, nd);
2866
/* Allow Boolean mask selection also */
2867
if ((PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
2868
PyArray_ISBOOL(op))) {
2869
if (PyObject_IsTrue(op)) {
2871
return (PyObject *)self;
2875
Py_INCREF(self->descr);
2876
return PyArray_NewFromDescr(self->ob_type,
2884
PyErr_SetString(PyExc_IndexError,
2885
"0-d arrays can't be indexed.");
2889
fancy = fancy_indexing_check(op);
2891
if (fancy != SOBJ_NOTFANCY) {
2893
oned = ((self->nd == 1) &&
2894
!(PyTuple_Check(op) && PyTuple_GET_SIZE(op) > 1));
2896
/* wrap arguments into a mapiter object */
2897
mit = (PyArrayMapIterObject *)\
2898
PyArray_MapIterNew(op, oned, fancy);
2899
if (mit == NULL) return NULL;
2901
PyArrayIterObject *it;
2903
it = (PyArrayIterObject *)\
2904
PyArray_IterNew((PyObject *)self);
2905
if (it == NULL) {Py_DECREF(mit); return NULL;}
2906
rval = iter_subscript(it, mit->indexobj);
2911
PyArray_MapIterBind(mit, self);
2912
other = (PyArrayObject *)PyArray_GetMap(mit);
2914
return (PyObject *)other;
2917
return array_subscript_simple(self, op);
2813
2979
_tuple_of_integers(PyObject *seq, intp *vals, int maxvals)
2819
for (i=0; i<maxvals; i++) {
2820
obj = PyTuple_GET_ITEM(seq, i);
2821
if ((PyArray_Check(obj) && PyArray_NDIM(obj) > 0) ||
2822
PyList_Check(obj)) return -1;
2823
temp = PyArray_PyIntAsIntp(obj);
2824
if (error_converting(temp)) return -1;
2985
for(i=0; i<maxvals; i++) {
2986
obj = PyTuple_GET_ITEM(seq, i);
2987
if ((PyArray_Check(obj) && PyArray_NDIM(obj) > 0) ||
2988
PyList_Check(obj)) return -1;
2989
temp = PyArray_PyIntAsIntp(obj);
2990
if (error_converting(temp)) return -1;
2832
2998
array_ass_sub(PyArrayObject *self, PyObject *index, PyObject *op)
2834
int ret, oned, fancy;
2835
PyArrayMapIterObject *mit;
2836
intp vals[MAX_DIMS];
2839
PyErr_SetString(PyExc_ValueError,
2840
"cannot delete array elements");
2843
if (!PyArray_ISWRITEABLE(self)) {
2844
PyErr_SetString(PyExc_RuntimeError,
2845
"array is not writeable");
2849
if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) ||
2850
PyLong_Check(index) || (PyIndex_Check(index) &&
2851
!PySequence_Check(index))) {
2853
value = PyArray_PyIntAsIntp(index);
2854
if (PyErr_Occurred())
2857
return array_ass_big_item(self, value, op);
2860
if (PyString_Check(index) || PyUnicode_Check(index)) {
2861
if (self->descr->names) {
2863
obj = PyDict_GetItem(self->descr->fields, index);
2865
PyArray_Descr *descr;
2869
if (PyArg_ParseTuple(obj, "Oi|O",
2870
&descr, &offset, &title)) {
2872
return PyArray_SetField(self, descr,
2878
PyErr_Format(PyExc_ValueError,
2879
"field named %s not found.",
2880
PyString_AsString(index));
2884
if (self->nd == 0) {
2885
if (index == Py_Ellipsis || index == Py_None || \
2886
(PyTuple_Check(index) && (0 == PyTuple_GET_SIZE(index) || \
2887
count_new_axes_0d(index) > 0)))
2888
return self->descr->f->setitem(op, self->data, self);
2889
PyErr_SetString(PyExc_IndexError,
2890
"0-d arrays can't be indexed.");
2894
/* optimization for integer-tuple */
2896
(PyTuple_Check(index) && (PyTuple_GET_SIZE(index) == self->nd))
2897
&& (_tuple_of_integers(index, vals, self->nd) >= 0)) {
2900
for (i=0; i<self->nd; i++) {
2901
if (vals[i] < 0) vals[i] += self->dimensions[i];
2902
if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
2903
PyErr_Format(PyExc_IndexError,
2904
"index (%"INTP_FMT") out of range "\
2905
"(0<=index<%"INTP_FMT") in dimension %d",
2906
vals[i], self->dimensions[i], i);
2910
item = PyArray_GetPtr(self, vals);
2911
/* fprintf(stderr, "Here I am...\n");*/
2912
return self->descr->f->setitem(op, item, self);
2916
fancy = fancy_indexing_check(index);
2918
if (fancy != SOBJ_NOTFANCY) {
2919
oned = ((self->nd == 1) &&
2920
!(PyTuple_Check(index) && PyTuple_GET_SIZE(index) > 1));
2922
mit = (PyArrayMapIterObject *) \
2923
PyArray_MapIterNew(index, oned, fancy);
2924
if (mit == NULL) return -1;
2926
PyArrayIterObject *it;
2928
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
2929
if (it == NULL) {Py_DECREF(mit); return -1;}
2930
rval = iter_ass_subscript(it, mit->indexobj, op);
2935
PyArray_MapIterBind(mit, self);
2936
ret = PyArray_SetMap(mit, op);
2941
return array_ass_sub_simple(self, index, op);
3000
int ret, oned, fancy;
3001
PyArrayMapIterObject *mit;
3002
intp vals[MAX_DIMS];
3005
PyErr_SetString(PyExc_ValueError,
3006
"cannot delete array elements");
3009
if (!PyArray_ISWRITEABLE(self)) {
3010
PyErr_SetString(PyExc_RuntimeError,
3011
"array is not writeable");
3015
if (PyInt_Check(index) || PyArray_IsScalar(index, Integer) ||
3016
PyLong_Check(index) || (PyIndex_Check(index) &&
3017
!PySequence_Check(index))) {
3019
value = PyArray_PyIntAsIntp(index);
3020
if (PyErr_Occurred())
3023
return array_ass_big_item(self, value, op);
3026
if (PyString_Check(index) || PyUnicode_Check(index)) {
3027
if (self->descr->names) {
3029
obj = PyDict_GetItem(self->descr->fields, index);
3031
PyArray_Descr *descr;
3035
if (PyArg_ParseTuple(obj, "Oi|O",
3036
&descr, &offset, &title)) {
3038
return PyArray_SetField(self, descr,
3044
PyErr_Format(PyExc_ValueError,
3045
"field named %s not found.",
3046
PyString_AsString(index));
3050
if (self->nd == 0) {
3051
/* Several different exceptions to the 0-d no-indexing rule
3055
3) Using newaxis (None)
3056
4) Boolean mask indexing
3058
if (index == Py_Ellipsis || index == Py_None || \
3059
(PyTuple_Check(index) && (0 == PyTuple_GET_SIZE(index) || \
3060
count_new_axes_0d(index) > 0)))
3061
return self->descr->f->setitem(op, self->data, self);
3062
if (PyBool_Check(index) || PyArray_IsScalar(index, Bool) ||
3063
(PyArray_Check(index) && (PyArray_DIMS(index)==0) &&
3064
PyArray_ISBOOL(index))) {
3065
if (PyObject_IsTrue(index)) {
3066
return self->descr->f->setitem(op, self->data, self);
3068
else { /* don't do anything */
3072
PyErr_SetString(PyExc_IndexError,
3073
"0-d arrays can't be indexed.");
3077
/* optimization for integer-tuple */
3079
(PyTuple_Check(index) && (PyTuple_GET_SIZE(index) == self->nd))
3080
&& (_tuple_of_integers(index, vals, self->nd) >= 0)) {
3083
for(i=0; i<self->nd; i++) {
3084
if (vals[i] < 0) vals[i] += self->dimensions[i];
3085
if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
3086
PyErr_Format(PyExc_IndexError,
3087
"index (%"INTP_FMT") out of range "\
3088
"(0<=index<%"INTP_FMT") in dimension %d",
3089
vals[i], self->dimensions[i], i);
3093
item = PyArray_GetPtr(self, vals);
3094
/* fprintf(stderr, "Here I am...\n");*/
3095
return self->descr->f->setitem(op, item, self);
3099
fancy = fancy_indexing_check(index);
3101
if (fancy != SOBJ_NOTFANCY) {
3102
oned = ((self->nd == 1) &&
3103
!(PyTuple_Check(index) && PyTuple_GET_SIZE(index) > 1));
3105
mit = (PyArrayMapIterObject *) \
3106
PyArray_MapIterNew(index, oned, fancy);
3107
if (mit == NULL) return -1;
3109
PyArrayIterObject *it;
3111
it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
3112
if (it == NULL) {Py_DECREF(mit); return -1;}
3113
rval = iter_ass_subscript(it, mit->indexobj, op);
3118
PyArray_MapIterBind(mit, self);
3119
ret = PyArray_SetMap(mit, op);
3124
return array_ass_sub_simple(self, index, op);
2952
3135
array_subscript_nice(PyArrayObject *self, PyObject *op)
2956
intp vals[MAX_DIMS];
2958
if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || \
2959
PyLong_Check(op) || (PyIndex_Check(op) &&
2960
!PySequence_Check(op))) {
2962
value = PyArray_PyIntAsIntp(op);
2963
if (PyErr_Occurred())
2966
return array_item_nice(self, (Py_ssize_t) value);
2969
/* optimization for a tuple of integers */
2970
if (self->nd > 1 && PyTuple_Check(op) &&
2971
(PyTuple_GET_SIZE(op) == self->nd)
2972
&& (_tuple_of_integers(op, vals, self->nd) >= 0)) {
2975
for (i=0; i<self->nd; i++) {
2976
if (vals[i] < 0) vals[i] += self->dimensions[i];
2977
if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
2978
PyErr_Format(PyExc_IndexError,
2979
"index (%"INTP_FMT") out of range "\
2980
"(0<=index<=%"INTP_FMT") in dimension %d",
2981
vals[i], self->dimensions[i], i);
2985
item = PyArray_GetPtr(self, vals);
2986
return PyArray_Scalar(item, self->descr, (PyObject *)self);
2990
mp = (PyArrayObject *)array_subscript(self, op);
2992
/* The following is just a copy of PyArray_Return with an
2993
additional logic in the nd == 0 case.
2996
if (mp == NULL) return NULL;
2998
if (PyErr_Occurred()) {
3139
intp vals[MAX_DIMS];
3141
if (PyInt_Check(op) || PyArray_IsScalar(op, Integer) || \
3142
PyLong_Check(op) || (PyIndex_Check(op) &&
3143
!PySequence_Check(op))) {
3145
value = PyArray_PyIntAsIntp(op);
3146
if (PyErr_Occurred())
3149
return array_item_nice(self, (Py_ssize_t) value);
3152
/* optimization for a tuple of integers */
3153
if (self->nd > 1 && PyTuple_Check(op) &&
3154
(PyTuple_GET_SIZE(op) == self->nd)
3155
&& (_tuple_of_integers(op, vals, self->nd) >= 0)) {
3158
for(i=0; i<self->nd; i++) {
3159
if (vals[i] < 0) vals[i] += self->dimensions[i];
3160
if ((vals[i] < 0) || (vals[i] >= self->dimensions[i])) {
3161
PyErr_Format(PyExc_IndexError,
3162
"index (%"INTP_FMT") out of range "\
3163
"(0<=index<%"INTP_FMT") in dimension %d",
3164
vals[i], self->dimensions[i], i);
3004
Bool noellipses = TRUE;
3005
if (op == Py_Ellipsis)
3007
else if (PySequence_Check(op)) {
3010
n = PySequence_Size(op);
3012
while (i<n && noellipses) {
3013
temp = PySequence_GetItem(op, i);
3014
if (temp == Py_Ellipsis)
3022
ret = PyArray_ToScalar(mp->data, mp);
3027
return (PyObject *)mp;
3168
item = PyArray_GetPtr(self, vals);
3169
return PyArray_Scalar(item, self->descr, (PyObject *)self);
3173
mp = (PyArrayObject *)array_subscript(self, op);
3175
/* mp could be a scalar if op is not an Int, Scalar, Long or other Index
3176
object and still convertable to an integer (so that the code goes to
3177
array_subscript_simple). So, this cast is a bit dangerous..
3180
/* The following is just a copy of PyArray_Return with an
3181
additional logic in the nd == 0 case.
3184
if (mp == NULL) return NULL;
3186
if (PyErr_Occurred()) {
3191
if (PyArray_Check(mp) && mp->nd == 0) {
3192
Bool noellipses = TRUE;
3193
if ((op == Py_Ellipsis) || PyString_Check(op) || PyUnicode_Check(op))
3195
else if (PyBool_Check(op) || PyArray_IsScalar(op, Bool) ||
3196
(PyArray_Check(op) && (PyArray_DIMS(op)==0) &&
3197
PyArray_ISBOOL(op))) {
3200
else if (PySequence_Check(op)) {
3203
n = PySequence_Size(op);
3205
while (i<n && noellipses) {
3206
temp = PySequence_GetItem(op, i);
3207
if (temp == Py_Ellipsis)
3215
ret = PyArray_ToScalar(mp->data, mp);
3220
return (PyObject *)mp;
3031
3224
static PyMappingMethods array_as_mapping = {
3032
3225
#if PY_VERSION_HEX >= 0x02050000
3033
(lenfunc)array_length, /*mp_length*/
3226
(lenfunc)array_length, /*mp_length*/
3035
(inquiry)array_length, /*mp_length*/
3228
(inquiry)array_length, /*mp_length*/
3037
(binaryfunc)array_subscript_nice, /*mp_subscript*/
3038
(objobjargproc)array_ass_sub, /*mp_ass_subscript*/
3230
(binaryfunc)array_subscript_nice, /*mp_subscript*/
3231
(objobjargproc)array_ass_sub, /*mp_ass_subscript*/
3041
3234
/****************** End of Mapping Protocol ******************************/
3326
3513
PyArray_GenericAccumulateFunction(PyArrayObject *m1, PyObject *op, int axis,
3327
3514
int rtype, PyArrayObject *out)
3329
PyObject *args, *ret=NULL, *meth;
3332
Py_INCREF(Py_NotImplemented);
3333
return Py_NotImplemented;
3335
args = Py_BuildValue("(Oi)", m1, axis);
3336
kwds = _get_keywords(rtype, out);
3337
meth = PyObject_GetAttrString(op, "accumulate");
3338
if (meth && PyCallable_Check(meth)) {
3339
ret = PyObject_Call(meth, args, kwds);
3516
PyObject *args, *ret=NULL, *meth;
3519
Py_INCREF(Py_NotImplemented);
3520
return Py_NotImplemented;
3522
args = Py_BuildValue("(Oi)", m1, axis);
3523
kwds = _get_keywords(rtype, out);
3524
meth = PyObject_GetAttrString(op, "accumulate");
3525
if (meth && PyCallable_Check(meth)) {
3526
ret = PyObject_Call(meth, args, kwds);
3348
3535
static PyObject *
3349
3536
PyArray_GenericBinaryFunction(PyArrayObject *m1, PyObject *m2, PyObject *op)
3352
Py_INCREF(Py_NotImplemented);
3353
return Py_NotImplemented;
3355
return PyObject_CallFunction(op, "OO", m1, m2);
3539
Py_INCREF(Py_NotImplemented);
3540
return Py_NotImplemented;
3542
return PyObject_CallFunction(op, "OO", m1, m2);
3358
3545
static PyObject *
3359
3546
PyArray_GenericUnaryFunction(PyArrayObject *m1, PyObject *op)
3362
Py_INCREF(Py_NotImplemented);
3363
return Py_NotImplemented;
3365
return PyObject_CallFunction(op, "(O)", m1);
3549
Py_INCREF(Py_NotImplemented);
3550
return Py_NotImplemented;
3552
return PyObject_CallFunction(op, "(O)", m1);
3368
3555
static PyObject *
3369
3556
PyArray_GenericInplaceBinaryFunction(PyArrayObject *m1,
3370
3557
PyObject *m2, PyObject *op)
3373
Py_INCREF(Py_NotImplemented);
3374
return Py_NotImplemented;
3376
return PyObject_CallFunction(op, "OOO", m1, m2, m1);
3560
Py_INCREF(Py_NotImplemented);
3561
return Py_NotImplemented;
3563
return PyObject_CallFunction(op, "OOO", m1, m2, m1);
3379
3566
static PyObject *
3380
3567
PyArray_GenericInplaceUnaryFunction(PyArrayObject *m1, PyObject *op)
3383
Py_INCREF(Py_NotImplemented);
3384
return Py_NotImplemented;
3386
return PyObject_CallFunction(op, "OO", m1, m1);
3570
Py_INCREF(Py_NotImplemented);
3571
return Py_NotImplemented;
3573
return PyObject_CallFunction(op, "OO", m1, m1);
3389
3576
static PyObject *
3390
3577
array_add(PyArrayObject *m1, PyObject *m2)
3392
return PyArray_GenericBinaryFunction(m1, m2, n_ops.add);
3579
return PyArray_GenericBinaryFunction(m1, m2, n_ops.add);
3395
3582
static PyObject *
3396
3583
array_subtract(PyArrayObject *m1, PyObject *m2)
3398
return PyArray_GenericBinaryFunction(m1, m2, n_ops.subtract);
3585
return PyArray_GenericBinaryFunction(m1, m2, n_ops.subtract);
3401
3588
static PyObject *
3402
3589
array_multiply(PyArrayObject *m1, PyObject *m2)
3404
return PyArray_GenericBinaryFunction(m1, m2, n_ops.multiply);
3591
return PyArray_GenericBinaryFunction(m1, m2, n_ops.multiply);
3407
3594
static PyObject *
3408
3595
array_divide(PyArrayObject *m1, PyObject *m2)
3410
return PyArray_GenericBinaryFunction(m1, m2, n_ops.divide);
3597
return PyArray_GenericBinaryFunction(m1, m2, n_ops.divide);
3413
3600
static PyObject *
3414
3601
array_remainder(PyArrayObject *m1, PyObject *m2)
3416
return PyArray_GenericBinaryFunction(m1, m2, n_ops.remainder);
3603
return PyArray_GenericBinaryFunction(m1, m2, n_ops.remainder);
3466
3653
/* optimize float array or complex array to a scalar power */
3467
3654
static PyObject *
3468
3655
fast_scalar_power(PyArrayObject *a1, PyObject *o2, int inplace) {
3470
if (PyArray_Check(a1) && array_power_is_scalar(o2, &exp)) {
3471
PyObject *fastop = NULL;
3472
if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) {
3474
/* we have to do this one special, as the
3475
"copy" method of array objects isn't set
3476
up early enough to be added
3477
by PyArray_SetNumericOps.
3481
return (PyObject *)a1;
3483
return PyArray_Copy(a1);
3485
} else if (exp == -1.0) {
3486
fastop = n_ops.reciprocal;
3487
} else if (exp == 0.0) {
3488
fastop = n_ops.ones_like;
3489
} else if (exp == 0.5) {
3490
fastop = n_ops.sqrt;
3491
} else if (exp == 2.0) {
3492
fastop = n_ops.square;
3497
return PyArray_GenericInplaceUnaryFunction(a1,
3500
return PyArray_GenericUnaryFunction(a1,
3504
else if (exp==2.0) {
3505
fastop = n_ops.multiply;
3507
return PyArray_GenericInplaceBinaryFunction \
3508
(a1, (PyObject *)a1, fastop);
3511
return PyArray_GenericBinaryFunction \
3512
(a1, (PyObject *)a1, fastop);
3657
if (PyArray_Check(a1) && array_power_is_scalar(o2, &exp)) {
3658
PyObject *fastop = NULL;
3659
if (PyArray_ISFLOAT(a1) || PyArray_ISCOMPLEX(a1)) {
3661
/* we have to do this one special, as the
3662
"copy" method of array objects isn't set
3663
up early enough to be added
3664
by PyArray_SetNumericOps.
3668
return (PyObject *)a1;
3670
return PyArray_Copy(a1);
3672
} else if (exp == -1.0) {
3673
fastop = n_ops.reciprocal;
3674
} else if (exp == 0.0) {
3675
fastop = n_ops.ones_like;
3676
} else if (exp == 0.5) {
3677
fastop = n_ops.sqrt;
3678
} else if (exp == 2.0) {
3679
fastop = n_ops.square;
3684
return PyArray_GenericInplaceUnaryFunction(a1,
3687
return PyArray_GenericUnaryFunction(a1,
3691
else if (exp==2.0) {
3692
fastop = n_ops.multiply;
3694
return PyArray_GenericInplaceBinaryFunction \
3695
(a1, (PyObject *)a1, fastop);
3698
return PyArray_GenericBinaryFunction \
3699
(a1, (PyObject *)a1, fastop);
3519
3706
static PyObject *
3520
3707
array_power(PyArrayObject *a1, PyObject *o2, PyObject *modulo)
3522
/* modulo is ignored! */
3524
value = fast_scalar_power(a1, o2, 0);
3526
value = PyArray_GenericBinaryFunction(a1, o2, n_ops.power);
3709
/* modulo is ignored! */
3711
value = fast_scalar_power(a1, o2, 0);
3713
value = PyArray_GenericBinaryFunction(a1, o2, n_ops.power);
3532
3719
static PyObject *
3533
3720
array_negative(PyArrayObject *m1)
3535
return PyArray_GenericUnaryFunction(m1, n_ops.negative);
3722
return PyArray_GenericUnaryFunction(m1, n_ops.negative);
3538
3725
static PyObject *
3539
3726
array_absolute(PyArrayObject *m1)
3541
return PyArray_GenericUnaryFunction(m1, n_ops.absolute);
3728
return PyArray_GenericUnaryFunction(m1, n_ops.absolute);
3544
3731
static PyObject *
3545
3732
array_invert(PyArrayObject *m1)
3547
return PyArray_GenericUnaryFunction(m1, n_ops.invert);
3734
return PyArray_GenericUnaryFunction(m1, n_ops.invert);
3550
3737
static PyObject *
3551
3738
array_left_shift(PyArrayObject *m1, PyObject *m2)
3553
return PyArray_GenericBinaryFunction(m1, m2, n_ops.left_shift);
3740
return PyArray_GenericBinaryFunction(m1, m2, n_ops.left_shift);
3556
3743
static PyObject *
3557
3744
array_right_shift(PyArrayObject *m1, PyObject *m2)
3559
return PyArray_GenericBinaryFunction(m1, m2, n_ops.right_shift);
3746
return PyArray_GenericBinaryFunction(m1, m2, n_ops.right_shift);
3562
3749
static PyObject *
3563
3750
array_bitwise_and(PyArrayObject *m1, PyObject *m2)
3565
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_and);
3752
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_and);
3568
3755
static PyObject *
3569
3756
array_bitwise_or(PyArrayObject *m1, PyObject *m2)
3571
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_or);
3758
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_or);
3574
3761
static PyObject *
3575
3762
array_bitwise_xor(PyArrayObject *m1, PyObject *m2)
3577
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_xor);
3764
return PyArray_GenericBinaryFunction(m1, m2, n_ops.bitwise_xor);
3580
3767
static PyObject *
3581
3768
array_inplace_add(PyArrayObject *m1, PyObject *m2)
3583
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.add);
3770
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.add);
3586
3773
static PyObject *
3587
3774
array_inplace_subtract(PyArrayObject *m1, PyObject *m2)
3589
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.subtract);
3776
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.subtract);
3592
3779
static PyObject *
3593
3780
array_inplace_multiply(PyArrayObject *m1, PyObject *m2)
3595
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.multiply);
3782
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.multiply);
3598
3785
static PyObject *
3599
3786
array_inplace_divide(PyArrayObject *m1, PyObject *m2)
3601
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.divide);
3788
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.divide);
3604
3791
static PyObject *
3605
3792
array_inplace_remainder(PyArrayObject *m1, PyObject *m2)
3607
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.remainder);
3794
return PyArray_GenericInplaceBinaryFunction(m1, m2, n_ops.remainder);
3610
3797
static PyObject *
3722
3909
static PyObject *
3723
3910
array_divmod(PyArrayObject *op1, PyObject *op2)
3725
PyObject *divp, *modp, *result;
3912
PyObject *divp, *modp, *result;
3727
divp = array_floor_divide(op1, op2);
3728
if (divp == NULL) return NULL;
3729
modp = array_remainder(op1, op2);
3734
result = Py_BuildValue("OO", divp, modp);
3914
divp = array_floor_divide(op1, op2);
3915
if (divp == NULL) return NULL;
3916
modp = array_remainder(op1, op2);
3735
3918
Py_DECREF(divp);
3921
result = Py_BuildValue("OO", divp, modp);
3741
3928
static PyObject *
3742
3929
array_int(PyArrayObject *v)
3745
if (PyArray_SIZE(v) != 1) {
3746
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can be"\
3747
" converted to Python scalars");
3750
pv = v->descr->f->getitem(v->data, v);
3751
if (pv == NULL) return NULL;
3752
if (pv->ob_type->tp_as_number == 0) {
3753
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3754
"scalar object is not a number");
3758
if (pv->ob_type->tp_as_number->nb_int == 0) {
3759
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3760
"scalar number to int");
3932
if (PyArray_SIZE(v) != 1) {
3933
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can be"\
3934
" converted to Python scalars");
3937
pv = v->descr->f->getitem(v->data, v);
3938
if (pv == NULL) return NULL;
3939
if (pv->ob_type->tp_as_number == 0) {
3940
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3941
"scalar object is not a number");
3945
if (pv->ob_type->tp_as_number->nb_int == 0) {
3946
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3947
"scalar number to int");
3765
pv2 = pv->ob_type->tp_as_number->nb_int(pv);
3952
pv2 = pv->ob_type->tp_as_number->nb_int(pv);
3770
3957
static PyObject *
3771
3958
array_float(PyArrayObject *v)
3774
if (PyArray_SIZE(v) != 1) {
3775
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3776
"be converted to Python scalars");
3779
pv = v->descr->f->getitem(v->data, v);
3780
if (pv == NULL) return NULL;
3781
if (pv->ob_type->tp_as_number == 0) {
3782
PyErr_SetString(PyExc_TypeError, "cannot convert to a "\
3783
"float; scalar object is not a number");
3787
if (pv->ob_type->tp_as_number->nb_float == 0) {
3788
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3789
"scalar number to float");
3793
pv2 = pv->ob_type->tp_as_number->nb_float(pv);
3961
if (PyArray_SIZE(v) != 1) {
3962
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3963
"be converted to Python scalars");
3966
pv = v->descr->f->getitem(v->data, v);
3967
if (pv == NULL) return NULL;
3968
if (pv->ob_type->tp_as_number == 0) {
3969
PyErr_SetString(PyExc_TypeError, "cannot convert to a "\
3970
"float; scalar object is not a number");
3974
if (pv->ob_type->tp_as_number->nb_float == 0) {
3975
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3976
"scalar number to float");
3980
pv2 = pv->ob_type->tp_as_number->nb_float(pv);
3798
3985
static PyObject *
3799
3986
array_long(PyArrayObject *v)
3802
if (PyArray_SIZE(v) != 1) {
3803
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3804
"be converted to Python scalars");
3807
pv = v->descr->f->getitem(v->data, v);
3808
if (pv->ob_type->tp_as_number == 0) {
3809
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3810
"scalar object is not a number");
3813
if (pv->ob_type->tp_as_number->nb_long == 0) {
3814
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3815
"scalar number to long");
3818
pv2 = pv->ob_type->tp_as_number->nb_long(pv);
3989
if (PyArray_SIZE(v) != 1) {
3990
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3991
"be converted to Python scalars");
3994
pv = v->descr->f->getitem(v->data, v);
3995
if (pv->ob_type->tp_as_number == 0) {
3996
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3997
"scalar object is not a number");
4000
if (pv->ob_type->tp_as_number->nb_long == 0) {
4001
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
4002
"scalar number to long");
4005
pv2 = pv->ob_type->tp_as_number->nb_long(pv);
3823
4010
static PyObject *
3824
4011
array_oct(PyArrayObject *v)
3827
if (PyArray_SIZE(v) != 1) {
3828
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3829
"be converted to Python scalars");
3832
pv = v->descr->f->getitem(v->data, v);
3833
if (pv->ob_type->tp_as_number == 0) {
3834
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3835
"scalar object is not a number");
3838
if (pv->ob_type->tp_as_number->nb_oct == 0) {
3839
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3840
"scalar number to oct");
3843
pv2 = pv->ob_type->tp_as_number->nb_oct(pv);
4014
if (PyArray_SIZE(v) != 1) {
4015
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
4016
"be converted to Python scalars");
4019
pv = v->descr->f->getitem(v->data, v);
4020
if (pv->ob_type->tp_as_number == 0) {
4021
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
4022
"scalar object is not a number");
4025
if (pv->ob_type->tp_as_number->nb_oct == 0) {
4026
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
4027
"scalar number to oct");
4030
pv2 = pv->ob_type->tp_as_number->nb_oct(pv);
3848
4035
static PyObject *
3849
4036
array_hex(PyArrayObject *v)
3852
if (PyArray_SIZE(v) != 1) {
3853
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
3854
"be converted to Python scalars");
3857
pv = v->descr->f->getitem(v->data, v);
3858
if (pv->ob_type->tp_as_number == 0) {
3859
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
3860
"scalar object is not a number");
3863
if (pv->ob_type->tp_as_number->nb_hex == 0) {
3864
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
3865
"scalar number to hex");
3868
pv2 = pv->ob_type->tp_as_number->nb_hex(pv);
4039
if (PyArray_SIZE(v) != 1) {
4040
PyErr_SetString(PyExc_TypeError, "only length-1 arrays can "\
4041
"be converted to Python scalars");
4044
pv = v->descr->f->getitem(v->data, v);
4045
if (pv->ob_type->tp_as_number == 0) {
4046
PyErr_SetString(PyExc_TypeError, "cannot convert to an int; "\
4047
"scalar object is not a number");
4050
if (pv->ob_type->tp_as_number->nb_hex == 0) {
4051
PyErr_SetString(PyExc_TypeError, "don't know how to convert "\
4052
"scalar number to hex");
4055
pv2 = pv->ob_type->tp_as_number->nb_hex(pv);
3873
4060
static PyObject *
3874
4061
_array_copy_nice(PyArrayObject *self)
3876
return PyArray_Return((PyArrayObject *) \
3877
PyArray_Copy(self));
4063
return PyArray_Return((PyArrayObject *) \
4064
PyArray_Copy(self));
3880
4067
#if PY_VERSION_HEX >= 0x02050000
3881
4068
static PyObject *
3882
4069
array_index(PyArrayObject *v)
3884
if (!PyArray_ISINTEGER(v) || PyArray_SIZE(v) != 1) {
3885
PyErr_SetString(PyExc_TypeError, "only integer arrays with " \
3886
"one element can be converted to an index");
3889
return v->descr->f->getitem(v->data, v);
4071
if (!PyArray_ISINTEGER(v) || PyArray_SIZE(v) != 1) {
4072
PyErr_SetString(PyExc_TypeError, "only integer arrays with " \
4073
"one element can be converted to an index");
4076
return v->descr->f->getitem(v->data, v);
3894
4081
static PyNumberMethods array_as_number = {
3895
(binaryfunc)array_add, /*nb_add*/
3896
(binaryfunc)array_subtract, /*nb_subtract*/
3897
(binaryfunc)array_multiply, /*nb_multiply*/
3898
(binaryfunc)array_divide, /*nb_divide*/
3899
(binaryfunc)array_remainder, /*nb_remainder*/
3900
(binaryfunc)array_divmod, /*nb_divmod*/
3901
(ternaryfunc)array_power, /*nb_power*/
3902
(unaryfunc)array_negative, /*nb_neg*/
3903
(unaryfunc)_array_copy_nice, /*nb_pos*/
3904
(unaryfunc)array_absolute, /*(unaryfunc)array_abs,*/
3905
(inquiry)_array_nonzero, /*nb_nonzero*/
3906
(unaryfunc)array_invert, /*nb_invert*/
3907
(binaryfunc)array_left_shift, /*nb_lshift*/
3908
(binaryfunc)array_right_shift, /*nb_rshift*/
3909
(binaryfunc)array_bitwise_and, /*nb_and*/
3910
(binaryfunc)array_bitwise_xor, /*nb_xor*/
3911
(binaryfunc)array_bitwise_or, /*nb_or*/
3913
(unaryfunc)array_int, /*nb_int*/
3914
(unaryfunc)array_long, /*nb_long*/
3915
(unaryfunc)array_float, /*nb_float*/
3916
(unaryfunc)array_oct, /*nb_oct*/
3917
(unaryfunc)array_hex, /*nb_hex*/
3919
/*This code adds augmented assignment functionality*/
3920
/*that was made available in Python 2.0*/
3921
(binaryfunc)array_inplace_add, /*inplace_add*/
3922
(binaryfunc)array_inplace_subtract, /*inplace_subtract*/
3923
(binaryfunc)array_inplace_multiply, /*inplace_multiply*/
3924
(binaryfunc)array_inplace_divide, /*inplace_divide*/
3925
(binaryfunc)array_inplace_remainder, /*inplace_remainder*/
3926
(ternaryfunc)array_inplace_power, /*inplace_power*/
3927
(binaryfunc)array_inplace_left_shift, /*inplace_lshift*/
3928
(binaryfunc)array_inplace_right_shift, /*inplace_rshift*/
3929
(binaryfunc)array_inplace_bitwise_and, /*inplace_and*/
3930
(binaryfunc)array_inplace_bitwise_xor, /*inplace_xor*/
3931
(binaryfunc)array_inplace_bitwise_or, /*inplace_or*/
3933
(binaryfunc)array_floor_divide, /*nb_floor_divide*/
3934
(binaryfunc)array_true_divide, /*nb_true_divide*/
3935
(binaryfunc)array_inplace_floor_divide, /*nb_inplace_floor_divide*/
3936
(binaryfunc)array_inplace_true_divide, /*nb_inplace_true_divide*/
4082
(binaryfunc)array_add, /*nb_add*/
4083
(binaryfunc)array_subtract, /*nb_subtract*/
4084
(binaryfunc)array_multiply, /*nb_multiply*/
4085
(binaryfunc)array_divide, /*nb_divide*/
4086
(binaryfunc)array_remainder, /*nb_remainder*/
4087
(binaryfunc)array_divmod, /*nb_divmod*/
4088
(ternaryfunc)array_power, /*nb_power*/
4089
(unaryfunc)array_negative, /*nb_neg*/
4090
(unaryfunc)_array_copy_nice, /*nb_pos*/
4091
(unaryfunc)array_absolute, /*(unaryfunc)array_abs,*/
4092
(inquiry)_array_nonzero, /*nb_nonzero*/
4093
(unaryfunc)array_invert, /*nb_invert*/
4094
(binaryfunc)array_left_shift, /*nb_lshift*/
4095
(binaryfunc)array_right_shift, /*nb_rshift*/
4096
(binaryfunc)array_bitwise_and, /*nb_and*/
4097
(binaryfunc)array_bitwise_xor, /*nb_xor*/
4098
(binaryfunc)array_bitwise_or, /*nb_or*/
4100
(unaryfunc)array_int, /*nb_int*/
4101
(unaryfunc)array_long, /*nb_long*/
4102
(unaryfunc)array_float, /*nb_float*/
4103
(unaryfunc)array_oct, /*nb_oct*/
4104
(unaryfunc)array_hex, /*nb_hex*/
4106
/*This code adds augmented assignment functionality*/
4107
/*that was made available in Python 2.0*/
4108
(binaryfunc)array_inplace_add, /*inplace_add*/
4109
(binaryfunc)array_inplace_subtract, /*inplace_subtract*/
4110
(binaryfunc)array_inplace_multiply, /*inplace_multiply*/
4111
(binaryfunc)array_inplace_divide, /*inplace_divide*/
4112
(binaryfunc)array_inplace_remainder, /*inplace_remainder*/
4113
(ternaryfunc)array_inplace_power, /*inplace_power*/
4114
(binaryfunc)array_inplace_left_shift, /*inplace_lshift*/
4115
(binaryfunc)array_inplace_right_shift, /*inplace_rshift*/
4116
(binaryfunc)array_inplace_bitwise_and, /*inplace_and*/
4117
(binaryfunc)array_inplace_bitwise_xor, /*inplace_xor*/
4118
(binaryfunc)array_inplace_bitwise_or, /*inplace_or*/
4120
(binaryfunc)array_floor_divide, /*nb_floor_divide*/
4121
(binaryfunc)array_true_divide, /*nb_true_divide*/
4122
(binaryfunc)array_inplace_floor_divide, /*nb_inplace_floor_divide*/
4123
(binaryfunc)array_inplace_true_divide, /*nb_inplace_true_divide*/
3938
4125
#if PY_VERSION_HEX >= 0x02050000
3939
(unaryfunc)array_index, /* nb_index */
4126
(unaryfunc)array_index, /* nb_index */
3957
4144
array_slice(PyArrayObject *self, Py_ssize_t ilow,
3958
4145
Py_ssize_t ihigh)
3964
if (self->nd == 0) {
3965
PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array");
3969
l=self->dimensions[0];
3970
if (ilow < 0) ilow = 0;
3971
else if (ilow > l) ilow = l;
3972
if (ihigh < ilow) ihigh = ilow;
3973
else if (ihigh > l) ihigh = l;
3975
if (ihigh != ilow) {
3976
data = index2ptr(self, ilow);
3977
if (data == NULL) return NULL;
3982
self->dimensions[0] = ihigh-ilow;
3983
Py_INCREF(self->descr);
3984
r = (PyArrayObject *) \
3985
PyArray_NewFromDescr(self->ob_type, self->descr,
3986
self->nd, self->dimensions,
3987
self->strides, data,
3988
self->flags, (PyObject *)self);
3989
self->dimensions[0] = l;
3990
if (r == NULL) return NULL;
3991
r->base = (PyObject *)self;
3993
PyArray_UpdateFlags(r, UPDATE_ALL);
3994
return (PyObject *)r;
4151
if (self->nd == 0) {
4152
PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array");
4156
l=self->dimensions[0];
4157
if (ilow < 0) ilow = 0;
4158
else if (ilow > l) ilow = l;
4159
if (ihigh < ilow) ihigh = ilow;
4160
else if (ihigh > l) ihigh = l;
4162
if (ihigh != ilow) {
4163
data = index2ptr(self, ilow);
4164
if (data == NULL) return NULL;
4169
self->dimensions[0] = ihigh-ilow;
4170
Py_INCREF(self->descr);
4171
r = (PyArrayObject *) \
4172
PyArray_NewFromDescr(self->ob_type, self->descr,
4173
self->nd, self->dimensions,
4174
self->strides, data,
4175
self->flags, (PyObject *)self);
4176
self->dimensions[0] = l;
4177
if (r == NULL) return NULL;
4178
r->base = (PyObject *)self;
4180
PyArray_UpdateFlags(r, UPDATE_ALL);
4181
return (PyObject *)r;
3999
4186
array_ass_slice(PyArrayObject *self, Py_ssize_t ilow,
4000
4187
Py_ssize_t ihigh, PyObject *v) {
4005
PyErr_SetString(PyExc_ValueError,
4006
"cannot delete array elements");
4009
if (!PyArray_ISWRITEABLE(self)) {
4010
PyErr_SetString(PyExc_RuntimeError,
4011
"array is not writeable");
4014
if ((tmp = (PyArrayObject *)array_slice(self, ilow, ihigh)) \
4017
ret = PyArray_CopyObject(tmp, v);
4192
PyErr_SetString(PyExc_ValueError,
4193
"cannot delete array elements");
4196
if (!PyArray_ISWRITEABLE(self)) {
4197
PyErr_SetString(PyExc_RuntimeError,
4198
"array is not writeable");
4201
if ((tmp = (PyArrayObject *)array_slice(self, ilow, ihigh)) \
4204
ret = PyArray_CopyObject(tmp, v);
4024
4211
array_contains(PyArrayObject *self, PyObject *el)
4026
/* equivalent to (self == el).any() */
4031
res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,
4033
if (res == NULL) return -1;
4034
ret = array_any_nonzero((PyArrayObject *)res);
4213
/* equivalent to (self == el).any() */
4218
res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self,
4220
if (res == NULL) return -1;
4221
ret = array_any_nonzero((PyArrayObject *)res);
4039
4226
static PySequenceMethods array_as_sequence = {
4040
4227
#if PY_VERSION_HEX >= 0x02050000
4041
(lenfunc)array_length, /*sq_length*/
4042
(binaryfunc)NULL, /* sq_concat is handled by nb_add*/
4044
(ssizeargfunc)array_item_nice,
4045
(ssizessizeargfunc)array_slice,
4046
(ssizeobjargproc)array_ass_item, /*sq_ass_item*/
4047
(ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
4048
(objobjproc) array_contains, /* sq_contains */
4049
(binaryfunc) NULL, /* sg_inplace_concat */
4228
(lenfunc)array_length, /*sq_length*/
4229
(binaryfunc)NULL, /*sq_concat is handled by nb_add*/
4231
(ssizeargfunc)array_item_nice,
4232
(ssizessizeargfunc)array_slice,
4233
(ssizeobjargproc)array_ass_item, /*sq_ass_item*/
4234
(ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
4235
(objobjproc) array_contains, /*sq_contains */
4236
(binaryfunc) NULL, /*sg_inplace_concat */
4052
(inquiry)array_length, /*sq_length*/
4053
(binaryfunc)NULL, /* sq_concat is handled by nb_add*/
4054
(intargfunc)NULL, /* sq_repeat is handled nb_multiply*/
4055
(intargfunc)array_item_nice, /*sq_item*/
4056
(intintargfunc)array_slice, /*sq_slice*/
4057
(intobjargproc)array_ass_item, /*sq_ass_item*/
4058
(intintobjargproc)array_ass_slice, /*sq_ass_slice*/
4059
(objobjproc) array_contains, /* sq_contains */
4060
(binaryfunc) NULL, /* sg_inplace_concat */
4061
(intargfunc) NULL /* sg_inplace_repeat */
4239
(inquiry)array_length, /*sq_length*/
4240
(binaryfunc)NULL, /*sq_concat is handled by nb_add*/
4241
(intargfunc)NULL, /*sq_repeat is handled nb_multiply*/
4242
(intargfunc)array_item_nice, /*sq_item*/
4243
(intintargfunc)array_slice, /*sq_slice*/
4244
(intobjargproc)array_ass_item, /*sq_ass_item*/
4245
(intintobjargproc)array_ass_slice, /*sq_ass_slice*/
4246
(objobjproc) array_contains, /*sq_contains */
4247
(binaryfunc) NULL, /*sg_inplace_concat */
4248
(intargfunc) NULL /*sg_inplace_repeat */
4119
4314
static PyObject *
4120
4315
array_repr_builtin(PyArrayObject *self, int repr)
4126
max_n = PyArray_NBYTES(self)*4*sizeof(char) + 7;
4128
if ((string = (char *)_pya_malloc(max_n)) == NULL) {
4129
PyErr_SetString(PyExc_MemoryError, "out of memory");
4135
sprintf(string, "array(");
4140
if (dump_data(&string, &n, &max_n, self->data,
4141
self->nd, self->dimensions,
4142
self->strides, self) < 0) {
4143
_pya_free(string); return NULL;
4147
if (PyArray_ISEXTENDED(self)) {
4149
snprintf(buf, sizeof(buf), "%d", self->descr->elsize);
4150
sprintf(string+n, ", '%c%s')", self->descr->type, buf);
4151
ret = PyString_FromStringAndSize(string, n+6+strlen(buf));
4154
sprintf(string+n, ", '%c')", self->descr->type);
4155
ret = PyString_FromStringAndSize(string, n+6);
4159
ret = PyString_FromStringAndSize(string, n);
4321
max_n = PyArray_NBYTES(self)*4*sizeof(char) + 7;
4323
if ((string = (char *)_pya_malloc(max_n)) == NULL) {
4324
PyErr_SetString(PyExc_MemoryError, "out of memory");
4330
sprintf(string, "array(");
4335
if (dump_data(&string, &n, &max_n, self->data,
4336
self->nd, self->dimensions,
4337
self->strides, self) < 0) {
4162
4338
_pya_free(string);
4343
if (PyArray_ISEXTENDED(self)) {
4345
snprintf(buf, sizeof(buf), "%d", self->descr->elsize);
4346
sprintf(string+n, ", '%c%s')", self->descr->type, buf);
4347
ret = PyString_FromStringAndSize(string, n+6+strlen(buf));
4350
sprintf(string+n, ", '%c')", self->descr->type);
4351
ret = PyString_FromStringAndSize(string, n+6);
4355
ret = PyString_FromStringAndSize(string, n);
4166
4362
static PyObject *PyArray_StrFunction=NULL;
4167
4363
static PyObject *PyArray_ReprFunction=NULL;
4170
Set the array print function to be a Python function.
4366
Set the array print function to be a Python function.
4173
4369
PyArray_SetStringFunction(PyObject *op, int repr)
4176
/* Dispose of previous callback */
4177
Py_XDECREF(PyArray_ReprFunction);
4178
/* Add a reference to new callback */
4180
/* Remember new callback */
4181
PyArray_ReprFunction = op;
4183
/* Dispose of previous callback */
4184
Py_XDECREF(PyArray_StrFunction);
4185
/* Add a reference to new callback */
4187
/* Remember new callback */
4188
PyArray_StrFunction = op;
4372
/* Dispose of previous callback */
4373
Py_XDECREF(PyArray_ReprFunction);
4374
/* Add a reference to new callback */
4376
/* Remember new callback */
4377
PyArray_ReprFunction = op;
4379
/* Dispose of previous callback */
4380
Py_XDECREF(PyArray_StrFunction);
4381
/* Add a reference to new callback */
4383
/* Remember new callback */
4384
PyArray_StrFunction = op;
4192
4388
static PyObject *
4193
4389
array_repr(PyArrayObject *self)
4195
PyObject *s, *arglist;
4391
PyObject *s, *arglist;
4197
if (PyArray_ReprFunction == NULL) {
4198
s = array_repr_builtin(self, 1);
4200
arglist = Py_BuildValue("(O)", self);
4201
s = PyEval_CallObject(PyArray_ReprFunction, arglist);
4393
if (PyArray_ReprFunction == NULL) {
4394
s = array_repr_builtin(self, 1);
4396
arglist = Py_BuildValue("(O)", self);
4397
s = PyEval_CallObject(PyArray_ReprFunction, arglist);
4207
4403
static PyObject *
4208
4404
array_str(PyArrayObject *self)
4210
PyObject *s, *arglist;
4406
PyObject *s, *arglist;
4212
if (PyArray_StrFunction == NULL) {
4213
s = array_repr_builtin(self, 0);
4215
arglist = Py_BuildValue("(O)", self);
4216
s = PyEval_CallObject(PyArray_StrFunction, arglist);
4408
if (PyArray_StrFunction == NULL) {
4409
s = array_repr_builtin(self, 0);
4411
arglist = Py_BuildValue("(O)", self);
4412
s = PyEval_CallObject(PyArray_StrFunction, arglist);
4336
4558
_char_copy_n_strip(char *original, char *temp, int nc)
4338
if (nc > SMALL_STRING) {
4560
if (nc > SMALL_STRING) {
4345
memcpy(temp, original, nc);
4567
memcpy(temp, original, nc);
4351
4573
_char_release(char *ptr, int nc)
4353
if (nc > SMALL_STRING) {
4575
if (nc > SMALL_STRING) {
4359
4581
_uni_copy_n_strip(char *original, char *temp, int nc)
4361
if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
4362
temp = malloc(nc*sizeof(PyArray_UCS4));
4583
if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
4584
temp = malloc(nc*sizeof(PyArray_UCS4));
4368
memcpy(temp, original, nc*sizeof(PyArray_UCS4));
4369
_unistripw((PyArray_UCS4 *)temp, nc);
4590
memcpy(temp, original, nc*sizeof(PyArray_UCS4));
4591
_unistripw((PyArray_UCS4 *)temp, nc);
4374
4596
_uni_release(char *ptr, int nc)
4376
if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
4598
if (nc*sizeof(PyArray_UCS4) > SMALL_STRING) {
4382
4604
/* End borrowed from numarray */
4384
#define _rstrip_loop(CMP) { \
4385
void *aptr, *bptr; \
4386
char atemp[SMALL_STRING], btemp[SMALL_STRING]; \
4388
aptr = stripfunc(iself->dataptr, atemp, N1); \
4389
if (!aptr) return -1; \
4390
bptr = stripfunc(iother->dataptr, btemp, N2); \
4392
relfunc(aptr, N1); \
4395
val = cmpfunc(aptr, bptr, N1, N2); \
4396
*dptr = (val CMP 0); \
4397
PyArray_ITER_NEXT(iself); \
4398
PyArray_ITER_NEXT(iother); \
4400
relfunc(aptr, N1); \
4401
relfunc(bptr, N2); \
4405
#define _reg_loop(CMP) { \
4407
val = cmpfunc((void *)iself->dataptr, \
4408
(void *)iother->dataptr, \
4410
*dptr = (val CMP 0); \
4411
PyArray_ITER_NEXT(iself); \
4412
PyArray_ITER_NEXT(iother); \
4417
#define _loop(CMP) if (rstrip) _rstrip_loop(CMP) \
4606
#define _rstrip_loop(CMP) { \
4607
void *aptr, *bptr; \
4608
char atemp[SMALL_STRING], btemp[SMALL_STRING]; \
4610
aptr = stripfunc(iself->dataptr, atemp, N1); \
4611
if (!aptr) return -1; \
4612
bptr = stripfunc(iother->dataptr, btemp, N2); \
4614
relfunc(aptr, N1); \
4617
val = cmpfunc(aptr, bptr, N1, N2); \
4618
*dptr = (val CMP 0); \
4619
PyArray_ITER_NEXT(iself); \
4620
PyArray_ITER_NEXT(iother); \
4622
relfunc(aptr, N1); \
4623
relfunc(bptr, N2); \
4627
#define _reg_loop(CMP) { \
4629
val = cmpfunc((void *)iself->dataptr, \
4630
(void *)iother->dataptr, \
4632
*dptr = (val CMP 0); \
4633
PyArray_ITER_NEXT(iself); \
4634
PyArray_ITER_NEXT(iother); \
4639
#define _loop(CMP) if (rstrip) _rstrip_loop(CMP) \
4418
4640
else _reg_loop(CMP)
4421
4643
_compare_strings(PyObject *result, PyArrayMultiIterObject *multi,
4422
4644
int cmp_op, void *func, int rstrip)
4424
PyArrayIterObject *iself, *iother;
4429
int (*cmpfunc)(void *, void *, int, int);
4430
void (*relfunc)(char *, int);
4431
char* (*stripfunc)(char *, char *, int);
4646
PyArrayIterObject *iself, *iother;
4651
int (*cmpfunc)(void *, void *, int, int);
4652
void (*relfunc)(char *, int);
4653
char* (*stripfunc)(char *, char *, int);
4434
dptr = (Bool *)PyArray_DATA(result);
4435
iself = multi->iters[0];
4436
iother = multi->iters[1];
4438
N1 = iself->ao->descr->elsize;
4439
N2 = iother->ao->descr->elsize;
4440
if ((void *)cmpfunc == (void *)_myunincmp) {
4443
stripfunc = _uni_copy_n_strip;
4444
relfunc = _uni_release;
4447
stripfunc = _char_copy_n_strip;
4448
relfunc = _char_release;
4470
PyErr_SetString(PyExc_RuntimeError,
4471
"bad comparison operator");
4656
dptr = (Bool *)PyArray_DATA(result);
4657
iself = multi->iters[0];
4658
iother = multi->iters[1];
4660
N1 = iself->ao->descr->elsize;
4661
N2 = iother->ao->descr->elsize;
4662
if ((void *)cmpfunc == (void *)_myunincmp) {
4665
stripfunc = _uni_copy_n_strip;
4666
relfunc = _uni_release;
4669
stripfunc = _char_copy_n_strip;
4670
relfunc = _char_release;
4692
PyErr_SetString(PyExc_RuntimeError,
4693
"bad comparison operator");
4566
4798
static PyObject *
4567
4799
_void_compare(PyArrayObject *self, PyArrayObject *other, int cmp_op)
4569
if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) {
4570
PyErr_SetString(PyExc_ValueError, "Void-arrays can only" \
4571
"be compared for equality.");
4574
if (PyArray_HASFIELDS(self)) {
4575
PyObject *res=NULL, *temp, *a, *b;
4576
PyObject *key, *value, *temp2;
4579
op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or);
4580
while (PyDict_Next(self->descr->fields, &pos, &key, &value)) {
4581
a = PyArray_EnsureAnyArray(array_subscript(self, key));
4582
if (a==NULL) {Py_XDECREF(res); return NULL;}
4583
b = array_subscript(other, key);
4584
if (b==NULL) {Py_XDECREF(res); Py_DECREF(a); return NULL;}
4585
temp = array_richcompare((PyArrayObject *)a,b,cmp_op);
4588
if (temp == NULL) {Py_XDECREF(res); return NULL;}
4593
temp2 = PyObject_CallFunction(op, "OO", res, temp);
4596
if (temp2 == NULL) return NULL;
4600
if (res == NULL && !PyErr_Occurred()) {
4601
PyErr_SetString(PyExc_ValueError, "No fields found.");
4605
else { /* compare as a string */
4606
/* assumes self and other have same descr->type */
4607
return _strings_richcompare(self, other, cmp_op, 0);
4801
if (!(cmp_op == Py_EQ || cmp_op == Py_NE)) {
4802
PyErr_SetString(PyExc_ValueError,
4803
"Void-arrays can only be compared for equality.");
4806
if (PyArray_HASFIELDS(self)) {
4807
PyObject *res=NULL, *temp, *a, *b;
4808
PyObject *key, *value, *temp2;
4812
op = (cmp_op == Py_EQ ? n_ops.logical_and : n_ops.logical_or);
4813
while (PyDict_Next(self->descr->fields, &pos, &key, &value)) {
4814
a = PyArray_EnsureAnyArray(array_subscript(self, key));
4819
b = array_subscript(other, key);
4825
temp = array_richcompare((PyArrayObject *)a,b,cmp_op);
4836
temp2 = PyObject_CallFunction(op, "OO", res, temp);
4839
if (temp2 == NULL) {
4845
if (res == NULL && !PyErr_Occurred()) {
4846
PyErr_SetString(PyExc_ValueError, "No fields found.");
4851
/* compare as a string */
4852
/* assumes self and other have same descr->type */
4853
return _strings_richcompare(self, other, cmp_op, 0);
4611
4857
static PyObject *
4612
4858
array_richcompare(PyArrayObject *self, PyObject *other, int cmp_op)
4614
PyObject *array_other, *result = NULL;
4620
result = PyArray_GenericBinaryFunction(self, other,
4624
result = PyArray_GenericBinaryFunction(self, other,
4628
if (other == Py_None) {
4629
Py_INCREF(Py_False);
4632
/* Try to convert other to an array */
4633
if (!PyArray_Check(other)) {
4634
typenum = self->descr->type_num;
4635
if (typenum != PyArray_OBJECT) {
4636
typenum = PyArray_NOTYPE;
4638
array_other = PyArray_FromObject(other,
4640
/* If not successful, then return False
4641
This fixes code that used to
4642
allow equality comparisons between arrays
4643
and other objects which would give a result
4646
if ((array_other == NULL) || \
4647
(array_other == Py_None)) {
4648
Py_XDECREF(array_other);
4650
Py_INCREF(Py_False);
4656
array_other = other;
4658
result = PyArray_GenericBinaryFunction(self,
4661
if ((result == Py_NotImplemented) &&
4662
(self->descr->type_num == PyArray_VOID)) {
4664
_res = PyObject_RichCompareBool \
4665
((PyObject *)self->descr,
4667
PyArray_DESCR(array_other),
4671
Py_DECREF(array_other);
4676
result = _void_compare\
4678
(PyArrayObject *)array_other,
4680
Py_DECREF(array_other);
4684
/* If the comparison results in NULL, then the
4685
two array objects can not be compared together so
4688
Py_DECREF(array_other);
4689
if (result == NULL) {
4691
Py_INCREF(Py_False);
4696
if (other == Py_None) {
4700
/* Try to convert other to an array */
4701
if (!PyArray_Check(other)) {
4702
typenum = self->descr->type_num;
4703
if (typenum != PyArray_OBJECT) {
4704
typenum = PyArray_NOTYPE;
4706
array_other = PyArray_FromObject(other,
4708
/* If not successful, then objects cannot be
4709
compared and cannot be equal, therefore,
4712
if ((array_other == NULL) || \
4713
(array_other == Py_None)) {
4714
Py_XDECREF(array_other);
4722
array_other = other;
4724
result = PyArray_GenericBinaryFunction(self,
4727
if ((result == Py_NotImplemented) &&
4728
(self->descr->type_num == PyArray_VOID)) {
4730
_res = PyObject_RichCompareBool\
4731
((PyObject *)self->descr,
4733
PyArray_DESCR(array_other),
4737
Py_DECREF(array_other);
4742
result = _void_compare\
4744
(PyArrayObject *)array_other,
4746
Py_DECREF(array_other);
4751
Py_DECREF(array_other);
4752
if (result == NULL) {
4759
result = PyArray_GenericBinaryFunction(self, other,
4763
result = PyArray_GenericBinaryFunction(self, other,
4764
n_ops.greater_equal);
4767
result = Py_NotImplemented;
4770
if (result == Py_NotImplemented) {
4771
/* Try to handle string comparisons */
4772
if (self->descr->type_num == PyArray_OBJECT) return result;
4773
array_other = PyArray_FromObject(other,PyArray_NOTYPE, 0, 0);
4774
if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) {
4776
result = _strings_richcompare(self, (PyArrayObject *)
4777
array_other, cmp_op, 0);
4779
Py_DECREF(array_other);
4860
PyObject *array_other, *result = NULL;
4866
result = PyArray_GenericBinaryFunction(self, other,
4870
result = PyArray_GenericBinaryFunction(self, other,
4874
if (other == Py_None) {
4875
Py_INCREF(Py_False);
4878
/* Try to convert other to an array */
4879
if (!PyArray_Check(other)) {
4880
typenum = self->descr->type_num;
4881
if (typenum != PyArray_OBJECT) {
4882
typenum = PyArray_NOTYPE;
4884
array_other = PyArray_FromObject(other,
4886
/* If not successful, then return False
4887
This fixes code that used to
4888
allow equality comparisons between arrays
4889
and other objects which would give a result
4892
if ((array_other == NULL) || \
4893
(array_other == Py_None)) {
4894
Py_XDECREF(array_other);
4896
Py_INCREF(Py_False);
4902
array_other = other;
4904
result = PyArray_GenericBinaryFunction(self,
4907
if ((result == Py_NotImplemented) &&
4908
(self->descr->type_num == PyArray_VOID)) {
4910
_res = PyObject_RichCompareBool \
4911
((PyObject *)self->descr,
4913
PyArray_DESCR(array_other),
4917
Py_DECREF(array_other);
4922
result = _void_compare\
4924
(PyArrayObject *)array_other,
4926
Py_DECREF(array_other);
4930
/* If the comparison results in NULL, then the
4931
two array objects can not be compared together so
4934
Py_DECREF(array_other);
4935
if (result == NULL) {
4937
Py_INCREF(Py_False);
4942
if (other == Py_None) {
4946
/* Try to convert other to an array */
4947
if (!PyArray_Check(other)) {
4948
typenum = self->descr->type_num;
4949
if (typenum != PyArray_OBJECT) {
4950
typenum = PyArray_NOTYPE;
4952
array_other = PyArray_FromObject(other,
4954
/* If not successful, then objects cannot be
4955
compared and cannot be equal, therefore,
4958
if ((array_other == NULL) || \
4959
(array_other == Py_None)) {
4960
Py_XDECREF(array_other);
4968
array_other = other;
4970
result = PyArray_GenericBinaryFunction(self,
4973
if ((result == Py_NotImplemented) &&
4974
(self->descr->type_num == PyArray_VOID)) {
4976
_res = PyObject_RichCompareBool\
4977
((PyObject *)self->descr,
4979
PyArray_DESCR(array_other),
4983
Py_DECREF(array_other);
4988
result = _void_compare\
4990
(PyArrayObject *)array_other,
4992
Py_DECREF(array_other);
4997
Py_DECREF(array_other);
4998
if (result == NULL) {
5005
result = PyArray_GenericBinaryFunction(self, other,
5009
result = PyArray_GenericBinaryFunction(self, other,
5010
n_ops.greater_equal);
5013
result = Py_NotImplemented;
5016
if (result == Py_NotImplemented) {
5017
/* Try to handle string comparisons */
5018
if (self->descr->type_num == PyArray_OBJECT) return result;
5019
array_other = PyArray_FromObject(other,PyArray_NOTYPE, 0, 0);
5020
if (PyArray_ISSTRING(self) && PyArray_ISSTRING(array_other)) {
5022
result = _strings_richcompare(self, (PyArrayObject *)
5023
array_other, cmp_op, 0);
5025
Py_DECREF(array_other);
4784
5034
static PyObject *
4785
_check_axis(PyArrayObject *arr, int *axis, int flags)
5035
PyArray_CheckAxis(PyArrayObject *arr, int *axis, int flags)
4787
PyObject *temp1, *temp2;
5037
PyObject *temp1, *temp2;
4790
if ((*axis >= MAX_DIMS) || (n==0)) {
4792
temp1 = PyArray_Ravel(arr,0);
4793
if (temp1 == NULL) {*axis=0; return NULL;}
4794
*axis = PyArray_NDIM(temp1)-1;
4797
temp1 = (PyObject *)arr;
4801
if (!flags) return temp1;
4804
temp1 = (PyObject *)arr;
4808
temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL,
4811
if (temp2 == NULL) return NULL;
4814
temp2 = (PyObject *)temp1;
4816
n = PyArray_NDIM(temp2);
4817
if (*axis < 0) *axis += n;
4818
if ((*axis < 0) || (*axis >= n)) {
4819
PyErr_Format(PyExc_ValueError,
4820
"axis(=%d) out of bounds", *axis);
5040
if ((*axis >= MAX_DIMS) || (n==0)) {
5042
temp1 = PyArray_Ravel(arr,0);
5043
if (temp1 == NULL) {*axis=0; return NULL;}
5044
*axis = PyArray_NDIM(temp1)-1;
5047
temp1 = (PyObject *)arr;
5051
if (!flags) return temp1;
5054
temp1 = (PyObject *)arr;
5058
temp2 = PyArray_CheckFromAny((PyObject *)temp1, NULL,
5061
if (temp2 == NULL) return NULL;
5064
temp2 = (PyObject *)temp1;
5066
n = PyArray_NDIM(temp2);
5067
if (*axis < 0) *axis += n;
5068
if ((*axis < 0) || (*axis >= n)) {
5069
PyErr_Format(PyExc_ValueError,
5070
"axis(=%d) out of bounds", *axis);
5077
#define _check_axis PyArray_CheckAxis
4827
5079
#include "arraymethods.c"
4829
5081
/* Lifted from numarray */
4830
5082
/*MULTIARRAY_API
4831
PyArray_IntTupleFromIntp
5083
PyArray_IntTupleFromIntp
4833
5085
static PyObject *
4834
5086
PyArray_IntTupleFromIntp(int len, intp *vals)
4837
PyObject *intTuple = PyTuple_New(len);
4838
if (!intTuple) goto fail;
4839
for(i=0; i<len; i++) {
5089
PyObject *intTuple = PyTuple_New(len);
5090
if (!intTuple) goto fail;
5091
for(i=0; i<len; i++) {
4840
5092
#if SIZEOF_INTP <= SIZEOF_LONG
4841
PyObject *o = PyInt_FromLong((long) vals[i]);
5093
PyObject *o = PyInt_FromLong((long) vals[i]);
4843
PyObject *o = PyLong_FromLongLong((longlong) vals[i]);
5095
PyObject *o = PyLong_FromLongLong((longlong) vals[i]);
4846
Py_DECREF(intTuple);
4850
PyTuple_SET_ITEM(intTuple, i, o);
5098
Py_DECREF(intTuple);
5102
PyTuple_SET_ITEM(intTuple, i, o);
4856
5108
/* Returns the number of dimensions or -1 if an error occurred */
4857
5109
/* vals must be large enough to hold maxvals */
4858
5110
/*MULTIARRAY_API
4859
PyArray_IntpFromSequence
5111
PyArray_IntpFromSequence
4862
5114
PyArray_IntpFromSequence(PyObject *seq, intp *vals, int maxvals)
4867
/* Check to see if sequence is a single integer first.
4868
or, can be made into one */
4869
if ((nd=PySequence_Length(seq)) == -1) {
4870
if (PyErr_Occurred()) PyErr_Clear();
4871
#if SIZEOF_LONG >= SIZEOF_INTP
4872
if (!(op = PyNumber_Int(seq))) return -1;
4874
if (!(op = PyNumber_Long(seq))) return -1;
4877
#if SIZEOF_LONG >= SIZEOF_INTP
4878
vals[0] = (intp ) PyInt_AsLong(op);
4880
vals[0] = (intp ) PyLong_AsLongLong(op);
4884
for(i=0; i < MIN(nd,maxvals); i++) {
4885
op = PySequence_GetItem(seq, i);
4886
if (op == NULL) return -1;
4887
#if SIZEOF_LONG >= SIZEOF_INTP
4888
vals[i]=(intp )PyInt_AsLong(op);
4890
vals[i]=(intp )PyLong_AsLongLong(op);
4893
if(PyErr_Occurred()) return -1;
5119
/* Check to see if sequence is a single integer first.
5120
or, can be made into one */
5121
if ((nd=PySequence_Length(seq)) == -1) {
5122
if (PyErr_Occurred()) PyErr_Clear();
5123
#if SIZEOF_LONG >= SIZEOF_INTP
5124
if (!(op = PyNumber_Int(seq))) return -1;
5126
if (!(op = PyNumber_Long(seq))) return -1;
5129
#if SIZEOF_LONG >= SIZEOF_INTP
5130
vals[0] = (intp ) PyInt_AsLong(op);
5132
vals[0] = (intp ) PyLong_AsLongLong(op);
5136
for(i=0; i < MIN(nd,maxvals); i++) {
5137
op = PySequence_GetItem(seq, i);
5138
if (op == NULL) return -1;
5139
#if SIZEOF_LONG >= SIZEOF_INTP
5140
vals[i]=(intp )PyInt_AsLong(op);
5142
vals[i]=(intp )PyLong_AsLongLong(op);
5145
if(PyErr_Occurred()) return -1;
5177
5429
_update_descr_and_dimensions(PyArray_Descr **des, intp *newdims,
5178
5430
intp *newstrides, int oldnd, int isfortran)
5188
*des = old->subarray->base;
5191
mydim = newdims + oldnd;
5192
tuple = PyTuple_Check(old->subarray->shape);
5194
numnew = PyTuple_GET_SIZE(old->subarray->shape);
5201
newnd = oldnd + numnew;
5202
if (newnd > MAX_DIMS) goto finish;
5440
*des = old->subarray->base;
5443
mydim = newdims + oldnd;
5444
tuple = PyTuple_Check(old->subarray->shape);
5446
numnew = PyTuple_GET_SIZE(old->subarray->shape);
5453
newnd = oldnd + numnew;
5454
if (newnd > MAX_DIMS) goto finish;
5456
memmove(newdims+numnew, newdims, oldnd*sizeof(intp));
5461
for(i=0; i<numnew; i++) {
5462
mydim[i] = (intp) PyInt_AsLong \
5463
(PyTuple_GET_ITEM(old->subarray->shape, i));
5467
mydim[0] = (intp) PyInt_AsLong(old->subarray->shape);
5473
mystrides = newstrides + oldnd;
5203
5474
if (isfortran) {
5204
memmove(newdims+numnew, newdims, oldnd*sizeof(intp));
5209
for (i=0; i<numnew; i++) {
5210
mydim[i] = (intp) PyInt_AsLong \
5211
(PyTuple_GET_ITEM(old->subarray->shape, i));
5215
mydim[0] = (intp) PyInt_AsLong(old->subarray->shape);
5221
mystrides = newstrides + oldnd;
5223
memmove(newstrides+numnew, newstrides,
5224
oldnd*sizeof(intp));
5225
mystrides = newstrides;
5227
/* Make new strides -- alwasy C-contiguous */
5228
tempsize = (*des)->elsize;
5229
for (i=numnew-1; i>=0; i--) {
5230
mystrides[i] = tempsize;
5231
tempsize *= mydim[i] ? mydim[i] : 1;
5475
memmove(newstrides+numnew, newstrides,
5476
oldnd*sizeof(intp));
5477
mystrides = newstrides;
5479
/* Make new strides -- alwasy C-contiguous */
5480
tempsize = (*des)->elsize;
5481
for(i=numnew-1; i>=0; i--) {
5482
mystrides[i] = tempsize;
5483
tempsize *= mydim[i] ? mydim[i] : 1;
5242
5494
/* steals a reference to descr (even on failure) */
5244
Generic new array creation routine.
5496
Generic new array creation routine.
5246
5498
static PyObject *
5247
5499
PyArray_NewFromDescr(PyTypeObject *subtype, PyArray_Descr *descr, int nd,
5248
5500
intp *dims, intp *strides, void *data,
5249
5501
int flags, PyObject *obj)
5251
PyArrayObject *self;
5257
if (descr->subarray) {
5259
intp newdims[2*MAX_DIMS];
5260
intp *newstrides=NULL;
5262
isfortran = (data && (flags & FORTRAN) && !(flags & CONTIGUOUS)) || \
5264
memcpy(newdims, dims, nd*sizeof(intp));
5266
newstrides = newdims + MAX_DIMS;
5267
memcpy(newstrides, strides, nd*sizeof(intp));
5269
nd =_update_descr_and_dimensions(&descr, newdims,
5270
newstrides, nd, isfortran);
5271
ret = PyArray_NewFromDescr(subtype, descr, nd, newdims,
5278
PyErr_SetString(PyExc_ValueError,
5279
"number of dimensions must be >=0");
5283
if (nd > MAX_DIMS) {
5284
PyErr_Format(PyExc_ValueError,
5285
"maximum number of dimensions is %d", MAX_DIMS);
5290
/* Check dimensions */
5503
PyArrayObject *self;
5509
if (descr->subarray) {
5511
intp newdims[2*MAX_DIMS];
5512
intp *newstrides=NULL;
5514
isfortran = (data && (flags & FORTRAN) && !(flags & CONTIGUOUS)) || \
5516
memcpy(newdims, dims, nd*sizeof(intp));
5518
newstrides = newdims + MAX_DIMS;
5519
memcpy(newstrides, strides, nd*sizeof(intp));
5521
nd =_update_descr_and_dimensions(&descr, newdims,
5522
newstrides, nd, isfortran);
5523
ret = PyArray_NewFromDescr(subtype, descr, nd, newdims,
5530
PyErr_SetString(PyExc_ValueError,
5531
"number of dimensions must be >=0");
5535
if (nd > MAX_DIMS) {
5536
PyErr_Format(PyExc_ValueError,
5537
"maximum number of dimensions is %d", MAX_DIMS);
5542
/* Check dimensions */
5544
sd = (size_t) descr->elsize;
5546
if (!PyDataType_ISSTRING(descr)) {
5547
PyErr_SetString(PyExc_ValueError, "Empty data-type");
5551
PyArray_DESCR_REPLACE(descr);
5552
if (descr->type_num == NPY_STRING) descr->elsize = 1;
5553
else descr->elsize = sizeof(PyArray_UCS4);
5292
5554
sd = (size_t) descr->elsize;
5294
if (!PyDataType_ISSTRING(descr)) {
5295
PyErr_SetString(PyExc_ValueError, "Empty data-type");
5299
PyArray_DESCR_REPLACE(descr);
5300
if (descr->type_num == NPY_STRING) descr->elsize = 1;
5301
else descr->elsize = sizeof(PyArray_UCS4);
5302
sd = (size_t) descr->elsize;
5304
largest = MAX_INTP / sd;
5305
for (i=0;i<nd;i++) {
5306
if (dims[i] == 0) continue;
5308
PyErr_SetString(PyExc_ValueError,
5309
"negative dimensions " \
5315
if (size <=0 || size > largest) {
5316
PyErr_SetString(PyExc_ValueError,
5317
"dimensions too large.");
5323
self = (PyArrayObject *) subtype->tp_alloc(subtype, 0);
5329
self->dimensions = NULL;
5332
self->flags = DEFAULT;
5334
self->flags |= FORTRAN;
5335
if (nd > 1) self->flags &= ~CONTIGUOUS;
5339
else self->flags = (flags & ~UPDATEIFCOPY);
5341
self->descr = descr;
5342
self->base = (PyObject *)NULL;
5343
self->weakreflist = (PyObject *)NULL;
5346
self->dimensions = PyDimMem_NEW(2*nd);
5347
if (self->dimensions == NULL) {
5351
self->strides = self->dimensions + nd;
5352
memcpy(self->dimensions, dims, sizeof(intp)*nd);
5353
if (strides == NULL) { /* fill it in */
5354
sd = _array_fill_strides(self->strides, dims, nd, sd,
5355
flags, &(self->flags));
5357
else { /* we allow strides even when we create
5358
the memory, but be careful with this...
5360
memcpy(self->strides, strides, sizeof(intp)*nd);
5364
else { self->dimensions = self->strides = NULL; }
5368
/* Allocate something even for zero-space arrays
5369
e.g. shape=(0,) -- otherwise buffer exposure
5370
(a.data) doesn't work as it should. */
5372
if (sd==0) sd = descr->elsize;
5374
if ((data = PyDataMem_NEW(sd))==NULL) {
5378
self->flags |= OWNDATA;
5380
/* It is bad to have unitialized OBJECT pointers */
5381
/* which could also be sub-fields of a VOID array */
5382
if (PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
5383
memset(data, 0, sd);
5387
self->flags &= ~OWNDATA; /* If data is passed in,
5388
this object won't own it
5390
Caller must arrange for
5391
this to be reset if truly
5396
/* call the __array_finalize__
5397
method if a subtype.
5398
If obj is NULL, then call method with Py_None
5400
if ((subtype != &PyArray_Type)) {
5401
PyObject *res, *func, *args;
5402
static PyObject *str=NULL;
5405
str = PyString_InternFromString("__array_finalize__");
5407
func = PyObject_GetAttr((PyObject *)self, str);
5408
if (func && func != Py_None) {
5409
if (strides != NULL) { /* did not allocate own data
5411
/* update flags before finalize function */
5412
PyArray_UpdateFlags(self, UPDATE_ALL);
5414
if PyCObject_Check(func) { /* A C-function is stored here */
5415
PyArray_FinalizeFunc *cfunc;
5416
cfunc = PyCObject_AsVoidPtr(func);
5418
if (cfunc(self, obj) < 0) goto fail;
5421
args = PyTuple_New(1);
5422
if (obj == NULL) obj=Py_None;
5424
PyTuple_SET_ITEM(args, 0, obj);
5425
res = PyObject_Call(func, args, NULL);
5428
if (res == NULL) goto fail;
5429
else Py_DECREF(res);
5432
else Py_XDECREF(func);
5435
return (PyObject *)self;
5556
largest = MAX_INTP / sd;
5558
if (dims[i] == 0) continue;
5560
PyErr_SetString(PyExc_ValueError,
5561
"negative dimensions " \
5567
if (size > largest || size < 0) {
5568
PyErr_SetString(PyExc_ValueError,
5569
"dimensions too large.");
5575
self = (PyArrayObject *) subtype->tp_alloc(subtype, 0);
5581
self->dimensions = NULL;
5584
self->flags = DEFAULT;
5586
self->flags |= FORTRAN;
5587
if (nd > 1) self->flags &= ~CONTIGUOUS;
5591
else self->flags = (flags & ~UPDATEIFCOPY);
5593
self->descr = descr;
5594
self->base = (PyObject *)NULL;
5595
self->weakreflist = (PyObject *)NULL;
5598
self->dimensions = PyDimMem_NEW(2*nd);
5599
if (self->dimensions == NULL) {
5603
self->strides = self->dimensions + nd;
5604
memcpy(self->dimensions, dims, sizeof(intp)*nd);
5605
if (strides == NULL) { /* fill it in */
5606
sd = _array_fill_strides(self->strides, dims, nd, sd,
5607
flags, &(self->flags));
5609
else { /* we allow strides even when we create
5610
the memory, but be careful with this...
5612
memcpy(self->strides, strides, sizeof(intp)*nd);
5616
else { self->dimensions = self->strides = NULL; }
5620
/* Allocate something even for zero-space arrays
5621
e.g. shape=(0,) -- otherwise buffer exposure
5622
(a.data) doesn't work as it should. */
5624
if (sd==0) sd = descr->elsize;
5626
if ((data = PyDataMem_NEW(sd))==NULL) {
5630
self->flags |= OWNDATA;
5632
/* It is bad to have unitialized OBJECT pointers */
5633
/* which could also be sub-fields of a VOID array */
5634
if (PyDataType_FLAGCHK(descr, NPY_NEEDS_INIT)) {
5635
memset(data, 0, sd);
5639
self->flags &= ~OWNDATA; /* If data is passed in,
5640
this object won't own it
5642
Caller must arrange for
5643
this to be reset if truly
5648
/* call the __array_finalize__
5649
method if a subtype.
5650
If obj is NULL, then call method with Py_None
5652
if ((subtype != &PyArray_Type)) {
5653
PyObject *res, *func, *args;
5654
static PyObject *str=NULL;
5657
str = PyString_InternFromString("__array_finalize__");
5659
func = PyObject_GetAttr((PyObject *)self, str);
5660
if (func && func != Py_None) {
5661
if (strides != NULL) { /* did not allocate own data
5663
/* update flags before finalize function */
5664
PyArray_UpdateFlags(self, UPDATE_ALL);
5666
if PyCObject_Check(func) { /* A C-function is stored here */
5667
PyArray_FinalizeFunc *cfunc;
5668
cfunc = PyCObject_AsVoidPtr(func);
5670
if (cfunc(self, obj) < 0) goto fail;
5673
args = PyTuple_New(1);
5674
if (obj == NULL) obj=Py_None;
5676
PyTuple_SET_ITEM(args, 0, obj);
5677
res = PyObject_Call(func, args, NULL);
5680
if (res == NULL) goto fail;
5681
else Py_DECREF(res);
5684
else Py_XDECREF(func);
5687
return (PyObject *)self;
5443
5695
_putzero(char *optr, PyObject *zero, PyArray_Descr *dtype)
5445
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
5446
memset(optr, 0, dtype->elsize);
5448
else if (PyDescr_HASFIELDS(dtype)) {
5449
PyObject *key, *value, *title=NULL;
5453
while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
5454
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
5456
_putzero(optr + offset, zero, new);
5462
temp = (PyObject **)optr;
5697
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
5698
memset(optr, 0, dtype->elsize);
5700
else if (PyDescr_HASFIELDS(dtype)) {
5701
PyObject *key, *value, *title=NULL;
5705
while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
5706
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
5708
_putzero(optr + offset, zero, new);
5714
temp = (PyObject **)optr;
5470
Resize (reallocate data). Only works if nothing else is referencing
5471
this array and it is contiguous.
5472
If refcheck is 0, then the reference count is not checked
5473
and assumed to be 1.
5474
You still must own this data and have no weak-references and no base
5722
Resize (reallocate data). Only works if nothing else is referencing
5723
this array and it is contiguous.
5724
If refcheck is 0, then the reference count is not checked
5725
and assumed to be 1.
5726
You still must own this data and have no weak-references and no base
5477
5729
static PyObject *
5478
5730
PyArray_Resize(PyArrayObject *self, PyArray_Dims *newshape, int refcheck,
5479
5731
NPY_ORDER fortran)
5481
intp oldsize, newsize;
5482
int new_nd=newshape->len, k, n, elsize;
5484
intp* new_dimensions=newshape->ptr;
5485
intp new_strides[MAX_DIMS];
5491
if (!PyArray_ISONESEGMENT(self)) {
5492
PyErr_SetString(PyExc_ValueError,
5493
"resize only works on single-segment arrays");
5497
if (fortran == PyArray_ANYORDER)
5498
fortran = PyArray_CORDER;
5500
if (self->descr->elsize == 0) {
5501
PyErr_SetString(PyExc_ValueError, "Bad data-type size.");
5505
largest = MAX_INTP / self->descr->elsize;
5506
for (k=0; k<new_nd; k++) {
5507
if (new_dimensions[k]==0) break;
5508
if (new_dimensions[k] < 0) {
5509
PyErr_SetString(PyExc_ValueError,
5510
"negative dimensions not allowed");
5513
newsize *= new_dimensions[k];
5514
if (newsize <=0 || newsize > largest) {
5515
return PyErr_NoMemory();
5518
oldsize = PyArray_SIZE(self);
5520
if (oldsize != newsize) {
5521
if (!(self->flags & OWNDATA)) {
5522
PyErr_SetString(PyExc_ValueError,
5523
"cannot resize this array: " \
5524
"it does not own its data");
5528
if (refcheck) refcnt = REFCOUNT(self);
5530
if ((refcnt > 2) || (self->base != NULL) || \
5531
(self->weakreflist != NULL)) {
5532
PyErr_SetString(PyExc_ValueError,
5533
"cannot resize an array that has "\
5534
"been referenced or is referencing\n"\
5535
"another array in this way. Use the "\
5540
if (newsize == 0) sd = self->descr->elsize;
5541
else sd = newsize * self->descr->elsize;
5542
/* Reallocate space if needed */
5543
new_data = PyDataMem_RENEW(self->data, sd);
5544
if (new_data == NULL) {
5545
PyErr_SetString(PyExc_MemoryError,
5546
"cannot allocate memory for array");
5549
self->data = new_data;
5552
if ((newsize > oldsize) && PyArray_ISWRITEABLE(self)) {
5553
/* Fill new memory with zeros */
5554
elsize = self->descr->elsize;
5555
if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
5556
PyObject *zero = PyInt_FromLong(0);
5558
optr = self->data + oldsize*elsize;
5559
n = newsize - oldsize;
5560
for (k=0; k<n; k++) {
5561
_putzero((char *)optr, zero, self->descr);
5567
memset(self->data+oldsize*elsize, 0,
5568
(newsize-oldsize)*elsize);
5572
if (self->nd != new_nd) { /* Different number of dimensions. */
5575
/* Need new dimensions and strides arrays */
5576
dimptr = PyDimMem_RENEW(self->dimensions, 2*new_nd);
5577
if (dimptr == NULL) {
5578
PyErr_SetString(PyExc_MemoryError,
5579
"cannot allocate memory for array " \
5580
"(array may be corrupted)");
5583
self->dimensions = dimptr;
5584
self->strides = dimptr + new_nd;
5587
/* make new_strides variable */
5588
sd = (size_t) self->descr->elsize;
5589
sd = (size_t) _array_fill_strides(new_strides, new_dimensions, new_nd, sd,
5590
self->flags, &(self->flags));
5592
memmove(self->dimensions, new_dimensions, new_nd*sizeof(intp));
5593
memmove(self->strides, new_strides, new_nd*sizeof(intp));
5733
intp oldsize, newsize;
5734
int new_nd=newshape->len, k, n, elsize;
5736
intp* new_dimensions=newshape->ptr;
5737
intp new_strides[MAX_DIMS];
5743
if (!PyArray_ISONESEGMENT(self)) {
5744
PyErr_SetString(PyExc_ValueError,
5745
"resize only works on single-segment arrays");
5749
if (fortran == PyArray_ANYORDER)
5750
fortran = PyArray_CORDER;
5752
if (self->descr->elsize == 0) {
5753
PyErr_SetString(PyExc_ValueError, "Bad data-type size.");
5757
largest = MAX_INTP / self->descr->elsize;
5758
for(k=0; k<new_nd; k++) {
5759
if (new_dimensions[k]==0) break;
5760
if (new_dimensions[k] < 0) {
5761
PyErr_SetString(PyExc_ValueError,
5762
"negative dimensions not allowed");
5765
newsize *= new_dimensions[k];
5766
if (newsize <=0 || newsize > largest) {
5767
return PyErr_NoMemory();
5770
oldsize = PyArray_SIZE(self);
5772
if (oldsize != newsize) {
5773
if (!(self->flags & OWNDATA)) {
5774
PyErr_SetString(PyExc_ValueError,
5775
"cannot resize this array: " \
5776
"it does not own its data");
5780
if (refcheck) refcnt = REFCOUNT(self);
5782
if ((refcnt > 2) || (self->base != NULL) || \
5783
(self->weakreflist != NULL)) {
5784
PyErr_SetString(PyExc_ValueError,
5785
"cannot resize an array that has "\
5786
"been referenced or is referencing\n"\
5787
"another array in this way. Use the "\
5792
if (newsize == 0) sd = self->descr->elsize;
5793
else sd = newsize * self->descr->elsize;
5794
/* Reallocate space if needed */
5795
new_data = PyDataMem_RENEW(self->data, sd);
5796
if (new_data == NULL) {
5797
PyErr_SetString(PyExc_MemoryError,
5798
"cannot allocate memory for array");
5801
self->data = new_data;
5804
if ((newsize > oldsize) && PyArray_ISWRITEABLE(self)) {
5805
/* Fill new memory with zeros */
5806
elsize = self->descr->elsize;
5807
if (PyDataType_FLAGCHK(self->descr, NPY_ITEM_REFCOUNT)) {
5808
PyObject *zero = PyInt_FromLong(0);
5810
optr = self->data + oldsize*elsize;
5811
n = newsize - oldsize;
5812
for(k=0; k<n; k++) {
5813
_putzero((char *)optr, zero, self->descr);
5819
memset(self->data+oldsize*elsize, 0,
5820
(newsize-oldsize)*elsize);
5824
if (self->nd != new_nd) { /* Different number of dimensions. */
5827
/* Need new dimensions and strides arrays */
5828
dimptr = PyDimMem_RENEW(self->dimensions, 2*new_nd);
5829
if (dimptr == NULL) {
5830
PyErr_SetString(PyExc_MemoryError,
5831
"cannot allocate memory for array " \
5832
"(array may be corrupted)");
5835
self->dimensions = dimptr;
5836
self->strides = dimptr + new_nd;
5839
/* make new_strides variable */
5840
sd = (size_t) self->descr->elsize;
5841
sd = (size_t) _array_fill_strides(new_strides, new_dimensions, new_nd, sd,
5842
self->flags, &(self->flags));
5844
memmove(self->dimensions, new_dimensions, new_nd*sizeof(intp));
5845
memmove(self->strides, new_strides, new_nd*sizeof(intp));
5601
5853
_fillobject(char *optr, PyObject *obj, PyArray_Descr *dtype)
5603
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
5604
if ((obj == Py_None) ||
5605
(PyInt_Check(obj) && PyInt_AsLong(obj)==0))
5610
arr = PyArray_NewFromDescr(&PyArray_Type, dtype,
5611
0, NULL, NULL, NULL,
5614
dtype->f->setitem(obj, optr, arr);
5618
else if (PyDescr_HASFIELDS(dtype)) {
5619
PyObject *key, *value, *title=NULL;
5623
while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
5624
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
5626
_fillobject(optr + offset, obj, new);
5855
if (!PyDataType_FLAGCHK(dtype, NPY_ITEM_REFCOUNT)) {
5856
if ((obj == Py_None) ||
5857
(PyInt_Check(obj) && PyInt_AsLong(obj)==0))
5632
temp = (PyObject **)optr;
5862
arr = PyArray_NewFromDescr(&PyArray_Type, dtype,
5863
0, NULL, NULL, NULL,
5866
dtype->f->setitem(obj, optr, arr);
5870
else if (PyDescr_HASFIELDS(dtype)) {
5871
PyObject *key, *value, *title=NULL;
5875
while (PyDict_Next(dtype->fields, &pos, &key, &value)) {
5876
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
5878
_fillobject(optr + offset, obj, new);
5884
temp = (PyObject **)optr;
5638
5890
/* Assumes contiguous */
5641
5893
PyArray_FillObjectArray(PyArrayObject *arr, PyObject *obj)
5896
n = PyArray_SIZE(arr);
5897
if (arr->descr->type_num == PyArray_OBJECT) {
5899
optr = (PyObject **)(arr->data);
5644
5900
n = PyArray_SIZE(arr);
5645
if (arr->descr->type_num == PyArray_OBJECT) {
5647
optr = (PyObject **)(arr->data);
5648
n = PyArray_SIZE(arr);
5650
for (i=0; i<n; i++) {
5655
for (i=0; i<n; i++) {
5902
for(i=0; i<n; i++) {
5664
for (i=0; i<n; i++) {
5665
_fillobject(optr, obj, arr->descr);
5666
optr += arr->descr->elsize;
5907
for(i=0; i<n; i++) {
5916
for(i=0; i<n; i++) {
5917
_fillobject(optr, obj, arr->descr);
5918
optr += arr->descr->elsize;
5673
5925
PyArray_FillWithScalar(PyArrayObject *arr, PyObject *obj)
5678
PyArray_Descr *descr;
5680
PyArray_CopySwapFunc *copyswap;
5682
itemsize = arr->descr->elsize;
5683
if (PyArray_ISOBJECT(arr)) {
5689
descr = PyArray_DESCR(arr);
5691
newarr = PyArray_FromAny(obj, descr, 0,0, ALIGNED, NULL);
5692
if (newarr == NULL) return -1;
5693
fromptr = PyArray_DATA(newarr);
5694
swap=!PyArray_ISNOTSWAPPED(arr);
5696
size=PyArray_SIZE(arr);
5697
copyswap = arr->descr->f->copyswap;
5698
if (PyArray_ISONESEGMENT(arr)) {
5699
char *toptr=PyArray_DATA(arr);
5700
PyArray_FillWithScalarFunc* fillwithscalar =
5701
arr->descr->f->fillwithscalar;
5702
if (fillwithscalar && PyArray_ISALIGNED(arr)) {
5703
copyswap(fromptr, NULL, swap, newarr);
5704
fillwithscalar(toptr, size, fromptr, arr);
5708
copyswap(toptr, fromptr, swap, arr);
5714
PyArrayIterObject *iter;
5716
iter = (PyArrayIterObject *)\
5717
PyArray_IterNew((PyObject *)arr);
5723
copyswap(iter->dataptr, fromptr, swap, arr);
5724
PyArray_ITER_NEXT(iter);
5930
PyArray_Descr *descr;
5932
PyArray_CopySwapFunc *copyswap;
5934
itemsize = arr->descr->elsize;
5935
if (PyArray_ISOBJECT(arr)) {
5941
descr = PyArray_DESCR(arr);
5943
newarr = PyArray_FromAny(obj, descr, 0,0, ALIGNED, NULL);
5944
if (newarr == NULL) return -1;
5945
fromptr = PyArray_DATA(newarr);
5946
swap = (PyArray_ISNOTSWAPPED(arr) != PyArray_ISNOTSWAPPED(newarr));
5948
size=PyArray_SIZE(arr);
5949
copyswap = arr->descr->f->copyswap;
5950
if (PyArray_ISONESEGMENT(arr)) {
5951
char *toptr=PyArray_DATA(arr);
5952
PyArray_FillWithScalarFunc* fillwithscalar =
5953
arr->descr->f->fillwithscalar;
5954
if (fillwithscalar && PyArray_ISALIGNED(arr)) {
5955
copyswap(fromptr, NULL, swap, newarr);
5956
fillwithscalar(toptr, size, fromptr, arr);
5960
copyswap(toptr, fromptr, swap, arr);
5966
PyArrayIterObject *iter;
5968
iter = (PyArrayIterObject *)\
5969
PyArray_IterNew((PyObject *)arr);
5975
copyswap(iter->dataptr, fromptr, swap, arr);
5976
PyArray_ITER_NEXT(iter);
5732
5984
static PyObject *
5733
5985
array_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
5735
static char *kwlist[] = {"shape", "dtype", "buffer",
5736
"offset", "strides",
5738
PyArray_Descr *descr=NULL;
5740
PyArray_Dims dims = {NULL, 0};
5741
PyArray_Dims strides = {NULL, 0};
5742
PyArray_Chunk buffer;
5744
NPY_ORDER order=PyArray_CORDER;
5749
/* Usually called with shape and type
5750
but can also be called with buffer, strides, and swapped info
5753
/* For now, let's just use this to create an empty, contiguous
5754
array of a specific type and shape.
5757
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&",
5758
kwlist, PyArray_IntpConverter,
5760
PyArray_DescrConverter,
5762
PyArray_BufferConverter,
5765
&PyArray_IntpConverter,
5767
&PyArray_OrderConverter,
5771
if (order == PyArray_FORTRANORDER) fortran = 1;
5774
descr = PyArray_DescrFromType(PyArray_DEFAULT);
5776
itemsize = descr->elsize;
5778
if (itemsize == 0) {
5779
PyErr_SetString(PyExc_ValueError,
5780
"data-type with unspecified variable length");
5784
if (strides.ptr != NULL) {
5786
if (strides.len != dims.len) {
5787
PyErr_SetString(PyExc_ValueError,
5788
"strides, if given, must be " \
5789
"the same length as shape");
5793
if (buffer.ptr == NULL) {
5799
off = (intp) offset;
5803
if (!PyArray_CheckStrides(itemsize, dims.len,
5805
dims.ptr, strides.ptr)) {
5806
PyErr_SetString(PyExc_ValueError,
5807
"strides is incompatible " \
5808
"with shape of requested " \
5809
"array and size of buffer");
5987
static char *kwlist[] = {"shape", "dtype", "buffer",
5988
"offset", "strides",
5990
PyArray_Descr *descr=NULL;
5992
PyArray_Dims dims = {NULL, 0};
5993
PyArray_Dims strides = {NULL, 0};
5994
PyArray_Chunk buffer;
5996
NPY_ORDER order=PyArray_CORDER;
6001
/* Usually called with shape and type
6002
but can also be called with buffer, strides, and swapped info
6005
/* For now, let's just use this to create an empty, contiguous
6006
array of a specific type and shape.
6009
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|O&O&LO&O&",
6010
kwlist, PyArray_IntpConverter,
6012
PyArray_DescrConverter,
6014
PyArray_BufferConverter,
6017
&PyArray_IntpConverter,
6019
&PyArray_OrderConverter,
6023
if (order == PyArray_FORTRANORDER) fortran = 1;
6026
descr = PyArray_DescrFromType(PyArray_DEFAULT);
6028
itemsize = descr->elsize;
6030
if (itemsize == 0) {
6031
PyErr_SetString(PyExc_ValueError,
6032
"data-type with unspecified variable length");
6036
if (strides.ptr != NULL) {
6038
if (strides.len != dims.len) {
6039
PyErr_SetString(PyExc_ValueError,
6040
"strides, if given, must be " \
6041
"the same length as shape");
5814
6045
if (buffer.ptr == NULL) {
5815
ret = (PyArrayObject *) \
5816
PyArray_NewFromDescr(subtype, descr,
5819
strides.ptr, NULL, fortran, NULL);
5820
if (ret == NULL) {descr=NULL;goto fail;}
5821
if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) {
5822
/* place Py_None in object positions */
5823
PyArray_FillObjectArray(ret, Py_None);
5824
if (PyErr_Occurred()) {
5830
else { /* buffer given -- use it */
5831
if (dims.len == 1 && dims.ptr[0] == -1) {
5832
dims.ptr[0] = (buffer.len-(intp)offset) / itemsize;
5834
else if ((strides.ptr == NULL) && \
5835
(buffer.len < ((intp)itemsize)* \
5836
PyArray_MultiplyList(dims.ptr, dims.len))) {
5837
PyErr_SetString(PyExc_TypeError,
5838
"buffer is too small for " \
5842
/* get writeable and aligned */
5843
if (fortran) buffer.flags |= FORTRAN;
5844
ret = (PyArrayObject *)\
5845
PyArray_NewFromDescr(subtype, descr,
5848
offset + (char *)buffer.ptr,
5849
buffer.flags, NULL);
5850
if (ret == NULL) {descr=NULL; goto fail;}
5851
PyArray_UpdateFlags(ret, UPDATE_ALL);
5852
ret->base = buffer.base;
5853
Py_INCREF(buffer.base);
5856
PyDimMem_FREE(dims.ptr);
5857
if (strides.ptr) PyDimMem_FREE(strides.ptr);
5858
return (PyObject *)ret;
6051
off = (intp) offset;
6055
if (!PyArray_CheckStrides(itemsize, dims.len,
6057
dims.ptr, strides.ptr)) {
6058
PyErr_SetString(PyExc_ValueError,
6059
"strides is incompatible " \
6060
"with shape of requested " \
6061
"array and size of buffer");
6066
if (buffer.ptr == NULL) {
6067
ret = (PyArrayObject *) \
6068
PyArray_NewFromDescr(subtype, descr,
6071
strides.ptr, NULL, fortran, NULL);
6072
if (ret == NULL) {descr=NULL;goto fail;}
6073
if (PyDataType_FLAGCHK(descr, NPY_ITEM_HASOBJECT)) {
6074
/* place Py_None in object positions */
6075
PyArray_FillObjectArray(ret, Py_None);
6076
if (PyErr_Occurred()) {
6082
else { /* buffer given -- use it */
6083
if (dims.len == 1 && dims.ptr[0] == -1) {
6084
dims.ptr[0] = (buffer.len-(intp)offset) / itemsize;
6086
else if ((strides.ptr == NULL) && \
6087
(buffer.len < ((intp)itemsize)* \
6088
PyArray_MultiplyList(dims.ptr, dims.len))) {
6089
PyErr_SetString(PyExc_TypeError,
6090
"buffer is too small for " \
6094
/* get writeable and aligned */
6095
if (fortran) buffer.flags |= FORTRAN;
6096
ret = (PyArrayObject *)\
6097
PyArray_NewFromDescr(subtype, descr,
6100
offset + (char *)buffer.ptr,
6101
buffer.flags, NULL);
6102
if (ret == NULL) {descr=NULL; goto fail;}
6103
PyArray_UpdateFlags(ret, UPDATE_ALL);
6104
ret->base = buffer.base;
6105
Py_INCREF(buffer.base);
6108
PyDimMem_FREE(dims.ptr);
6109
if (strides.ptr) PyDimMem_FREE(strides.ptr);
6110
return (PyObject *)ret;
5862
if (dims.ptr) PyDimMem_FREE(dims.ptr);
5863
if (strides.ptr) PyDimMem_FREE(strides.ptr);
6114
if (dims.ptr) PyDimMem_FREE(dims.ptr);
6115
if (strides.ptr) PyDimMem_FREE(strides.ptr);
5868
6120
static PyObject *
5869
6121
array_iter(PyArrayObject *arr)
5872
PyErr_SetString(PyExc_TypeError,
5873
"iteration over a 0-d array");
5876
return PySeqIter_New((PyObject *)arr);
6124
PyErr_SetString(PyExc_TypeError,
6125
"iteration over a 0-d array");
6128
return PySeqIter_New((PyObject *)arr);
5882
6134
static PyObject *
5883
6135
array_ndim_get(PyArrayObject *self)
5885
return PyInt_FromLong(self->nd);
6137
return PyInt_FromLong(self->nd);
5888
6140
static PyObject *
5889
6141
array_flags_get(PyArrayObject *self)
5891
return PyArray_NewFlagsObject((PyObject *)self);
6143
return PyArray_NewFlagsObject((PyObject *)self);
5894
6146
static PyObject *
5895
6147
array_shape_get(PyArrayObject *self)
5897
return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
6149
return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
5902
6154
array_shape_set(PyArrayObject *self, PyObject *val)
5907
/* Assumes C-order */
5908
ret = PyArray_Reshape(self, val);
5909
if (ret == NULL) return -1;
5910
if (PyArray_DATA(ret) != PyArray_DATA(self)) {
5912
PyErr_SetString(PyExc_AttributeError,
5913
"incompatible shape for a non-contiguous "\
5918
/* Free old dimensions and strides */
5919
PyDimMem_FREE(self->dimensions);
5920
nd = PyArray_NDIM(ret);
5922
if (nd > 0) { /* create new dimensions and strides */
5923
self->dimensions = PyDimMem_NEW(2*nd);
5924
if (self->dimensions == NULL) {
5926
PyErr_SetString(PyExc_MemoryError,"");
5929
self->strides = self->dimensions + nd;
5930
memcpy(self->dimensions, PyArray_DIMS(ret),
5932
memcpy(self->strides, PyArray_STRIDES(ret),
5935
else {self->dimensions=NULL; self->strides=NULL;}
6159
/* Assumes C-order */
6160
ret = PyArray_Reshape(self, val);
6161
if (ret == NULL) return -1;
6162
if (PyArray_DATA(ret) != PyArray_DATA(self)) {
5936
6163
Py_DECREF(ret);
5937
PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
6164
PyErr_SetString(PyExc_AttributeError,
6165
"incompatible shape for a non-contiguous "\
6170
/* Free old dimensions and strides */
6171
PyDimMem_FREE(self->dimensions);
6172
nd = PyArray_NDIM(ret);
6174
if (nd > 0) { /* create new dimensions and strides */
6175
self->dimensions = PyDimMem_NEW(2*nd);
6176
if (self->dimensions == NULL) {
6178
PyErr_SetString(PyExc_MemoryError,"");
6181
self->strides = self->dimensions + nd;
6182
memcpy(self->dimensions, PyArray_DIMS(ret),
6184
memcpy(self->strides, PyArray_STRIDES(ret),
6187
else {self->dimensions=NULL; self->strides=NULL;}
6189
PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
5942
6194
static PyObject *
5943
6195
array_strides_get(PyArrayObject *self)
5945
return PyArray_IntTupleFromIntp(self->nd, self->strides);
6197
return PyArray_IntTupleFromIntp(self->nd, self->strides);
5949
6201
array_strides_set(PyArrayObject *self, PyObject *obj)
5951
PyArray_Dims newstrides = {NULL, 0};
5958
if (!PyArray_IntpConverter(obj, &newstrides) || \
5959
newstrides.ptr == NULL) {
5960
PyErr_SetString(PyExc_TypeError, "invalid strides");
5963
if (newstrides.len != self->nd) {
5964
PyErr_Format(PyExc_ValueError, "strides must be " \
5965
" same length as shape (%d)", self->nd);
5969
while(new->base && PyArray_Check(new->base)) {
5970
new = (PyArrayObject *)(new->base);
5972
/* Get the available memory through the buffer
5973
interface on new->base or if that fails
5974
from the current new */
5975
if (new->base && PyObject_AsReadBuffer(new->base,
5976
(const void **)&buf,
5978
offset = self->data - buf;
5979
numbytes = buf_len + offset;
5983
numbytes = PyArray_MultiplyList(new->dimensions,
5984
new->nd)*new->descr->elsize;
5985
offset = self->data - new->data;
5988
if (!PyArray_CheckStrides(self->descr->elsize, self->nd, numbytes,
5990
self->dimensions, newstrides.ptr)) {
5991
PyErr_SetString(PyExc_ValueError, "strides is not "\
5992
"compatible with available memory");
5995
memcpy(self->strides, newstrides.ptr, sizeof(intp)*newstrides.len);
5996
PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
5997
PyDimMem_FREE(newstrides.ptr);
6203
PyArray_Dims newstrides = {NULL, 0};
6210
if (!PyArray_IntpConverter(obj, &newstrides) || \
6211
newstrides.ptr == NULL) {
6212
PyErr_SetString(PyExc_TypeError, "invalid strides");
6215
if (newstrides.len != self->nd) {
6216
PyErr_Format(PyExc_ValueError, "strides must be " \
6217
" same length as shape (%d)", self->nd);
6221
while(new->base && PyArray_Check(new->base)) {
6222
new = (PyArrayObject *)(new->base);
6224
/* Get the available memory through the buffer
6225
interface on new->base or if that fails
6226
from the current new */
6227
if (new->base && PyObject_AsReadBuffer(new->base,
6228
(const void **)&buf,
6230
offset = self->data - buf;
6231
numbytes = buf_len + offset;
6235
numbytes = PyArray_MultiplyList(new->dimensions,
6236
new->nd)*new->descr->elsize;
6237
offset = self->data - new->data;
6240
if (!PyArray_CheckStrides(self->descr->elsize, self->nd, numbytes,
6242
self->dimensions, newstrides.ptr)) {
6243
PyErr_SetString(PyExc_ValueError, "strides is not "\
6244
"compatible with available memory");
6247
memcpy(self->strides, newstrides.ptr, sizeof(intp)*newstrides.len);
6248
PyArray_UpdateFlags(self, CONTIGUOUS | FORTRAN);
6249
PyDimMem_FREE(newstrides.ptr);
6001
PyDimMem_FREE(newstrides.ptr);
6253
PyDimMem_FREE(newstrides.ptr);
6066
6318
static PyObject *
6067
6319
array_dataptr_get(PyArrayObject *self)
6069
return Py_BuildValue("NO",
6070
PyLong_FromVoidPtr(self->data),
6071
(self->flags & WRITEABLE ? Py_False :
6321
return Py_BuildValue("NO",
6322
PyLong_FromVoidPtr(self->data),
6323
(self->flags & WRITEABLE ? Py_False :
6075
6327
static PyObject *
6076
6328
array_ctypes_get(PyArrayObject *self)
6078
return PyObject_CallMethod(_numpy_internal, "_ctypes",
6080
PyLong_FromVoidPtr(self->data));
6330
PyObject *_numpy_internal;
6332
_numpy_internal = PyImport_ImportModule("numpy.core._internal");
6333
if (_numpy_internal == NULL) return NULL;
6334
ret = PyObject_CallMethod(_numpy_internal, "_ctypes",
6336
PyLong_FromVoidPtr(self->data));
6337
Py_DECREF(_numpy_internal);
6083
6341
static PyObject *
6084
6342
array_interface_get(PyArrayObject *self)
6088
dict = PyDict_New();
6089
if (dict == NULL) return NULL;
6092
obj = array_dataptr_get(self);
6093
PyDict_SetItemString(dict, "data", obj);
6096
obj = array_protocol_strides_get(self);
6097
PyDict_SetItemString(dict, "strides", obj);
6100
obj = array_protocol_descr_get(self);
6101
PyDict_SetItemString(dict, "descr", obj);
6104
obj = arraydescr_protocol_typestr_get(self->descr);
6105
PyDict_SetItemString(dict, "typestr", obj);
6108
obj = array_shape_get(self);
6109
PyDict_SetItemString(dict, "shape", obj);
6112
obj = PyInt_FromLong(3);
6113
PyDict_SetItemString(dict, "version", obj);
6346
dict = PyDict_New();
6347
if (dict == NULL) return NULL;
6350
obj = array_dataptr_get(self);
6351
PyDict_SetItemString(dict, "data", obj);
6354
obj = array_protocol_strides_get(self);
6355
PyDict_SetItemString(dict, "strides", obj);
6358
obj = array_protocol_descr_get(self);
6359
PyDict_SetItemString(dict, "descr", obj);
6362
obj = arraydescr_protocol_typestr_get(self->descr);
6363
PyDict_SetItemString(dict, "typestr", obj);
6366
obj = array_shape_get(self);
6367
PyDict_SetItemString(dict, "shape", obj);
6370
obj = PyInt_FromLong(3);
6371
PyDict_SetItemString(dict, "version", obj);
6119
6377
static PyObject *
6120
6378
array_data_get(PyArrayObject *self)
6123
if (!(PyArray_ISONESEGMENT(self))) {
6124
PyErr_SetString(PyExc_AttributeError, "cannot get single-"\
6125
"segment buffer for discontiguous array");
6128
nbytes = PyArray_NBYTES(self);
6129
if PyArray_ISWRITEABLE(self)
6130
return PyBuffer_FromReadWriteObject((PyObject *)self, 0,
6133
return PyBuffer_FromObject((PyObject *)self, 0, (int) nbytes);
6381
if (!(PyArray_ISONESEGMENT(self))) {
6382
PyErr_SetString(PyExc_AttributeError, "cannot get single-"\
6383
"segment buffer for discontiguous array");
6386
nbytes = PyArray_NBYTES(self);
6387
if PyArray_ISWRITEABLE(self)
6388
return PyBuffer_FromReadWriteObject((PyObject *)self, 0,
6391
return PyBuffer_FromObject((PyObject *)self, 0, (int) nbytes);
6137
6395
array_data_set(PyArrayObject *self, PyObject *op)
6143
if (PyObject_AsWriteBuffer(op, &buf, &buf_len) < 0) {
6145
if (PyObject_AsReadBuffer(op, (const void **)&buf,
6147
PyErr_SetString(PyExc_AttributeError,
6148
"object does not have single-segment " \
6149
"buffer interface");
6153
if (!PyArray_ISONESEGMENT(self)) {
6154
PyErr_SetString(PyExc_AttributeError, "cannot set single-" \
6155
"segment buffer for discontiguous array");
6158
if (PyArray_NBYTES(self) > buf_len) {
6159
PyErr_SetString(PyExc_AttributeError,
6160
"not enough data for array");
6163
if (self->flags & OWNDATA) {
6164
PyArray_XDECREF(self);
6165
PyDataMem_FREE(self->data);
6168
if (self->flags & UPDATEIFCOPY) {
6169
((PyArrayObject *)self->base)->flags |= WRITEABLE;
6170
self->flags &= ~UPDATEIFCOPY;
6172
Py_DECREF(self->base);
6177
self->flags = CARRAY;
6179
self->flags &= ~WRITEABLE;
6401
if (PyObject_AsWriteBuffer(op, &buf, &buf_len) < 0) {
6403
if (PyObject_AsReadBuffer(op, (const void **)&buf,
6405
PyErr_SetString(PyExc_AttributeError,
6406
"object does not have single-segment " \
6407
"buffer interface");
6411
if (!PyArray_ISONESEGMENT(self)) {
6412
PyErr_SetString(PyExc_AttributeError, "cannot set single-" \
6413
"segment buffer for discontiguous array");
6416
if (PyArray_NBYTES(self) > buf_len) {
6417
PyErr_SetString(PyExc_AttributeError,
6418
"not enough data for array");
6421
if (self->flags & OWNDATA) {
6422
PyArray_XDECREF(self);
6423
PyDataMem_FREE(self->data);
6426
if (self->flags & UPDATEIFCOPY) {
6427
((PyArrayObject *)self->base)->flags |= WRITEABLE;
6428
self->flags &= ~UPDATEIFCOPY;
6430
Py_DECREF(self->base);
6435
self->flags = CARRAY;
6437
self->flags &= ~WRITEABLE;
6184
6442
static PyObject *
6185
6443
array_itemsize_get(PyArrayObject *self)
6187
return PyInt_FromLong((long) self->descr->elsize);
6445
return PyInt_FromLong((long) self->descr->elsize);
6190
6448
static PyObject *
6191
6449
array_size_get(PyArrayObject *self)
6193
intp size=PyArray_SIZE(self);
6451
intp size=PyArray_SIZE(self);
6194
6452
#if SIZEOF_INTP <= SIZEOF_LONG
6453
return PyInt_FromLong((long) size);
6455
if (size > MAX_LONG || size < MIN_LONG)
6456
return PyLong_FromLongLong(size);
6195
6458
return PyInt_FromLong((long) size);
6197
if (size > MAX_LONG || size < MIN_LONG)
6198
return PyLong_FromLongLong(size);
6200
return PyInt_FromLong((long) size);
6204
6462
static PyObject *
6205
6463
array_nbytes_get(PyArrayObject *self)
6207
intp nbytes = PyArray_NBYTES(self);
6465
intp nbytes = PyArray_NBYTES(self);
6208
6466
#if SIZEOF_INTP <= SIZEOF_LONG
6467
return PyInt_FromLong((long) nbytes);
6469
if (nbytes > MAX_LONG || nbytes < MIN_LONG)
6470
return PyLong_FromLongLong(nbytes);
6209
6472
return PyInt_FromLong((long) nbytes);
6211
if (nbytes > MAX_LONG || nbytes < MIN_LONG)
6212
return PyLong_FromLongLong(nbytes);
6214
return PyInt_FromLong((long) nbytes);
6219
6477
/* If the type is changed.
6220
Also needing change: strides, itemsize
6222
Either itemsize is exactly the same
6223
or the array is single-segment (contiguous or fortran) with
6224
compatibile dimensions
6226
The shape and strides will be adjusted in that case as well.
6478
Also needing change: strides, itemsize
6480
Either itemsize is exactly the same
6481
or the array is single-segment (contiguous or fortran) with
6482
compatibile dimensions
6484
The shape and strides will be adjusted in that case as well.
6230
6488
array_descr_set(PyArrayObject *self, PyObject *arg)
6232
PyArray_Descr *newtype=NULL;
6235
char *msg = "new type not compatible with array.";
6237
if (!(PyArray_DescrConverter(arg, &newtype)) ||
6239
PyErr_SetString(PyExc_TypeError, "invalid data-type for array");
6242
if (PyDataType_FLAGCHK(newtype, NPY_ITEM_HASOBJECT) ||
6243
PyDataType_FLAGCHK(newtype, NPY_ITEM_IS_POINTER) ||
6244
PyDataType_FLAGCHK(self->descr, NPY_ITEM_HASOBJECT) ||
6245
PyDataType_FLAGCHK(self->descr, NPY_ITEM_IS_POINTER)) {
6246
PyErr_SetString(PyExc_TypeError, \
6247
"Cannot change data-type for object " \
6253
if (newtype->elsize == 0) {
6254
PyErr_SetString(PyExc_TypeError,
6255
"data-type must not be 0-sized");
6261
if ((newtype->elsize != self->descr->elsize) && \
6262
(self->nd == 0 || !PyArray_ISONESEGMENT(self) || \
6263
newtype->subarray)) goto fail;
6265
if (PyArray_ISCONTIGUOUS(self)) index = self->nd - 1;
6268
if (newtype->elsize < self->descr->elsize) {
6269
/* if it is compatible increase the size of the
6270
dimension at end (or at the front for FORTRAN)
6272
if (self->descr->elsize % newtype->elsize != 0)
6274
newdim = self->descr->elsize / newtype->elsize;
6275
self->dimensions[index] *= newdim;
6276
self->strides[index] = newtype->elsize;
6279
else if (newtype->elsize > self->descr->elsize) {
6281
/* Determine if last (or first if FORTRAN) dimension
6284
newdim = self->dimensions[index] * self->descr->elsize;
6285
if ((newdim % newtype->elsize) != 0) goto fail;
6287
self->dimensions[index] = newdim / newtype->elsize;
6288
self->strides[index] = newtype->elsize;
6291
/* fall through -- adjust type*/
6293
Py_DECREF(self->descr);
6294
if (newtype->subarray) {
6295
/* create new array object from data and update
6296
dimensions, strides and descr from it */
6297
PyArrayObject *temp;
6299
/* We would decref newtype here --- temp will
6300
steal a reference to it */
6301
temp = (PyArrayObject *) \
6302
PyArray_NewFromDescr(&PyArray_Type, newtype, self->nd,
6303
self->dimensions, self->strides,
6304
self->data, self->flags, NULL);
6305
if (temp == NULL) return -1;
6306
PyDimMem_FREE(self->dimensions);
6307
self->dimensions = temp->dimensions;
6308
self->nd = temp->nd;
6309
self->strides = temp->strides;
6310
newtype = temp->descr;
6311
Py_INCREF(temp->descr);
6312
/* Fool deallocator not to delete these*/
6314
temp->dimensions = NULL;
6318
self->descr = newtype;
6319
PyArray_UpdateFlags(self, UPDATE_ALL);
6490
PyArray_Descr *newtype=NULL;
6493
char *msg = "new type not compatible with array.";
6495
if (!(PyArray_DescrConverter(arg, &newtype)) ||
6497
PyErr_SetString(PyExc_TypeError, "invalid data-type for array");
6500
if (PyDataType_FLAGCHK(newtype, NPY_ITEM_HASOBJECT) ||
6501
PyDataType_FLAGCHK(newtype, NPY_ITEM_IS_POINTER) ||
6502
PyDataType_FLAGCHK(self->descr, NPY_ITEM_HASOBJECT) ||
6503
PyDataType_FLAGCHK(self->descr, NPY_ITEM_IS_POINTER)) {
6504
PyErr_SetString(PyExc_TypeError, \
6505
"Cannot change data-type for object " \
6511
if (newtype->elsize == 0) {
6512
PyErr_SetString(PyExc_TypeError,
6513
"data-type must not be 0-sized");
6519
if ((newtype->elsize != self->descr->elsize) && \
6520
(self->nd == 0 || !PyArray_ISONESEGMENT(self) || \
6521
newtype->subarray)) goto fail;
6523
if (PyArray_ISCONTIGUOUS(self)) index = self->nd - 1;
6526
if (newtype->elsize < self->descr->elsize) {
6527
/* if it is compatible increase the size of the
6528
dimension at end (or at the front for FORTRAN)
6530
if (self->descr->elsize % newtype->elsize != 0)
6532
newdim = self->descr->elsize / newtype->elsize;
6533
self->dimensions[index] *= newdim;
6534
self->strides[index] = newtype->elsize;
6537
else if (newtype->elsize > self->descr->elsize) {
6539
/* Determine if last (or first if FORTRAN) dimension
6542
newdim = self->dimensions[index] * self->descr->elsize;
6543
if ((newdim % newtype->elsize) != 0) goto fail;
6545
self->dimensions[index] = newdim / newtype->elsize;
6546
self->strides[index] = newtype->elsize;
6549
/* fall through -- adjust type*/
6551
Py_DECREF(self->descr);
6552
if (newtype->subarray) {
6553
/* create new array object from data and update
6554
dimensions, strides and descr from it */
6555
PyArrayObject *temp;
6557
/* We would decref newtype here --- temp will
6558
steal a reference to it */
6559
temp = (PyArrayObject *) \
6560
PyArray_NewFromDescr(&PyArray_Type, newtype, self->nd,
6561
self->dimensions, self->strides,
6562
self->data, self->flags, NULL);
6563
if (temp == NULL) return -1;
6564
PyDimMem_FREE(self->dimensions);
6565
self->dimensions = temp->dimensions;
6566
self->nd = temp->nd;
6567
self->strides = temp->strides;
6568
newtype = temp->descr;
6569
Py_INCREF(temp->descr);
6570
/* Fool deallocator not to delete these*/
6572
temp->dimensions = NULL;
6576
self->descr = newtype;
6577
PyArray_UpdateFlags(self, UPDATE_ALL);
6324
PyErr_SetString(PyExc_ValueError, msg);
6582
PyErr_SetString(PyExc_ValueError, msg);
6329
6587
static PyObject *
6330
6588
array_struct_get(PyArrayObject *self)
6332
PyArrayInterface *inter;
6590
PyArrayInterface *inter;
6334
inter = (PyArrayInterface *)_pya_malloc(sizeof(PyArrayInterface));
6335
if (inter==NULL) return PyErr_NoMemory();
6337
inter->nd = self->nd;
6338
inter->typekind = self->descr->kind;
6339
inter->itemsize = self->descr->elsize;
6340
inter->flags = self->flags;
6341
/* reset unused flags */
6342
inter->flags &= ~(UPDATEIFCOPY | OWNDATA);
6343
if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NOTSWAPPED;
6344
/* Copy shape and strides over since these can be reset
6345
when the array is "reshaped".
6348
inter->shape = (intp *)_pya_malloc(2*sizeof(intp)*self->nd);
6349
if (inter->shape == NULL) {
6351
return PyErr_NoMemory();
6353
inter->strides = inter->shape + self->nd;
6354
memcpy(inter->shape, self->dimensions, sizeof(intp)*self->nd);
6355
memcpy(inter->strides, self->strides, sizeof(intp)*self->nd);
6358
inter->shape = NULL;
6359
inter->strides = NULL;
6361
inter->data = self->data;
6362
if (self->descr->names) {
6363
inter->descr = arraydescr_protocol_descr_get(self->descr);
6364
if (inter->descr == NULL) PyErr_Clear();
6365
else inter->flags &= ARR_HAS_DESCR;
6367
else inter->descr = NULL;
6369
return PyCObject_FromVoidPtrAndDesc(inter, self, gentype_struct_free);
6592
inter = (PyArrayInterface *)_pya_malloc(sizeof(PyArrayInterface));
6593
if (inter==NULL) return PyErr_NoMemory();
6595
inter->nd = self->nd;
6596
inter->typekind = self->descr->kind;
6597
inter->itemsize = self->descr->elsize;
6598
inter->flags = self->flags;
6599
/* reset unused flags */
6600
inter->flags &= ~(UPDATEIFCOPY | OWNDATA);
6601
if (PyArray_ISNOTSWAPPED(self)) inter->flags |= NOTSWAPPED;
6602
/* Copy shape and strides over since these can be reset
6603
when the array is "reshaped".
6606
inter->shape = (intp *)_pya_malloc(2*sizeof(intp)*self->nd);
6607
if (inter->shape == NULL) {
6609
return PyErr_NoMemory();
6611
inter->strides = inter->shape + self->nd;
6612
memcpy(inter->shape, self->dimensions, sizeof(intp)*self->nd);
6613
memcpy(inter->strides, self->strides, sizeof(intp)*self->nd);
6616
inter->shape = NULL;
6617
inter->strides = NULL;
6619
inter->data = self->data;
6620
if (self->descr->names) {
6621
inter->descr = arraydescr_protocol_descr_get(self->descr);
6622
if (inter->descr == NULL) PyErr_Clear();
6623
else inter->flags &= ARR_HAS_DESCR;
6625
else inter->descr = NULL;
6627
return PyCObject_FromVoidPtrAndDesc(inter, self, gentype_struct_free);
6372
6630
static PyObject *
6373
6631
array_base_get(PyArrayObject *self)
6375
if (self->base == NULL) {
6380
Py_INCREF(self->base);
6633
if (self->base == NULL) {
6638
Py_INCREF(self->base);
6385
6643
/* Create a view of a complex array with an equivalent data-type
6389
6647
static PyArrayObject *
6390
6648
_get_part(PyArrayObject *self, int imag)
6392
PyArray_Descr *type;
6396
type = PyArray_DescrFromType(self->descr->type_num -
6397
PyArray_NUM_FLOATTYPE);
6398
offset = (imag ? type->elsize : 0);
6400
if (!PyArray_ISNBO(self->descr->byteorder)) {
6402
new = PyArray_DescrNew(type);
6403
new->byteorder = self->descr->byteorder;
6407
ret = (PyArrayObject *) \
6408
PyArray_NewFromDescr(self->ob_type,
6413
self->data + offset,
6414
self->flags, (PyObject *)self);
6415
if (ret == NULL) return NULL;
6416
ret->flags &= ~CONTIGUOUS;
6417
ret->flags &= ~FORTRAN;
6419
ret->base = (PyObject *)self;
6650
PyArray_Descr *type;
6654
type = PyArray_DescrFromType(self->descr->type_num -
6655
PyArray_NUM_FLOATTYPE);
6656
offset = (imag ? type->elsize : 0);
6658
if (!PyArray_ISNBO(self->descr->byteorder)) {
6660
new = PyArray_DescrNew(type);
6661
new->byteorder = self->descr->byteorder;
6665
ret = (PyArrayObject *) \
6666
PyArray_NewFromDescr(self->ob_type,
6671
self->data + offset,
6672
self->flags, (PyObject *)self);
6673
if (ret == NULL) return NULL;
6674
ret->flags &= ~CONTIGUOUS;
6675
ret->flags &= ~FORTRAN;
6677
ret->base = (PyObject *)self;
6423
6681
static PyObject *
6424
6682
array_real_get(PyArrayObject *self)
6428
if (PyArray_ISCOMPLEX(self)) {
6429
ret = _get_part(self, 0);
6430
return (PyObject *)ret;
6434
return (PyObject *)self;
6686
if (PyArray_ISCOMPLEX(self)) {
6687
ret = _get_part(self, 0);
6688
return (PyObject *)ret;
6692
return (PyObject *)self;
6440
6698
array_real_set(PyArrayObject *self, PyObject *val)
6704
if (PyArray_ISCOMPLEX(self)) {
6705
ret = _get_part(self, 0);
6706
if (ret == NULL) return -1;
6712
new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
6713
if (new == NULL) {Py_DECREF(ret); return -1;}
6714
rint = PyArray_MoveInto(ret, new);
6721
array_imag_get(PyArrayObject *self)
6724
PyArray_Descr *type;
6726
if (PyArray_ISCOMPLEX(self)) {
6727
ret = _get_part(self, 1);
6728
return (PyObject *) ret;
6733
ret = (PyArrayObject *)PyArray_Zeros(self->nd,
6736
PyArray_ISFORTRAN(self));
6737
ret->flags &= ~WRITEABLE;
6738
if (PyArray_CheckExact(self))
6739
return (PyObject *)ret;
6742
newret = PyArray_View(ret, NULL, self->ob_type);
6750
array_imag_set(PyArrayObject *self, PyObject *val)
6752
if (PyArray_ISCOMPLEX(self)) {
6442
6753
PyArrayObject *ret;
6443
6754
PyArrayObject *new;
6446
if (PyArray_ISCOMPLEX(self)) {
6447
ret = _get_part(self, 0);
6448
if (ret == NULL) return -1;
6757
ret = _get_part(self, 1);
6758
if (ret == NULL) return -1;
6454
6759
new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
6455
6760
if (new == NULL) {Py_DECREF(ret); return -1;}
6456
6761
rint = PyArray_MoveInto(ret, new);
6457
6762
Py_DECREF(ret);
6458
6763
Py_DECREF(new);
6463
array_imag_get(PyArrayObject *self)
6466
PyArray_Descr *type;
6468
if (PyArray_ISCOMPLEX(self)) {
6469
ret = _get_part(self, 1);
6470
return (PyObject *) ret;
6475
ret = (PyArrayObject *)PyArray_Zeros(self->nd,
6478
PyArray_ISFORTRAN(self));
6479
ret->flags &= ~WRITEABLE;
6480
if (PyArray_CheckExact(self))
6481
return (PyObject *)ret;
6484
newret = PyArray_View(ret, NULL, self->ob_type);
6492
array_imag_set(PyArrayObject *self, PyObject *val)
6494
if (PyArray_ISCOMPLEX(self)) {
6499
ret = _get_part(self, 1);
6500
if (ret == NULL) return -1;
6501
new = (PyArrayObject *)PyArray_FromAny(val, NULL, 0, 0, 0, NULL);
6502
if (new == NULL) {Py_DECREF(ret); return -1;}
6503
rint = PyArray_MoveInto(ret, new);
6509
PyErr_SetString(PyExc_TypeError, "array does not have "\
6510
"imaginary part to set");
6767
PyErr_SetString(PyExc_TypeError, "array does not have "\
6768
"imaginary part to set");
6515
6773
static PyObject *
6516
6774
array_flat_get(PyArrayObject *self)
6518
return PyArray_IterNew((PyObject *)self);
6776
return PyArray_IterNew((PyObject *)self);
6522
6780
array_flat_set(PyArrayObject *self, PyObject *val)
6526
PyArrayIterObject *selfit=NULL, *arrit=NULL;
6527
PyArray_Descr *typecode;
6529
PyArray_CopySwapFunc *copyswap;
6531
typecode = self->descr;
6532
Py_INCREF(typecode);
6533
arr = PyArray_FromAny(val, typecode,
6534
0, 0, FORCECAST | FORTRAN_IF(self), NULL);
6535
if (arr == NULL) return -1;
6536
arrit = (PyArrayIterObject *)PyArray_IterNew(arr);
6537
if (arrit == NULL) goto exit;
6538
selfit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
6539
if (selfit == NULL) goto exit;
6541
if (arrit->size == 0) {retval = 0; goto exit;}
6543
swap = PyArray_ISNOTSWAPPED(self) != PyArray_ISNOTSWAPPED(arr);
6544
copyswap = self->descr->f->copyswap;
6545
if (PyDataType_REFCHK(self->descr)) {
6546
while(selfit->index < selfit->size) {
6547
PyArray_Item_XDECREF(selfit->dataptr, self->descr);
6548
PyArray_Item_INCREF(arrit->dataptr, PyArray_DESCR(arr));
6549
memmove(selfit->dataptr, arrit->dataptr,
6550
sizeof(PyObject **));
6552
copyswap(selfit->dataptr, NULL, swap, self);
6553
PyArray_ITER_NEXT(selfit);
6554
PyArray_ITER_NEXT(arrit);
6555
if (arrit->index == arrit->size)
6556
PyArray_ITER_RESET(arrit);
6784
PyArrayIterObject *selfit=NULL, *arrit=NULL;
6785
PyArray_Descr *typecode;
6787
PyArray_CopySwapFunc *copyswap;
6789
typecode = self->descr;
6790
Py_INCREF(typecode);
6791
arr = PyArray_FromAny(val, typecode,
6792
0, 0, FORCECAST | FORTRAN_IF(self), NULL);
6793
if (arr == NULL) return -1;
6794
arrit = (PyArrayIterObject *)PyArray_IterNew(arr);
6795
if (arrit == NULL) goto exit;
6796
selfit = (PyArrayIterObject *)PyArray_IterNew((PyObject *)self);
6797
if (selfit == NULL) goto exit;
6799
if (arrit->size == 0) {retval = 0; goto exit;}
6801
swap = PyArray_ISNOTSWAPPED(self) != PyArray_ISNOTSWAPPED(arr);
6802
copyswap = self->descr->f->copyswap;
6803
if (PyDataType_REFCHK(self->descr)) {
6562
6804
while(selfit->index < selfit->size) {
6563
memmove(selfit->dataptr, arrit->dataptr, self->descr->elsize);
6565
copyswap(selfit->dataptr, NULL, swap, self);
6566
PyArray_ITER_NEXT(selfit);
6567
PyArray_ITER_NEXT(arrit);
6568
if (arrit->index == arrit->size)
6569
PyArray_ITER_RESET(arrit);
6805
PyArray_Item_XDECREF(selfit->dataptr, self->descr);
6806
PyArray_Item_INCREF(arrit->dataptr, PyArray_DESCR(arr));
6807
memmove(selfit->dataptr, arrit->dataptr,
6808
sizeof(PyObject **));
6810
copyswap(selfit->dataptr, NULL, swap, self);
6811
PyArray_ITER_NEXT(selfit);
6812
PyArray_ITER_NEXT(arrit);
6813
if (arrit->index == arrit->size)
6814
PyArray_ITER_RESET(arrit);
6820
while(selfit->index < selfit->size) {
6821
memmove(selfit->dataptr, arrit->dataptr, self->descr->elsize);
6823
copyswap(selfit->dataptr, NULL, swap, self);
6824
PyArray_ITER_NEXT(selfit);
6825
PyArray_ITER_NEXT(arrit);
6826
if (arrit->index == arrit->size)
6827
PyArray_ITER_RESET(arrit);
6579
6837
static PyObject *
6580
6838
array_transpose_get(PyArrayObject *self)
6582
return PyArray_Transpose(self, NULL);
6840
return PyArray_Transpose(self, NULL);
6585
6843
/* If this is None, no function call is made
6666
6924
static PyObject *
6667
6925
array_alloc(PyTypeObject *type, Py_ssize_t nitems)
6670
/* nitems will always be 0 */
6671
obj = (PyObject *)_pya_malloc(sizeof(PyArrayObject));
6672
PyObject_Init(obj, type);
6928
/* nitems will always be 0 */
6929
obj = (PyObject *)_pya_malloc(sizeof(PyArrayObject));
6930
PyObject_Init(obj, type);
6677
6935
static PyTypeObject PyArray_Type = {
6678
PyObject_HEAD_INIT(NULL)
6680
"numpy.ndarray", /*tp_name*/
6681
sizeof(PyArrayObject), /*tp_basicsize*/
6684
(destructor)array_dealloc, /*tp_dealloc */
6685
(printfunc)NULL, /*tp_print*/
6688
(cmpfunc)0, /*tp_compare*/
6689
(reprfunc)array_repr, /*tp_repr*/
6690
&array_as_number, /*tp_as_number*/
6691
&array_as_sequence, /*tp_as_sequence*/
6692
&array_as_mapping, /*tp_as_mapping*/
6693
(hashfunc)0, /*tp_hash*/
6694
(ternaryfunc)0, /*tp_call*/
6695
(reprfunc)array_str, /*tp_str*/
6697
(getattrofunc)0, /*tp_getattro*/
6698
(setattrofunc)0, /*tp_setattro*/
6699
&array_as_buffer, /*tp_as_buffer*/
6701
| Py_TPFLAGS_BASETYPE
6702
| Py_TPFLAGS_CHECKTYPES), /*tp_flags*/
6703
/*Documentation string */
6706
(traverseproc)0, /*tp_traverse */
6707
(inquiry)0, /*tp_clear */
6708
(richcmpfunc)array_richcompare, /*tp_richcompare */
6709
offsetof(PyArrayObject, weakreflist), /*tp_weaklistoffset */
6711
/* Iterator support (use standard) */
6713
(getiterfunc)array_iter, /* tp_iter */
6714
(iternextfunc)0, /* tp_iternext */
6716
/* Sub-classing (new-style object) support */
6718
array_methods, /* tp_methods */
6720
array_getsetlist, /* tp_getset */
6723
0, /* tp_descr_get */
6724
0, /* tp_descr_set */
6725
0, /* tp_dictoffset */
6726
(initproc)0, /* tp_init */
6727
array_alloc, /* tp_alloc */
6728
(newfunc)array_new, /* tp_new */
6734
0, /* tp_subclasses */
6936
PyObject_HEAD_INIT(NULL)
6938
"numpy.ndarray", /*tp_name*/
6939
sizeof(PyArrayObject), /*tp_basicsize*/
6942
(destructor)array_dealloc, /*tp_dealloc */
6943
(printfunc)NULL, /*tp_print*/
6946
(cmpfunc)0, /*tp_compare*/
6947
(reprfunc)array_repr, /*tp_repr*/
6948
&array_as_number, /*tp_as_number*/
6949
&array_as_sequence, /*tp_as_sequence*/
6950
&array_as_mapping, /*tp_as_mapping*/
6951
(hashfunc)0, /*tp_hash*/
6952
(ternaryfunc)0, /*tp_call*/
6953
(reprfunc)array_str, /*tp_str*/
6955
(getattrofunc)0, /*tp_getattro*/
6956
(setattrofunc)0, /*tp_setattro*/
6957
&array_as_buffer, /*tp_as_buffer*/
6959
| Py_TPFLAGS_BASETYPE
6960
| Py_TPFLAGS_CHECKTYPES), /*tp_flags*/
6961
/*Documentation string */
6964
(traverseproc)0, /*tp_traverse */
6965
(inquiry)0, /*tp_clear */
6966
(richcmpfunc)array_richcompare, /*tp_richcompare */
6967
offsetof(PyArrayObject, weakreflist), /*tp_weaklistoffset */
6969
/* Iterator support (use standard) */
6971
(getiterfunc)array_iter, /* tp_iter */
6972
(iternextfunc)0, /* tp_iternext */
6974
/* Sub-classing (new-style object) support */
6976
array_methods, /* tp_methods */
6978
array_getsetlist, /* tp_getset */
6981
0, /* tp_descr_get */
6982
0, /* tp_descr_set */
6983
0, /* tp_dictoffset */
6984
(initproc)0, /* tp_init */
6985
array_alloc, /* tp_alloc */
6986
(newfunc)array_new, /* tp_new */
6992
0, /* tp_subclasses */
6738
6996
/* The rest of this code is to build the right kind of array from a python */
6742
7000
discover_depth(PyObject *s, int max, int stop_at_string, int stop_at_tuple)
6747
if(max < 1) return -1;
6749
if(! PySequence_Check(s) || PyInstance_Check(s) || \
6750
PySequence_Length(s) < 0) {
6751
PyErr_Clear(); return 0;
6753
if (PyArray_Check(s))
6754
return PyArray_NDIM(s);
6755
if (PyArray_IsScalar(s, Generic)) return 0;
6756
if (PyString_Check(s) || PyBuffer_Check(s) || PyUnicode_Check(s))
6757
return stop_at_string ? 0:1;
6758
if (stop_at_tuple && PyTuple_Check(s)) return 0;
6759
if ((e=PyObject_GetAttrString(s, "__array_struct__")) != NULL) {
6761
if (PyCObject_Check(e)) {
6762
PyArrayInterface *inter;
6763
inter = (PyArrayInterface *)PyCObject_AsVoidPtr(e);
6764
if (inter->two == 2) {
6769
if (d > -1) return d;
6772
if ((e=PyObject_GetAttrString(s, "__array_interface__")) != NULL) {
6774
if (PyDict_Check(e)) {
6776
new = PyDict_GetItemString(e, "shape");
6777
if (new && PyTuple_Check(new))
6778
d = PyTuple_GET_SIZE(new);
6785
if (PySequence_Length(s) == 0)
6787
if ((e=PySequence_GetItem(s,0)) == NULL) return -1;
6789
d=discover_depth(e, max-1, stop_at_string, stop_at_tuple);
7008
if(!PySequence_Check(s) || PyInstance_Check(s) ||
7009
PySequence_Length(s) < 0) {
7013
if (PyArray_Check(s)) {
7014
return PyArray_NDIM(s);
7016
if (PyArray_IsScalar(s, Generic)) {
7019
if (PyString_Check(s) || PyBuffer_Check(s) || PyUnicode_Check(s)) {
7020
return stop_at_string ? 0:1;
7022
if (stop_at_tuple && PyTuple_Check(s)) {
7025
if ((e = PyObject_GetAttrString(s, "__array_struct__")) != NULL) {
7027
if (PyCObject_Check(e)) {
7028
PyArrayInterface *inter;
7029
inter = (PyArrayInterface *)PyCObject_AsVoidPtr(e);
7030
if (inter->two == 2) {
7042
if ((e=PyObject_GetAttrString(s, "__array_interface__")) != NULL) {
7044
if (PyDict_Check(e)) {
7046
new = PyDict_GetItemString(e, "shape");
7047
if (new && PyTuple_Check(new)) {
7048
d = PyTuple_GET_SIZE(new);
7058
if (PySequence_Length(s) == 0) {
7061
if ((e=PySequence_GetItem(s,0)) == NULL) {
7065
d = discover_depth(e, max-1, stop_at_string, stop_at_tuple);
6797
7075
discover_itemsize(PyObject *s, int nd, int *itemsize)
6802
n = PyObject_Length(s);
6804
if ((nd == 0) || PyString_Check(s) || \
7080
if (PyArray_Check(s)) {
7081
*itemsize = MAX(*itemsize, PyArray_ITEMSIZE(s));
7085
n = PyObject_Length(s);
7087
if ((nd == 0) || PyString_Check(s) ||
6805
7088
PyUnicode_Check(s) || PyBuffer_Check(s)) {
6806
if PyUnicode_Check(s)
6807
*itemsize = MAX(*itemsize, 4*n);
6809
*itemsize = MAX(*itemsize, n);
6812
for (i=0; i<n; i++) {
6813
if ((e=PySequence_GetItem(s,i))==NULL) return -1;
6814
r=discover_itemsize(e,nd-1,itemsize);
6816
if (r == -1) return -1;
7089
*itemsize = MAX(*itemsize, n);
7092
for(i = 0; i < n; i++) {
7093
if ((e = PySequence_GetItem(s,i))==NULL) {
7096
r = discover_itemsize(e,nd-1,itemsize);
6821
/* Take an arbitrary object known to represent
6822
an array of ndim nd, and determine the size in each dimension
7106
* Take an arbitrary object known to represent
7107
* an array of ndim nd, and determine the size in each dimension
6826
7110
discover_dimensions(PyObject *s, int nd, intp *d, int check_it)
6829
int r, n, i, n_lower;
6831
n=PyObject_Length(s);
6833
if(*d < 0) return -1;
6834
if(nd <= 1) return 0;
6836
for(i=0; i<n; i++) {
6837
if ((e=PySequence_GetItem(s,i)) == NULL) return -1;
6838
r=discover_dimensions(e,nd-1,d+1,check_it);
6841
if (r == -1) return -1;
6842
if (check_it && n_lower != 0 && n_lower != d[1]) {
6843
PyErr_SetString(PyExc_ValueError,
6844
"inconsistent shape in sequence");
6847
if (d[1] > n_lower) n_lower = d[1];
7113
int r, n, i, n_lower;
7116
if (PyArray_Check(s)) {
7117
for (i=0; i<nd; i++) {
7118
d[i] = PyArray_DIM(s,i);
7123
n=PyObject_Length(s);
7132
for(i = 0; i < n; i++) {
7133
if ((e = PySequence_GetItem(s,i)) == NULL) {
7136
r = discover_dimensions(e, nd - 1, d + 1, check_it);
7142
if (check_it && n_lower != 0 && n_lower != d[1]) {
7143
PyErr_SetString(PyExc_ValueError,
7144
"inconsistent shape in sequence");
7147
if (d[1] > n_lower) {
6855
/* doesn't alter refcount of chktype or mintype ---
6856
unless one of them is returned */
7158
* doesn't alter refcount of chktype or mintype ---
7159
* unless one of them is returned
6857
7161
static PyArray_Descr *
6858
7162
_array_small_type(PyArray_Descr *chktype, PyArray_Descr* mintype)
6860
PyArray_Descr *outtype;
6861
int outtype_num, save_num;
6863
if (PyArray_EquivTypes(chktype, mintype)) {
6868
if (chktype->type_num > mintype->type_num)
6869
outtype_num = chktype->type_num;
6871
outtype_num = mintype->type_num;
6873
save_num = outtype_num;
6874
while(outtype_num < PyArray_NTYPES &&
6875
!(PyArray_CanCastSafely(chktype->type_num, outtype_num)
6876
&& PyArray_CanCastSafely(mintype->type_num, outtype_num)))
6878
if (outtype_num == PyArray_NTYPES) {
6879
outtype = PyArray_DescrFromType(save_num);
6882
outtype = PyArray_DescrFromType(outtype_num);
6884
if (PyTypeNum_ISEXTENDED(outtype->type_num) && \
6885
(PyTypeNum_ISEXTENDED(mintype->type_num) || \
6886
mintype->type_num==0)) {
6887
int testsize = outtype->elsize;
6888
register int chksize, minsize;
6889
chksize = chktype->elsize;
6890
minsize = mintype->elsize;
6891
/* Handle string->unicode case separately
6892
because string itemsize is twice as large */
6893
if (outtype->type_num == PyArray_UNICODE &&
6894
mintype->type_num == PyArray_STRING) {
6895
testsize = MAX(chksize, 4*minsize);
6898
testsize = MAX(chksize, minsize);
6900
if (testsize != outtype->elsize) {
6901
PyArray_DESCR_REPLACE(outtype);
6902
outtype->elsize = testsize;
6903
Py_XDECREF(outtype->fields);
6904
outtype->fields = NULL;
6905
Py_XDECREF(outtype->names);
6906
outtype->names = NULL;
7164
PyArray_Descr *outtype;
7165
int outtype_num, save_num;
7167
if (PyArray_EquivTypes(chktype, mintype)) {
7173
if (chktype->type_num > mintype->type_num)
7174
outtype_num = chktype->type_num;
7176
if (PyDataType_ISOBJECT(chktype) && \
7177
PyDataType_ISSTRING(mintype)) {
7178
return PyArray_DescrFromType(NPY_OBJECT);
7181
outtype_num = mintype->type_num;
7185
save_num = outtype_num;
7186
while(outtype_num < PyArray_NTYPES &&
7187
!(PyArray_CanCastSafely(chktype->type_num, outtype_num)
7188
&& PyArray_CanCastSafely(mintype->type_num, outtype_num)))
7190
if (outtype_num == PyArray_NTYPES) {
7191
outtype = PyArray_DescrFromType(save_num);
7194
outtype = PyArray_DescrFromType(outtype_num);
7196
if (PyTypeNum_ISEXTENDED(outtype->type_num)) {
7197
int testsize = outtype->elsize;
7198
register int chksize, minsize;
7199
chksize = chktype->elsize;
7200
minsize = mintype->elsize;
7201
/* Handle string->unicode case separately
7202
because string itemsize is 4* as large */
7203
if (outtype->type_num == PyArray_UNICODE &&
7204
mintype->type_num == PyArray_STRING) {
7205
testsize = MAX(chksize, 4*minsize);
7208
testsize = MAX(chksize, minsize);
7210
if (testsize != outtype->elsize) {
7211
PyArray_DESCR_REPLACE(outtype);
7212
outtype->elsize = testsize;
7213
Py_XDECREF(outtype->fields);
7214
outtype->fields = NULL;
7215
Py_XDECREF(outtype->names);
7216
outtype->names = NULL;
6912
7222
static PyArray_Descr *
6947
7282
static PyArray_Descr *
6948
7283
_array_find_type(PyObject *op, PyArray_Descr *minitype, int max)
6952
PyArray_Descr *chktype=NULL;
6953
PyArray_Descr *outtype;
6955
/* These need to come first because if op already carries
6956
a descr structure, then we want it to be the result if minitype
6960
if (PyArray_Check(op)) {
6961
chktype = PyArray_DESCR(op);
6963
if (minitype == NULL) return chktype;
6964
Py_INCREF(minitype);
6968
if (PyArray_IsScalar(op, Generic)) {
6969
chktype = PyArray_DescrFromScalar(op);
6970
if (minitype == NULL) return chktype;
6971
Py_INCREF(minitype);
6975
if (minitype == NULL) {
6976
minitype = PyArray_DescrFromType(PyArray_BOOL);
6978
else Py_INCREF(minitype);
6980
if (max < 0) goto deflt;
6982
chktype = _array_find_python_scalar_type(op);
6987
if ((ip=PyObject_GetAttrString(op, "__array_interface__"))!=NULL) {
6988
if (PyDict_Check(ip)) {
6990
new = PyDict_GetItemString(ip, "typestr");
6991
if (new && PyString_Check(new)) {
6992
chktype =_array_typedescr_fromstr \
6993
(PyString_AS_STRING(new));
6997
if (chktype) goto finish;
7001
if ((ip=PyObject_GetAttrString(op, "__array_struct__")) != NULL) {
7002
PyArrayInterface *inter;
7004
if (PyCObject_Check(ip)) {
7005
inter=(PyArrayInterface *)PyCObject_AsVoidPtr(ip);
7006
if (inter->two == 2) {
7007
snprintf(buf, 40, "|%c%d", inter->typekind,
7009
chktype = _array_typedescr_fromstr(buf);
7013
if (chktype) goto finish;
7017
if (PyString_Check(op)) {
7018
chktype = PyArray_DescrNewFromType(PyArray_STRING);
7019
chktype->elsize = PyString_GET_SIZE(op);
7023
if (PyUnicode_Check(op)) {
7024
chktype = PyArray_DescrNewFromType(PyArray_UNICODE);
7025
chktype->elsize = PyUnicode_GET_DATA_SIZE(op);
7287
PyArray_Descr *chktype=NULL;
7288
PyArray_Descr *outtype;
7290
/* These need to come first because if op already carries
7291
a descr structure, then we want it to be the result if minitype
7295
if (PyArray_Check(op)) {
7296
chktype = PyArray_DESCR(op);
7298
if (minitype == NULL) return chktype;
7299
Py_INCREF(minitype);
7303
if (PyArray_IsScalar(op, Generic)) {
7304
chktype = PyArray_DescrFromScalar(op);
7305
if (minitype == NULL) return chktype;
7306
Py_INCREF(minitype);
7310
if (minitype == NULL) {
7311
minitype = PyArray_DescrFromType(PyArray_BOOL);
7313
else Py_INCREF(minitype);
7315
if (max < 0) goto deflt;
7317
chktype = _array_find_python_scalar_type(op);
7322
if ((ip=PyObject_GetAttrString(op, "__array_interface__"))!=NULL) {
7323
if (PyDict_Check(ip)) {
7325
new = PyDict_GetItemString(ip, "typestr");
7326
if (new && PyString_Check(new)) {
7327
chktype =_array_typedescr_fromstr \
7328
(PyString_AS_STRING(new));
7332
if (chktype) goto finish;
7336
if ((ip=PyObject_GetAttrString(op, "__array_struct__")) != NULL) {
7337
PyArrayInterface *inter;
7339
if (PyCObject_Check(ip)) {
7340
inter=(PyArrayInterface *)PyCObject_AsVoidPtr(ip);
7341
if (inter->two == 2) {
7342
snprintf(buf, 40, "|%c%d", inter->typekind,
7344
chktype = _array_typedescr_fromstr(buf);
7348
if (chktype) goto finish;
7352
if (PyString_Check(op)) {
7353
chktype = PyArray_DescrNewFromType(PyArray_STRING);
7354
chktype->elsize = PyString_GET_SIZE(op);
7358
if (PyUnicode_Check(op)) {
7359
chktype = PyArray_DescrNewFromType(PyArray_UNICODE);
7360
chktype->elsize = PyUnicode_GET_DATA_SIZE(op);
7026
7361
#ifndef Py_UNICODE_WIDE
7027
chktype->elsize <<= 1;
7362
chktype->elsize <<= 1;
7032
if (PyBuffer_Check(op)) {
7033
chktype = PyArray_DescrNewFromType(PyArray_VOID);
7034
chktype->elsize = op->ob_type->tp_as_sequence->sq_length(op);
7367
if (PyBuffer_Check(op)) {
7368
chktype = PyArray_DescrNewFromType(PyArray_VOID);
7369
chktype->elsize = op->ob_type->tp_as_sequence->sq_length(op);
7374
if (PyObject_HasAttrString(op, "__array__")) {
7375
ip = PyObject_CallMethod(op, "__array__", NULL);
7376
if(ip && PyArray_Check(ip)) {
7377
chktype = PyArray_DESCR(ip);
7383
if (PyErr_Occurred()) PyErr_Clear();
7386
if (PyInstance_Check(op)) goto deflt;
7388
if (PySequence_Check(op)) {
7390
l = PyObject_Length(op);
7391
if (l < 0 && PyErr_Occurred()) {
7395
if (l == 0 && minitype->type_num == PyArray_BOOL) {
7396
Py_DECREF(minitype);
7397
minitype = PyArray_DescrFromType(PyArray_DEFAULT);
7400
PyArray_Descr *newtype;
7401
ip = PySequence_GetItem(op, l);
7039
if (PyObject_HasAttrString(op, "__array__")) {
7040
ip = PyObject_CallMethod(op, "__array__", NULL);
7041
if(ip && PyArray_Check(ip)) {
7042
chktype = PyArray_DESCR(ip);
7048
if (PyErr_Occurred()) PyErr_Clear();
7051
if (PyInstance_Check(op)) goto deflt;
7053
if (PySequence_Check(op)) {
7055
l = PyObject_Length(op);
7056
if (l < 0 && PyErr_Occurred()) {
7060
if (l == 0 && minitype->type_num == PyArray_BOOL) {
7061
Py_DECREF(minitype);
7062
minitype = PyArray_DescrFromType(PyArray_DEFAULT);
7065
PyArray_Descr *newtype;
7066
ip = PySequence_GetItem(op, l);
7071
chktype = _array_find_type(ip, minitype, max-1);
7072
newtype = _array_small_type(chktype, minitype);
7073
Py_DECREF(minitype);
7079
Py_INCREF(minitype);
7406
chktype = _array_find_type(ip, minitype, max-1);
7407
newtype = _array_small_type(chktype, minitype);
7408
Py_DECREF(minitype);
7414
Py_INCREF(minitype);
7085
chktype = PyArray_DescrFromType(PyArray_OBJECT);
7420
chktype = _use_default_type(op);
7089
outtype = _array_small_type(chktype, minitype);
7091
Py_DECREF(minitype);
7092
/* VOID Arrays should not occur by "default"
7093
unless input was already a VOID */
7094
if (outtype->type_num == PyArray_VOID && \
7095
minitype->type_num != PyArray_VOID) {
7097
return PyArray_DescrFromType(PyArray_OBJECT);
7424
outtype = _array_small_type(chktype, minitype);
7426
Py_DECREF(minitype);
7427
/* VOID Arrays should not occur by "default"
7428
unless input was already a VOID */
7429
if (outtype->type_num == PyArray_VOID && \
7430
minitype->type_num != PyArray_VOID) {
7432
return PyArray_DescrFromType(PyArray_OBJECT);
7102
7437
/* adapted from Numarray */
7104
7439
setArrayFromSequence(PyArrayObject *a, PyObject *s, int dim, intp offset)
7106
Py_ssize_t i, slen = PySequence_Length(s);
7110
PyErr_Format(PyExc_ValueError,
7111
"setArrayFromSequence: sequence/array dimensions mismatch.");
7115
if (slen != a->dimensions[dim]) {
7116
PyErr_Format(PyExc_ValueError,
7117
"setArrayFromSequence: sequence/array shape mismatch.");
7121
for(i=0; i<slen; i++) {
7122
PyObject *o = PySequence_GetItem(s, i);
7123
if ((a->nd - dim) > 1) {
7124
res = setArrayFromSequence(a, o, dim+1, offset);
7127
res = a->descr->f->setitem(o, (a->data + offset), a);
7130
if (res < 0) return res;
7131
offset += a->strides[dim];
7444
/* This code is to ensure that the sequence access below will
7445
return a lower-dimensional sequence.
7447
if (PyArray_Check(s) && !(PyArray_CheckExact(s))) {
7448
/* FIXME: This could probably copy the entire subarray
7449
at once here using a faster algorithm.
7450
Right now, just make sure a base-class array
7451
is used so that the dimensionality reduction assumption
7454
s = PyArray_EnsureArray(s);
7458
PyErr_Format(PyExc_ValueError,
7459
"setArrayFromSequence: sequence/array dimensions mismatch.");
7463
slen = PySequence_Length(s);
7465
if (slen != a->dimensions[dim]) {
7466
PyErr_Format(PyExc_ValueError,
7467
"setArrayFromSequence: sequence/array shape mismatch.");
7471
for(i=0; i<slen; i++) {
7472
PyObject *o = PySequence_GetItem(s, i);
7473
if ((a->nd - dim) > 1) {
7474
res = setArrayFromSequence(a, o, dim+1, offset);
7477
res = a->descr->f->setitem(o, (a->data + offset), a);
7480
if (res < 0) return res;
7481
offset += a->strides[dim];
7138
7488
Assign_Array(PyArrayObject *self, PyObject *v)
7140
if (!PySequence_Check(v)) {
7141
PyErr_SetString(PyExc_ValueError,
7142
"assignment from non-sequence");
7145
if (self->nd == 0) {
7146
PyErr_SetString(PyExc_ValueError,
7147
"assignment to 0-d array");
7490
if (!PySequence_Check(v)) {
7491
PyErr_SetString(PyExc_ValueError,
7492
"assignment from non-sequence");
7495
if (self->nd == 0) {
7496
PyErr_SetString(PyExc_ValueError,
7497
"assignment to 0-d array");
7151
return setArrayFromSequence(self, v, 0, 0);
7501
return setArrayFromSequence(self, v, 0, 0);
7154
7504
/* "Array Scalars don't call this code" */
7207
7561
object_depth_and_dimension(PyObject *s, int max, intp *dims)
7209
intp *newdims, *test_dims;
7215
islist = PyList_Check(s);
7216
if (!(islist || PyTuple_Check(s)) ||
7217
((size = PySequence_Size(s)) == 0))
7220
if (max < 1) return 0;
7224
newdims = PyDimMem_NEW(2*(max-1));
7225
test_dims = newdims + (max-1);
7226
if (islist) obj = PyList_GET_ITEM(s, 0);
7227
else obj = PyTuple_GET_ITEM(s, 0);
7228
nd = object_depth_and_dimension(obj, max-1, newdims);
7229
for (i=1; i<size; i++) {
7230
if (islist) obj = PyList_GET_ITEM(s, i);
7231
else obj = PyTuple_GET_ITEM(s, i);
7232
test_nd = object_depth_and_dimension(obj, max-1, test_dims);
7233
if ((nd != test_nd) ||
7234
(!PyArray_CompareLists(newdims, test_dims, nd))) {
7240
for (i=1; i<=nd; i++) dims[i] = newdims[i-1];
7563
intp *newdims, *test_dims;
7565
int i, islist, istuple;
7569
islist = PyList_Check(s);
7570
istuple = PyTuple_Check(s);
7571
if (!(islist || istuple)) {
7575
size = PySequence_Size(s);
7241
7583
dims[0] = size;
7242
PyDimMem_FREE(newdims);
7587
newdims = PyDimMem_NEW(2*(max - 1));
7588
test_dims = newdims + (max - 1);
7590
obj = PyList_GET_ITEM(s, 0);
7593
obj = PyTuple_GET_ITEM(s, 0);
7595
nd = object_depth_and_dimension(obj, max - 1, newdims);
7597
for(i = 1; i < size; i++) {
7599
obj = PyList_GET_ITEM(s, i);
7602
obj = PyTuple_GET_ITEM(s, i);
7604
test_nd = object_depth_and_dimension(obj, max-1, test_dims);
7606
if ((nd != test_nd) ||
7607
(!PyArray_CompareLists(newdims, test_dims, nd))) {
7613
for(i = 1; i <= nd; i++) {
7614
dims[i] = newdims[i-1];
7617
PyDimMem_FREE(newdims);
7246
7621
static PyObject *
7247
7622
ObjectArray_FromNestedList(PyObject *s, PyArray_Descr *typecode, int fortran)
7253
/* Get the depth and the number of dimensions */
7254
nd = object_depth_and_dimension(s, MAX_DIMS, d);
7255
if (nd < 0) return NULL;
7257
if (nd == 0) return Array_FromPyScalar(s, typecode);
7259
r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
7265
if(Assign_Array(r,s) == -1) {
7269
return (PyObject*)r;
7628
/* Get the depth and the number of dimensions */
7629
nd = object_depth_and_dimension(s, MAX_DIMS, d);
7634
return Array_FromPyScalar(s, typecode);
7637
r = (PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
7645
if(Assign_Array(r,s) == -1) {
7649
return (PyObject*)r;
7272
/* isobject means that we are constructing an
7273
object array on-purpose with a nested list.
7274
Only a list is interpreted as a sequence with these rules
7653
* isobject means that we are constructing an
7654
* object array on-purpose with a nested list.
7655
* Only a list is interpreted as a sequence with these rules
7276
7657
/* steals reference to typecode */
7277
7658
static PyObject *
7278
7659
Array_FromSequence(PyObject *s, PyArray_Descr *typecode, int fortran,
7279
7660
int min_depth, int max_depth)
7287
int type = typecode->type_num;
7288
int itemsize = typecode->elsize;
7290
check_it = (typecode->type != PyArray_CHARLTR);
7292
stop_at_string = ((type == PyArray_OBJECT) ||
7293
(type == PyArray_STRING &&
7294
typecode->type == PyArray_STRINGLTR) ||
7295
(type == PyArray_UNICODE) ||
7296
(type == PyArray_VOID));
7298
stop_at_tuple = (type == PyArray_VOID && (typecode->names \
7299
|| typecode->subarray));
7301
if (!((nd=discover_depth(s, MAX_DIMS+1, stop_at_string,
7302
stop_at_tuple)) > 0)) {
7304
return Array_FromPyScalar(s, typecode);
7305
PyErr_SetString(PyExc_ValueError,
7306
"invalid input sequence");
7310
if (max_depth && PyTypeNum_ISOBJECT(type) && (nd > max_depth)) {
7314
if ((max_depth && nd > max_depth) || \
7315
(min_depth && nd < min_depth)) {
7316
PyErr_SetString(PyExc_ValueError,
7317
"invalid number of dimensions");
7321
if(discover_dimensions(s,nd,d, check_it) == -1) goto fail;
7323
if (typecode->type == PyArray_CHARLTR && nd > 0 && d[nd-1]==1) {
7327
if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
7328
if (discover_itemsize(s, nd, &itemsize) == -1) goto fail;
7329
if (type == PyArray_UNICODE) itemsize*=4;
7332
if (itemsize != typecode->elsize) {
7333
PyArray_DESCR_REPLACE(typecode);
7334
typecode->elsize = itemsize;
7337
r=(PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
7343
if(Assign_Array(r,s) == -1) {
7347
return (PyObject*)r;
7669
int type = typecode->type_num;
7670
int itemsize = typecode->elsize;
7672
check_it = (typecode->type != PyArray_CHARLTR);
7674
stop_at_string = (type != PyArray_STRING) ||
7675
(typecode->type == PyArray_STRINGLTR);
7677
stop_at_tuple = (type == PyArray_VOID && (typecode->names \
7678
|| typecode->subarray));
7680
nd = discover_depth(s, MAX_DIMS + 1, stop_at_string, stop_at_tuple);
7682
return Array_FromPyScalar(s, typecode);
7685
PyErr_SetString(PyExc_ValueError,
7686
"invalid input sequence");
7689
if (max_depth && PyTypeNum_ISOBJECT(type) && (nd > max_depth)) {
7692
if ((max_depth && nd > max_depth) || (min_depth && nd < min_depth)) {
7693
PyErr_SetString(PyExc_ValueError,
7694
"invalid number of dimensions");
7698
err = discover_dimensions(s, nd, d, check_it);
7702
if (typecode->type == PyArray_CHARLTR && nd > 0 && d[nd - 1] == 1) {
7706
if (itemsize == 0 && PyTypeNum_ISEXTENDED(type)) {
7707
err = discover_itemsize(s, nd, &itemsize);
7711
if (type == PyArray_UNICODE) {
7715
if (itemsize != typecode->elsize) {
7716
PyArray_DESCR_REPLACE(typecode);
7717
typecode->elsize = itemsize;
7720
r = (PyArrayObject*)PyArray_NewFromDescr(&PyArray_Type, typecode,
7728
err = Assign_Array(r,s);
7733
return (PyObject*)r;
7350
Py_DECREF(typecode);
7736
Py_DECREF(typecode);
7356
Is the typenum valid?
7742
Is the typenum valid?
7359
7745
PyArray_ValidType(int type)
7361
PyArray_Descr *descr;
7747
PyArray_Descr *descr;
7364
descr = PyArray_DescrFromType(type);
7365
if (descr==NULL) res = FALSE;
7750
descr = PyArray_DescrFromType(type);
7751
if (descr == NULL) {
7370
7758
/* For backward compatibility */
7372
7760
/* steals reference to at --- cannot be NULL*/
7374
Cast an array using typecode structure.
7762
*Cast an array using typecode structure.
7376
7764
static PyObject *
7377
7765
PyArray_CastToType(PyArrayObject *mp, PyArray_Descr *at, int fortran)
7385
if (((mpd == at) || ((mpd->type_num == at->type_num) && \
7386
PyArray_EquivByteorders(mpd->byteorder,\
7388
((mpd->elsize == at->elsize) || \
7389
(at->elsize==0)))) && \
7390
PyArray_ISBEHAVED_RO(mp)) {
7393
return (PyObject *)mp;
7396
if (at->elsize == 0) {
7397
PyArray_DESCR_REPLACE(at);
7398
if (at == NULL) return NULL;
7399
if (mpd->type_num == PyArray_STRING && \
7400
at->type_num == PyArray_UNICODE)
7401
at->elsize = mpd->elsize << 2;
7402
if (mpd->type_num == PyArray_UNICODE &&
7403
at->type_num == PyArray_STRING)
7404
at->elsize = mpd->elsize >> 2;
7405
if (at->type_num == PyArray_VOID)
7406
at->elsize = mpd->elsize;
7409
out = PyArray_NewFromDescr(mp->ob_type, at,
7416
if (out == NULL) return NULL;
7417
ret = PyArray_CastTo((PyArrayObject *)out, mp);
7418
if (ret != -1) return out;
7773
if (((mpd == at) || ((mpd->type_num == at->type_num) && \
7774
PyArray_EquivByteorders(mpd->byteorder,\
7776
((mpd->elsize == at->elsize) || \
7777
(at->elsize==0)))) && \
7778
PyArray_ISBEHAVED_RO(mp)) {
7781
return (PyObject *)mp;
7784
if (at->elsize == 0) {
7785
PyArray_DESCR_REPLACE(at);
7789
if (mpd->type_num == PyArray_STRING &&
7790
at->type_num == PyArray_UNICODE) {
7791
at->elsize = mpd->elsize << 2;
7793
if (mpd->type_num == PyArray_UNICODE &&
7794
at->type_num == PyArray_STRING) {
7795
at->elsize = mpd->elsize >> 2;
7797
if (at->type_num == PyArray_VOID) {
7798
at->elsize = mpd->elsize;
7802
out = PyArray_NewFromDescr(mp->ob_type, at,
7812
ret = PyArray_CastTo((PyArrayObject *)out, mp);
7426
Get a cast function to cast from the input descriptor to the
7427
output type_number (must be a registered data-type).
7428
Returns NULL if un-successful.
7823
Get a cast function to cast from the input descriptor to the
7824
output type_number (must be a registered data-type).
7825
Returns NULL if un-successful.
7430
7827
static PyArray_VectorUnaryFunc *
7431
7828
PyArray_GetCastFunc(PyArray_Descr *descr, int type_num)
7433
PyArray_VectorUnaryFunc *castfunc=NULL;
7434
if (type_num < PyArray_NTYPES) {
7435
castfunc = descr->f->cast[type_num];
7437
if (castfunc == NULL) {
7438
PyObject *obj = descr->f->castdict;
7439
if (obj && PyDict_Check(obj)) {
7442
key = PyInt_FromLong(type_num);
7443
cobj = PyDict_GetItem(obj, key);
7445
if (PyCObject_Check(cobj)) {
7446
castfunc = PyCObject_AsVoidPtr(cobj);
7449
if (castfunc) return castfunc;
7451
else return castfunc;
7453
PyErr_SetString(PyExc_ValueError,
7454
"No cast function available.");
7830
PyArray_VectorUnaryFunc *castfunc=NULL;
7831
if (type_num < PyArray_NTYPES) {
7832
castfunc = descr->f->cast[type_num];
7834
if (castfunc == NULL) {
7835
PyObject *obj = descr->f->castdict;
7836
if (obj && PyDict_Check(obj)) {
7840
key = PyInt_FromLong(type_num);
7841
cobj = PyDict_GetItem(obj, key);
7843
if (PyCObject_Check(cobj)) {
7844
castfunc = PyCObject_AsVoidPtr(cobj);
7855
PyErr_SetString(PyExc_ValueError,
7856
"No cast function available.");
7458
7860
/* Reference counts:
7472
7874
PyArray_VectorUnaryFunc *castfunc,
7473
7875
PyArrayObject *dest, PyArrayObject *src)
7477
/* 1. copy input to buffer and swap
7478
2. cast input to output
7479
3. swap output if necessary and copy from output buffer
7481
scopyfunc(buffers[1], selsize, sptr, sstride, N, sswap, src);
7482
castfunc(buffers[1], buffers[0], N, src, dest);
7483
dcopyfunc(dptr, dstride, buffers[0], delsize, N, dswap, dest);
7487
/* otherwise we need to divide up into bufsize pieces */
7491
newN = MIN(N, bufsize);
7492
_strided_buffered_cast(dptr+i*dstride, dstride, delsize,
7494
sptr+i*sstride, sstride, selsize,
7496
newN, buffers, bufsize, castfunc, dest, src);
7879
/* 1. copy input to buffer and swap
7880
2. cast input to output
7881
3. swap output if necessary and copy from output buffer
7883
scopyfunc(buffers[1], selsize, sptr, sstride, N, sswap, src);
7884
castfunc(buffers[1], buffers[0], N, src, dest);
7885
dcopyfunc(dptr, dstride, buffers[0], delsize, N, dswap, dest);
7889
/* otherwise we need to divide up into bufsize pieces */
7893
newN = MIN(N, bufsize);
7894
_strided_buffered_cast(dptr+i*dstride, dstride, delsize,
7896
sptr+i*sstride, sstride, selsize,
7898
newN, buffers, bufsize, castfunc, dest, src);
7504
7906
_broadcast_cast(PyArrayObject *out, PyArrayObject *in,
7505
7907
PyArray_VectorUnaryFunc *castfunc, int iswap, int oswap)
7507
int delsize, selsize, maxaxis, i, N;
7508
PyArrayMultiIterObject *multi;
7509
intp maxdim, ostrides, istrides;
7511
PyArray_CopySwapNFunc *ocopyfunc, *icopyfunc;
7514
NPY_BEGIN_THREADS_DEF
7516
delsize = PyArray_ITEMSIZE(out);
7517
selsize = PyArray_ITEMSIZE(in);
7518
multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, out, in);
7519
if (multi == NULL) return -1;
7521
if (multi->size != PyArray_SIZE(out)) {
7522
PyErr_SetString(PyExc_ValueError,
7523
"array dimensions are not "\
7524
"compatible for copy");
7529
icopyfunc = in->descr->f->copyswapn;
7530
ocopyfunc = out->descr->f->copyswapn;
7531
maxaxis = PyArray_RemoveSmallest(multi);
7532
if (maxaxis < 0) { /* cast 1 0-d array to another */
7539
maxdim = multi->dimensions[maxaxis];
7540
N = (int) (MIN(maxdim, PyArray_BUFSIZE));
7541
ostrides = multi->iters[0]->strides[maxaxis];
7542
istrides = multi->iters[1]->strides[maxaxis];
7545
buffers[0] = _pya_malloc(N*delsize);
7546
if (buffers[0] == NULL) {
7550
buffers[1] = _pya_malloc(N*selsize);
7551
if (buffers[1] == NULL) {
7552
_pya_free(buffers[0]);
7556
if (PyDataType_FLAGCHK(out->descr, NPY_NEEDS_INIT))
7557
memset(buffers[0], 0, N*delsize);
7558
if (PyDataType_FLAGCHK(in->descr, NPY_NEEDS_INIT))
7559
memset(buffers[1], 0, N*selsize);
7561
#if NPY_ALLOW_THREADS
7562
if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
7567
while(multi->index < multi->size) {
7568
_strided_buffered_cast(multi->iters[0]->dataptr,
7570
delsize, oswap, ocopyfunc,
7571
multi->iters[1]->dataptr,
7573
selsize, iswap, icopyfunc,
7576
PyArray_MultiIter_NEXT(multi);
7578
#if NPY_ALLOW_THREADS
7579
if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
7909
int delsize, selsize, maxaxis, i, N;
7910
PyArrayMultiIterObject *multi;
7911
intp maxdim, ostrides, istrides;
7913
PyArray_CopySwapNFunc *ocopyfunc, *icopyfunc;
7915
NPY_BEGIN_THREADS_DEF;
7917
delsize = PyArray_ITEMSIZE(out);
7918
selsize = PyArray_ITEMSIZE(in);
7919
multi = (PyArrayMultiIterObject *)PyArray_MultiIterNew(2, out, in);
7920
if (multi == NULL) {
7924
if (multi->size != PyArray_SIZE(out)) {
7925
PyErr_SetString(PyExc_ValueError,
7926
"array dimensions are not "\
7927
"compatible for copy");
7583
7928
Py_DECREF(multi);
7584
if (PyDataType_REFCHK(in->descr)) {
7586
for (i=0; i<N; i++, obptr+=selsize)
7587
PyArray_Item_XDECREF(obptr, out->descr);
7589
if (PyDataType_REFCHK(out->descr)) {
7591
for (i=0; i<N; i++, obptr+=delsize)
7592
PyArray_Item_XDECREF(obptr, out->descr);
7932
icopyfunc = in->descr->f->copyswapn;
7933
ocopyfunc = out->descr->f->copyswapn;
7934
maxaxis = PyArray_RemoveSmallest(multi);
7936
/* cast 1 0-d array to another */
7943
maxdim = multi->dimensions[maxaxis];
7944
N = (int) (MIN(maxdim, PyArray_BUFSIZE));
7945
ostrides = multi->iters[0]->strides[maxaxis];
7946
istrides = multi->iters[1]->strides[maxaxis];
7949
buffers[0] = _pya_malloc(N*delsize);
7950
if (buffers[0] == NULL) {
7954
buffers[1] = _pya_malloc(N*selsize);
7955
if (buffers[1] == NULL) {
7594
7956
_pya_free(buffers[0]);
7595
_pya_free(buffers[1]);
7596
if (PyErr_Occurred()) return -1;
7960
if (PyDataType_FLAGCHK(out->descr, NPY_NEEDS_INIT)) {
7961
memset(buffers[0], 0, N*delsize);
7963
if (PyDataType_FLAGCHK(in->descr, NPY_NEEDS_INIT)) {
7964
memset(buffers[1], 0, N*selsize);
7967
#if NPY_ALLOW_THREADS
7968
if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
7973
while(multi->index < multi->size) {
7974
_strided_buffered_cast(multi->iters[0]->dataptr,
7976
delsize, oswap, ocopyfunc,
7977
multi->iters[1]->dataptr,
7979
selsize, iswap, icopyfunc,
7982
PyArray_MultiIter_NEXT(multi);
7984
#if NPY_ALLOW_THREADS
7985
if (PyArray_ISNUMBER(in) && PyArray_ISNUMBER(out)) {
7990
if (PyDataType_REFCHK(in->descr)) {
7992
for(i = 0; i < N; i++, obptr+=selsize) {
7993
PyArray_Item_XDECREF(obptr, out->descr);
7996
if (PyDataType_REFCHK(out->descr)) {
7998
for(i = 0; i < N; i++, obptr+=delsize) {
7999
PyArray_Item_XDECREF(obptr, out->descr);
8002
_pya_free(buffers[0]);
8003
_pya_free(buffers[1]);
8004
if (PyErr_Occurred()) {
7602
/* Must be broadcastable.
7603
This code is very similar to PyArray_CopyInto/PyArray_MoveInto
7604
except casting is done --- PyArray_BUFSIZE is used
7605
as the size of the casting buffer.
8014
* Must be broadcastable.
8015
* This code is very similar to PyArray_CopyInto/PyArray_MoveInto
8016
* except casting is done --- PyArray_BUFSIZE is used
8017
* as the size of the casting buffer.
7609
Cast to an already created array.
8021
* Cast to an already created array.
7612
8024
PyArray_CastTo(PyArrayObject *out, PyArrayObject *mp)
7617
PyArray_VectorUnaryFunc *castfunc=NULL;
7618
int mpsize = PyArray_SIZE(mp);
8028
PyArray_VectorUnaryFunc *castfunc=NULL;
8029
int mpsize = PyArray_SIZE(mp);
8031
NPY_BEGIN_THREADS_DEF;
8036
if (!PyArray_ISWRITEABLE(out)) {
8037
PyErr_SetString(PyExc_ValueError,
8038
"output array is not writeable");
8042
castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
8043
if (castfunc == NULL) {
8047
same = PyArray_SAMESHAPE(out, mp);
8048
simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
8049
(PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
8051
#if NPY_ALLOW_THREADS
8052
if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
8056
castfunc(mp->data, out->data, mpsize, mp, out);
8058
#if NPY_ALLOW_THREADS
8059
if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
8063
if (PyErr_Occurred()) {
8070
* If the input or output is OBJECT, STRING, UNICODE, or VOID
8071
* then getitem and setitem are used for the cast
8072
* and byteswapping is handled by those methods
8074
if (PyArray_ISFLEXIBLE(mp) || PyArray_ISOBJECT(mp) || PyArray_ISOBJECT(out) ||
8075
PyArray_ISFLEXIBLE(out)) {
8079
iswap = PyArray_ISBYTESWAPPED(mp);
8080
oswap = PyArray_ISBYTESWAPPED(out);
8083
return _broadcast_cast(out, mp, castfunc, iswap, oswap);
8088
_bufferedcast(PyArrayObject *out, PyArrayObject *in,
8089
PyArray_VectorUnaryFunc *castfunc)
8091
char *inbuffer, *bptr, *optr;
8092
char *outbuffer=NULL;
8093
PyArrayIterObject *it_in=NULL, *it_out=NULL;
8094
register intp i, index;
8095
intp ncopies = PyArray_SIZE(out) / PyArray_SIZE(in);
8096
int elsize=in->descr->elsize;
8097
int nels = PyArray_BUFSIZE;
8099
int inswap, outswap=0;
8100
int obuf=!PyArray_ISCARRAY(out);
8101
int oelsize = out->descr->elsize;
8102
PyArray_CopySwapFunc *in_csn;
8103
PyArray_CopySwapFunc *out_csn;
8106
in_csn = in->descr->f->copyswap;
8107
out_csn = out->descr->f->copyswap;
8110
* If the input or output is STRING, UNICODE, or VOID
8111
* then getitem and setitem are used for the cast
8112
* and byteswapping is handled by those methods
8115
inswap = !(PyArray_ISFLEXIBLE(in) || PyArray_ISNOTSWAPPED(in));
8117
inbuffer = PyDataMem_NEW(PyArray_BUFSIZE*elsize);
8118
if (inbuffer == NULL) return -1;
8119
if (PyArray_ISOBJECT(in))
8120
memset(inbuffer, 0, PyArray_BUFSIZE*elsize);
8121
it_in = (PyArrayIterObject *)PyArray_IterNew((PyObject *)in);
8122
if (it_in == NULL) goto exit;
8125
outswap = !(PyArray_ISFLEXIBLE(out) || \
8126
PyArray_ISNOTSWAPPED(out));
8127
outbuffer = PyDataMem_NEW(PyArray_BUFSIZE*oelsize);
8128
if (outbuffer == NULL) goto exit;
8129
if (PyArray_ISOBJECT(out))
8130
memset(outbuffer, 0, PyArray_BUFSIZE*oelsize);
8132
it_out = (PyArrayIterObject *)PyArray_IterNew((PyObject *)out);
8133
if (it_out == NULL) goto exit;
8135
nels = MIN(nels, PyArray_BUFSIZE);
8138
optr = (obuf) ? outbuffer: out->data;
8142
index = it_in->size;
8143
PyArray_ITER_RESET(it_in);
8145
in_csn(bptr, it_in->dataptr, inswap, in);
8147
PyArray_ITER_NEXT(it_in);
8149
if ((el == nels) || (index == 0)) {
8150
/* buffer filled, do cast */
8152
castfunc(inbuffer, optr, el, in, out);
8155
/* Copy from outbuffer to array */
8156
for(i=0; i<el; i++) {
8157
out_csn(it_out->dataptr,
8161
PyArray_ITER_NEXT(it_out);
8166
optr += out->descr->elsize * nels;
8176
PyDataMem_FREE(inbuffer);
8177
PyDataMem_FREE(outbuffer);
8185
Cast to an already created array. Arrays don't have to be "broadcastable"
8186
Only requirement is they have the same number of elements.
8189
PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp)
8192
PyArray_VectorUnaryFunc *castfunc=NULL;
8193
int mpsize = PyArray_SIZE(mp);
8195
if (mpsize == 0) return 0;
8196
if (!PyArray_ISWRITEABLE(out)) {
8197
PyErr_SetString(PyExc_ValueError,
8198
"output array is not writeable");
8202
if (!(mpsize == PyArray_SIZE(out))) {
8203
PyErr_SetString(PyExc_ValueError,
8204
"arrays must have the same number of"
8205
" elements for the cast.");
8209
castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
8210
if (castfunc == NULL) return -1;
8213
simple = ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
8214
(PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
8217
castfunc(mp->data, out->data, mpsize, mp, out);
8221
if (PyArray_SAMESHAPE(out, mp)) {
7619
8222
int iswap, oswap;
7621
NPY_BEGIN_THREADS_DEF
7623
if (mpsize == 0) return 0;
7624
if (!PyArray_ISWRITEABLE(out)) {
7625
PyErr_SetString(PyExc_ValueError,
7626
"output array is not writeable");
7630
castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
7631
if (castfunc == NULL) return -1;
7634
same = PyArray_SAMESHAPE(out, mp);
7635
simple = same && ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
7636
(PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
7640
#if NPY_ALLOW_THREADS
7641
if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
7644
castfunc(mp->data, out->data, mpsize, mp, out);
7646
#if NPY_ALLOW_THREADS
7647
if (PyArray_ISNUMBER(mp) && PyArray_ISNUMBER(out)) {
7650
if (!PyArray_ISNUMBER(mp) && PyErr_Occurred()) return -1;
7653
/* If the input or output is STRING, UNICODE, or VOID */
7654
/* then getitem and setitem are used for the cast */
7655
/* and byteswapping is handled by those methods */
7657
8223
iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp);
7658
8224
oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out);
7660
8225
return _broadcast_cast(out, mp, castfunc, iswap, oswap);
7665
_bufferedcast(PyArrayObject *out, PyArrayObject *in,
7666
PyArray_VectorUnaryFunc *castfunc)
7668
char *inbuffer, *bptr, *optr;
7669
char *outbuffer=NULL;
7670
PyArrayIterObject *it_in=NULL, *it_out=NULL;
7671
register intp i, index;
7672
intp ncopies = PyArray_SIZE(out) / PyArray_SIZE(in);
7673
int elsize=in->descr->elsize;
7674
int nels = PyArray_BUFSIZE;
7676
int inswap, outswap=0;
7677
int obuf=!PyArray_ISCARRAY(out);
7678
int oelsize = out->descr->elsize;
7679
PyArray_CopySwapFunc *in_csn;
7680
PyArray_CopySwapFunc *out_csn;
7683
in_csn = in->descr->f->copyswap;
7684
out_csn = out->descr->f->copyswap;
7686
/* If the input or output is STRING, UNICODE, or VOID */
7687
/* then getitem and setitem are used for the cast */
7688
/* and byteswapping is handled by those methods */
7690
inswap = !(PyArray_ISFLEXIBLE(in) || PyArray_ISNOTSWAPPED(in));
7692
inbuffer = PyDataMem_NEW(PyArray_BUFSIZE*elsize);
7693
if (inbuffer == NULL) return -1;
7694
if (PyArray_ISOBJECT(in))
7695
memset(inbuffer, 0, PyArray_BUFSIZE*elsize);
7696
it_in = (PyArrayIterObject *)PyArray_IterNew((PyObject *)in);
7697
if (it_in == NULL) goto exit;
7700
outswap = !(PyArray_ISFLEXIBLE(out) || \
7701
PyArray_ISNOTSWAPPED(out));
7702
outbuffer = PyDataMem_NEW(PyArray_BUFSIZE*oelsize);
7703
if (outbuffer == NULL) goto exit;
7704
if (PyArray_ISOBJECT(out))
7705
memset(outbuffer, 0, PyArray_BUFSIZE*oelsize);
7707
it_out = (PyArrayIterObject *)PyArray_IterNew((PyObject *)out);
7708
if (it_out == NULL) goto exit;
7710
nels = MIN(nels, PyArray_BUFSIZE);
7713
optr = (obuf) ? outbuffer: out->data;
7717
index = it_in->size;
7718
PyArray_ITER_RESET(it_in);
7720
in_csn(bptr, it_in->dataptr, inswap, in);
7722
PyArray_ITER_NEXT(it_in);
7724
if ((el == nels) || (index == 0)) {
7725
/* buffer filled, do cast */
7727
castfunc(inbuffer, optr, el, in, out);
7730
/* Copy from outbuffer to array */
7731
for(i=0; i<el; i++) {
7732
out_csn(it_out->dataptr,
7736
PyArray_ITER_NEXT(it_out);
7741
optr += out->descr->elsize * nels;
7751
PyDataMem_FREE(inbuffer);
7752
PyDataMem_FREE(outbuffer);
7760
Cast to an already created array. Arrays don't have to be "broadcastable"
7761
Only requirement is they have the same number of elements.
7764
PyArray_CastAnyTo(PyArrayObject *out, PyArrayObject *mp)
7767
PyArray_VectorUnaryFunc *castfunc=NULL;
7768
int mpsize = PyArray_SIZE(mp);
7770
if (mpsize == 0) return 0;
7771
if (!PyArray_ISWRITEABLE(out)) {
7772
PyErr_SetString(PyExc_ValueError,
7773
"output array is not writeable");
7777
if (!(mpsize == PyArray_SIZE(out))) {
7778
PyErr_SetString(PyExc_ValueError,
7779
"arrays must have the same number of"
7780
" elements for the cast.");
7784
castfunc = PyArray_GetCastFunc(mp->descr, out->descr->type_num);
7785
if (castfunc == NULL) return -1;
7788
simple = ((PyArray_ISCARRAY_RO(mp) && PyArray_ISCARRAY(out)) ||
7789
(PyArray_ISFARRAY_RO(mp) && PyArray_ISFARRAY(out)));
7792
castfunc(mp->data, out->data, mpsize, mp, out);
7796
if (PyArray_SAMESHAPE(out, mp)) {
7798
iswap = PyArray_ISBYTESWAPPED(mp) && !PyArray_ISFLEXIBLE(mp);
7799
oswap = PyArray_ISBYTESWAPPED(out) && !PyArray_ISFLEXIBLE(out);
7800
return _broadcast_cast(out, mp, castfunc, iswap, oswap);
7803
return _bufferedcast(out, mp, castfunc);
8228
return _bufferedcast(out, mp, castfunc);
7811
8236
PyArray_FromArray(PyArrayObject *arr, PyArray_Descr *newtype, int flags)
7814
PyArrayObject *ret=NULL;
7818
PyArray_Descr *oldtype;
7819
char *msg = "cannot copy back to a read-only array";
7820
PyTypeObject *subtype;
7822
oldtype = PyArray_DESCR(arr);
7824
subtype = arr->ob_type;
7826
if (newtype == NULL) {newtype = oldtype; Py_INCREF(oldtype);}
8239
PyArrayObject *ret=NULL;
8243
PyArray_Descr *oldtype;
8244
char *msg = "cannot copy back to a read-only array";
8245
PyTypeObject *subtype;
8247
oldtype = PyArray_DESCR(arr);
8249
subtype = arr->ob_type;
8251
if (newtype == NULL) {
8252
newtype = oldtype; Py_INCREF(oldtype);
8254
itemsize = newtype->elsize;
8255
if (itemsize == 0) {
8256
PyArray_DESCR_REPLACE(newtype);
8257
if (newtype == NULL) {
8260
newtype->elsize = oldtype->elsize;
7827
8261
itemsize = newtype->elsize;
7828
if (itemsize == 0) {
7829
PyArray_DESCR_REPLACE(newtype);
7830
if (newtype == NULL) return NULL;
7831
newtype->elsize = oldtype->elsize;
7832
itemsize = newtype->elsize;
7835
/* Can't cast unless ndim-0 array, FORCECAST is specified
7836
or the cast is safe.
7838
if (!(flags & FORCECAST) && !PyArray_NDIM(arr)==0 &&
7839
!PyArray_CanCastTo(oldtype, newtype)) {
8264
/* Can't cast unless ndim-0 array, FORCECAST is specified
8265
or the cast is safe.
8267
if (!(flags & FORCECAST) && !PyArray_NDIM(arr)==0 &&
8268
!PyArray_CanCastTo(oldtype, newtype)) {
8270
PyErr_SetString(PyExc_TypeError,
8271
"array cannot be safely cast " \
8272
"to required type");
8276
/* Don't copy if sizes are compatible */
8277
if ((flags & ENSURECOPY) || PyArray_EquivTypes(oldtype, newtype)) {
8278
arrflags = arr->flags;
8280
copy = (flags & ENSURECOPY) || \
8281
((flags & CONTIGUOUS) && (!(arrflags & CONTIGUOUS))) \
8282
|| ((flags & ALIGNED) && (!(arrflags & ALIGNED))) \
8283
|| (arr->nd > 1 && \
8284
((flags & FORTRAN) && (!(arrflags & FORTRAN)))) \
8285
|| ((flags & WRITEABLE) && (!(arrflags & WRITEABLE)));
8288
if ((flags & UPDATEIFCOPY) && \
8289
(!PyArray_ISWRITEABLE(arr))) {
7840
8290
Py_DECREF(newtype);
7841
PyErr_SetString(PyExc_TypeError,
7842
"array cannot be safely cast " \
7843
"to required type");
7847
/* Don't copy if sizes are compatible */
7848
if ((flags & ENSURECOPY) || PyArray_EquivTypes(oldtype, newtype)) {
7849
arrflags = arr->flags;
7851
copy = (flags & ENSURECOPY) || \
7852
((flags & CONTIGUOUS) && (!(arrflags & CONTIGUOUS))) \
7853
|| ((flags & ALIGNED) && (!(arrflags & ALIGNED))) \
7854
|| (arr->nd > 1 && \
7855
((flags & FORTRAN) && (!(arrflags & FORTRAN)))) \
7856
|| ((flags & WRITEABLE) && (!(arrflags & WRITEABLE)));
7859
if ((flags & UPDATEIFCOPY) && \
7860
(!PyArray_ISWRITEABLE(arr))) {
7862
PyErr_SetString(PyExc_ValueError, msg);
7865
if ((flags & ENSUREARRAY)) {
7866
subtype = &PyArray_Type;
7868
ret = (PyArrayObject *) \
7869
PyArray_NewFromDescr(subtype, newtype,
7875
if (ret == NULL) return NULL;
7876
if (PyArray_CopyInto(ret, arr) == -1)
7877
{Py_DECREF(ret); return NULL;}
7878
if (flags & UPDATEIFCOPY) {
7879
ret->flags |= UPDATEIFCOPY;
7880
ret->base = (PyObject *)arr;
7881
PyArray_FLAGS(ret->base) &= ~WRITEABLE;
7885
/* If no copy then just increase the reference
7886
count and return the input */
7889
if ((flags & ENSUREARRAY) &&
7890
!PyArray_CheckExact(arr)) {
7891
Py_INCREF(arr->descr);
7892
ret = (PyArrayObject *) \
7893
PyArray_NewFromDescr(&PyArray_Type,
7900
if (ret == NULL) return NULL;
7901
ret->base = (PyObject *)arr;
7910
/* The desired output type is different than the input
7911
array type and copy was not specified */
8291
PyErr_SetString(PyExc_ValueError, msg);
8294
if ((flags & ENSUREARRAY)) {
8295
subtype = &PyArray_Type;
8297
ret = (PyArrayObject *) \
8298
PyArray_NewFromDescr(subtype, newtype,
8307
if (PyArray_CopyInto(ret, arr) == -1) {
8311
if (flags & UPDATEIFCOPY) {
8312
ret->flags |= UPDATEIFCOPY;
8313
ret->base = (PyObject *)arr;
8314
PyArray_FLAGS(ret->base) &= ~WRITEABLE;
8318
/* If no copy then just increase the reference
8319
count and return the input */
7913
if ((flags & UPDATEIFCOPY) && \
7914
(!PyArray_ISWRITEABLE(arr))) {
7916
PyErr_SetString(PyExc_ValueError, msg);
7919
if ((flags & ENSUREARRAY)) {
7920
subtype = &PyArray_Type;
7922
ret = (PyArrayObject *) \
7923
PyArray_NewFromDescr(subtype, newtype,
7924
arr->nd, arr->dimensions,
7928
if (ret == NULL) return NULL;
7929
if (PyArray_CastTo(ret, arr) < 0) {
7933
if (flags & UPDATEIFCOPY) {
7934
ret->flags |= UPDATEIFCOPY;
7935
ret->base = (PyObject *)arr;
7936
PyArray_FLAGS(ret->base) &= ~WRITEABLE;
7940
return (PyObject *)ret;
8322
if ((flags & ENSUREARRAY) &&
8323
!PyArray_CheckExact(arr)) {
8324
Py_INCREF(arr->descr);
8325
ret = (PyArrayObject *) \
8326
PyArray_NewFromDescr(&PyArray_Type,
8336
ret->base = (PyObject *)arr;
8345
/* The desired output type is different than the input
8346
array type and copy was not specified */
8348
if ((flags & UPDATEIFCOPY) && \
8349
(!PyArray_ISWRITEABLE(arr))) {
8351
PyErr_SetString(PyExc_ValueError, msg);
8354
if ((flags & ENSUREARRAY)) {
8355
subtype = &PyArray_Type;
8357
ret = (PyArrayObject *) \
8358
PyArray_NewFromDescr(subtype, newtype,
8359
arr->nd, arr->dimensions,
8366
if (PyArray_CastTo(ret, arr) < 0) {
8370
if (flags & UPDATEIFCOPY) {
8371
ret->flags |= UPDATEIFCOPY;
8372
ret->base = (PyObject *)arr;
8373
PyArray_FLAGS(ret->base) &= ~WRITEABLE;
8377
return (PyObject *)ret;
7943
8380
/* new reference */
7944
8381
static PyArray_Descr *
7945
8382
_array_typedescr_fromstr(char *str)
7947
PyArray_Descr *descr;
7951
char msg[] = "unsupported typestring";
7958
#define _MY_FAIL { \
7959
PyErr_SetString(PyExc_ValueError, msg); \
7964
size = atoi(str + 1);
7967
if (size == sizeof(Bool))
7968
type_num = PyArray_BOOL;
7972
if (size == sizeof(uintp))
7973
type_num = PyArray_UINTP;
7974
else if (size == sizeof(char))
7975
type_num = PyArray_UBYTE;
7976
else if (size == sizeof(short))
7977
type_num = PyArray_USHORT;
7978
else if (size == sizeof(ulong))
7979
type_num = PyArray_ULONG;
7980
else if (size == sizeof(int))
7981
type_num = PyArray_UINT;
7982
else if (size == sizeof(ulonglong))
7983
type_num = PyArray_ULONGLONG;
7987
if (size == sizeof(intp))
7988
type_num = PyArray_INTP;
7989
else if (size == sizeof(char))
7990
type_num = PyArray_BYTE;
7991
else if (size == sizeof(short))
7992
type_num = PyArray_SHORT;
7993
else if (size == sizeof(long))
7994
type_num = PyArray_LONG;
7995
else if (size == sizeof(int))
7996
type_num = PyArray_INT;
7997
else if (size == sizeof(longlong))
7998
type_num = PyArray_LONGLONG;
8002
if (size == sizeof(float))
8003
type_num = PyArray_FLOAT;
8004
else if (size == sizeof(double))
8005
type_num = PyArray_DOUBLE;
8006
else if (size == sizeof(longdouble))
8007
type_num = PyArray_LONGDOUBLE;
8011
if (size == sizeof(float)*2)
8012
type_num = PyArray_CFLOAT;
8013
else if (size == sizeof(double)*2)
8014
type_num = PyArray_CDOUBLE;
8015
else if (size == sizeof(longdouble)*2)
8016
type_num = PyArray_CLONGDOUBLE;
8020
if (size == sizeof(PyObject *))
8021
type_num = PyArray_OBJECT;
8024
case PyArray_STRINGLTR:
8025
type_num = PyArray_STRING;
8027
case PyArray_UNICODELTR:
8028
type_num = PyArray_UNICODE;
8032
type_num = PyArray_VOID;
8384
PyArray_Descr *descr;
8388
char msg[] = "unsupported typestring";
8395
#define _MY_FAIL { \
8396
PyErr_SetString(PyExc_ValueError, msg); \
8401
size = atoi(str + 1);
8404
if (size == sizeof(Bool))
8405
type_num = PyArray_BOOL;
8409
if (size == sizeof(uintp))
8410
type_num = PyArray_UINTP;
8411
else if (size == sizeof(char))
8412
type_num = PyArray_UBYTE;
8413
else if (size == sizeof(short))
8414
type_num = PyArray_USHORT;
8415
else if (size == sizeof(ulong))
8416
type_num = PyArray_ULONG;
8417
else if (size == sizeof(int))
8418
type_num = PyArray_UINT;
8419
else if (size == sizeof(ulonglong))
8420
type_num = PyArray_ULONGLONG;
8424
if (size == sizeof(intp))
8425
type_num = PyArray_INTP;
8426
else if (size == sizeof(char))
8427
type_num = PyArray_BYTE;
8428
else if (size == sizeof(short))
8429
type_num = PyArray_SHORT;
8430
else if (size == sizeof(long))
8431
type_num = PyArray_LONG;
8432
else if (size == sizeof(int))
8433
type_num = PyArray_INT;
8434
else if (size == sizeof(longlong))
8435
type_num = PyArray_LONGLONG;
8439
if (size == sizeof(float))
8440
type_num = PyArray_FLOAT;
8441
else if (size == sizeof(double))
8442
type_num = PyArray_DOUBLE;
8443
else if (size == sizeof(longdouble))
8444
type_num = PyArray_LONGDOUBLE;
8448
if (size == sizeof(float)*2)
8449
type_num = PyArray_CFLOAT;
8450
else if (size == sizeof(double)*2)
8451
type_num = PyArray_CDOUBLE;
8452
else if (size == sizeof(longdouble)*2)
8453
type_num = PyArray_CLONGDOUBLE;
8457
if (size == sizeof(PyObject *))
8458
type_num = PyArray_OBJECT;
8461
case PyArray_STRINGLTR:
8462
type_num = PyArray_STRING;
8464
case PyArray_UNICODELTR:
8465
type_num = PyArray_UNICODE;
8469
type_num = PyArray_VOID;
8038
8475
#undef _MY_FAIL
8112
8549
static PyObject *
8113
8550
PyArray_FromInterface(PyObject *input)
8115
PyObject *attr=NULL, *item=NULL;
8116
PyObject *tstr=NULL, *shape=NULL;
8117
PyObject *inter=NULL;
8118
PyObject *base=NULL;
8120
PyArray_Descr *type=NULL;
8122
Py_ssize_t buffer_len;
8124
intp dims[MAX_DIMS], strides[MAX_DIMS];
8125
int dataflags = BEHAVED;
8127
/* Get the memory from __array_data__ and __array_offset__ */
8129
/* Get the typestring -- ignore array_descr */
8130
/* Get the strides */
8132
inter = PyObject_GetAttrString(input, "__array_interface__");
8133
if (inter == NULL) {PyErr_Clear(); return Py_NotImplemented;}
8134
if (!PyDict_Check(inter)) {Py_DECREF(inter); return Py_NotImplemented;}
8136
shape = PyDict_GetItemString(inter, "shape");
8137
if (shape == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
8138
tstr = PyDict_GetItemString(inter, "typestr");
8139
if (tstr == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
8141
attr = PyDict_GetItemString(inter, "data");
8143
if ((attr == NULL) || (attr==Py_None) || (!PyTuple_Check(attr))) {
8144
if (attr && (attr != Py_None)) item=attr;
8146
res = PyObject_AsWriteBuffer(item, (void **)&data,
8150
res = PyObject_AsReadBuffer(item, (const void **)&data,
8152
if (res < 0) goto fail;
8153
dataflags &= ~WRITEABLE;
8155
attr = PyDict_GetItemString(inter, "offset");
8157
longlong num = PyLong_AsLongLong(attr);
8158
if (error_converting(num)) {
8159
PyErr_SetString(PyExc_TypeError,
8161
"must be an integer");
8552
PyObject *attr=NULL, *item=NULL;
8553
PyObject *tstr=NULL, *shape=NULL;
8554
PyObject *inter=NULL;
8555
PyObject *base=NULL;
8557
PyArray_Descr *type=NULL;
8559
Py_ssize_t buffer_len;
8561
intp dims[MAX_DIMS], strides[MAX_DIMS];
8562
int dataflags = BEHAVED;
8564
/* Get the memory from __array_data__ and __array_offset__ */
8566
/* Get the typestring -- ignore array_descr */
8567
/* Get the strides */
8569
inter = PyObject_GetAttrString(input, "__array_interface__");
8570
if (inter == NULL) {PyErr_Clear(); return Py_NotImplemented;}
8571
if (!PyDict_Check(inter)) {Py_DECREF(inter); return Py_NotImplemented;}
8573
shape = PyDict_GetItemString(inter, "shape");
8574
if (shape == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
8575
tstr = PyDict_GetItemString(inter, "typestr");
8576
if (tstr == NULL) {Py_DECREF(inter); return Py_NotImplemented;}
8578
attr = PyDict_GetItemString(inter, "data");
8580
if ((attr == NULL) || (attr==Py_None) || (!PyTuple_Check(attr))) {
8581
if (attr && (attr != Py_None)) item=attr;
8583
res = PyObject_AsWriteBuffer(item, (void **)&data,
8587
res = PyObject_AsReadBuffer(item, (const void **)&data,
8589
if (res < 0) goto fail;
8590
dataflags &= ~WRITEABLE;
8592
attr = PyDict_GetItemString(inter, "offset");
8594
longlong num = PyLong_AsLongLong(attr);
8595
if (error_converting(num)) {
8596
PyErr_SetString(PyExc_TypeError,
8598
"must be an integer");
8607
if (PyTuple_GET_SIZE(attr) != 2) {
8608
PyErr_SetString(PyExc_TypeError,
8609
"data must return " \
8610
"a 2-tuple with (data pointer "\
8611
"integer, read-only flag)");
8614
dataptr = PyTuple_GET_ITEM(attr, 0);
8615
if (PyString_Check(dataptr)) {
8616
res = sscanf(PyString_AsString(dataptr),
8617
"%p", (void **)&data);
8619
PyErr_SetString(PyExc_TypeError,
8620
"data string cannot be " \
8625
else if (PyIntOrLong_Check(dataptr)) {
8626
data = PyLong_AsVoidPtr(dataptr);
8170
if (PyTuple_GET_SIZE(attr) != 2) {
8171
PyErr_SetString(PyExc_TypeError,
8172
"data must return " \
8173
"a 2-tuple with (data pointer "\
8174
"integer, read-only flag)");
8177
dataptr = PyTuple_GET_ITEM(attr, 0);
8178
if (PyString_Check(dataptr)) {
8179
res = sscanf(PyString_AsString(dataptr),
8180
"%p", (void **)&data);
8182
PyErr_SetString(PyExc_TypeError,
8183
"data string cannot be " \
8188
else if (PyIntOrLong_Check(dataptr)) {
8189
data = PyLong_AsVoidPtr(dataptr);
8192
PyErr_SetString(PyExc_TypeError, "first element " \
8193
"of data tuple must be integer" \
8197
if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) {
8198
dataflags &= ~WRITEABLE;
8202
if (!PyString_Check(attr)) {
8203
PyErr_SetString(PyExc_TypeError, "typestr must be a string");
8206
type = _array_typedescr_fromstr(PyString_AS_STRING(attr));
8207
if (type==NULL) goto fail;
8629
PyErr_SetString(PyExc_TypeError, "first element " \
8630
"of data tuple must be integer" \
8634
if (PyObject_IsTrue(PyTuple_GET_ITEM(attr,1))) {
8635
dataflags &= ~WRITEABLE;
8639
if (!PyString_Check(attr)) {
8640
PyErr_SetString(PyExc_TypeError, "typestr must be a string");
8643
type = _array_typedescr_fromstr(PyString_AS_STRING(attr));
8644
if (type==NULL) goto fail;
8646
if (!PyTuple_Check(attr)) {
8647
PyErr_SetString(PyExc_TypeError, "shape must be a tuple");
8651
n = PyTuple_GET_SIZE(attr);
8652
for(i=0; i<n; i++) {
8653
item = PyTuple_GET_ITEM(attr, i);
8654
dims[i] = PyArray_PyIntAsIntp(item);
8655
if (error_converting(dims[i])) break;
8658
ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type,
8662
if (ret == NULL) return NULL;
8666
attr = PyDict_GetItemString(inter, "strides");
8667
if (attr != NULL && attr != Py_None) {
8209
8668
if (!PyTuple_Check(attr)) {
8210
PyErr_SetString(PyExc_TypeError, "shape must be a tuple");
8214
n = PyTuple_GET_SIZE(attr);
8215
for (i=0; i<n; i++) {
8216
item = PyTuple_GET_ITEM(attr, i);
8217
dims[i] = PyArray_PyIntAsIntp(item);
8218
if (error_converting(dims[i])) break;
8221
ret = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type, type,
8225
if (ret == NULL) return NULL;
8229
attr = PyDict_GetItemString(inter, "strides");
8230
if (attr != NULL && attr != Py_None) {
8231
if (!PyTuple_Check(attr)) {
8232
PyErr_SetString(PyExc_TypeError,
8233
"strides must be a tuple");
8237
if (n != PyTuple_GET_SIZE(attr)) {
8238
PyErr_SetString(PyExc_ValueError,
8239
"mismatch in length of "\
8240
"strides and shape");
8244
for (i=0; i<n; i++) {
8245
item = PyTuple_GET_ITEM(attr, i);
8246
strides[i] = PyArray_PyIntAsIntp(item);
8247
if (error_converting(strides[i])) break;
8249
if (PyErr_Occurred()) PyErr_Clear();
8250
memcpy(ret->strides, strides, n*sizeof(intp));
8253
PyArray_UpdateFlags(ret, UPDATE_ALL);
8255
return (PyObject *)ret;
8669
PyErr_SetString(PyExc_TypeError,
8670
"strides must be a tuple");
8674
if (n != PyTuple_GET_SIZE(attr)) {
8675
PyErr_SetString(PyExc_ValueError,
8676
"mismatch in length of "\
8677
"strides and shape");
8681
for(i=0; i<n; i++) {
8682
item = PyTuple_GET_ITEM(attr, i);
8683
strides[i] = PyArray_PyIntAsIntp(item);
8684
if (error_converting(strides[i])) break;
8686
if (PyErr_Occurred()) PyErr_Clear();
8687
memcpy(ret->strides, strides, n*sizeof(intp));
8690
PyArray_UpdateFlags(ret, UPDATE_ALL);
8692
return (PyObject *)ret;
8263
8700
static PyObject *
8264
8701
PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *typecode, PyObject *context)
8267
PyObject *array_meth;
8704
PyObject *array_meth;
8269
array_meth = PyObject_GetAttrString(op, "__array__");
8270
if (array_meth == NULL) {PyErr_Clear(); return Py_NotImplemented;}
8271
if (context == NULL) {
8272
if (typecode == NULL) new = PyObject_CallFunction(array_meth,
8274
else new = PyObject_CallFunction(array_meth, "O", typecode);
8706
array_meth = PyObject_GetAttrString(op, "__array__");
8707
if (array_meth == NULL) {PyErr_Clear(); return Py_NotImplemented;}
8708
if (context == NULL) {
8709
if (typecode == NULL) new = PyObject_CallFunction(array_meth,
8711
else new = PyObject_CallFunction(array_meth, "O", typecode);
8714
if (typecode == NULL) {
8715
new = PyObject_CallFunction(array_meth, "OO", Py_None,
8717
if (new == NULL && \
8718
PyErr_ExceptionMatches(PyExc_TypeError)) {
8720
new = PyObject_CallFunction(array_meth, "");
8277
if (typecode == NULL) {
8278
new = PyObject_CallFunction(array_meth, "OO", Py_None,
8280
if (new == NULL && \
8281
PyErr_ExceptionMatches(PyExc_TypeError)) {
8283
new = PyObject_CallFunction(array_meth, "");
8287
new = PyObject_CallFunction(array_meth, "OO",
8289
if (new == NULL && \
8290
PyErr_ExceptionMatches(PyExc_TypeError)) {
8292
new = PyObject_CallFunction(array_meth, "O",
8297
Py_DECREF(array_meth);
8298
if (new == NULL) return NULL;
8299
if (!PyArray_Check(new)) {
8300
PyErr_SetString(PyExc_ValueError,
8301
"object __array__ method not " \
8302
"producing an array");
8724
new = PyObject_CallFunction(array_meth, "OO",
8726
if (new == NULL && \
8727
PyErr_ExceptionMatches(PyExc_TypeError)) {
8729
new = PyObject_CallFunction(array_meth, "O",
8734
Py_DECREF(array_meth);
8735
if (new == NULL) return NULL;
8736
if (!PyArray_Check(new)) {
8737
PyErr_SetString(PyExc_ValueError,
8738
"object __array__ method not " \
8739
"producing an array");
8309
8746
/* Does not check for ENSURECOPY and NOTSWAPPED in flags */
8313
8750
PyArray_FromAny(PyObject *op, PyArray_Descr *newtype, int min_depth,
8314
8751
int max_depth, int flags, PyObject *context)
8316
/* This is the main code to make a NumPy array from a Python
8317
Object. It is called from lot's of different places which
8318
is why there are so many checks. The comments try to
8319
explain some of the checks. */
8324
/* Is input object already an array? */
8325
/* This is where the flags are used */
8326
if (PyArray_Check(op))
8327
r = PyArray_FromArray((PyArrayObject *)op, newtype, flags);
8328
else if (PyArray_IsScalar(op, Generic)) {
8329
if (flags & UPDATEIFCOPY) goto err;
8330
r = PyArray_FromScalar(op, newtype);
8331
} else if (newtype == NULL &&
8332
(newtype = _array_find_python_scalar_type(op))) {
8333
if (flags & UPDATEIFCOPY) goto err;
8753
/* This is the main code to make a NumPy array from a Python
8754
Object. It is called from lot's of different places which
8755
is why there are so many checks. The comments try to
8756
explain some of the checks. */
8761
/* Is input object already an array? */
8762
/* This is where the flags are used */
8763
if (PyArray_Check(op)) {
8764
r = PyArray_FromArray((PyArrayObject *)op, newtype, flags);
8766
else if (PyArray_IsScalar(op, Generic)) {
8767
if (flags & UPDATEIFCOPY) {
8770
r = PyArray_FromScalar(op, newtype);
8772
else if (newtype == NULL &&
8773
(newtype = _array_find_python_scalar_type(op))) {
8774
if (flags & UPDATEIFCOPY) {
8777
r = Array_FromPyScalar(op, newtype);
8779
else if (PyArray_HasArrayInterfaceType(op, newtype, context, r)) {
8782
Py_XDECREF(newtype);
8785
if (newtype != NULL || flags != 0) {
8786
new = PyArray_FromArray((PyArrayObject *)r, newtype,
8795
if (flags & UPDATEIFCOPY) {
8798
if (newtype == NULL) {
8799
newtype = _array_find_type(op, NULL, MAX_DIMS);
8801
else if (newtype->type_num == PyArray_OBJECT) {
8804
if (!PyString_Check(op) && PySequence_Check(op)) {
8805
PyObject *thiserr = NULL;
8807
/* necessary but not sufficient */
8809
r = Array_FromSequence(op, newtype, flags & FORTRAN,
8810
min_depth, max_depth);
8811
if (r == NULL && (thiserr=PyErr_Occurred())) {
8812
if (PyErr_GivenExceptionMatches(thiserr,
8813
PyExc_MemoryError)) {
8817
* If object was explicitly requested,
8818
* then try nested list object array creation
8823
r = ObjectArray_FromNestedList \
8824
(op, newtype, flags & FORTRAN);
8334
8835
r = Array_FromPyScalar(op, newtype);
8336
else if (PyArray_HasArrayInterfaceType(op, newtype, context, r)) {
8338
if (r == NULL) {Py_XDECREF(newtype); return NULL;}
8339
if (newtype != NULL || flags != 0) {
8340
new = PyArray_FromArray((PyArrayObject *)r, newtype,
8348
if (flags & UPDATEIFCOPY) goto err;
8349
if (newtype == NULL) {
8350
newtype = _array_find_type(op, NULL, MAX_DIMS);
8352
else if (newtype->type_num == PyArray_OBJECT) {
8355
if (PySequence_Check(op)) {
8356
PyObject *thiserr=NULL;
8357
/* necessary but not sufficient */
8359
r = Array_FromSequence(op, newtype, flags & FORTRAN,
8360
min_depth, max_depth);
8361
if (r == NULL && (thiserr=PyErr_Occurred())) {
8362
if (PyErr_GivenExceptionMatches(thiserr,
8365
/* If object was explicitly requested,
8366
then try nested list object array creation
8371
r = ObjectArray_FromNestedList \
8372
(op, newtype, flags & FORTRAN);
8383
r = Array_FromPyScalar(op, newtype);
8386
/* If we didn't succeed return NULL */
8387
if (r == NULL) return NULL;
8389
/* Be sure we succeed here */
8391
if(!PyArray_Check(r)) {
8392
PyErr_SetString(PyExc_RuntimeError,
8393
"internal error: PyArray_FromAny "\
8394
"not producing an array");
8399
if (min_depth != 0 && ((PyArrayObject *)r)->nd < min_depth) {
8400
PyErr_SetString(PyExc_ValueError,
8401
"object of too small depth for desired array");
8405
if (max_depth != 0 && ((PyArrayObject *)r)->nd > max_depth) {
8406
PyErr_SetString(PyExc_ValueError,
8407
"object too deep for desired array");
8839
/* If we didn't succeed return NULL */
8844
/* Be sure we succeed here */
8846
if(!PyArray_Check(r)) {
8847
PyErr_SetString(PyExc_RuntimeError,
8848
"internal error: PyArray_FromAny "\
8849
"not producing an array");
8854
if (min_depth != 0 && ((PyArrayObject *)r)->nd < min_depth) {
8855
PyErr_SetString(PyExc_ValueError,
8856
"object of too small depth for desired array");
8860
if (max_depth != 0 && ((PyArrayObject *)r)->nd > max_depth) {
8861
PyErr_SetString(PyExc_ValueError,
8862
"object too deep for desired array");
8414
Py_XDECREF(newtype);
8415
PyErr_SetString(PyExc_TypeError,
8416
"UPDATEIFCOPY used for non-array input.");
8869
Py_XDECREF(newtype);
8870
PyErr_SetString(PyExc_TypeError,
8871
"UPDATEIFCOPY used for non-array input.");
8420
8875
/* new reference -- accepts NULL for mintype*/
8533
8988
static PyObject *
8534
8989
PyArray_EnsureArray(PyObject *op)
8538
if (op == NULL) return NULL;
8540
if (PyArray_CheckExact(op)) return op;
8542
if (PyArray_Check(op)) {
8543
new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type);
8547
if (PyArray_IsScalar(op, Generic)) {
8548
new = PyArray_FromScalar(op, NULL);
8552
new = PyArray_FromAny(op, NULL, 0, 0, ENSUREARRAY, NULL);
8993
if (op == NULL) return NULL;
8995
if (PyArray_CheckExact(op)) return op;
8997
if (PyArray_Check(op)) {
8998
new = PyArray_View((PyArrayObject *)op, NULL, &PyArray_Type);
9002
if (PyArray_IsScalar(op, Generic)) {
9003
new = PyArray_FromScalar(op, NULL);
9007
new = PyArray_FromAny(op, NULL, 0, 0, ENSUREARRAY, NULL);
8558
9013
static PyObject *
8559
9014
PyArray_EnsureAnyArray(PyObject *op)
8561
if (op && PyArray_Check(op)) return op;
8562
return PyArray_EnsureArray(op);
9016
if (op && PyArray_Check(op)) return op;
9017
return PyArray_EnsureArray(op);
8566
Check the type coercion rules.
9021
Check the type coercion rules.
8569
9024
PyArray_CanCastSafely(int fromtype, int totype)
8571
PyArray_Descr *from, *to;
8572
register int felsize, telsize;
8574
if (fromtype == totype) return 1;
8575
if (fromtype == PyArray_BOOL) return 1;
8576
if (totype == PyArray_BOOL) return 0;
8577
if (totype == PyArray_OBJECT || totype == PyArray_VOID) return 1;
8578
if (fromtype == PyArray_OBJECT || fromtype == PyArray_VOID) return 0;
8580
from = PyArray_DescrFromType(fromtype);
8581
/* cancastto is a PyArray_NOTYPE terminated C-int-array of types that
8582
the data-type can be cast to safely.
8584
if (from->f->cancastto) {
8586
curtype = from->f->cancastto;
8587
while (*curtype != PyArray_NOTYPE) {
8588
if (*curtype++ == totype) return 1;
9026
PyArray_Descr *from, *to;
9027
register int felsize, telsize;
9029
if (fromtype == totype) return 1;
9030
if (fromtype == PyArray_BOOL) return 1;
9031
if (totype == PyArray_BOOL) return 0;
9032
if (totype == PyArray_OBJECT || totype == PyArray_VOID) return 1;
9033
if (fromtype == PyArray_OBJECT || fromtype == PyArray_VOID) return 0;
9035
from = PyArray_DescrFromType(fromtype);
9036
/* cancastto is a PyArray_NOTYPE terminated C-int-array of types that
9037
the data-type can be cast to safely.
9039
if (from->f->cancastto) {
9041
curtype = from->f->cancastto;
9042
while (*curtype != PyArray_NOTYPE) {
9043
if (*curtype++ == totype) return 1;
8591
if (PyTypeNum_ISUSERDEF(totype)) return 0;
8593
to = PyArray_DescrFromType(totype);
8594
telsize = to->elsize;
8595
felsize = from->elsize;
8604
case PyArray_LONGLONG:
8605
if (PyTypeNum_ISINTEGER(totype)) {
8606
if (PyTypeNum_ISUNSIGNED(totype)) {
8610
return (telsize >= felsize);
8613
else if (PyTypeNum_ISFLOAT(totype)) {
8615
return (telsize > felsize);
8617
return (telsize >= felsize);
8619
else if (PyTypeNum_ISCOMPLEX(totype)) {
8621
return ((telsize >> 1) > felsize);
8623
return ((telsize >> 1) >= felsize);
8625
else return totype > fromtype;
8627
case PyArray_USHORT:
8630
case PyArray_ULONGLONG:
8631
if (PyTypeNum_ISINTEGER(totype)) {
8632
if (PyTypeNum_ISSIGNED(totype)) {
8633
return (telsize > felsize);
8636
return (telsize >= felsize);
8639
else if (PyTypeNum_ISFLOAT(totype)) {
8641
return (telsize > felsize);
8643
return (telsize >= felsize);
8645
else if (PyTypeNum_ISCOMPLEX(totype)) {
8647
return ((telsize >> 1) > felsize);
8649
return ((telsize >> 1) >= felsize);
8651
else return totype > fromtype;
8653
case PyArray_DOUBLE:
8654
case PyArray_LONGDOUBLE:
8655
if (PyTypeNum_ISCOMPLEX(totype))
8656
return ((telsize >> 1) >= felsize);
8658
return (totype > fromtype);
8659
case PyArray_CFLOAT:
8660
case PyArray_CDOUBLE:
8661
case PyArray_CLONGDOUBLE:
8662
return (totype > fromtype);
8663
case PyArray_STRING:
8664
case PyArray_UNICODE:
8665
return (totype > fromtype);
9046
if (PyTypeNum_ISUSERDEF(totype)) return 0;
9048
to = PyArray_DescrFromType(totype);
9049
telsize = to->elsize;
9050
felsize = from->elsize;
9059
case PyArray_LONGLONG:
9060
if (PyTypeNum_ISINTEGER(totype)) {
9061
if (PyTypeNum_ISUNSIGNED(totype)) {
9065
return (telsize >= felsize);
9068
else if (PyTypeNum_ISFLOAT(totype)) {
9070
return (telsize > felsize);
9072
return (telsize >= felsize);
9074
else if (PyTypeNum_ISCOMPLEX(totype)) {
9076
return ((telsize >> 1) > felsize);
9078
return ((telsize >> 1) >= felsize);
9080
else return totype > fromtype;
9082
case PyArray_USHORT:
9085
case PyArray_ULONGLONG:
9086
if (PyTypeNum_ISINTEGER(totype)) {
9087
if (PyTypeNum_ISSIGNED(totype)) {
9088
return (telsize > felsize);
9091
return (telsize >= felsize);
9094
else if (PyTypeNum_ISFLOAT(totype)) {
9096
return (telsize > felsize);
9098
return (telsize >= felsize);
9100
else if (PyTypeNum_ISCOMPLEX(totype)) {
9102
return ((telsize >> 1) > felsize);
9104
return ((telsize >> 1) >= felsize);
9106
else return totype > fromtype;
9108
case PyArray_DOUBLE:
9109
case PyArray_LONGDOUBLE:
9110
if (PyTypeNum_ISCOMPLEX(totype))
9111
return ((telsize >> 1) >= felsize);
9113
return (totype > fromtype);
9114
case PyArray_CFLOAT:
9115
case PyArray_CDOUBLE:
9116
case PyArray_CLONGDOUBLE:
9117
return (totype > fromtype);
9118
case PyArray_STRING:
9119
case PyArray_UNICODE:
9120
return (totype > fromtype);
8671
9126
/* leaves reference count alone --- cannot be NULL*/
8935
9390
static PyObject *
8936
9391
arrayiter_next(PyArrayIterObject *it)
8940
if (it->index < it->size) {
8941
ret = PyArray_ToScalar(it->dataptr, it->ao);
8942
PyArray_ITER_NEXT(it);
9395
if (it->index < it->size) {
9396
ret = PyArray_ToScalar(it->dataptr, it->ao);
9397
PyArray_ITER_NEXT(it);
8949
9404
arrayiter_dealloc(PyArrayIterObject *it)
8955
9410
static Py_ssize_t
8956
9411
iter_length(PyArrayIterObject *self)
8962
9417
static PyObject *
8963
9418
iter_subscript_Bool(PyArrayIterObject *self, PyArrayObject *ind)
8965
int index, strides, itemsize;
8970
PyArray_CopySwapFunc *copyswap;
8974
PyErr_SetString(PyExc_ValueError,
8975
"boolean index array should have 1 dimension");
8978
index = ind->dimensions[0];
8979
if (index > self->size) {
8980
PyErr_SetString(PyExc_ValueError,
8981
"too many boolean indices");
8985
strides = ind->strides[0];
8987
/* Get size of return array */
8989
if (*((Bool *)dptr) != 0)
8993
itemsize = self->ao->descr->elsize;
9420
int index, strides, itemsize;
9425
PyArray_CopySwapFunc *copyswap;
9429
PyErr_SetString(PyExc_ValueError,
9430
"boolean index array should have 1 dimension");
9433
index = ind->dimensions[0];
9434
if (index > self->size) {
9435
PyErr_SetString(PyExc_ValueError,
9436
"too many boolean indices");
9440
strides = ind->strides[0];
9442
/* Get size of return array */
9444
if (*((Bool *)dptr) != 0)
9448
itemsize = self->ao->descr->elsize;
9449
Py_INCREF(self->ao->descr);
9450
r = PyArray_NewFromDescr(self->ao->ob_type,
9451
self->ao->descr, 1, &count,
9453
0, (PyObject *)self->ao);
9454
if (r==NULL) return NULL;
9457
optr = PyArray_DATA(r);
9458
index = ind->dimensions[0];
9461
copyswap = self->ao->descr->f->copyswap;
9462
/* Loop over Boolean array */
9463
swap = (PyArray_ISNOTSWAPPED(self->ao) != PyArray_ISNOTSWAPPED(r));
9465
if (*((Bool *)dptr) != 0) {
9466
copyswap(optr, self->dataptr, swap, self->ao);
9470
PyArray_ITER_NEXT(self);
9472
PyArray_ITER_RESET(self);
9477
iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind)
9481
PyArrayIterObject *ind_it;
9486
PyArray_CopySwapFunc *copyswap;
9488
itemsize = self->ao->descr->elsize;
9490
num = *((intp *)ind->data);
9491
if (num < 0) num += self->size;
9492
if (num < 0 || num >= self->size) {
9493
PyErr_Format(PyExc_IndexError,
9494
"index %d out of bounds" \
9495
" 0<=index<%d", (int) num,
9500
PyArray_ITER_GOTO1D(self, num);
9501
r = PyArray_ToScalar(self->dataptr, self->ao);
9503
PyArray_ITER_RESET(self);
9507
Py_INCREF(self->ao->descr);
9508
r = PyArray_NewFromDescr(self->ao->ob_type, self->ao->descr,
9509
ind->nd, ind->dimensions,
9511
0, (PyObject *)self->ao);
9512
if (r==NULL) return NULL;
9514
optr = PyArray_DATA(r);
9515
ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
9516
if (ind_it == NULL) {Py_DECREF(r); return NULL;}
9517
index = ind_it->size;
9518
copyswap = PyArray_DESCR(r)->f->copyswap;
9519
swap = (PyArray_ISNOTSWAPPED(r) != PyArray_ISNOTSWAPPED(self->ao));
9521
num = *((intp *)(ind_it->dataptr));
9522
if (num < 0) num += self->size;
9523
if (num < 0 || num >= self->size) {
9524
PyErr_Format(PyExc_IndexError,
9525
"index %d out of bounds" \
9526
" 0<=index<%d", (int) num,
9530
PyArray_ITER_RESET(self);
9533
PyArray_ITER_GOTO1D(self, num);
9534
copyswap(optr, self->dataptr, swap, r);
9536
PyArray_ITER_NEXT(ind_it);
9539
PyArray_ITER_RESET(self);
9545
iter_subscript(PyArrayIterObject *self, PyObject *ind)
9547
PyArray_Descr *indtype=NULL;
9548
intp start, step_size;
9553
PyObject *obj = NULL;
9554
PyArray_CopySwapFunc *copyswap;
9556
if (ind == Py_Ellipsis) {
9557
ind = PySlice_New(NULL, NULL, NULL);
9558
obj = iter_subscript(self, ind);
9562
if (PyTuple_Check(ind)) {
9564
len = PyTuple_GET_SIZE(ind);
9565
if (len > 1) goto fail;
9567
Py_INCREF(self->ao);
9568
return (PyObject *)self->ao;
9570
ind = PyTuple_GET_ITEM(ind, 0);
9573
/* Tuples >1d not accepted --- i.e. no newaxis */
9574
/* Could implement this with adjusted strides
9575
and dimensions in iterator */
9577
/* Check for Boolean -- this is first becasue
9578
Bool is a subclass of Int */
9579
PyArray_ITER_RESET(self);
9581
if (PyBool_Check(ind)) {
9582
if (PyObject_IsTrue(ind)) {
9583
return PyArray_ToScalar(self->dataptr, self->ao);
9585
else { /* empty array */
9587
Py_INCREF(self->ao->descr);
9588
r = PyArray_NewFromDescr(self->ao->ob_type,
9592
(PyObject *)self->ao);
9597
/* Check for Integer or Slice */
9599
if (PyLong_Check(ind) || PyInt_Check(ind) || PySlice_Check(ind)) {
9600
start = parse_subindex(ind, &step_size, &n_steps,
9604
if (n_steps == RubberIndex || n_steps == PseudoIndex) {
9605
PyErr_SetString(PyExc_IndexError,
9606
"cannot use Ellipsis or newaxes here");
9609
PyArray_ITER_GOTO1D(self, start)
9610
if (n_steps == SingleIndex) { /* Integer */
9611
r = PyArray_ToScalar(self->dataptr, self->ao);
9612
PyArray_ITER_RESET(self);
9615
size = self->ao->descr->elsize;
8994
9616
Py_INCREF(self->ao->descr);
8995
9617
r = PyArray_NewFromDescr(self->ao->ob_type,
8996
self->ao->descr, 1, &count,
8998
0, (PyObject *)self->ao);
8999
if (r==NULL) return NULL;
9002
optr = PyArray_DATA(r);
9003
index = ind->dimensions[0];
9006
copyswap = self->ao->descr->f->copyswap;
9007
/* Loop over Boolean array */
9008
swap = (PyArray_ISNOTSWAPPED(self->ao) != PyArray_ISNOTSWAPPED(r));
9010
if (*((Bool *)dptr) != 0) {
9011
copyswap(optr, self->dataptr, swap, self->ao);
9015
PyArray_ITER_NEXT(self);
9017
PyArray_ITER_RESET(self);
9022
iter_subscript_int(PyArrayIterObject *self, PyArrayObject *ind)
9026
PyArrayIterObject *ind_it;
9031
PyArray_CopySwapFunc *copyswap;
9033
itemsize = self->ao->descr->elsize;
9035
num = *((intp *)ind->data);
9036
if (num < 0) num += self->size;
9037
if (num < 0 || num >= self->size) {
9038
PyErr_Format(PyExc_IndexError,
9039
"index %d out of bounds" \
9040
" 0<=index<%d", (int) num,
9045
PyArray_ITER_GOTO1D(self, num);
9046
r = PyArray_ToScalar(self->dataptr, self->ao);
9048
PyArray_ITER_RESET(self);
9052
Py_INCREF(self->ao->descr);
9053
r = PyArray_NewFromDescr(self->ao->ob_type, self->ao->descr,
9054
ind->nd, ind->dimensions,
9056
0, (PyObject *)self->ao);
9057
if (r==NULL) return NULL;
9059
optr = PyArray_DATA(r);
9060
ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
9061
if (ind_it == NULL) {Py_DECREF(r); return NULL;}
9062
index = ind_it->size;
9621
0, (PyObject *)self->ao);
9622
if (r==NULL) goto fail;
9623
dptr = PyArray_DATA(r);
9063
9624
copyswap = PyArray_DESCR(r)->f->copyswap;
9064
swap = (PyArray_ISNOTSWAPPED(r) != PyArray_ISNOTSWAPPED(self->ao));
9066
num = *((intp *)(ind_it->dataptr));
9067
if (num < 0) num += self->size;
9068
if (num < 0 || num >= self->size) {
9069
PyErr_Format(PyExc_IndexError,
9070
"index %d out of bounds" \
9071
" 0<=index<%d", (int) num,
9075
PyArray_ITER_RESET(self);
9078
PyArray_ITER_GOTO1D(self, num);
9079
copyswap(optr, self->dataptr, swap, r);
9081
PyArray_ITER_NEXT(ind_it);
9626
copyswap(dptr, self->dataptr, 0, r);
9628
PyArray_ITER_GOTO1D(self, start)
9084
9631
PyArray_ITER_RESET(self);
9090
iter_subscript(PyArrayIterObject *self, PyObject *ind)
9092
PyArray_Descr *indtype=NULL;
9093
intp start, step_size;
9098
PyObject *obj = NULL;
9100
PyArray_CopySwapFunc *copyswap;
9102
if (ind == Py_Ellipsis) {
9103
ind = PySlice_New(NULL, NULL, NULL);
9104
obj = iter_subscript(self, ind);
9108
if (PyTuple_Check(ind)) {
9110
len = PyTuple_GET_SIZE(ind);
9111
if (len > 1) goto fail;
9113
Py_INCREF(self->ao);
9114
return (PyObject *)self->ao;
9116
ind = PyTuple_GET_ITEM(ind, 0);
9119
/* Tuples >1d not accepted --- i.e. no newaxis */
9120
/* Could implement this with adjusted strides
9121
and dimensions in iterator */
9123
/* Check for Boolean -- this is first becasue
9124
Bool is a subclass of Int */
9125
PyArray_ITER_RESET(self);
9127
if (PyBool_Check(ind)) {
9128
if (PyObject_IsTrue(ind)) {
9129
return PyArray_ToScalar(self->dataptr, self->ao);
9131
else { /* empty array */
9133
Py_INCREF(self->ao->descr);
9134
r = PyArray_NewFromDescr(self->ao->ob_type,
9138
(PyObject *)self->ao);
9143
/* Check for Integer or Slice */
9145
if (PyLong_Check(ind) || PyInt_Check(ind) || PySlice_Check(ind)) {
9146
start = parse_subindex(ind, &step_size, &n_steps,
9150
if (n_steps == RubberIndex || n_steps == PseudoIndex) {
9151
PyErr_SetString(PyExc_IndexError,
9152
"cannot use Ellipsis or newaxes here");
9155
PyArray_ITER_GOTO1D(self, start)
9156
if (n_steps == SingleIndex) { /* Integer */
9157
r = PyArray_ToScalar(self->dataptr, self->ao);
9158
PyArray_ITER_RESET(self);
9161
size = self->ao->descr->elsize;
9162
Py_INCREF(self->ao->descr);
9163
r = PyArray_NewFromDescr(self->ao->ob_type,
9167
0, (PyObject *)self->ao);
9168
if (r==NULL) goto fail;
9169
dptr = PyArray_DATA(r);
9170
swap = !PyArray_ISNOTSWAPPED(self->ao);
9171
copyswap = PyArray_DESCR(r)->f->copyswap;
9173
copyswap(dptr, self->dataptr, swap, r);
9175
PyArray_ITER_GOTO1D(self, start)
9178
PyArray_ITER_RESET(self);
9182
/* convert to INTP array if Integer array scalar or List */
9184
indtype = PyArray_DescrFromType(PyArray_INTP);
9185
if (PyArray_IsScalar(ind, Integer) || PyList_Check(ind)) {
9187
obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
9188
if (obj == NULL) goto fail;
9635
/* convert to INTP array if Integer array scalar or List */
9637
indtype = PyArray_DescrFromType(PyArray_INTP);
9638
if (PyArray_IsScalar(ind, Integer) || PyList_Check(ind)) {
9640
obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
9641
if (obj == NULL) goto fail;
9648
if (PyArray_Check(obj)) {
9649
/* Check for Boolean object */
9650
if (PyArray_TYPE(obj)==PyArray_BOOL) {
9651
r = iter_subscript_Bool(self, (PyArrayObject *)obj);
9654
/* Check for integer array */
9655
else if (PyArray_ISINTEGER(obj)) {
9657
new = PyArray_FromAny(obj, indtype, 0, 0,
9658
FORCECAST | ALIGNED, NULL);
9659
if (new==NULL) goto fail;
9662
r = iter_subscript_int(self, (PyArrayObject *)obj);
9195
if (PyArray_Check(obj)) {
9196
/* Check for Boolean object */
9197
if (PyArray_TYPE(obj)==PyArray_BOOL) {
9198
r = iter_subscript_Bool(self, (PyArrayObject *)obj);
9201
/* Check for integer array */
9202
else if (PyArray_ISINTEGER(obj)) {
9204
new = PyArray_FromAny(obj, indtype, 0, 0,
9205
FORCECAST | ALIGNED, NULL);
9206
if (new==NULL) goto fail;
9209
r = iter_subscript_int(self, (PyArrayObject *)obj);
9217
else Py_DECREF(indtype);
9670
else Py_DECREF(indtype);
9221
if (!PyErr_Occurred())
9222
PyErr_SetString(PyExc_IndexError, "unsupported iterator index");
9223
Py_XDECREF(indtype);
9674
if (!PyErr_Occurred())
9675
PyErr_SetString(PyExc_IndexError, "unsupported iterator index");
9676
Py_XDECREF(indtype);
9231
9684
iter_ass_sub_Bool(PyArrayIterObject *self, PyArrayObject *ind,
9232
9685
PyArrayIterObject *val, int swap)
9236
PyArray_CopySwapFunc *copyswap;
9239
PyErr_SetString(PyExc_ValueError,
9240
"boolean index array should have 1 dimension");
9243
index = ind->dimensions[0];
9244
strides = ind->strides[0];
9246
PyArray_ITER_RESET(self);
9247
/* Loop over Boolean array */
9248
copyswap = self->ao->descr->f->copyswap;
9250
if (*((Bool *)dptr) != 0) {
9251
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9252
PyArray_ITER_NEXT(val);
9253
if (val->index==val->size)
9254
PyArray_ITER_RESET(val);
9257
PyArray_ITER_NEXT(self);
9259
PyArray_ITER_RESET(self);
9689
PyArray_CopySwapFunc *copyswap;
9692
PyErr_SetString(PyExc_ValueError,
9693
"boolean index array should have 1 dimension");
9697
index = ind->dimensions[0];
9698
if (index > self->size) {
9699
PyErr_SetString(PyExc_ValueError,
9700
"boolean index array has too many values");
9704
strides = ind->strides[0];
9706
PyArray_ITER_RESET(self);
9707
/* Loop over Boolean array */
9708
copyswap = self->ao->descr->f->copyswap;
9710
if (*((Bool *)dptr) != 0) {
9711
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9712
PyArray_ITER_NEXT(val);
9713
if (val->index==val->size)
9714
PyArray_ITER_RESET(val);
9717
PyArray_ITER_NEXT(self);
9719
PyArray_ITER_RESET(self);
9264
9724
iter_ass_sub_int(PyArrayIterObject *self, PyArrayObject *ind,
9265
PyArrayIterObject *val, int swap)
9725
PyArrayIterObject *val, int swap)
9267
PyArray_Descr *typecode;
9269
PyArrayIterObject *ind_it;
9271
PyArray_CopySwapFunc *copyswap;
9727
PyArray_Descr *typecode;
9729
PyArrayIterObject *ind_it;
9731
PyArray_CopySwapFunc *copyswap;
9273
typecode = self->ao->descr;
9274
copyswap = self->ao->descr->f->copyswap;
9276
num = *((intp *)ind->data);
9277
PyArray_ITER_GOTO1D(self, num);
9278
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9281
ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
9282
if (ind_it == NULL) return -1;
9283
index = ind_it->size;
9285
num = *((intp *)(ind_it->dataptr));
9286
if (num < 0) num += self->size;
9287
if ((num < 0) || (num >= self->size)) {
9288
PyErr_Format(PyExc_IndexError,
9289
"index %d out of bounds" \
9290
" 0<=index<%d", (int) num,
9295
PyArray_ITER_GOTO1D(self, num);
9296
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9297
PyArray_ITER_NEXT(ind_it);
9298
PyArray_ITER_NEXT(val);
9299
if (val->index == val->size)
9300
PyArray_ITER_RESET(val);
9733
typecode = self->ao->descr;
9734
copyswap = self->ao->descr->f->copyswap;
9736
num = *((intp *)ind->data);
9737
PyArray_ITER_GOTO1D(self, num);
9738
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9741
ind_it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)ind);
9742
if (ind_it == NULL) return -1;
9743
index = ind_it->size;
9745
num = *((intp *)(ind_it->dataptr));
9746
if (num < 0) num += self->size;
9747
if ((num < 0) || (num >= self->size)) {
9748
PyErr_Format(PyExc_IndexError,
9749
"index %d out of bounds" \
9750
" 0<=index<%d", (int) num,
9755
PyArray_ITER_GOTO1D(self, num);
9756
copyswap(self->dataptr, val->dataptr, swap, self->ao);
9757
PyArray_ITER_NEXT(ind_it);
9758
PyArray_ITER_NEXT(val);
9759
if (val->index == val->size)
9760
PyArray_ITER_RESET(val);
9307
9767
iter_ass_subscript(PyArrayIterObject *self, PyObject *ind, PyObject *val)
9309
PyObject *arrval=NULL;
9310
PyArrayIterObject *val_it=NULL;
9311
PyArray_Descr *type;
9312
PyArray_Descr *indtype=NULL;
9313
int swap, retval=-1;
9314
intp start, step_size;
9317
PyArray_CopySwapFunc *copyswap;
9320
if (ind == Py_Ellipsis) {
9321
ind = PySlice_New(NULL, NULL, NULL);
9322
retval = iter_ass_subscript(self, ind, val);
9327
if (PyTuple_Check(ind)) {
9329
len = PyTuple_GET_SIZE(ind);
9330
if (len > 1) goto finish;
9331
ind = PyTuple_GET_ITEM(ind, 0);
9334
type = self->ao->descr;
9336
/* Check for Boolean -- this is first becasue
9337
Bool is a subclass of Int */
9339
if (PyBool_Check(ind)) {
9341
if (PyObject_IsTrue(ind)) {
9342
retval = type->f->setitem(val, self->dataptr, self->ao);
9347
if (PySequence_Check(ind) || PySlice_Check(ind)) goto skip;
9348
start = PyArray_PyIntAsIntp(ind);
9349
if (start==-1 && PyErr_Occurred()) PyErr_Clear();
9351
if (start < -self->size || start >= self->size) {
9352
PyErr_Format(PyExc_ValueError,
9353
"index (%" NPY_INTP_FMT \
9354
") out of range", start);
9358
PyArray_ITER_GOTO1D(self, start);
9359
retval = type->f->setitem(val, self->dataptr, self->ao);
9360
PyArray_ITER_RESET(self);
9362
PyErr_SetString(PyExc_ValueError,
9363
"Error setting single item of array.");
9769
PyObject *arrval=NULL;
9770
PyArrayIterObject *val_it=NULL;
9771
PyArray_Descr *type;
9772
PyArray_Descr *indtype=NULL;
9773
int swap, retval=-1;
9774
intp start, step_size;
9777
PyArray_CopySwapFunc *copyswap;
9780
if (ind == Py_Ellipsis) {
9781
ind = PySlice_New(NULL, NULL, NULL);
9782
retval = iter_ass_subscript(self, ind, val);
9787
if (PyTuple_Check(ind)) {
9789
len = PyTuple_GET_SIZE(ind);
9790
if (len > 1) goto finish;
9791
ind = PyTuple_GET_ITEM(ind, 0);
9794
type = self->ao->descr;
9796
/* Check for Boolean -- this is first becasue
9797
Bool is a subclass of Int */
9799
if (PyBool_Check(ind)) {
9801
if (PyObject_IsTrue(ind)) {
9802
retval = type->f->setitem(val, self->dataptr, self->ao);
9807
if (PySequence_Check(ind) || PySlice_Check(ind)) goto skip;
9808
start = PyArray_PyIntAsIntp(ind);
9809
if (start==-1 && PyErr_Occurred()) PyErr_Clear();
9811
if (start < -self->size || start >= self->size) {
9812
PyErr_Format(PyExc_ValueError,
9813
"index (%" NPY_INTP_FMT \
9814
") out of range", start);
9818
PyArray_ITER_GOTO1D(self, start);
9819
retval = type->f->setitem(val, self->dataptr, self->ao);
9820
PyArray_ITER_RESET(self);
9822
PyErr_SetString(PyExc_ValueError,
9823
"Error setting single item of array.");
9370
arrval = PyArray_FromAny(val, type, 0, 0, 0, NULL);
9371
if (arrval==NULL) return -1;
9372
val_it = (PyArrayIterObject *)PyArray_IterNew(arrval);
9373
if (val_it==NULL) goto finish;
9374
if (val_it->size == 0) {retval = 0; goto finish;}
9376
copyswap = PyArray_DESCR(arrval)->f->copyswap;
9377
swap = (PyArray_ISNOTSWAPPED(self->ao)!=PyArray_ISNOTSWAPPED(arrval));
9381
if (PySlice_Check(ind)) {
9382
start = parse_subindex(ind, &step_size, &n_steps,
9384
if (start == -1) goto finish;
9385
if (n_steps == RubberIndex || n_steps == PseudoIndex) {
9386
PyErr_SetString(PyExc_IndexError,
9387
"cannot use Ellipsis or newaxes here");
9390
PyArray_ITER_GOTO1D(self, start);
9391
if (n_steps == SingleIndex) { /* Integer */
9392
copyswap(self->dataptr, PyArray_DATA(arrval),
9394
PyArray_ITER_RESET(self);
9399
copyswap(self->dataptr, val_it->dataptr,
9402
PyArray_ITER_GOTO1D(self, start)
9403
PyArray_ITER_NEXT(val_it);
9404
if (val_it->index == val_it->size)
9405
PyArray_ITER_RESET(val_it);
9407
PyArray_ITER_RESET(self);
9412
/* convert to INTP array if Integer array scalar or List */
9414
indtype = PyArray_DescrFromType(PyArray_INTP);
9415
if (PyList_Check(ind)) {
9417
obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
9424
if (obj != NULL && PyArray_Check(obj)) {
9425
/* Check for Boolean object */
9426
if (PyArray_TYPE(obj)==PyArray_BOOL) {
9427
if (iter_ass_sub_Bool(self, (PyArrayObject *)obj,
9432
/* Check for integer array */
9433
else if (PyArray_ISINTEGER(obj)) {
9436
new = PyArray_CheckFromAny(obj, indtype, 0, 0,
9437
FORCECAST | BEHAVED_NS, NULL);
9440
if (new==NULL) goto finish;
9441
if (iter_ass_sub_int(self, (PyArrayObject *)obj,
9830
arrval = PyArray_FromAny(val, type, 0, 0, 0, NULL);
9831
if (arrval==NULL) return -1;
9832
val_it = (PyArrayIterObject *)PyArray_IterNew(arrval);
9833
if (val_it==NULL) goto finish;
9834
if (val_it->size == 0) {retval = 0; goto finish;}
9836
copyswap = PyArray_DESCR(arrval)->f->copyswap;
9837
swap = (PyArray_ISNOTSWAPPED(self->ao)!=PyArray_ISNOTSWAPPED(arrval));
9841
if (PySlice_Check(ind)) {
9842
start = parse_subindex(ind, &step_size, &n_steps,
9844
if (start == -1) goto finish;
9845
if (n_steps == RubberIndex || n_steps == PseudoIndex) {
9846
PyErr_SetString(PyExc_IndexError,
9847
"cannot use Ellipsis or newaxes here");
9850
PyArray_ITER_GOTO1D(self, start);
9851
if (n_steps == SingleIndex) { /* Integer */
9852
copyswap(self->dataptr, PyArray_DATA(arrval),
9854
PyArray_ITER_RESET(self);
9859
copyswap(self->dataptr, val_it->dataptr,
9862
PyArray_ITER_GOTO1D(self, start)
9863
PyArray_ITER_NEXT(val_it);
9864
if (val_it->index == val_it->size)
9865
PyArray_ITER_RESET(val_it);
9867
PyArray_ITER_RESET(self);
9872
/* convert to INTP array if Integer array scalar or List */
9874
indtype = PyArray_DescrFromType(PyArray_INTP);
9875
if (PyList_Check(ind)) {
9877
obj = PyArray_FromAny(ind, indtype, 0, 0, FORCECAST, NULL);
9884
if (obj != NULL && PyArray_Check(obj)) {
9885
/* Check for Boolean object */
9886
if (PyArray_TYPE(obj)==PyArray_BOOL) {
9887
if (iter_ass_sub_Bool(self, (PyArrayObject *)obj,
9892
/* Check for integer array */
9893
else if (PyArray_ISINTEGER(obj)) {
9896
new = PyArray_CheckFromAny(obj, indtype, 0, 0,
9897
FORCECAST | BEHAVED_NS, NULL);
9900
if (new==NULL) goto finish;
9901
if (iter_ass_sub_int(self, (PyArrayObject *)obj,
9449
if (!PyErr_Occurred() && retval < 0)
9450
PyErr_SetString(PyExc_IndexError,
9451
"unsupported iterator index");
9452
Py_XDECREF(indtype);
9909
if (!PyErr_Occurred() && retval < 0)
9910
PyErr_SetString(PyExc_IndexError,
9911
"unsupported iterator index");
9912
Py_XDECREF(indtype);
9461
9921
static PyMappingMethods iter_as_mapping = {
9462
9922
#if PY_VERSION_HEX >= 0x02050000
9463
(lenfunc)iter_length, /*mp_length*/
9923
(lenfunc)iter_length, /*mp_length*/
9465
(inquiry)iter_length, /*mp_length*/
9925
(inquiry)iter_length, /*mp_length*/
9467
(binaryfunc)iter_subscript, /*mp_subscript*/
9468
(objobjargproc)iter_ass_subscript, /*mp_ass_subscript*/
9927
(binaryfunc)iter_subscript, /*mp_subscript*/
9928
(objobjargproc)iter_ass_subscript, /*mp_ass_subscript*/
9474
9934
iter_array(PyArrayIterObject *it, PyObject *op)
9480
/* Any argument ignored */
9483
1) underlying array is contiguous
9484
-- return 1-d wrapper around it
9485
2) underlying array is not contiguous
9486
-- make new 1-d contiguous array with updateifcopy flag set
9487
to copy back to the old array
9490
size = PyArray_SIZE(it->ao);
9491
Py_INCREF(it->ao->descr);
9492
if (PyArray_ISCONTIGUOUS(it->ao)) {
9493
r = PyArray_NewFromDescr(&PyArray_Type,
9498
(PyObject *)it->ao);
9499
if (r==NULL) return NULL;
9502
r = PyArray_NewFromDescr(&PyArray_Type,
9506
0, (PyObject *)it->ao);
9507
if (r==NULL) return NULL;
9508
if (_flat_copyinto(r, (PyObject *)it->ao,
9509
PyArray_CORDER) < 0) {
9513
PyArray_FLAGS(r) |= UPDATEIFCOPY;
9514
it->ao->flags &= ~WRITEABLE;
9517
PyArray_BASE(r) = (PyObject *)it->ao;
9940
/* Any argument ignored */
9943
1) underlying array is contiguous
9944
-- return 1-d wrapper around it
9945
2) underlying array is not contiguous
9946
-- make new 1-d contiguous array with updateifcopy flag set
9947
to copy back to the old array
9950
size = PyArray_SIZE(it->ao);
9951
Py_INCREF(it->ao->descr);
9952
if (PyArray_ISCONTIGUOUS(it->ao)) {
9953
r = PyArray_NewFromDescr(&PyArray_Type,
9958
(PyObject *)it->ao);
9959
if (r==NULL) return NULL;
9962
r = PyArray_NewFromDescr(&PyArray_Type,
9966
0, (PyObject *)it->ao);
9967
if (r==NULL) return NULL;
9968
if (_flat_copyinto(r, (PyObject *)it->ao,
9969
PyArray_CORDER) < 0) {
9973
PyArray_FLAGS(r) |= UPDATEIFCOPY;
9974
it->ao->flags &= ~WRITEABLE;
9977
PyArray_BASE(r) = (PyObject *)it->ao;
9522
9982
static PyObject *
9523
9983
iter_copy(PyArrayIterObject *it, PyObject *args)
9525
if (!PyArg_ParseTuple(args, "")) return NULL;
9526
return PyArray_Flatten(it->ao, 0);
9985
if (!PyArg_ParseTuple(args, "")) return NULL;
9986
return PyArray_Flatten(it->ao, 0);
9529
9989
static PyMethodDef iter_methods[] = {
9531
{"__array__", (PyCFunction)iter_array, 1, NULL},
9532
{"copy", (PyCFunction)iter_copy, 1, NULL},
9533
{NULL, NULL} /* sentinel */
9991
{"__array__", (PyCFunction)iter_array, 1, NULL},
9992
{"copy", (PyCFunction)iter_copy, 1, NULL},
9993
{NULL, NULL} /* sentinel */
9536
9996
static PyObject *
9537
9997
iter_richcompare(PyArrayIterObject *self, PyObject *other, int cmp_op)
9541
new = (PyArrayObject *)iter_array(self, NULL);
9542
if (new == NULL) return NULL;
9543
ret = array_richcompare(new, other, cmp_op);
10001
new = (PyArrayObject *)iter_array(self, NULL);
10002
if (new == NULL) return NULL;
10003
ret = array_richcompare(new, other, cmp_op);
9549
10009
static PyMemberDef iter_members[] = {
9550
{"base", T_OBJECT, offsetof(PyArrayIterObject, ao), RO, NULL},
9551
{"index", T_INT, offsetof(PyArrayIterObject, index), RO, NULL},
10010
{"base", T_OBJECT, offsetof(PyArrayIterObject, ao), RO, NULL},
10011
{"index", T_INT, offsetof(PyArrayIterObject, index), RO, NULL},
9555
10015
static PyObject *
9556
10016
iter_coords_get(PyArrayIterObject *self)
9560
if (self->contiguous) { /* coordinates not kept track of --- need to generate
9565
for (i=0;i<nd; i++) {
9566
self->coordinates[i] = val / self->factors[i];
9567
val = val % self->factors[i];
10020
if (self->contiguous) { /* coordinates not kept track of --- need to generate
10025
for(i=0;i<nd; i++) {
10026
self->coordinates[i] = val / self->factors[i];
10027
val = val % self->factors[i];
9570
return PyArray_IntTupleFromIntp(nd, self->coordinates);
10030
return PyArray_IntTupleFromIntp(nd, self->coordinates);
9573
10033
static PyGetSetDef iter_getsets[] = {
9575
(getter)iter_coords_get,
9578
{NULL, NULL, NULL, NULL},
10035
(getter)iter_coords_get,
10038
{NULL, NULL, NULL, NULL},
9581
10041
static PyTypeObject PyArrayIter_Type = {
9582
PyObject_HEAD_INIT(NULL)
9584
"numpy.flatiter", /* tp_name */
9585
sizeof(PyArrayIterObject), /* tp_basicsize */
9586
0, /* tp_itemsize */
9588
(destructor)arrayiter_dealloc, /* tp_dealloc */
9594
0, /* tp_as_number */
9595
0, /* tp_as_sequence */
9596
&iter_as_mapping, /* tp_as_mapping */
9600
0, /* tp_getattro */
9601
0, /* tp_setattro */
9602
0, /* tp_as_buffer */
9603
Py_TPFLAGS_DEFAULT, /* tp_flags */
9605
0, /* tp_traverse */
9607
(richcmpfunc)iter_richcompare, /* tp_richcompare */
9608
0, /* tp_weaklistoffset */
9610
(iternextfunc)arrayiter_next, /* tp_iternext */
9611
iter_methods, /* tp_methods */
9612
iter_members, /* tp_members */
9613
iter_getsets, /* tp_getset */
10042
PyObject_HEAD_INIT(NULL)
10044
"numpy.flatiter", /* tp_name */
10045
sizeof(PyArrayIterObject), /* tp_basicsize */
10046
0, /* tp_itemsize */
10048
(destructor)arrayiter_dealloc, /* tp_dealloc */
10050
0, /* tp_getattr */
10051
0, /* tp_setattr */
10052
0, /* tp_compare */
10054
0, /* tp_as_number */
10055
0, /* tp_as_sequence */
10056
&iter_as_mapping, /* tp_as_mapping */
10060
0, /* tp_getattro */
10061
0, /* tp_setattro */
10062
0, /* tp_as_buffer */
10063
Py_TPFLAGS_DEFAULT, /* tp_flags */
10065
0, /* tp_traverse */
10067
(richcmpfunc)iter_richcompare, /* tp_richcompare */
10068
0, /* tp_weaklistoffset */
10070
(iternextfunc)arrayiter_next, /* tp_iternext */
10071
iter_methods, /* tp_methods */
10072
iter_members, /* tp_members */
10073
iter_getsets, /* tp_getset */
9633
10093
if possible -- otherwise, it is a Slice or Ellipsis object
9634
10094
and has to be interpreted on bind to a particular
9635
10095
array so leave it NULL for now.
9638
10098
_convert_obj(PyObject *obj, PyArrayIterObject **iter)
9640
PyArray_Descr *indtype;
10100
PyArray_Descr *indtype;
9643
if (PySlice_Check(obj) || (obj == Py_Ellipsis))
9645
else if (PyArray_Check(obj) && PyArray_ISBOOL(obj)) {
9646
return _nonzero_indices(obj, iter);
9649
indtype = PyArray_DescrFromType(PyArray_INTP);
9650
arr = PyArray_FromAny(obj, indtype, 0, 0, FORCECAST, NULL);
9651
if (arr == NULL) return -1;
9652
*iter = (PyArrayIterObject *)PyArray_IterNew(arr);
9654
if (*iter == NULL) return -1;
10103
if (PySlice_Check(obj) || (obj == Py_Ellipsis))
10105
else if (PyArray_Check(obj) && PyArray_ISBOOL(obj)) {
10106
return _nonzero_indices(obj, iter);
10109
indtype = PyArray_DescrFromType(PyArray_INTP);
10110
arr = PyArray_FromAny(obj, indtype, 0, 0, FORCECAST, NULL);
10111
if (arr == NULL) return -1;
10112
*iter = (PyArrayIterObject *)PyArray_IterNew(arr);
10114
if (*iter == NULL) return -1;
9659
10119
/* Adjust dimensionality and strides for index object iterators
9660
10120
--- i.e. broadcast
9662
10122
/*OBJECT_API*/
9664
10124
PyArray_Broadcast(PyArrayMultiIterObject *mit)
9668
PyArrayIterObject *it;
9670
/* Discover the broadcast number of dimensions */
9671
for (i=0, nd=0; i<mit->numiter; i++)
9672
nd = MAX(nd, mit->iters[i]->ao->nd);
9675
/* Discover the broadcast shape in each dimension */
9676
for (i=0; i<nd; i++) {
9677
mit->dimensions[i] = 1;
9678
for (j=0; j<mit->numiter; j++) {
9680
/* This prepends 1 to shapes not already
9682
k = i + it->ao->nd - nd;
9684
tmp = it->ao->dimensions[k];
9685
if (tmp == 1) continue;
9686
if (mit->dimensions[i] == 1)
9687
mit->dimensions[i] = tmp;
9688
else if (mit->dimensions[i] != tmp) {
9689
PyErr_SetString(PyExc_ValueError,
9690
"shape mismatch: objects" \
9691
" cannot be broadcast" \
9692
" to a single shape");
9699
/* Reset the iterator dimensions and strides of each iterator
9700
object -- using 0 valued strides for broadcasting */
9702
tmp = PyArray_MultiplyList(mit->dimensions, mit->nd);
9704
for (i=0; i<mit->numiter; i++) {
9706
it->nd_m1 = mit->nd - 1;
9709
it->factors[mit->nd-1] = 1;
9710
for (j=0; j < mit->nd; j++) {
9711
it->dims_m1[j] = mit->dimensions[j] - 1;
9712
k = j + nd - mit->nd;
9713
/* If this dimension was added or shape
9714
of underlying array was 1 */
9716
it->ao->dimensions[k] != mit->dimensions[j]) {
9721
it->strides[j] = it->ao->strides[k];
9723
it->backstrides[j] = it->strides[j] * \
9726
it->factors[mit->nd-j-1] = \
9727
it->factors[mit->nd-j] * \
9728
mit->dimensions[mit->nd-j];
9730
PyArray_ITER_RESET(it);
10128
PyArrayIterObject *it;
10130
/* Discover the broadcast number of dimensions */
10131
for(i=0, nd=0; i<mit->numiter; i++)
10132
nd = MAX(nd, mit->iters[i]->ao->nd);
10135
/* Discover the broadcast shape in each dimension */
10136
for(i=0; i<nd; i++) {
10137
mit->dimensions[i] = 1;
10138
for(j=0; j<mit->numiter; j++) {
10139
it = mit->iters[j];
10140
/* This prepends 1 to shapes not already
10142
k = i + it->ao->nd - nd;
10144
tmp = it->ao->dimensions[k];
10145
if (tmp == 1) continue;
10146
if (mit->dimensions[i] == 1)
10147
mit->dimensions[i] = tmp;
10148
else if (mit->dimensions[i] != tmp) {
10149
PyErr_SetString(PyExc_ValueError,
10150
"shape mismatch: objects" \
10151
" cannot be broadcast" \
10152
" to a single shape");
10159
/* Reset the iterator dimensions and strides of each iterator
10160
object -- using 0 valued strides for broadcasting */
10161
/* Need to check for overflow */
10162
tmp = PyArray_OverflowMultiplyList(mit->dimensions, mit->nd);
10164
PyErr_SetString(PyExc_ValueError,
10165
"broadcast dimensions too large.");
10169
for(i=0; i<mit->numiter; i++) {
10170
it = mit->iters[i];
10171
it->nd_m1 = mit->nd - 1;
10174
it->factors[mit->nd-1] = 1;
10175
for(j=0; j < mit->nd; j++) {
10176
it->dims_m1[j] = mit->dimensions[j] - 1;
10177
k = j + nd - mit->nd;
10178
/* If this dimension was added or shape
10179
of underlying array was 1 */
10181
it->ao->dimensions[k] != mit->dimensions[j]) {
10182
it->contiguous = 0;
10183
it->strides[j] = 0;
10186
it->strides[j] = it->ao->strides[k];
10188
it->backstrides[j] = it->strides[j] * \
10191
it->factors[mit->nd-j-1] = \
10192
it->factors[mit->nd-j] * \
10193
mit->dimensions[mit->nd-j];
10195
PyArray_ITER_RESET(it);
9735
10200
/* Reset the map iterator to the beginning */
9737
10202
PyArray_MapIterReset(PyArrayMapIterObject *mit)
9739
int i,j; intp coord[MAX_DIMS];
9740
PyArrayIterObject *it;
9741
PyArray_CopySwapFunc *copyswap;
9745
copyswap = mit->iters[0]->ao->descr->f->copyswap;
9747
if (mit->subspace != NULL) {
9748
memcpy(coord, mit->bscoord, sizeof(intp)*mit->ait->ao->nd);
9749
PyArray_ITER_RESET(mit->subspace);
9750
for (i=0; i<mit->numiter; i++) {
9752
PyArray_ITER_RESET(it);
9753
j = mit->iteraxes[i];
9754
copyswap(coord+j,it->dataptr,
9755
!PyArray_ISNOTSWAPPED(it->ao),
9758
PyArray_ITER_GOTO(mit->ait, coord);
9759
mit->subspace->dataptr = mit->ait->dataptr;
9760
mit->dataptr = mit->subspace->dataptr;
9763
for (i=0; i<mit->numiter; i++) {
9765
if (it->size != 0) {
9766
PyArray_ITER_RESET(it);
9767
copyswap(coord+i,it->dataptr,
9768
!PyArray_ISNOTSWAPPED(it->ao),
9773
PyArray_ITER_GOTO(mit->ait, coord);
9774
mit->dataptr = mit->ait->dataptr;
10204
int i,j; intp coord[MAX_DIMS];
10205
PyArrayIterObject *it;
10206
PyArray_CopySwapFunc *copyswap;
10210
copyswap = mit->iters[0]->ao->descr->f->copyswap;
10212
if (mit->subspace != NULL) {
10213
memcpy(coord, mit->bscoord, sizeof(intp)*mit->ait->ao->nd);
10214
PyArray_ITER_RESET(mit->subspace);
10215
for(i=0; i<mit->numiter; i++) {
10216
it = mit->iters[i];
10217
PyArray_ITER_RESET(it);
10218
j = mit->iteraxes[i];
10219
copyswap(coord+j,it->dataptr,
10220
!PyArray_ISNOTSWAPPED(it->ao),
10223
PyArray_ITER_GOTO(mit->ait, coord);
10224
mit->subspace->dataptr = mit->ait->dataptr;
10225
mit->dataptr = mit->subspace->dataptr;
10228
for(i=0; i<mit->numiter; i++) {
10229
it = mit->iters[i];
10230
if (it->size != 0) {
10231
PyArray_ITER_RESET(it);
10232
copyswap(coord+i,it->dataptr,
10233
!PyArray_ISNOTSWAPPED(it->ao),
10238
PyArray_ITER_GOTO(mit->ait, coord);
10239
mit->dataptr = mit->ait->dataptr;
9779
10244
/* This function needs to update the state of the map iterator
9845
10310
PyArray_MapIterBind(PyArrayMapIterObject *mit, PyArrayObject *arr)
9848
PyObject *sub, *obj=NULL;
9849
int i, j, n, curraxis, ellipexp, noellip;
9850
PyArrayIterObject *it;
9854
subnd = arr->nd - mit->numiter;
9856
PyErr_SetString(PyExc_ValueError,
9857
"too many indices for array");
9861
mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr);
9862
if (mit->ait == NULL) return;
9864
/* no subspace iteration needed. Finish up and Return */
9867
for (i=0; i<n; i++) {
9868
mit->iteraxes[i] = i;
9873
/* all indexing arrays have been converted to 0
9874
therefore we can extract the subspace with a simple
9875
getitem call which will use view semantics
9877
/* But, be sure to do it with a true array.
9879
if (PyArray_CheckExact(arr)) {
9880
sub = array_subscript_simple(arr, mit->indexobj);
10313
PyObject *sub, *obj=NULL;
10314
int i, j, n, curraxis, ellipexp, noellip;
10315
PyArrayIterObject *it;
10319
subnd = arr->nd - mit->numiter;
10321
PyErr_SetString(PyExc_ValueError,
10322
"too many indices for array");
10326
mit->ait = (PyArrayIterObject *)PyArray_IterNew((PyObject *)arr);
10327
if (mit->ait == NULL) return;
10329
/* no subspace iteration needed. Finish up and Return */
10332
for(i=0; i<n; i++) {
10333
mit->iteraxes[i] = i;
10338
/* all indexing arrays have been converted to 0
10339
therefore we can extract the subspace with a simple
10340
getitem call which will use view semantics
10342
/* But, be sure to do it with a true array.
10344
if (PyArray_CheckExact(arr)) {
10345
sub = array_subscript_simple(arr, mit->indexobj);
10349
obj = PyArray_EnsureArray((PyObject *)arr);
10350
if (obj == NULL) goto fail;
10351
sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj);
10355
if (sub == NULL) goto fail;
10356
mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub);
10358
if (mit->subspace == NULL) goto fail;
10360
/* Expand dimensions of result */
10361
n = mit->subspace->ao->nd;
10363
mit->dimensions[mit->nd+i] = mit->subspace->ao->dimensions[i];
10366
/* Now, we still need to interpret the ellipsis and slice objects
10367
to determine which axes the indexing arrays are referring to
10369
n = PyTuple_GET_SIZE(mit->indexobj);
10371
/* The number of dimensions an ellipsis takes up */
10372
ellipexp = arr->nd - n + 1;
10373
/* Now fill in iteraxes -- remember indexing arrays have been
10374
converted to 0's in mit->indexobj */
10377
noellip = 1; /* Only expand the first ellipsis */
10378
memset(mit->bscoord, 0, sizeof(intp)*arr->nd);
10379
for(i=0; i<n; i++) {
10380
/* We need to fill in the starting coordinates for
10382
obj = PyTuple_GET_ITEM(mit->indexobj, i);
10383
if (PyInt_Check(obj) || PyLong_Check(obj))
10384
mit->iteraxes[j++] = curraxis++;
10385
else if (noellip && obj == Py_Ellipsis) {
10386
curraxis += ellipexp;
9884
obj = PyArray_EnsureArray((PyObject *)arr);
9885
if (obj == NULL) goto fail;
9886
sub = array_subscript_simple((PyArrayObject *)obj, mit->indexobj);
9890
if (sub == NULL) goto fail;
9891
mit->subspace = (PyArrayIterObject *)PyArray_IterNew(sub);
9893
if (mit->subspace == NULL) goto fail;
9895
/* Expand dimensions of result */
9896
n = mit->subspace->ao->nd;
9898
mit->dimensions[mit->nd+i] = mit->subspace->ao->dimensions[i];
9901
/* Now, we still need to interpret the ellipsis and slice objects
9902
to determine which axes the indexing arrays are referring to
9904
n = PyTuple_GET_SIZE(mit->indexobj);
9906
/* The number of dimensions an ellipsis takes up */
9907
ellipexp = arr->nd - n + 1;
9908
/* Now fill in iteraxes -- remember indexing arrays have been
9909
converted to 0's in mit->indexobj */
9912
noellip = 1; /* Only expand the first ellipsis */
9913
memset(mit->bscoord, 0, sizeof(intp)*arr->nd);
9914
for (i=0; i<n; i++) {
9915
/* We need to fill in the starting coordinates for
9917
obj = PyTuple_GET_ITEM(mit->indexobj, i);
9918
if (PyInt_Check(obj) || PyLong_Check(obj))
9919
mit->iteraxes[j++] = curraxis++;
9920
else if (noellip && obj == Py_Ellipsis) {
9921
curraxis += ellipexp;
9927
/* Should be slice object or
9929
if (obj == Py_Ellipsis) {
9930
mit->bscoord[curraxis] = 0;
9932
else if (!PySlice_Check(obj) || \
9933
(slice_GetIndices((PySliceObject *)obj,
9934
arr->dimensions[curraxis],
9935
&start, &stop, &step,
9937
PyErr_Format(PyExc_ValueError,
9938
"unexpected object " \
9939
"(%s) in selection position %d",
9940
obj->ob_type->tp_name, i);
9944
mit->bscoord[curraxis] = start;
10392
/* Should be slice object or
10393
another Ellipsis */
10394
if (obj == Py_Ellipsis) {
10395
mit->bscoord[curraxis] = 0;
10397
else if (!PySlice_Check(obj) || \
10398
(slice_GetIndices((PySliceObject *)obj,
10399
arr->dimensions[curraxis],
10400
&start, &stop, &step,
10402
PyErr_Format(PyExc_ValueError,
10403
"unexpected object " \
10404
"(%s) in selection position %d",
10405
obj->ob_type->tp_name, i);
10409
mit->bscoord[curraxis] = start;
9950
/* Here check the indexes (now that we have iteraxes) */
9951
mit->size = PyArray_MultiplyList(mit->dimensions, mit->nd);
9952
if (mit->ait->size == 0 && mit->size != 0) {
9953
PyErr_SetString(PyExc_ValueError,
9954
"invalid index into a 0-size array");
10415
/* Here check the indexes (now that we have iteraxes) */
10416
mit->size = PyArray_OverflowMultiplyList(mit->dimensions, mit->nd);
10417
if (mit->size < 0) {
10418
PyErr_SetString(PyExc_ValueError,
10419
"dimensions too large in fancy indexing");
10422
if (mit->ait->size == 0 && mit->size != 0) {
10423
PyErr_SetString(PyExc_ValueError,
10424
"invalid index into a 0-size array");
10428
for(i=0; i<mit->numiter; i++) {
10430
it = mit->iters[i];
10431
PyArray_ITER_RESET(it);
10432
dimsize = arr->dimensions[mit->iteraxes[i]];
10433
while(it->index < it->size) {
10434
indptr = ((intp *)it->dataptr);
10436
if (indval < 0) indval += dimsize;
10437
if (indval < 0 || indval >= dimsize) {
10438
PyErr_Format(PyExc_IndexError,
10439
"index (%d) out of range "\
10440
"(0<=index<%d) in dimension %d",
10441
(int) indval, (int) (dimsize-1),
9958
for (i=0; i<mit->numiter; i++) {
9961
PyArray_ITER_RESET(it);
9962
dimsize = arr->dimensions[mit->iteraxes[i]];
9963
while(it->index < it->size) {
9964
indptr = ((intp *)it->dataptr);
9966
if (indval < 0) indval += dimsize;
9967
if (indval < 0 || indval >= dimsize) {
9968
PyErr_Format(PyExc_IndexError,
9969
"index (%d) out of range "\
9970
"(0<=index<=%d) in dimension %d",
9971
(int) indval, (int) (dimsize-1),
9975
PyArray_ITER_NEXT(it);
9977
PyArray_ITER_RESET(it);
10445
PyArray_ITER_NEXT(it);
10447
PyArray_ITER_RESET(it);
9982
Py_XDECREF(mit->subspace);
9983
Py_XDECREF(mit->ait);
9984
mit->subspace = NULL;
10452
Py_XDECREF(mit->subspace);
10453
Py_XDECREF(mit->ait);
10454
mit->subspace = NULL;
9989
10459
/* This function takes a Boolean array and constructs index objects and
9993
10463
_nonzero_indices(PyObject *myBool, PyArrayIterObject **iters)
9995
PyArray_Descr *typecode;
9996
PyArrayObject *ba =NULL, *new=NULL;
9998
intp size, i, count;
10000
intp coords[MAX_DIMS], dims_m1[MAX_DIMS];
10001
intp *dptr[MAX_DIMS];
10003
typecode=PyArray_DescrFromType(PyArray_BOOL);
10004
ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0,
10006
if (ba == NULL) return -1;
10008
for (j=0; j<nd; j++) iters[j] = NULL;
10009
size = PyArray_SIZE(ba);
10010
ptr = (Bool *)ba->data;
10013
/* pre-determine how many nonzero entries there are */
10014
for (i=0; i<size; i++)
10015
if (*(ptr++)) count++;
10017
/* create count-sized index arrays for each dimension */
10018
for (j=0; j<nd; j++) {
10019
new = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &count,
10020
PyArray_INTP, NULL, NULL,
10022
if (new == NULL) goto fail;
10023
iters[j] = (PyArrayIterObject *) \
10024
PyArray_IterNew((PyObject *)new);
10026
if (iters[j] == NULL) goto fail;
10027
dptr[j] = (intp *)iters[j]->ao->data;
10465
PyArray_Descr *typecode;
10466
PyArrayObject *ba =NULL, *new=NULL;
10468
intp size, i, count;
10470
intp coords[MAX_DIMS], dims_m1[MAX_DIMS];
10471
intp *dptr[MAX_DIMS];
10473
typecode=PyArray_DescrFromType(PyArray_BOOL);
10474
ba = (PyArrayObject *)PyArray_FromAny(myBool, typecode, 0, 0,
10476
if (ba == NULL) return -1;
10478
for(j=0; j<nd; j++) iters[j] = NULL;
10479
size = PyArray_SIZE(ba);
10480
ptr = (Bool *)ba->data;
10483
/* pre-determine how many nonzero entries there are */
10484
for(i=0; i<size; i++)
10485
if (*(ptr++)) count++;
10487
/* create count-sized index arrays for each dimension */
10488
for(j=0; j<nd; j++) {
10489
new = (PyArrayObject *)PyArray_New(&PyArray_Type, 1, &count,
10490
PyArray_INTP, NULL, NULL,
10492
if (new == NULL) goto fail;
10493
iters[j] = (PyArrayIterObject *) \
10494
PyArray_IterNew((PyObject *)new);
10496
if (iters[j] == NULL) goto fail;
10497
dptr[j] = (intp *)iters[j]->ao->data;
10499
dims_m1[j] = ba->dimensions[j]-1;
10502
ptr = (Bool *)ba->data;
10504
if (count == 0) goto finish;
10506
/* Loop through the Boolean array and copy coordinates
10507
for non-zero entries */
10508
for(i=0; i<size; i++) {
10510
for(j=0; j<nd; j++)
10511
*(dptr[j]++) = coords[j];
10513
/* Borrowed from ITER_NEXT macro */
10514
for(j=nd-1; j>=0; j--) {
10515
if (coords[j] < dims_m1[j]) {
10028
10520
coords[j] = 0;
10029
dims_m1[j] = ba->dimensions[j]-1;
10032
ptr = (Bool *)ba->data;
10034
if (count == 0) goto finish;
10036
/* Loop through the Boolean array and copy coordinates
10037
for non-zero entries */
10038
for (i=0; i<size; i++) {
10040
for (j=0; j<nd; j++)
10041
*(dptr[j]++) = coords[j];
10043
/* Borrowed from ITER_NEXT macro */
10044
for (j=nd-1; j>=0; j--) {
10045
if (coords[j] < dims_m1[j]) {
10060
for (j=0; j<nd; j++) {
10061
Py_XDECREF(iters[j]);
10530
for(j=0; j<nd; j++) {
10531
Py_XDECREF(iters[j]);
10067
10537
static PyObject *
10068
10538
PyArray_MapIterNew(PyObject *indexobj, int oned, int fancy)
10070
PyArrayMapIterObject *mit;
10071
PyArray_Descr *indtype;
10072
PyObject *arr = NULL;
10073
int i, n, started, nonindex;
10075
if (fancy == SOBJ_BADARRAY) {
10076
PyErr_SetString(PyExc_IndexError, \
10077
"arrays used as indices must be of " \
10078
"integer (or boolean) type");
10081
if (fancy == SOBJ_TOOMANY) {
10082
PyErr_SetString(PyExc_IndexError, "too many indices");
10086
mit = (PyArrayMapIterObject *)_pya_malloc(sizeof(PyArrayMapIterObject));
10087
PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type);
10090
for (i=0; i<MAX_DIMS; i++)
10091
mit->iters[i] = NULL;
10094
mit->subspace = NULL;
10097
Py_INCREF(indexobj);
10540
PyArrayMapIterObject *mit;
10541
PyArray_Descr *indtype;
10542
PyObject *arr = NULL;
10543
int i, n, started, nonindex;
10545
if (fancy == SOBJ_BADARRAY) {
10546
PyErr_SetString(PyExc_IndexError, \
10547
"arrays used as indices must be of " \
10548
"integer (or boolean) type");
10551
if (fancy == SOBJ_TOOMANY) {
10552
PyErr_SetString(PyExc_IndexError, "too many indices");
10556
mit = (PyArrayMapIterObject *)_pya_malloc(sizeof(PyArrayMapIterObject));
10557
PyObject_Init((PyObject *)mit, &PyArrayMapIter_Type);
10560
for(i=0; i<MAX_DIMS; i++)
10561
mit->iters[i] = NULL;
10564
mit->subspace = NULL;
10567
Py_INCREF(indexobj);
10568
mit->indexobj = indexobj;
10570
if (fancy == SOBJ_LISTTUP) {
10572
newobj = PySequence_Tuple(indexobj);
10573
if (newobj == NULL) goto fail;
10574
Py_DECREF(indexobj);
10098
10576
mit->indexobj = indexobj;
10100
if (fancy == SOBJ_LISTTUP) {
10102
newobj = PySequence_Tuple(indexobj);
10103
if (newobj == NULL) goto fail;
10104
Py_DECREF(indexobj);
10106
mit->indexobj = indexobj;
10109
10579
#undef SOBJ_NOTFANCY
10110
10580
#undef SOBJ_ISFANCY
10112
10582
#undef SOBJ_TOOMANY
10113
10583
#undef SOBJ_LISTTUP
10115
if (oned) return (PyObject *)mit;
10117
/* Must have some kind of fancy indexing if we are here */
10118
/* indexobj is either a list, an arrayobject, or a tuple
10119
(with at least 1 list or arrayobject or Bool object), */
10121
/* convert all inputs to iterators */
10122
if (PyArray_Check(indexobj) && \
10123
(PyArray_TYPE(indexobj) == PyArray_BOOL)) {
10124
mit->numiter = _nonzero_indices(indexobj, mit->iters);
10125
if (mit->numiter < 0) goto fail;
10127
mit->dimensions[0] = mit->iters[0]->dims_m1[0]+1;
10128
Py_DECREF(mit->indexobj);
10129
mit->indexobj = PyTuple_New(mit->numiter);
10130
if (mit->indexobj == NULL) goto fail;
10131
for (i=0; i<mit->numiter; i++) {
10132
PyTuple_SET_ITEM(mit->indexobj, i,
10133
PyInt_FromLong(0));
10137
else if (PyArray_Check(indexobj) || !PyTuple_Check(indexobj)) {
10139
indtype = PyArray_DescrFromType(PyArray_INTP);
10140
arr = PyArray_FromAny(indexobj, indtype, 0, 0, FORCECAST, NULL);
10141
if (arr == NULL) goto fail;
10142
mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew(arr);
10143
if (mit->iters[0] == NULL) {Py_DECREF(arr); goto fail;}
10144
mit->nd = PyArray_NDIM(arr);
10145
memcpy(mit->dimensions,PyArray_DIMS(arr),mit->nd*sizeof(intp));
10146
mit->size = PyArray_SIZE(arr);
10148
Py_DECREF(mit->indexobj);
10149
mit->indexobj = Py_BuildValue("(N)", PyInt_FromLong(0));
10151
else { /* must be a tuple */
10153
PyArrayIterObject **iterp;
10155
int numiters, j, n2;
10156
/* Make a copy of the tuple -- we will be replacing
10157
index objects with 0's */
10158
n = PyTuple_GET_SIZE(indexobj);
10160
new = PyTuple_New(n2);
10161
if (new == NULL) goto fail;
10165
for (i=0; i<n; i++) {
10166
obj = PyTuple_GET_ITEM(indexobj,i);
10167
iterp = mit->iters + mit->numiter;
10168
if ((numiters=_convert_obj(obj, iterp)) < 0) {
10172
if (numiters > 0) {
10174
if (nonindex) mit->consec = 0;
10175
mit->numiter += numiters;
10176
if (numiters == 1) {
10177
PyTuple_SET_ITEM(new,j++,
10178
PyInt_FromLong(0));
10180
else { /* we need to grow the
10181
new indexing object and fill
10182
it with 0s for each of the iterators
10185
n2 += numiters - 1;
10186
if (_PyTuple_Resize(&new, n2) < 0)
10188
for (k=0;k<numiters;k++) {
10191
PyInt_FromLong(0));
10196
if (started) nonindex = 1;
10198
PyTuple_SET_ITEM(new,j++,obj);
10201
Py_DECREF(mit->indexobj);
10202
mit->indexobj = new;
10203
/* Store the number of iterators actually converted */
10204
/* These will be mapped to actual axes at bind time */
10205
if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0)
10585
if (oned) return (PyObject *)mit;
10587
/* Must have some kind of fancy indexing if we are here */
10588
/* indexobj is either a list, an arrayobject, or a tuple
10589
(with at least 1 list or arrayobject or Bool object), */
10591
/* convert all inputs to iterators */
10592
if (PyArray_Check(indexobj) && \
10593
(PyArray_TYPE(indexobj) == PyArray_BOOL)) {
10594
mit->numiter = _nonzero_indices(indexobj, mit->iters);
10595
if (mit->numiter < 0) goto fail;
10597
mit->dimensions[0] = mit->iters[0]->dims_m1[0]+1;
10598
Py_DECREF(mit->indexobj);
10599
mit->indexobj = PyTuple_New(mit->numiter);
10600
if (mit->indexobj == NULL) goto fail;
10601
for(i=0; i<mit->numiter; i++) {
10602
PyTuple_SET_ITEM(mit->indexobj, i,
10603
PyInt_FromLong(0));
10607
else if (PyArray_Check(indexobj) || !PyTuple_Check(indexobj)) {
10609
indtype = PyArray_DescrFromType(PyArray_INTP);
10610
arr = PyArray_FromAny(indexobj, indtype, 0, 0, FORCECAST, NULL);
10611
if (arr == NULL) goto fail;
10612
mit->iters[0] = (PyArrayIterObject *)PyArray_IterNew(arr);
10613
if (mit->iters[0] == NULL) {Py_DECREF(arr); goto fail;}
10614
mit->nd = PyArray_NDIM(arr);
10615
memcpy(mit->dimensions,PyArray_DIMS(arr),mit->nd*sizeof(intp));
10616
mit->size = PyArray_SIZE(arr);
10618
Py_DECREF(mit->indexobj);
10619
mit->indexobj = Py_BuildValue("(N)", PyInt_FromLong(0));
10621
else { /* must be a tuple */
10623
PyArrayIterObject **iterp;
10625
int numiters, j, n2;
10626
/* Make a copy of the tuple -- we will be replacing
10627
index objects with 0's */
10628
n = PyTuple_GET_SIZE(indexobj);
10630
new = PyTuple_New(n2);
10631
if (new == NULL) goto fail;
10635
for(i=0; i<n; i++) {
10636
obj = PyTuple_GET_ITEM(indexobj,i);
10637
iterp = mit->iters + mit->numiter;
10638
if ((numiters=_convert_obj(obj, iterp)) < 0) {
10642
if (numiters > 0) {
10644
if (nonindex) mit->consec = 0;
10645
mit->numiter += numiters;
10646
if (numiters == 1) {
10647
PyTuple_SET_ITEM(new,j++,
10648
PyInt_FromLong(0));
10650
else { /* we need to grow the
10651
new indexing object and fill
10652
it with 0s for each of the iterators
10655
n2 += numiters - 1;
10656
if (_PyTuple_Resize(&new, n2) < 0)
10658
for(k=0;k<numiters;k++) {
10661
PyInt_FromLong(0));
10666
if (started) nonindex = 1;
10668
PyTuple_SET_ITEM(new,j++,obj);
10671
Py_DECREF(mit->indexobj);
10672
mit->indexobj = new;
10673
/* Store the number of iterators actually converted */
10674
/* These will be mapped to actual axes at bind time */
10675
if (PyArray_Broadcast((PyArrayMultiIterObject *)mit) < 0)
10209
return (PyObject *)mit;
10679
return (PyObject *)mit;
10218
10688
arraymapiter_dealloc(PyArrayMapIterObject *mit)
10221
Py_XDECREF(mit->indexobj);
10222
Py_XDECREF(mit->ait);
10223
Py_XDECREF(mit->subspace);
10224
for (i=0; i<mit->numiter; i++)
10225
Py_XDECREF(mit->iters[i]);
10691
Py_XDECREF(mit->indexobj);
10692
Py_XDECREF(mit->ait);
10693
Py_XDECREF(mit->subspace);
10694
for(i=0; i<mit->numiter; i++)
10695
Py_XDECREF(mit->iters[i]);
10229
10699
/* The mapiter object must be created new each time. It does not work
10297
10767
static PyObject *
10298
10768
PyArray_MultiIterNew(int n, ...)
10301
PyArrayMultiIterObject *multi;
10307
if (n < 2 || n > NPY_MAXARGS) {
10308
PyErr_Format(PyExc_ValueError,
10309
"Need between 2 and (%d) " \
10310
"array objects (inclusive).", NPY_MAXARGS);
10313
/* fprintf(stderr, "multi new...");*/
10315
multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
10316
if (multi == NULL) return PyErr_NoMemory();
10317
PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
10319
for (i=0; i<n; i++) multi->iters[i] = NULL;
10320
multi->numiter = n;
10324
for (i=0; i<n; i++) {
10325
current = va_arg(va, PyObject *);
10326
arr = PyArray_FROM_O(current);
10331
multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr);
10338
if (!err && PyArray_Broadcast(multi) < 0) err=1;
10345
PyArray_MultiIter_RESET(multi);
10347
return (PyObject *)multi;
10771
PyArrayMultiIterObject *multi;
10777
if (n < 2 || n > NPY_MAXARGS) {
10778
PyErr_Format(PyExc_ValueError,
10779
"Need between 2 and (%d) " \
10780
"array objects (inclusive).", NPY_MAXARGS);
10784
/* fprintf(stderr, "multi new...");*/
10786
multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
10787
if (multi == NULL) return PyErr_NoMemory();
10788
PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
10790
for(i=0; i<n; i++) multi->iters[i] = NULL;
10791
multi->numiter = n;
10795
for(i=0; i<n; i++) {
10796
current = va_arg(va, PyObject *);
10797
arr = PyArray_FROM_O(current);
10802
multi->iters[i] = (PyArrayIterObject *)PyArray_IterNew(arr);
10809
if (!err && PyArray_Broadcast(multi) < 0) err=1;
10816
PyArray_MultiIter_RESET(multi);
10818
return (PyObject *)multi;
10350
10821
static PyObject *
10351
10822
arraymultiter_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
10355
PyArrayMultiIterObject *multi;
10358
if (kwds != NULL) {
10359
PyErr_SetString(PyExc_ValueError,
10360
"keyword arguments not accepted.");
10364
n = PyTuple_Size(args);
10365
if (n < 2 || n > NPY_MAXARGS) {
10366
if (PyErr_Occurred()) return NULL;
10367
PyErr_Format(PyExc_ValueError,
10368
"Need at least two and fewer than (%d) " \
10369
"array objects.", NPY_MAXARGS);
10373
multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
10374
if (multi == NULL) return PyErr_NoMemory();
10375
PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
10377
multi->numiter = n;
10379
for (i=0; i<n; i++) multi->iters[i] = NULL;
10380
for (i=0; i<n; i++) {
10381
arr = PyArray_FromAny(PyTuple_GET_ITEM(args, i), NULL, 0, 0, 0, NULL);
10382
if (arr == NULL) goto fail;
10383
if ((multi->iters[i] = \
10384
(PyArrayIterObject *)PyArray_IterNew(arr))==NULL)
10388
if (PyArray_Broadcast(multi) < 0) goto fail;
10389
PyArray_MultiIter_RESET(multi);
10391
return (PyObject *)multi;
10826
PyArrayMultiIterObject *multi;
10829
if (kwds != NULL) {
10830
PyErr_SetString(PyExc_ValueError,
10831
"keyword arguments not accepted.");
10835
n = PyTuple_Size(args);
10836
if (n < 2 || n > NPY_MAXARGS) {
10837
if (PyErr_Occurred()) return NULL;
10838
PyErr_Format(PyExc_ValueError,
10839
"Need at least two and fewer than (%d) " \
10840
"array objects.", NPY_MAXARGS);
10844
multi = _pya_malloc(sizeof(PyArrayMultiIterObject));
10845
if (multi == NULL) return PyErr_NoMemory();
10846
PyObject_Init((PyObject *)multi, &PyArrayMultiIter_Type);
10848
multi->numiter = n;
10850
for(i=0; i<n; i++) multi->iters[i] = NULL;
10851
for(i=0; i<n; i++) {
10852
arr = PyArray_FromAny(PyTuple_GET_ITEM(args, i), NULL, 0, 0, 0, NULL);
10853
if (arr == NULL) goto fail;
10854
if ((multi->iters[i] = \
10855
(PyArrayIterObject *)PyArray_IterNew(arr))==NULL)
10859
if (PyArray_Broadcast(multi) < 0) goto fail;
10860
PyArray_MultiIter_RESET(multi);
10862
return (PyObject *)multi;
10398
10869
static PyObject *
10399
10870
arraymultiter_next(PyArrayMultiIterObject *multi)
10404
n = multi->numiter;
10405
ret = PyTuple_New(n);
10406
if (ret == NULL) return NULL;
10407
if (multi->index < multi->size) {
10408
for (i=0; i < n; i++) {
10409
PyArrayIterObject *it=multi->iters[i];
10410
PyTuple_SET_ITEM(ret, i,
10411
PyArray_ToScalar(it->dataptr, it->ao));
10412
PyArray_ITER_NEXT(it);
10875
n = multi->numiter;
10876
ret = PyTuple_New(n);
10877
if (ret == NULL) return NULL;
10878
if (multi->index < multi->size) {
10879
for(i=0; i < n; i++) {
10880
PyArrayIterObject *it=multi->iters[i];
10881
PyTuple_SET_ITEM(ret, i,
10882
PyArray_ToScalar(it->dataptr, it->ao));
10883
PyArray_ITER_NEXT(it);
10421
10892
arraymultiter_dealloc(PyArrayMultiIterObject *multi)
10425
for (i=0; i<multi->numiter; i++)
10426
Py_XDECREF(multi->iters[i]);
10427
multi->ob_type->tp_free((PyObject *)multi);
10896
for(i=0; i<multi->numiter; i++)
10897
Py_XDECREF(multi->iters[i]);
10898
multi->ob_type->tp_free((PyObject *)multi);
10430
10901
static PyObject *
10431
10902
arraymultiter_size_get(PyArrayMultiIterObject *self)
10433
10904
#if SIZEOF_INTP <= SIZEOF_LONG
10905
return PyInt_FromLong((long) self->size);
10907
if (self->size < MAX_LONG)
10434
10908
return PyInt_FromLong((long) self->size);
10436
if (self->size < MAX_LONG)
10437
return PyInt_FromLong((long) self->size);
10439
return PyLong_FromLongLong((longlong) self->size);
10910
return PyLong_FromLongLong((longlong) self->size);
10444
10915
arraymultiter_index_get(PyArrayMultiIterObject *self)
10446
10917
#if SIZEOF_INTP <= SIZEOF_LONG
10918
return PyInt_FromLong((long) self->index);
10920
if (self->size < MAX_LONG)
10447
10921
return PyInt_FromLong((long) self->index);
10449
if (self->size < MAX_LONG)
10450
return PyInt_FromLong((long) self->index);
10452
return PyLong_FromLongLong((longlong) self->index);
10923
return PyLong_FromLongLong((longlong) self->index);
10456
10927
static PyObject *
10457
10928
arraymultiter_shape_get(PyArrayMultiIterObject *self)
10459
return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
10930
return PyArray_IntTupleFromIntp(self->nd, self->dimensions);
10462
10933
static PyObject *
10463
10934
arraymultiter_iters_get(PyArrayMultiIterObject *self)
10468
res = PyTuple_New(n);
10469
if (res == NULL) return res;
10470
for (i=0; i<n; i++) {
10471
Py_INCREF(self->iters[i]);
10472
PyTuple_SET_ITEM(res, i, (PyObject *)self->iters[i]);
10939
res = PyTuple_New(n);
10940
if (res == NULL) return res;
10941
for(i=0; i<n; i++) {
10942
Py_INCREF(self->iters[i]);
10943
PyTuple_SET_ITEM(res, i, (PyObject *)self->iters[i]);
10477
10948
static PyGetSetDef arraymultiter_getsetlist[] = {
10479
(getter)arraymultiter_size_get,
10482
(getter)arraymultiter_index_get,
10485
(getter)arraymultiter_shape_get,
10488
(getter)arraymultiter_iters_get,
10490
{NULL, NULL, NULL, NULL},
10950
(getter)arraymultiter_size_get,
10953
(getter)arraymultiter_index_get,
10956
(getter)arraymultiter_shape_get,
10959
(getter)arraymultiter_iters_get,
10961
{NULL, NULL, NULL, NULL},
10493
10964
static PyMemberDef arraymultiter_members[] = {
10494
{"numiter", T_INT, offsetof(PyArrayMultiIterObject, numiter),
10496
{"nd", T_INT, offsetof(PyArrayMultiIterObject, nd), RO, NULL},
10965
{"numiter", T_INT, offsetof(PyArrayMultiIterObject, numiter),
10967
{"nd", T_INT, offsetof(PyArrayMultiIterObject, nd), RO, NULL},
10500
10971
static PyObject *
10501
10972
arraymultiter_reset(PyArrayMultiIterObject *self, PyObject *args)
10503
if (!PyArg_ParseTuple(args, "")) return NULL;
10974
if (!PyArg_ParseTuple(args, "")) return NULL;
10505
PyArray_MultiIter_RESET(self);
10506
Py_INCREF(Py_None);
10976
PyArray_MultiIter_RESET(self);
10977
Py_INCREF(Py_None);
10510
10981
static PyMethodDef arraymultiter_methods[] = {
10511
{"reset", (PyCFunction) arraymultiter_reset, METH_VARARGS, NULL},
10982
{"reset", (PyCFunction) arraymultiter_reset, METH_VARARGS, NULL},
10515
10986
static PyTypeObject PyArrayMultiIter_Type = {
10516
PyObject_HEAD_INIT(NULL)
10518
"numpy.broadcast", /* tp_name */
10519
sizeof(PyArrayMultiIterObject), /* tp_basicsize */
10520
0, /* tp_itemsize */
10522
(destructor)arraymultiter_dealloc, /* tp_dealloc */
10524
0, /* tp_getattr */
10525
0, /* tp_setattr */
10526
0, /* tp_compare */
10528
0, /* tp_as_number */
10529
0, /* tp_as_sequence */
10530
0, /* tp_as_mapping */
10534
0, /* tp_getattro */
10535
0, /* tp_setattro */
10536
0, /* tp_as_buffer */
10537
Py_TPFLAGS_DEFAULT, /* tp_flags */
10539
0, /* tp_traverse */
10541
0, /* tp_richcompare */
10542
0, /* tp_weaklistoffset */
10544
(iternextfunc)arraymultiter_next, /* tp_iternext */
10545
arraymultiter_methods, /* tp_methods */
10546
arraymultiter_members, /* tp_members */
10547
arraymultiter_getsetlist, /* tp_getset */
10550
0, /* tp_descr_get */
10551
0, /* tp_descr_set */
10552
0, /* tp_dictoffset */
10553
(initproc)0, /* tp_init */
10555
arraymultiter_new, /* tp_new */
10561
0, /* tp_subclasses */
10562
0 /* tp_weaklist */
10987
PyObject_HEAD_INIT(NULL)
10989
"numpy.broadcast", /* tp_name */
10990
sizeof(PyArrayMultiIterObject), /* tp_basicsize */
10991
0, /* tp_itemsize */
10993
(destructor)arraymultiter_dealloc, /* tp_dealloc */
10995
0, /* tp_getattr */
10996
0, /* tp_setattr */
10997
0, /* tp_compare */
10999
0, /* tp_as_number */
11000
0, /* tp_as_sequence */
11001
0, /* tp_as_mapping */
11005
0, /* tp_getattro */
11006
0, /* tp_setattro */
11007
0, /* tp_as_buffer */
11008
Py_TPFLAGS_DEFAULT, /* tp_flags */
11010
0, /* tp_traverse */
11012
0, /* tp_richcompare */
11013
0, /* tp_weaklistoffset */
11015
(iternextfunc)arraymultiter_next, /* tp_iternext */
11016
arraymultiter_methods, /* tp_methods */
11017
arraymultiter_members, /* tp_members */
11018
arraymultiter_getsetlist, /* tp_getset */
11021
0, /* tp_descr_get */
11022
0, /* tp_descr_set */
11023
0, /* tp_dictoffset */
11024
(initproc)0, /* tp_init */
11026
arraymultiter_new, /* tp_new */
11032
0, /* tp_subclasses */
11033
0 /* tp_weaklist */
10565
11036
/*OBJECT_API*/
10566
11037
static PyArray_Descr *
10567
11038
PyArray_DescrNewFromType(int type_num)
10569
PyArray_Descr *old;
10570
PyArray_Descr *new;
11040
PyArray_Descr *old;
11041
PyArray_Descr *new;
10572
old = PyArray_DescrFromType(type_num);
10573
new = PyArray_DescrNew(old);
11043
old = PyArray_DescrFromType(type_num);
11044
new = PyArray_DescrNew(old);
10578
11049
/*** Array Descr Objects for dynamic types **/
10646
11117
data. Currently no attributes of dtype objects can be set.
10648
11119
static PyMemberDef arraydescr_members[] = {
10649
{"type", T_OBJECT, offsetof(PyArray_Descr, typeobj), RO, NULL},
10650
{"kind", T_CHAR, offsetof(PyArray_Descr, kind), RO, NULL},
10651
{"char", T_CHAR, offsetof(PyArray_Descr, type), RO, NULL},
10652
{"num", T_INT, offsetof(PyArray_Descr, type_num), RO, NULL},
10653
{"byteorder", T_CHAR, offsetof(PyArray_Descr, byteorder), RO, NULL},
10654
{"itemsize", T_INT, offsetof(PyArray_Descr, elsize), RO, NULL},
10655
{"alignment", T_INT, offsetof(PyArray_Descr, alignment), RO, NULL},
10656
{"flags", T_UBYTE, offsetof(PyArray_Descr, hasobject), RO, NULL},
10657
{"names", T_OBJECT, offsetof(PyArray_Descr, names), RO, NULL},
11120
{"type", T_OBJECT, offsetof(PyArray_Descr, typeobj), RO, NULL},
11121
{"kind", T_CHAR, offsetof(PyArray_Descr, kind), RO, NULL},
11122
{"char", T_CHAR, offsetof(PyArray_Descr, type), RO, NULL},
11123
{"num", T_INT, offsetof(PyArray_Descr, type_num), RO, NULL},
11124
{"byteorder", T_CHAR, offsetof(PyArray_Descr, byteorder), RO, NULL},
11125
{"itemsize", T_INT, offsetof(PyArray_Descr, elsize), RO, NULL},
11126
{"alignment", T_INT, offsetof(PyArray_Descr, alignment), RO, NULL},
11127
{"flags", T_UBYTE, offsetof(PyArray_Descr, hasobject), RO, NULL},
10661
11131
static PyObject *
10662
11132
arraydescr_subdescr_get(PyArray_Descr *self)
10664
if (self->subarray == NULL) {
10665
Py_INCREF(Py_None);
10668
return Py_BuildValue("OO", (PyObject *)self->subarray->base,
10669
self->subarray->shape);
11134
if (self->subarray == NULL) {
11135
Py_INCREF(Py_None);
11138
return Py_BuildValue("OO", (PyObject *)self->subarray->base,
11139
self->subarray->shape);
10672
11142
static PyObject *
10673
11143
arraydescr_protocol_typestr_get(PyArray_Descr *self)
10675
char basic_=self->kind;
10676
char endian = self->byteorder;
10677
int size=self->elsize;
10679
if (endian == '=') {
10681
if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
10684
if (self->type_num == PyArray_UNICODE) {
10687
return PyString_FromFormat("%c%c%d", endian, basic_, size);
11145
char basic_=self->kind;
11146
char endian = self->byteorder;
11147
int size=self->elsize;
11149
if (endian == '=') {
11151
if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
11154
if (self->type_num == PyArray_UNICODE) {
11157
return PyString_FromFormat("%c%c%d", endian, basic_, size);
10690
11160
static PyObject *
10691
11161
arraydescr_typename_get(PyArray_Descr *self)
10694
PyTypeObject *typeobj = self->typeobj;
10697
static int prefix_len=0;
10699
if (PyTypeNum_ISUSERDEF(self->type_num)) {
10700
s = strrchr(typeobj->tp_name, '.');
10702
res = PyString_FromString(typeobj->tp_name);
10705
res = PyString_FromStringAndSize(s+1, strlen(s)-1);
11164
PyTypeObject *typeobj = self->typeobj;
11167
static int prefix_len=0;
11169
if (PyTypeNum_ISUSERDEF(self->type_num)) {
11170
s = strrchr(typeobj->tp_name, '.');
11172
res = PyString_FromString(typeobj->tp_name);
10710
if (prefix_len == 0)
10711
prefix_len = strlen("numpy.");
10713
len = strlen(typeobj->tp_name);
10714
if (*(typeobj->tp_name + (len-1)) == '_')
10717
res = PyString_FromStringAndSize(typeobj->tp_name+prefix_len, len);
10719
if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) {
10721
p = PyString_FromFormat("%d", self->elsize * 8);
10722
PyString_ConcatAndDel(&res, p);
11175
res = PyString_FromStringAndSize(s+1, strlen(s)-1);
11180
if (prefix_len == 0)
11181
prefix_len = strlen("numpy.");
11183
len = strlen(typeobj->tp_name);
11184
if (*(typeobj->tp_name + (len-1)) == '_')
11187
res = PyString_FromStringAndSize(typeobj->tp_name+prefix_len, len);
11189
if (PyTypeNum_ISFLEXIBLE(self->type_num) && self->elsize != 0) {
11191
p = PyString_FromFormat("%d", self->elsize * 8);
11192
PyString_ConcatAndDel(&res, p);
10727
11197
static PyObject *
10728
11198
arraydescr_base_get(PyArray_Descr *self)
10730
if (self->subarray == NULL) {
10732
return (PyObject *)self;
10734
Py_INCREF(self->subarray->base);
10735
return (PyObject *)(self->subarray->base);
11200
if (self->subarray == NULL) {
11202
return (PyObject *)self;
11204
Py_INCREF(self->subarray->base);
11205
return (PyObject *)(self->subarray->base);
10738
11208
static PyObject *
10739
11209
arraydescr_shape_get(PyArray_Descr *self)
10741
if (self->subarray == NULL) {
10742
return PyTuple_New(0);
10744
if (PyTuple_Check(self->subarray->shape)) {
10745
Py_INCREF(self->subarray->shape);
10746
return (PyObject *)(self->subarray->shape);
10748
return Py_BuildValue("(O)", self->subarray->shape);
11211
if (self->subarray == NULL) {
11212
return PyTuple_New(0);
11214
if (PyTuple_Check(self->subarray->shape)) {
11215
Py_INCREF(self->subarray->shape);
11216
return (PyObject *)(self->subarray->shape);
11218
return Py_BuildValue("(O)", self->subarray->shape);
10751
11221
static PyObject *
10752
11222
arraydescr_protocol_descr_get(PyArray_Descr *self)
10754
PyObject *dobj, *res;
10756
if (self->names == NULL) {
10758
dobj = PyTuple_New(2);
10759
if (dobj == NULL) return NULL;
10760
PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
10761
PyTuple_SET_ITEM(dobj, 1, \
10762
arraydescr_protocol_typestr_get(self));
10763
res = PyList_New(1);
10764
if (res == NULL) {Py_DECREF(dobj); return NULL;}
10765
PyList_SET_ITEM(res, 0, dobj);
10769
return PyObject_CallMethod(_numpy_internal, "_array_descr",
11224
PyObject *dobj, *res;
11225
PyObject *_numpy_internal;
11227
if (self->names == NULL) {
11229
dobj = PyTuple_New(2);
11230
if (dobj == NULL) return NULL;
11231
PyTuple_SET_ITEM(dobj, 0, PyString_FromString(""));
11232
PyTuple_SET_ITEM(dobj, 1, \
11233
arraydescr_protocol_typestr_get(self));
11234
res = PyList_New(1);
11235
if (res == NULL) {Py_DECREF(dobj); return NULL;}
11236
PyList_SET_ITEM(res, 0, dobj);
11240
_numpy_internal = PyImport_ImportModule("numpy.core._internal");
11241
if (_numpy_internal == NULL) return NULL;
11242
res = PyObject_CallMethod(_numpy_internal, "_array_descr",
11244
Py_DECREF(_numpy_internal);
10773
11248
/* returns 1 for a builtin type
10813
11288
static PyObject *
10814
11289
arraydescr_isnative_get(PyArray_Descr *self)
10818
retval = _arraydescr_isnative(self);
10819
if (retval == -1) return NULL;
10820
ret = (retval ? Py_True : Py_False);
11293
retval = _arraydescr_isnative(self);
11294
if (retval == -1) return NULL;
11295
ret = (retval ? Py_True : Py_False);
10825
11300
static PyObject *
10826
11301
arraydescr_fields_get(PyArray_Descr *self)
10828
if (self->names == NULL) {
10829
Py_INCREF(Py_None);
10832
return PyDictProxy_New(self->fields);
11303
if (self->names == NULL) {
11304
Py_INCREF(Py_None);
11307
return PyDictProxy_New(self->fields);
10835
11310
static PyObject *
10836
11311
arraydescr_hasobject_get(PyArray_Descr *self)
10839
if (PyDataType_FLAGCHK(self, NPY_ITEM_HASOBJECT))
11314
if (PyDataType_FLAGCHK(self, NPY_ITEM_HASOBJECT))
11323
arraydescr_names_get(PyArray_Descr *self)
11325
if (self->names == NULL) {
11326
Py_INCREF(Py_None);
11329
Py_INCREF(self->names);
11330
return self->names;
11334
arraydescr_names_set(PyArray_Descr *self, PyObject *val)
11338
PyObject *new_names;
11339
if (self->names == NULL) {
11340
PyErr_SetString(PyExc_ValueError, "there are no fields defined");
11344
N = PyTuple_GET_SIZE(self->names);
11345
if (!PySequence_Check(val) || PyObject_Size((PyObject *)val) != N) {
11346
PyErr_Format(PyExc_ValueError, "must replace all names at once" \
11347
" with a sequence of length %d", N);
11350
/* Make sure all entries are strings */
11351
for(i=0; i<N; i++) {
11354
item = PySequence_GetItem(val, i);
11355
valid = PyString_Check(item);
11358
PyErr_Format(PyExc_ValueError,
11359
"item #%d of names is of type %s and not string",
11360
i, item->ob_type->tp_name);
11364
/* Update dictionary keys in fields */
11365
new_names = PySequence_Tuple(val);
11367
for(i=0; i<N; i++) {
11371
key = PyTuple_GET_ITEM(self->names, i);
11372
/* Borrowed reference to item */
11373
item = PyDict_GetItem(self->fields, key);
11374
new_key = PyTuple_GET_ITEM(new_names, i);
11375
PyDict_SetItem(self->fields, new_key, item);
11376
PyDict_DelItem(self->fields, key);
11379
/* Replace names */
11380
Py_DECREF(self->names);
11381
self->names = new_names;
10847
11386
static PyGetSetDef arraydescr_getsets[] = {
10849
(getter)arraydescr_subdescr_get,
10852
(getter)arraydescr_protocol_descr_get,
10855
(getter)arraydescr_protocol_typestr_get,
10858
(getter)arraydescr_typename_get,
10861
(getter)arraydescr_base_get,
10864
(getter)arraydescr_shape_get,
10867
(getter)arraydescr_isbuiltin_get,
10870
(getter)arraydescr_isnative_get,
10873
(getter)arraydescr_fields_get,
10876
(getter)arraydescr_hasobject_get,
10878
{NULL, NULL, NULL, NULL},
11388
(getter)arraydescr_subdescr_get,
11391
(getter)arraydescr_protocol_descr_get,
11394
(getter)arraydescr_protocol_typestr_get,
11397
(getter)arraydescr_typename_get,
11400
(getter)arraydescr_base_get,
11403
(getter)arraydescr_shape_get,
11406
(getter)arraydescr_isbuiltin_get,
11409
(getter)arraydescr_isnative_get,
11412
(getter)arraydescr_fields_get,
11415
(getter)arraydescr_names_get,
11416
(setter)arraydescr_names_set,
11419
(getter)arraydescr_hasobject_get,
11421
{NULL, NULL, NULL, NULL},
10881
11424
static PyObject *
10882
11425
arraydescr_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
10885
PyArray_Descr *descr, *conv;
10888
static char *kwlist[] = {"dtype", "align", "copy", NULL};
10890
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&",
10892
PyArray_BoolConverter, &align,
10893
PyArray_BoolConverter, ©))
10897
if (!PyArray_DescrAlignConverter(odescr, &conv))
10900
else if (!PyArray_DescrConverter(odescr, &conv))
10902
/* Get a new copy of it unless it's already a copy */
10903
if (copy && conv->fields == Py_None) {
10904
descr = PyArray_DescrNew(conv);
10908
return (PyObject *)conv;
11428
PyArray_Descr *descr, *conv;
11431
static char *kwlist[] = {"dtype", "align", "copy", NULL};
11433
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O&O&",
11435
PyArray_BoolConverter, &align,
11436
PyArray_BoolConverter, ©))
11440
if (!PyArray_DescrAlignConverter(odescr, &conv))
11443
else if (!PyArray_DescrConverter(odescr, &conv))
11445
/* Get a new copy of it unless it's already a copy */
11446
if (copy && conv->fields == Py_None) {
11447
descr = PyArray_DescrNew(conv);
11451
return (PyObject *)conv;
10913
11456
static PyObject *
10914
11457
arraydescr_reduce(PyArray_Descr *self, PyObject *args)
10916
/* version number of this pickle type. Increment if we need to
10917
change the format. Be sure to handle the old versions in
10918
arraydescr_setstate. */
10919
const int version = 3;
10920
PyObject *ret, *mod, *obj;
10923
int elsize, alignment;
10925
ret = PyTuple_New(3);
10926
if (ret == NULL) return NULL;
10927
mod = PyImport_ImportModule("numpy.core.multiarray");
10928
if (mod == NULL) {Py_DECREF(ret); return NULL;}
10929
obj = PyObject_GetAttrString(mod, "dtype");
10931
if (obj == NULL) {Py_DECREF(ret); return NULL;}
10932
PyTuple_SET_ITEM(ret, 0, obj);
10933
if (PyTypeNum_ISUSERDEF(self->type_num) || \
10934
((self->type_num == PyArray_VOID && \
10935
self->typeobj != &PyVoidArrType_Type))) {
10936
obj = (PyObject *)self->typeobj;
10940
elsize = self->elsize;
10941
if (self->type_num == PyArray_UNICODE) {
10944
obj = PyString_FromFormat("%c%d",self->kind, elsize);
10946
PyTuple_SET_ITEM(ret, 1, Py_BuildValue("(Nii)", obj, 0, 1));
10948
/* Now return the state which is at least
10949
byteorder, subarray, and fields */
10950
endian = self->byteorder;
10951
if (endian == '=') {
10953
if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
10955
state = PyTuple_New(8);
10956
PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
10957
PyTuple_SET_ITEM(state, 1, PyString_FromFormat("%c", endian));
10958
PyTuple_SET_ITEM(state, 2, arraydescr_subdescr_get(self));
10960
Py_INCREF(self->names);
10961
Py_INCREF(self->fields);
10962
PyTuple_SET_ITEM(state, 3, self->names);
10963
PyTuple_SET_ITEM(state, 4, self->fields);
10966
PyTuple_SET_ITEM(state, 3, Py_None);
10967
PyTuple_SET_ITEM(state, 4, Py_None);
10968
Py_INCREF(Py_None);
10969
Py_INCREF(Py_None);
10972
/* for extended types it also includes elsize and alignment */
10973
if (PyTypeNum_ISEXTENDED(self->type_num)) {
10974
elsize = self->elsize;
10975
alignment = self->alignment;
10977
else {elsize = -1; alignment = -1;}
10979
PyTuple_SET_ITEM(state, 5, PyInt_FromLong(elsize));
10980
PyTuple_SET_ITEM(state, 6, PyInt_FromLong(alignment));
10981
PyTuple_SET_ITEM(state, 7, PyInt_FromLong(self->hasobject));
10983
PyTuple_SET_ITEM(ret, 2, state);
11459
/* version number of this pickle type. Increment if we need to
11460
change the format. Be sure to handle the old versions in
11461
arraydescr_setstate. */
11462
const int version = 3;
11463
PyObject *ret, *mod, *obj;
11466
int elsize, alignment;
11468
ret = PyTuple_New(3);
11469
if (ret == NULL) return NULL;
11470
mod = PyImport_ImportModule("numpy.core.multiarray");
11471
if (mod == NULL) {Py_DECREF(ret); return NULL;}
11472
obj = PyObject_GetAttrString(mod, "dtype");
11474
if (obj == NULL) {Py_DECREF(ret); return NULL;}
11475
PyTuple_SET_ITEM(ret, 0, obj);
11476
if (PyTypeNum_ISUSERDEF(self->type_num) || \
11477
((self->type_num == PyArray_VOID && \
11478
self->typeobj != &PyVoidArrType_Type))) {
11479
obj = (PyObject *)self->typeobj;
11483
elsize = self->elsize;
11484
if (self->type_num == PyArray_UNICODE) {
11487
obj = PyString_FromFormat("%c%d",self->kind, elsize);
11489
PyTuple_SET_ITEM(ret, 1, Py_BuildValue("(Nii)", obj, 0, 1));
11491
/* Now return the state which is at least
11492
byteorder, subarray, and fields */
11493
endian = self->byteorder;
11494
if (endian == '=') {
11496
if (!PyArray_IsNativeByteOrder(endian)) endian = '>';
11498
state = PyTuple_New(8);
11499
PyTuple_SET_ITEM(state, 0, PyInt_FromLong(version));
11500
PyTuple_SET_ITEM(state, 1, PyString_FromFormat("%c", endian));
11501
PyTuple_SET_ITEM(state, 2, arraydescr_subdescr_get(self));
11503
Py_INCREF(self->names);
11504
Py_INCREF(self->fields);
11505
PyTuple_SET_ITEM(state, 3, self->names);
11506
PyTuple_SET_ITEM(state, 4, self->fields);
11509
PyTuple_SET_ITEM(state, 3, Py_None);
11510
PyTuple_SET_ITEM(state, 4, Py_None);
11511
Py_INCREF(Py_None);
11512
Py_INCREF(Py_None);
11515
/* for extended types it also includes elsize and alignment */
11516
if (PyTypeNum_ISEXTENDED(self->type_num)) {
11517
elsize = self->elsize;
11518
alignment = self->alignment;
11520
else {elsize = -1; alignment = -1;}
11522
PyTuple_SET_ITEM(state, 5, PyInt_FromLong(elsize));
11523
PyTuple_SET_ITEM(state, 6, PyInt_FromLong(alignment));
11524
PyTuple_SET_ITEM(state, 7, PyInt_FromLong(self->hasobject));
11526
PyTuple_SET_ITEM(ret, 2, state);
10987
11530
/* returns 1 if this data-type has an object portion
10988
11531
used when setting the state because hasobject is not stored.
10991
11534
_descr_find_object(PyArray_Descr *self)
10993
if (self->hasobject || self->type_num == PyArray_OBJECT ||
11536
if (self->hasobject || self->type_num == PyArray_OBJECT ||
11538
return NPY_OBJECT_DTYPE_FLAGS;
11539
if (PyDescr_HASFIELDS(self)) {
11540
PyObject *key, *value, *title=NULL;
11541
PyArray_Descr *new;
11544
while (PyDict_Next(self->fields, &pos, &key, &value)) {
11545
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
11550
if (_descr_find_object(new)) {
11551
new->hasobject = NPY_OBJECT_DTYPE_FLAGS;
10995
11552
return NPY_OBJECT_DTYPE_FLAGS;
10996
if (PyDescr_HASFIELDS(self)) {
10997
PyObject *key, *value, *title=NULL;
10998
PyArray_Descr *new;
11001
while (PyDict_Next(self->fields, &pos, &key, &value)) {
11002
if (!PyArg_ParseTuple(value, "Oi|O", &new, &offset,
11007
if (_descr_find_object(new)) {
11008
new->hasobject = NPY_OBJECT_DTYPE_FLAGS;
11009
return NPY_OBJECT_DTYPE_FLAGS;
11016
11559
/* state is at least byteorder, subarray, and fields but could include elsize
11020
11563
static PyObject *
11021
11564
arraydescr_setstate(PyArray_Descr *self, PyObject *args)
11023
int elsize = -1, alignment = -1;
11026
PyObject *subarray, *fields, *names=NULL;
11027
int incref_names = 1;
11030
if (self->fields == Py_None) {Py_INCREF(Py_None); return Py_None;}
11032
if (PyTuple_GET_SIZE(args) != 1 ||
11033
!(PyTuple_Check(PyTuple_GET_ITEM(args, 0)))) {
11034
PyErr_BadInternalCall();
11037
switch (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0))) {
11039
if (!PyArg_ParseTuple(args, "(icOOOiii)", &version, &endian,
11040
&subarray, &names, &fields, &elsize,
11041
&alignment, &dtypeflags)) {
11046
if (!PyArg_ParseTuple(args, "(icOOOii)", &version, &endian,
11047
&subarray, &names, &fields, &elsize,
11053
if (!PyArg_ParseTuple(args, "(icOOii)", &version,
11054
&endian, &subarray, &fields,
11055
&elsize, &alignment)) {
11061
if (!PyArg_ParseTuple(args, "(cOOii)",
11062
&endian, &subarray, &fields, &elsize,
11068
version = -1; /* raise an error */
11071
/* If we ever need another pickle format, increment the version
11072
number. But we should still be able to handle the old versions.
11074
if (version < 0 || version > 3) {
11075
PyErr_Format(PyExc_ValueError,
11076
"can't handle version %d of numpy.dtype pickle",
11081
if (version == 1 || version == 0) {
11082
if (fields != Py_None) {
11083
PyObject *key, *list;
11084
key = PyInt_FromLong(-1);
11085
list = PyDict_GetItem(fields, key);
11086
if (!list) return NULL;
11089
PyDict_DelItem(fields, key);
11098
if ((fields == Py_None && names != Py_None) || \
11099
(names == Py_None && fields != Py_None)) {
11100
PyErr_Format(PyExc_ValueError,
11101
"inconsistent fields and names");
11105
if (endian != '|' &&
11106
PyArray_IsNativeByteOrder(endian)) endian = '=';
11108
self->byteorder = endian;
11109
if (self->subarray) {
11110
Py_XDECREF(self->subarray->base);
11111
Py_XDECREF(self->subarray->shape);
11112
_pya_free(self->subarray);
11114
self->subarray = NULL;
11116
if (subarray != Py_None) {
11117
self->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
11118
self->subarray->base = (PyArray_Descr *)PyTuple_GET_ITEM(subarray, 0);
11119
Py_INCREF(self->subarray->base);
11120
self->subarray->shape = PyTuple_GET_ITEM(subarray, 1);
11121
Py_INCREF(self->subarray->shape);
11566
int elsize = -1, alignment = -1;
11569
PyObject *subarray, *fields, *names=NULL;
11570
int incref_names = 1;
11573
if (self->fields == Py_None) {Py_INCREF(Py_None); return Py_None;}
11575
if (PyTuple_GET_SIZE(args) != 1 ||
11576
!(PyTuple_Check(PyTuple_GET_ITEM(args, 0)))) {
11577
PyErr_BadInternalCall();
11580
switch (PyTuple_GET_SIZE(PyTuple_GET_ITEM(args,0))) {
11582
if (!PyArg_ParseTuple(args, "(icOOOiii)", &version, &endian,
11583
&subarray, &names, &fields, &elsize,
11584
&alignment, &dtypeflags)) {
11589
if (!PyArg_ParseTuple(args, "(icOOOii)", &version, &endian,
11590
&subarray, &names, &fields, &elsize,
11596
if (!PyArg_ParseTuple(args, "(icOOii)", &version,
11597
&endian, &subarray, &fields,
11598
&elsize, &alignment)) {
11604
if (!PyArg_ParseTuple(args, "(cOOii)",
11605
&endian, &subarray, &fields, &elsize,
11611
version = -1; /* raise an error */
11614
/* If we ever need another pickle format, increment the version
11615
number. But we should still be able to handle the old versions.
11617
if (version < 0 || version > 3) {
11618
PyErr_Format(PyExc_ValueError,
11619
"can't handle version %d of numpy.dtype pickle",
11624
if (version == 1 || version == 0) {
11124
11625
if (fields != Py_None) {
11125
Py_XDECREF(self->fields);
11126
self->fields = fields;
11128
Py_XDECREF(self->names);
11129
self->names = names;
11134
if (PyTypeNum_ISEXTENDED(self->type_num)) {
11135
self->elsize = elsize;
11136
self->alignment = alignment;
11139
self->hasobject = dtypeflags;
11141
self->hasobject = _descr_find_object(self);
11143
Py_INCREF(Py_None);
11626
PyObject *key, *list;
11627
key = PyInt_FromLong(-1);
11628
list = PyDict_GetItem(fields, key);
11629
if (!list) return NULL;
11632
PyDict_DelItem(fields, key);
11641
if ((fields == Py_None && names != Py_None) || \
11642
(names == Py_None && fields != Py_None)) {
11643
PyErr_Format(PyExc_ValueError,
11644
"inconsistent fields and names");
11648
if (endian != '|' &&
11649
PyArray_IsNativeByteOrder(endian)) endian = '=';
11651
self->byteorder = endian;
11652
if (self->subarray) {
11653
Py_XDECREF(self->subarray->base);
11654
Py_XDECREF(self->subarray->shape);
11655
_pya_free(self->subarray);
11657
self->subarray = NULL;
11659
if (subarray != Py_None) {
11660
self->subarray = _pya_malloc(sizeof(PyArray_ArrayDescr));
11661
self->subarray->base = (PyArray_Descr *)PyTuple_GET_ITEM(subarray, 0);
11662
Py_INCREF(self->subarray->base);
11663
self->subarray->shape = PyTuple_GET_ITEM(subarray, 1);
11664
Py_INCREF(self->subarray->shape);
11667
if (fields != Py_None) {
11668
Py_XDECREF(self->fields);
11669
self->fields = fields;
11671
Py_XDECREF(self->names);
11672
self->names = names;
11677
if (PyTypeNum_ISEXTENDED(self->type_num)) {
11678
self->elsize = elsize;
11679
self->alignment = alignment;
11682
self->hasobject = dtypeflags;
11684
self->hasobject = _descr_find_object(self);
11686
Py_INCREF(Py_None);
11148
11691
/* returns a copy of the PyArray_Descr structure with the byteorder
11150
no arguments: The byteorder is swapped (in all subfields as well)
11151
single argument: The byteorder is forced to the given state
11152
(in all subfields as well)
11154
Valid states: ('big', '>') or ('little' or '<')
11157
If a descr structure with | is encountered it's own
11158
byte-order is not changed but any fields are:
11693
no arguments: The byteorder is swapped (in all subfields as well)
11694
single argument: The byteorder is forced to the given state
11695
(in all subfields as well)
11697
Valid states: ('big', '>') or ('little' or '<')
11700
If a descr structure with | is encountered it's own
11701
byte-order is not changed but any fields are:
11162
11705
Deep bytorder change of a data-type descriptor
11163
11706
*** Leaves reference count of self unchanged --- does not DECREF self ***
11165
11708
static PyArray_Descr *
11166
11709
PyArray_DescrNewByteorder(PyArray_Descr *self, char newendian)
11168
PyArray_Descr *new;
11171
new = PyArray_DescrNew(self);
11172
endian = new->byteorder;
11173
if (endian != PyArray_IGNORE) {
11174
if (newendian == PyArray_SWAP) { /* swap byteorder */
11175
if PyArray_ISNBO(endian) endian = PyArray_OPPBYTE;
11176
else endian = PyArray_NATBYTE;
11177
new->byteorder = endian;
11179
else if (newendian != PyArray_IGNORE) {
11180
new->byteorder = newendian;
11184
PyObject *newfields;
11185
PyObject *key, *value;
11186
PyObject *newvalue;
11188
PyArray_Descr *newdescr;
11189
Py_ssize_t pos = 0;
11191
newfields = PyDict_New();
11192
/* make new dictionary with replaced */
11193
/* PyArray_Descr Objects */
11194
while(PyDict_Next(self->fields, &pos, &key, &value)) {
11195
if (!PyString_Check(key) || \
11196
!PyTuple_Check(value) || \
11197
((len=PyTuple_GET_SIZE(value)) < 2))
11200
old = PyTuple_GET_ITEM(value, 0);
11201
if (!PyArray_DescrCheck(old)) continue;
11202
newdescr = PyArray_DescrNewByteorder \
11203
((PyArray_Descr *)old, newendian);
11204
if (newdescr == NULL) {
11205
Py_DECREF(newfields); Py_DECREF(new);
11208
newvalue = PyTuple_New(len);
11209
PyTuple_SET_ITEM(newvalue, 0, \
11210
(PyObject *)newdescr);
11211
for(i=1; i<len; i++) {
11212
old = PyTuple_GET_ITEM(value, i);
11214
PyTuple_SET_ITEM(newvalue, i, old);
11216
PyDict_SetItem(newfields, key, newvalue);
11217
Py_DECREF(newvalue);
11219
Py_DECREF(new->fields);
11220
new->fields = newfields;
11222
if (new->subarray) {
11223
Py_DECREF(new->subarray->base);
11224
new->subarray->base = PyArray_DescrNewByteorder \
11225
(self->subarray->base, newendian);
11711
PyArray_Descr *new;
11714
new = PyArray_DescrNew(self);
11715
endian = new->byteorder;
11716
if (endian != PyArray_IGNORE) {
11717
if (newendian == PyArray_SWAP) { /* swap byteorder */
11718
if PyArray_ISNBO(endian) endian = PyArray_OPPBYTE;
11719
else endian = PyArray_NATBYTE;
11720
new->byteorder = endian;
11722
else if (newendian != PyArray_IGNORE) {
11723
new->byteorder = newendian;
11727
PyObject *newfields;
11728
PyObject *key, *value;
11729
PyObject *newvalue;
11731
PyArray_Descr *newdescr;
11732
Py_ssize_t pos = 0;
11734
newfields = PyDict_New();
11735
/* make new dictionary with replaced */
11736
/* PyArray_Descr Objects */
11737
while(PyDict_Next(self->fields, &pos, &key, &value)) {
11738
if (!PyString_Check(key) || \
11739
!PyTuple_Check(value) || \
11740
((len=PyTuple_GET_SIZE(value)) < 2))
11743
old = PyTuple_GET_ITEM(value, 0);
11744
if (!PyArray_DescrCheck(old)) continue;
11745
newdescr = PyArray_DescrNewByteorder \
11746
((PyArray_Descr *)old, newendian);
11747
if (newdescr == NULL) {
11748
Py_DECREF(newfields); Py_DECREF(new);
11751
newvalue = PyTuple_New(len);
11752
PyTuple_SET_ITEM(newvalue, 0, \
11753
(PyObject *)newdescr);
11754
for(i=1; i<len; i++) {
11755
old = PyTuple_GET_ITEM(value, i);
11757
PyTuple_SET_ITEM(newvalue, i, old);
11759
PyDict_SetItem(newfields, key, newvalue);
11760
Py_DECREF(newvalue);
11762
Py_DECREF(new->fields);
11763
new->fields = newfields;
11765
if (new->subarray) {
11766
Py_DECREF(new->subarray->base);
11767
new->subarray->base = PyArray_DescrNewByteorder \
11768
(self->subarray->base, newendian);
11231
11774
static PyObject *
11232
11775
arraydescr_newbyteorder(PyArray_Descr *self, PyObject *args)
11234
char endian=PyArray_SWAP;
11236
if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
11237
&endian)) return NULL;
11239
return (PyObject *)PyArray_DescrNewByteorder(self, endian);
11777
char endian=PyArray_SWAP;
11779
if (!PyArg_ParseTuple(args, "|O&", PyArray_ByteorderConverter,
11780
&endian)) return NULL;
11782
return (PyObject *)PyArray_DescrNewByteorder(self, endian);
11242
11785
static PyMethodDef arraydescr_methods[] = {
11244
{"__reduce__", (PyCFunction)arraydescr_reduce, METH_VARARGS,
11246
{"__setstate__", (PyCFunction)arraydescr_setstate, METH_VARARGS,
11248
{"newbyteorder", (PyCFunction)arraydescr_newbyteorder, METH_VARARGS,
11250
{NULL, NULL} /* sentinel */
11787
{"__reduce__", (PyCFunction)arraydescr_reduce, METH_VARARGS,
11789
{"__setstate__", (PyCFunction)arraydescr_setstate, METH_VARARGS,
11791
{"newbyteorder", (PyCFunction)arraydescr_newbyteorder, METH_VARARGS,
11793
{NULL, NULL} /* sentinel */
11253
11796
static PyObject *
11254
11797
arraydescr_str(PyArray_Descr *self)
11260
lst = arraydescr_protocol_descr_get(self);
11262
sub = PyString_FromString("<err>");
11265
else sub = PyObject_Str(lst);
11267
if (self->type_num != PyArray_VOID) {
11269
PyObject *t=PyString_FromString("'");
11270
p = arraydescr_protocol_typestr_get(self);
11271
PyString_Concat(&p, t);
11272
PyString_ConcatAndDel(&t, p);
11273
p = PyString_FromString("(");
11274
PyString_ConcatAndDel(&p, t);
11275
PyString_ConcatAndDel(&p, PyString_FromString(", "));
11276
PyString_ConcatAndDel(&p, sub);
11277
PyString_ConcatAndDel(&p, PyString_FromString(")"));
11281
else if (self->subarray) {
11283
PyObject *t = PyString_FromString("(");
11285
p = arraydescr_str(self->subarray->base);
11286
if (!self->subarray->base->names && !self->subarray->base->subarray) {
11287
PyObject *t=PyString_FromString("'");
11288
PyString_Concat(&p, t);
11289
PyString_ConcatAndDel(&t, p);
11292
PyString_ConcatAndDel(&t, p);
11293
PyString_ConcatAndDel(&t, PyString_FromString(","));
11294
if (!PyTuple_Check(self->subarray->shape)) {
11295
sh = Py_BuildValue("(O)", self->subarray->shape);
11298
sh = self->subarray->shape;
11301
PyString_ConcatAndDel(&t, PyObject_Str(sh));
11303
PyString_ConcatAndDel(&t, PyString_FromString(")"));
11306
else if (PyDataType_ISFLEXIBLE(self) || !PyArray_ISNBO(self->byteorder)) {
11307
sub = arraydescr_protocol_typestr_get(self);
11803
lst = arraydescr_protocol_descr_get(self);
11805
sub = PyString_FromString("<err>");
11808
else sub = PyObject_Str(lst);
11810
if (self->type_num != PyArray_VOID) {
11812
PyObject *t=PyString_FromString("'");
11813
p = arraydescr_protocol_typestr_get(self);
11814
PyString_Concat(&p, t);
11815
PyString_ConcatAndDel(&t, p);
11816
p = PyString_FromString("(");
11817
PyString_ConcatAndDel(&p, t);
11818
PyString_ConcatAndDel(&p, PyString_FromString(", "));
11819
PyString_ConcatAndDel(&p, sub);
11820
PyString_ConcatAndDel(&p, PyString_FromString(")"));
11824
else if (self->subarray) {
11826
PyObject *t = PyString_FromString("(");
11828
p = arraydescr_str(self->subarray->base);
11829
if (!self->subarray->base->names && !self->subarray->base->subarray) {
11830
PyObject *t=PyString_FromString("'");
11831
PyString_Concat(&p, t);
11832
PyString_ConcatAndDel(&t, p);
11835
PyString_ConcatAndDel(&t, p);
11836
PyString_ConcatAndDel(&t, PyString_FromString(","));
11837
if (!PyTuple_Check(self->subarray->shape)) {
11838
sh = Py_BuildValue("(O)", self->subarray->shape);
11310
sub = arraydescr_typename_get(self);
11841
sh = self->subarray->shape;
11844
PyString_ConcatAndDel(&t, PyObject_Str(sh));
11846
PyString_ConcatAndDel(&t, PyString_FromString(")"));
11849
else if (PyDataType_ISFLEXIBLE(self) || !PyArray_ISNBO(self->byteorder)) {
11850
sub = arraydescr_protocol_typestr_get(self);
11853
sub = arraydescr_typename_get(self);
11315
11858
static PyObject *
11316
11859
arraydescr_repr(PyArray_Descr *self)
11319
s = PyString_FromString("dtype(");
11320
sub = arraydescr_str(self);
11321
if (!self->names && !self->subarray) {
11322
PyObject *t=PyString_FromString("'");
11323
PyString_Concat(&sub, t);
11324
PyString_ConcatAndDel(&t, sub);
11327
PyString_ConcatAndDel(&s, sub);
11328
sub = PyString_FromString(")");
11329
PyString_ConcatAndDel(&s, sub);
11862
s = PyString_FromString("dtype(");
11863
sub = arraydescr_str(self);
11864
if (!self->names && !self->subarray) {
11865
PyObject *t=PyString_FromString("'");
11866
PyString_Concat(&sub, t);
11867
PyString_ConcatAndDel(&t, sub);
11870
PyString_ConcatAndDel(&s, sub);
11871
sub = PyString_FromString(")");
11872
PyString_ConcatAndDel(&s, sub);
11333
11876
static PyObject *
11334
11877
arraydescr_richcompare(PyArray_Descr *self, PyObject *other, int cmp_op)
11336
PyArray_Descr *new=NULL;
11337
PyObject *result = Py_NotImplemented;
11338
if (!PyArray_DescrCheck(other)) {
11339
if (PyArray_DescrConverter(other, &new) == PY_FAIL)
11343
new = (PyArray_Descr *)other;
11348
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new))
11354
if (PyArray_CanCastTo(self, new))
11360
if (PyArray_EquivTypes(self, new))
11366
if (PyArray_EquivTypes(self, new))
11372
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self))
11378
if (PyArray_CanCastTo(new, self))
11384
result = Py_NotImplemented;
11879
PyArray_Descr *new=NULL;
11880
PyObject *result = Py_NotImplemented;
11881
if (!PyArray_DescrCheck(other)) {
11882
if (PyArray_DescrConverter(other, &new) == PY_FAIL)
11886
new = (PyArray_Descr *)other;
11891
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(self, new))
11897
if (PyArray_CanCastTo(self, new))
11903
if (PyArray_EquivTypes(self, new))
11909
if (PyArray_EquivTypes(self, new))
11915
if (!PyArray_EquivTypes(self, new) && PyArray_CanCastTo(new, self))
11921
if (PyArray_CanCastTo(new, self))
11927
result = Py_NotImplemented;
11392
11935
/*************************************************************************
11397
11940
descr_length(PyObject *self0)
11400
PyArray_Descr *self = (PyArray_Descr *)self0;
11943
PyArray_Descr *self = (PyArray_Descr *)self0;
11403
return PyDict_Size(self->fields);
11946
return PyTuple_GET_SIZE(self->names);
11407
11950
static PyObject *
11408
11951
descr_repeat(PyObject *self, Py_ssize_t length)
11411
PyArray_Descr *new;
11413
return PyErr_Format(PyExc_ValueError,
11954
PyArray_Descr *new;
11956
return PyErr_Format(PyExc_ValueError,
11414
11957
#if (PY_VERSION_HEX < 0x02050000)
11415
"Array length must be >= 0, not %d",
11958
"Array length must be >= 0, not %d",
11417
"Array length must be >= 0, not %zd",
11960
"Array length must be >= 0, not %zd",
11420
tup = Py_BuildValue("O" NPY_SSIZE_T_PYFMT, self, length);
11421
if (tup == NULL) return NULL;
11422
PyArray_DescrConverter(tup, &new);
11424
return (PyObject *)new;
11963
tup = Py_BuildValue("O" NPY_SSIZE_T_PYFMT, self, length);
11964
if (tup == NULL) return NULL;
11965
PyArray_DescrConverter(tup, &new);
11967
return (PyObject *)new;
11427
11970
static PyObject *
11428
11971
descr_subscript(PyArray_Descr *self, PyObject *op)
11432
if (PyString_Check(op) || PyUnicode_Check(op)) {
11434
obj = PyDict_GetItem(self->fields, op);
11437
descr = PyTuple_GET_ITEM(obj, 0);
11442
PyErr_Format(PyExc_KeyError,
11443
"field named \'%s\' not found.",
11444
PyString_AsString(op));
11450
value = PyArray_PyIntAsInt(op);
11451
if (!PyErr_Occurred()) {
11453
size = PyTuple_GET_SIZE(self->names);
11454
if (value < 0) value += size;
11455
if (value < 0 || value >= size) {
11456
PyErr_Format(PyExc_IndexError,
11457
"0<=index<%d not %d",
11461
name = PyTuple_GET_ITEM(self->names, value);
11462
return descr_subscript(self, name);
11465
PyErr_SetString(PyExc_ValueError,
11466
"only integers, strings or unicode values "
11467
"allowed for getting fields.");
11471
astr = arraydescr_str(self);
11975
if (PyString_Check(op) || PyUnicode_Check(op)) {
11977
obj = PyDict_GetItem(self->fields, op);
11980
descr = PyTuple_GET_ITEM(obj, 0);
11472
11985
PyErr_Format(PyExc_KeyError,
11473
"there are no fields in dtype %s.",
11474
PyString_AsString(astr));
11986
"field named \'%s\' not found.",
11987
PyString_AsString(op));
11993
value = PyArray_PyIntAsInt(op);
11994
if (!PyErr_Occurred()) {
11996
size = PyTuple_GET_SIZE(self->names);
11997
if (value < 0) value += size;
11998
if (value < 0 || value >= size) {
11999
PyErr_Format(PyExc_IndexError,
12000
"0<=index<%d not %d",
12004
name = PyTuple_GET_ITEM(self->names, value);
12005
return descr_subscript(self, name);
12008
PyErr_SetString(PyExc_ValueError,
12009
"only integers, strings or unicode values "
12010
"allowed for getting fields.");
12014
astr = arraydescr_str(self);
12015
PyErr_Format(PyExc_KeyError,
12016
"there are no fields in dtype %s.",
12017
PyString_AsString(astr));
11480
12023
static PySequenceMethods descr_as_sequence = {
11486
12029
static PyMappingMethods descr_as_mapping = {
11487
descr_length, /*mp_length*/
11488
(binaryfunc)descr_subscript, /*mp_subscript*/
11489
(objobjargproc)NULL, /*mp_ass_subscript*/
12030
descr_length, /*mp_length*/
12031
(binaryfunc)descr_subscript, /*mp_subscript*/
12032
(objobjargproc)NULL, /*mp_ass_subscript*/
11492
12035
/****************** End of Mapping Protocol ******************************/
11495
12038
static PyTypeObject PyArrayDescr_Type = {
11496
PyObject_HEAD_INIT(NULL)
11498
"numpy.dtype", /* tp_name */
11499
sizeof(PyArray_Descr), /* tp_basicsize */
11500
0, /* tp_itemsize */
11502
(destructor)arraydescr_dealloc, /* tp_dealloc */
11504
0, /* tp_getattr */
11505
0, /* tp_setattr */
11506
0, /* tp_compare */
11507
(reprfunc)arraydescr_repr, /* tp_repr */
11508
0, /* tp_as_number */
11509
&descr_as_sequence, /* tp_as_sequence */
11510
&descr_as_mapping, /* tp_as_mapping */
11513
(reprfunc)arraydescr_str, /* tp_str */
11514
0, /* tp_getattro */
11515
0, /* tp_setattro */
11516
0, /* tp_as_buffer */
11517
Py_TPFLAGS_DEFAULT, /* tp_flags */
11519
0, /* tp_traverse */
11521
(richcmpfunc)arraydescr_richcompare, /* tp_richcompare */
11522
0, /* tp_weaklistoffset */
11524
0, /* tp_iternext */
11525
arraydescr_methods, /* tp_methods */
11526
arraydescr_members, /* tp_members */
11527
arraydescr_getsets, /* tp_getset */
11530
0, /* tp_descr_get */
11531
0, /* tp_descr_set */
11532
0, /* tp_dictoffset */
11535
arraydescr_new, /* tp_new */
11541
0, /* tp_subclasses */
11542
0 /* tp_weaklist */
12039
PyObject_HEAD_INIT(NULL)
12041
"numpy.dtype", /* tp_name */
12042
sizeof(PyArray_Descr), /* tp_basicsize */
12043
0, /* tp_itemsize */
12045
(destructor)arraydescr_dealloc, /* tp_dealloc */
12047
0, /* tp_getattr */
12048
0, /* tp_setattr */
12049
0, /* tp_compare */
12050
(reprfunc)arraydescr_repr, /* tp_repr */
12051
0, /* tp_as_number */
12052
&descr_as_sequence, /* tp_as_sequence */
12053
&descr_as_mapping, /* tp_as_mapping */
12056
(reprfunc)arraydescr_str, /* tp_str */
12057
0, /* tp_getattro */
12058
0, /* tp_setattro */
12059
0, /* tp_as_buffer */
12060
Py_TPFLAGS_DEFAULT, /* tp_flags */
12062
0, /* tp_traverse */
12064
(richcmpfunc)arraydescr_richcompare, /* tp_richcompare */
12065
0, /* tp_weaklistoffset */
12067
0, /* tp_iternext */
12068
arraydescr_methods, /* tp_methods */
12069
arraydescr_members, /* tp_members */
12070
arraydescr_getsets, /* tp_getset */
12073
0, /* tp_descr_get */
12074
0, /* tp_descr_set */
12075
0, /* tp_dictoffset */
12078
arraydescr_new, /* tp_new */
12084
0, /* tp_subclasses */
12085
0 /* tp_weaklist */
11546
12089
/** Array Flags Object **/
11548
typedef struct PyArrayFlagsObject {
11552
} PyArrayFlagsObject;
11555
Get New ArrayFlagsObject
12092
Get New ArrayFlagsObject
11557
12094
static PyObject *
11558
12095
PyArray_NewFlagsObject(PyObject *obj)
11563
flags = CONTIGUOUS | OWNDATA | FORTRAN | ALIGNED;
11566
flags = PyArray_FLAGS(obj);
11568
flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0);
11569
if (flagobj == NULL) return NULL;
11571
((PyArrayFlagsObject *)flagobj)->arr = obj;
11572
((PyArrayFlagsObject *)flagobj)->flags = flags;
12100
flags = CONTIGUOUS | OWNDATA | FORTRAN | ALIGNED;
12103
flags = PyArray_FLAGS(obj);
12105
flagobj = PyArrayFlags_Type.tp_alloc(&PyArrayFlags_Type, 0);
12106
if (flagobj == NULL) return NULL;
12108
((PyArrayFlagsObject *)flagobj)->arr = obj;
12109
((PyArrayFlagsObject *)flagobj)->flags = flags;
11578
12115
arrayflags_dealloc(PyArrayFlagsObject *self)
11580
Py_XDECREF(self->arr);
11581
self->ob_type->tp_free((PyObject *)self);
12117
Py_XDECREF(self->arr);
12118
self->ob_type->tp_free((PyObject *)self);
11585
#define _define_get(UPPER, lower) \
11586
static PyObject * \
11587
arrayflags_ ## lower ## _get(PyArrayFlagsObject *self) \
12122
#define _define_get(UPPER, lower) \
12123
static PyObject * \
12124
arrayflags_ ## lower ## _get(PyArrayFlagsObject *self) \
11590
12127
item = ((self->flags & (UPPER)) == (UPPER)) ? Py_True : Py_False; \
11595
12132
_define_get(CONTIGUOUS, contiguous)
11596
12133
_define_get(FORTRAN, fortran)
11605
12142
static PyObject *
11606
12143
arrayflags_forc_get(PyArrayFlagsObject *self)
11610
if (((self->flags & FORTRAN) == FORTRAN) ||
11611
((self->flags & CONTIGUOUS) == CONTIGUOUS))
12147
if (((self->flags & FORTRAN) == FORTRAN) ||
12148
((self->flags & CONTIGUOUS) == CONTIGUOUS))
11620
12157
static PyObject *
11621
12158
arrayflags_fnc_get(PyArrayFlagsObject *self)
11625
if (((self->flags & FORTRAN) == FORTRAN) &&
11626
!((self->flags & CONTIGUOUS) == CONTIGUOUS))
12162
if (((self->flags & FORTRAN) == FORTRAN) &&
12163
!((self->flags & CONTIGUOUS) == CONTIGUOUS))
11635
12172
static PyObject *
11636
12173
arrayflags_farray_get(PyArrayFlagsObject *self)
11640
if (((self->flags & (ALIGNED|WRITEABLE|FORTRAN)) == \
11641
(ALIGNED|WRITEABLE|FORTRAN)) &&
11642
!((self->flags & CONTIGUOUS) == CONTIGUOUS))
12177
if (((self->flags & (ALIGNED|WRITEABLE|FORTRAN)) == \
12178
(ALIGNED|WRITEABLE|FORTRAN)) &&
12179
!((self->flags & CONTIGUOUS) == CONTIGUOUS))
11651
12188
static PyObject *
11652
12189
arrayflags_num_get(PyArrayFlagsObject *self)
11654
return PyInt_FromLong(self->flags);
12191
return PyInt_FromLong(self->flags);
11657
12194
/* relies on setflags order being write, align, uic */
11659
12196
arrayflags_updateifcopy_set(PyArrayFlagsObject *self, PyObject *obj)
11662
if (self->arr == NULL) {
11663
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
11666
res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None,
11667
(PyObject_IsTrue(obj) ? Py_True : Py_False));
11668
if (res == NULL) return -1;
12199
if (self->arr == NULL) {
12200
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
12203
res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None,
12204
(PyObject_IsTrue(obj) ? Py_True : Py_False));
12205
if (res == NULL) return -1;
11674
12211
arrayflags_aligned_set(PyArrayFlagsObject *self, PyObject *obj)
11677
if (self->arr == NULL) {
11678
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
11681
res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None,
11682
(PyObject_IsTrue(obj) ? Py_True : Py_False),
11684
if (res == NULL) return -1;
12214
if (self->arr == NULL) {
12215
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
12218
res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None,
12219
(PyObject_IsTrue(obj) ? Py_True : Py_False),
12221
if (res == NULL) return -1;
11690
12227
arrayflags_writeable_set(PyArrayFlagsObject *self, PyObject *obj)
11693
if (self->arr == NULL) {
11694
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
11697
res = PyObject_CallMethod(self->arr, "setflags", "OOO",
11698
(PyObject_IsTrue(obj) ? Py_True : Py_False),
11700
if (res == NULL) return -1;
12230
if (self->arr == NULL) {
12231
PyErr_SetString(PyExc_ValueError, "Cannot set flags on array scalars.");
12234
res = PyObject_CallMethod(self->arr, "setflags", "OOO",
12235
(PyObject_IsTrue(obj) ? Py_True : Py_False),
12237
if (res == NULL) return -1;
11706
12243
static PyGetSetDef arrayflags_getsets[] = {
11708
(getter)arrayflags_contiguous_get,
11712
(getter)arrayflags_contiguous_get,
11716
(getter)arrayflags_fortran_get,
11720
(getter)arrayflags_fortran_get,
11724
(getter)arrayflags_updateifcopy_get,
11725
(setter)arrayflags_updateifcopy_set,
11728
(getter)arrayflags_owndata_get,
11732
(getter)arrayflags_aligned_get,
11733
(setter)arrayflags_aligned_set,
11736
(getter)arrayflags_writeable_get,
11737
(setter)arrayflags_writeable_set,
11740
(getter)arrayflags_fnc_get,
11744
(getter)arrayflags_forc_get,
11748
(getter)arrayflags_behaved_get,
11752
(getter)arrayflags_carray_get,
11756
(getter)arrayflags_farray_get,
11760
(getter)arrayflags_num_get,
11763
{NULL, NULL, NULL, NULL},
12245
(getter)arrayflags_contiguous_get,
12249
(getter)arrayflags_contiguous_get,
12253
(getter)arrayflags_fortran_get,
12257
(getter)arrayflags_fortran_get,
12261
(getter)arrayflags_updateifcopy_get,
12262
(setter)arrayflags_updateifcopy_set,
12265
(getter)arrayflags_owndata_get,
12269
(getter)arrayflags_aligned_get,
12270
(setter)arrayflags_aligned_set,
12273
(getter)arrayflags_writeable_get,
12274
(setter)arrayflags_writeable_set,
12277
(getter)arrayflags_fnc_get,
12281
(getter)arrayflags_forc_get,
12285
(getter)arrayflags_behaved_get,
12289
(getter)arrayflags_carray_get,
12293
(getter)arrayflags_farray_get,
12297
(getter)arrayflags_num_get,
12300
{NULL, NULL, NULL, NULL},
11766
12303
static PyObject *
11767
12304
arrayflags_getitem(PyArrayFlagsObject *self, PyObject *ind)
11771
if (!PyString_Check(ind)) goto fail;
11772
key = PyString_AS_STRING(ind);
11773
n = PyString_GET_SIZE(ind);
11778
return arrayflags_contiguous_get(self);
11780
return arrayflags_fortran_get(self);
11782
return arrayflags_writeable_get(self);
11784
return arrayflags_behaved_get(self);
11786
return arrayflags_owndata_get(self);
11788
return arrayflags_aligned_get(self);
11790
return arrayflags_updateifcopy_get(self);
11796
if (strncmp(key, "CA", n)==0)
11797
return arrayflags_carray_get(self);
11798
if (strncmp(key, "FA", n)==0)
11799
return arrayflags_farray_get(self);
11802
if (strncmp(key, "FNC", n)==0)
11803
return arrayflags_fnc_get(self);
11806
if (strncmp(key, "FORC", n)==0)
11807
return arrayflags_forc_get(self);
11810
if (strncmp(key, "CARRAY", n)==0)
11811
return arrayflags_carray_get(self);
11812
if (strncmp(key, "FARRAY", n)==0)
11813
return arrayflags_farray_get(self);
11816
if (strncmp(key,"FORTRAN",n)==0)
11817
return arrayflags_fortran_get(self);
11818
if (strncmp(key,"BEHAVED",n)==0)
11819
return arrayflags_behaved_get(self);
11820
if (strncmp(key,"OWNDATA",n)==0)
11821
return arrayflags_owndata_get(self);
11822
if (strncmp(key,"ALIGNED",n)==0)
11823
return arrayflags_aligned_get(self);
11826
if (strncmp(key,"WRITEABLE",n)==0)
11827
return arrayflags_writeable_get(self);
11830
if (strncmp(key,"CONTIGUOUS",n)==0)
11831
return arrayflags_contiguous_get(self);
11834
if (strncmp(key, "UPDATEIFCOPY", n)==0)
11835
return arrayflags_updateifcopy_get(self);
11836
if (strncmp(key, "C_CONTIGUOUS", n)==0)
11837
return arrayflags_contiguous_get(self);
11838
if (strncmp(key, "F_CONTIGUOUS", n)==0)
11839
return arrayflags_fortran_get(self);
12308
if (!PyString_Check(ind)) goto fail;
12309
key = PyString_AS_STRING(ind);
12310
n = PyString_GET_SIZE(ind);
12315
return arrayflags_contiguous_get(self);
12317
return arrayflags_fortran_get(self);
12319
return arrayflags_writeable_get(self);
12321
return arrayflags_behaved_get(self);
12323
return arrayflags_owndata_get(self);
12325
return arrayflags_aligned_get(self);
12327
return arrayflags_updateifcopy_get(self);
12333
if (strncmp(key, "CA", n)==0)
12334
return arrayflags_carray_get(self);
12335
if (strncmp(key, "FA", n)==0)
12336
return arrayflags_farray_get(self);
12339
if (strncmp(key, "FNC", n)==0)
12340
return arrayflags_fnc_get(self);
12343
if (strncmp(key, "FORC", n)==0)
12344
return arrayflags_forc_get(self);
12347
if (strncmp(key, "CARRAY", n)==0)
12348
return arrayflags_carray_get(self);
12349
if (strncmp(key, "FARRAY", n)==0)
12350
return arrayflags_farray_get(self);
12353
if (strncmp(key,"FORTRAN",n)==0)
12354
return arrayflags_fortran_get(self);
12355
if (strncmp(key,"BEHAVED",n)==0)
12356
return arrayflags_behaved_get(self);
12357
if (strncmp(key,"OWNDATA",n)==0)
12358
return arrayflags_owndata_get(self);
12359
if (strncmp(key,"ALIGNED",n)==0)
12360
return arrayflags_aligned_get(self);
12363
if (strncmp(key,"WRITEABLE",n)==0)
12364
return arrayflags_writeable_get(self);
12367
if (strncmp(key,"CONTIGUOUS",n)==0)
12368
return arrayflags_contiguous_get(self);
12371
if (strncmp(key, "UPDATEIFCOPY", n)==0)
12372
return arrayflags_updateifcopy_get(self);
12373
if (strncmp(key, "C_CONTIGUOUS", n)==0)
12374
return arrayflags_contiguous_get(self);
12375
if (strncmp(key, "F_CONTIGUOUS", n)==0)
12376
return arrayflags_fortran_get(self);
11844
PyErr_SetString(PyExc_KeyError, "Unknown flag");
12381
PyErr_SetString(PyExc_KeyError, "Unknown flag");
11849
12386
arrayflags_setitem(PyArrayFlagsObject *self, PyObject *ind, PyObject *item)
11853
if (!PyString_Check(ind)) goto fail;
11854
key = PyString_AS_STRING(ind);
11855
n = PyString_GET_SIZE(ind);
11856
if (((n==9) && (strncmp(key, "WRITEABLE", n)==0)) ||
11857
((n==1) && (strncmp(key, "W", n)==0)))
11858
return arrayflags_writeable_set(self, item);
11859
else if (((n==7) && (strncmp(key, "ALIGNED", n)==0)) ||
11860
((n==1) && (strncmp(key, "A", n)==0)))
11861
return arrayflags_aligned_set(self, item);
11862
else if (((n==12) && (strncmp(key, "UPDATEIFCOPY", n)==0)) ||
11863
((n==1) && (strncmp(key, "U", n)==0)))
11864
return arrayflags_updateifcopy_set(self, item);
12390
if (!PyString_Check(ind)) goto fail;
12391
key = PyString_AS_STRING(ind);
12392
n = PyString_GET_SIZE(ind);
12393
if (((n==9) && (strncmp(key, "WRITEABLE", n)==0)) ||
12394
((n==1) && (strncmp(key, "W", n)==0)))
12395
return arrayflags_writeable_set(self, item);
12396
else if (((n==7) && (strncmp(key, "ALIGNED", n)==0)) ||
12397
((n==1) && (strncmp(key, "A", n)==0)))
12398
return arrayflags_aligned_set(self, item);
12399
else if (((n==12) && (strncmp(key, "UPDATEIFCOPY", n)==0)) ||
12400
((n==1) && (strncmp(key, "U", n)==0)))
12401
return arrayflags_updateifcopy_set(self, item);
11867
PyErr_SetString(PyExc_KeyError, "Unknown flag");
12404
PyErr_SetString(PyExc_KeyError, "Unknown flag");
11871
12408
static char *
11872
12409
_torf_(int flags, int val)
11874
if ((flags & val) == val) return "True";
11875
else return "False";
12411
if ((flags & val) == val) return "True";
12412
else return "False";
11878
12415
static PyObject *
11879
12416
arrayflags_print(PyArrayFlagsObject *self)
11881
int fl = self->flags;
11883
return PyString_FromFormat(" %s : %s\n %s : %s\n %s : %s\n"\
11884
" %s : %s\n %s : %s\n %s : %s",
11885
"C_CONTIGUOUS", _torf_(fl, CONTIGUOUS),
11886
"F_CONTIGUOUS", _torf_(fl, FORTRAN),
11887
"OWNDATA", _torf_(fl, OWNDATA),
11888
"WRITEABLE", _torf_(fl, WRITEABLE),
11889
"ALIGNED", _torf_(fl, ALIGNED),
11890
"UPDATEIFCOPY", _torf_(fl, UPDATEIFCOPY));
12418
int fl = self->flags;
12420
return PyString_FromFormat(" %s : %s\n %s : %s\n %s : %s\n"\
12421
" %s : %s\n %s : %s\n %s : %s",
12422
"C_CONTIGUOUS", _torf_(fl, CONTIGUOUS),
12423
"F_CONTIGUOUS", _torf_(fl, FORTRAN),
12424
"OWNDATA", _torf_(fl, OWNDATA),
12425
"WRITEABLE", _torf_(fl, WRITEABLE),
12426
"ALIGNED", _torf_(fl, ALIGNED),
12427
"UPDATEIFCOPY", _torf_(fl, UPDATEIFCOPY));
12432
arrayflags_compare(PyArrayFlagsObject *self, PyArrayFlagsObject *other)
12434
if (self->flags == other->flags)
12436
else if (self->flags < other->flags)
11894
12442
static PyMappingMethods arrayflags_as_mapping = {
11895
12443
#if PY_VERSION_HEX >= 0x02050000
11896
(lenfunc)NULL, /*mp_length*/
12444
(lenfunc)NULL, /*mp_length*/
11898
(inquiry)NULL, /*mp_length*/
12446
(inquiry)NULL, /*mp_length*/
11900
(binaryfunc)arrayflags_getitem, /*mp_subscript*/
11901
(objobjargproc)arrayflags_setitem, /*mp_ass_subscript*/
12448
(binaryfunc)arrayflags_getitem, /*mp_subscript*/
12449
(objobjargproc)arrayflags_setitem, /*mp_ass_subscript*/
11905
12453
static PyObject *
11906
12454
arrayflags_new(PyTypeObject *self, PyObject *args, PyObject *kwds)
11908
PyObject *arg=NULL;
11909
if (!PyArg_UnpackTuple(args, "flagsobj", 0, 1, &arg))
12456
PyObject *arg=NULL;
12457
if (!PyArg_UnpackTuple(args, "flagsobj", 0, 1, &arg))
11912
if ((arg != NULL) && PyArray_Check(arg)) {
11913
return PyArray_NewFlagsObject(arg);
11916
return PyArray_NewFlagsObject(NULL);
12460
if ((arg != NULL) && PyArray_Check(arg)) {
12461
return PyArray_NewFlagsObject(arg);
12464
return PyArray_NewFlagsObject(NULL);
11920
12468
static PyTypeObject PyArrayFlags_Type = {
11921
PyObject_HEAD_INIT(NULL)
11924
sizeof(PyArrayFlagsObject),
11925
0, /* tp_itemsize */
11927
(destructor)arrayflags_dealloc, /* tp_dealloc */
11929
0, /* tp_getattr */
11930
0, /* tp_setattr */
11931
0, /* tp_compare */
11932
(reprfunc)arrayflags_print, /* tp_repr */
11933
0, /* tp_as_number */
11934
0, /* tp_as_sequence */
11935
&arrayflags_as_mapping, /* tp_as_mapping */
11938
(reprfunc)arrayflags_print, /* tp_str */
11939
0, /* tp_getattro */
11940
0, /* tp_setattro */
11941
0, /* tp_as_buffer */
11942
Py_TPFLAGS_DEFAULT, /* tp_flags */
11944
0, /* tp_traverse */
11946
0, /* tp_richcompare */
11947
0, /* tp_weaklistoffset */
11949
0, /* tp_iternext */
11950
0, /* tp_methods */
11951
0, /* tp_members */
11952
arrayflags_getsets, /* tp_getset */
11955
0, /* tp_descr_get */
11956
0, /* tp_descr_set */
11957
0, /* tp_dictoffset */
11960
arrayflags_new, /* tp_new */
11966
0, /* tp_subclasses */
11967
0 /* tp_weaklist */
12469
PyObject_HEAD_INIT(NULL)
12472
sizeof(PyArrayFlagsObject),
12473
0, /* tp_itemsize */
12475
(destructor)arrayflags_dealloc, /* tp_dealloc */
12477
0, /* tp_getattr */
12478
0, /* tp_setattr */
12479
(cmpfunc)arrayflags_compare, /* tp_compare */
12480
(reprfunc)arrayflags_print, /* tp_repr */
12481
0, /* tp_as_number */
12482
0, /* tp_as_sequence */
12483
&arrayflags_as_mapping, /* tp_as_mapping */
12486
(reprfunc)arrayflags_print, /* tp_str */
12487
0, /* tp_getattro */
12488
0, /* tp_setattro */
12489
0, /* tp_as_buffer */
12490
Py_TPFLAGS_DEFAULT, /* tp_flags */
12492
0, /* tp_traverse */
12494
0, /* tp_richcompare */
12495
0, /* tp_weaklistoffset */
12497
0, /* tp_iternext */
12498
0, /* tp_methods */
12499
0, /* tp_members */
12500
arrayflags_getsets, /* tp_getset */
12503
0, /* tp_descr_get */
12504
0, /* tp_descr_set */
12505
0, /* tp_dictoffset */
12508
arrayflags_new, /* tp_new */
12514
0, /* tp_subclasses */
12515
0 /* tp_weaklist */