MCPcopy Create free account
hub / github.com/numpy/numpy / PyArray_CopyInitialReduceValues

Function PyArray_CopyInitialReduceValues

numpy/core/src/umath/reduction.c:74–144  ·  view source on GitHub ↗

* This function initializes a result array for a reduction operation * which has no identity. This means it needs to copy the first element * it sees along the reduction axes to result. * * If a reduction has an identity, such as 0 or 1, the result should be * fully initialized to the identity, because this function raises an * exception when there are no elements to reduce (which is appropr

Source from the content-addressed store, hash-verified

72 * which is the number of elements already initialized.
73 */
74static npy_intp
75PyArray_CopyInitialReduceValues(
76 PyArrayObject *result, PyArrayObject *operand,
77 const npy_bool *axis_flags, const char *funcname,
78 int keepdims)
79{
80 npy_intp shape[NPY_MAXDIMS], strides[NPY_MAXDIMS];
81 npy_intp *shape_orig = PyArray_SHAPE(operand);
82 npy_intp *strides_orig = PyArray_STRIDES(operand);
83 PyArrayObject *op_view = NULL;
84
85 int ndim = PyArray_NDIM(operand);
86
87 /*
88 * Copy the subarray of the first element along each reduction axis.
89 *
90 * Adjust the shape to only look at the first element along
91 * any of the reduction axes. If keepdims is False remove the axes
92 * entirely.
93 */
94 int idim_out = 0;
95 npy_intp size = 1;
96 for (int idim = 0; idim < ndim; idim++) {
97 if (axis_flags[idim]) {
98 if (NPY_UNLIKELY(shape_orig[idim] == 0)) {
99 PyErr_Format(PyExc_ValueError,
100 "zero-size array to reduction operation %s "
101 "which has no identity", funcname);
102 return -1;
103 }
104 if (keepdims) {
105 shape[idim_out] = 1;
106 strides[idim_out] = 0;
107 idim_out++;
108 }
109 }
110 else {
111 size *= shape_orig[idim];
112 shape[idim_out] = shape_orig[idim];
113 strides[idim_out] = strides_orig[idim];
114 idim_out++;
115 }
116 }
117
118 PyArray_Descr *descr = PyArray_DESCR(operand);
119 Py_INCREF(descr);
120 op_view = (PyArrayObject *)PyArray_NewFromDescr(
121 &PyArray_Type, descr, idim_out, shape, strides,
122 PyArray_DATA(operand), 0, NULL);
123 if (op_view == NULL) {
124 return -1;
125 }
126
127 /*
128 * Copy the elements into the result to start.
129 */
130 int res = PyArray_CopyInto(result, op_view);
131 Py_DECREF(op_view);

Callers 1

PyUFunc_ReduceWrapperFunction · 0.85

Calls 7

PyArray_SHAPEFunction · 0.85
PyArray_STRIDESFunction · 0.85
PyArray_NDIMFunction · 0.85
PyArray_DESCRFunction · 0.85
PyArray_NewFromDescrFunction · 0.85
PyArray_DATAFunction · 0.85
PyArray_CopyIntoFunction · 0.85

Tested by

no test coverage detected