/* See array_assign.h for parameter documentation */ NPY_NO_EXPORT int broadcast_strides(int ndim, npy_intp *shape, int strides_ndim, npy_intp *strides_shape, npy_intp *strides, char *strides_name, npy_intp *out_strides) { int idim, idim_start = ndim - strides_ndim; /* Can't broadcast to fewer dimensions */ if (idim_start < 0) { goto broadcast_error; } /* * Process from the end to the start, so that 'strides' and 'out_strides' * can point to the same memory. */ for (idim = ndim - 1; idim >= idim_start; --idim) { npy_intp strides_shape_value = strides_shape[idim - idim_start]; /* If it doesn't have dimension one, it must match */ if (strides_shape_value == 1) { out_strides[idim] = 0; } else if (strides_shape_value != shape[idim]) { goto broadcast_error; } else { out_strides[idim] = strides[idim - idim_start]; } } /* New dimensions get a zero stride */ for (idim = 0; idim < idim_start; ++idim) { out_strides[idim] = 0; } return 0; broadcast_error: { PyObject *errmsg; errmsg = PyUString_FromFormat("could not broadcast %s from shape ", strides_name); PyUString_ConcatAndDel(&errmsg, build_shape_string(strides_ndim, strides_shape)); PyUString_ConcatAndDel(&errmsg, PyUString_FromString(" into shape ")); PyUString_ConcatAndDel(&errmsg, build_shape_string(ndim, shape)); PyErr_SetObject(PyExc_ValueError, errmsg); Py_DECREF(errmsg); return -1; } }
/** * Convert an array shape to a string such as "(1, 2)". * * @param Dimensionality of the shape * @param npy_intp pointer to shape array * @param String to append after the shape `(1, 2)%s`. * * @return Python unicode string */ NPY_NO_EXPORT PyObject * convert_shape_to_string(npy_intp n, npy_intp *vals, char *ending) { npy_intp i; PyObject *ret, *tmp; /* * Negative dimension indicates "newaxis", which can * be discarded for printing if it's a leading dimension. * Find the first non-"newaxis" dimension. */ for (i = 0; i < n && vals[i] < 0; i++); if (i == n) { return PyUString_FromFormat("()%s", ending); } else { ret = PyUString_FromFormat("(%" NPY_INTP_FMT, vals[i++]); if (ret == NULL) { return NULL; } } for (; i < n; ++i) { if (vals[i] < 0) { tmp = PyUString_FromString(",newaxis"); } else { tmp = PyUString_FromFormat(",%" NPY_INTP_FMT, vals[i]); } if (tmp == NULL) { Py_DECREF(ret); return NULL; } PyUString_ConcatAndDel(&ret, tmp); if (ret == NULL) { return NULL; } } if (i == 1) { tmp = PyUString_FromFormat(",)%s", ending); } else { tmp = PyUString_FromFormat(")%s", ending); } PyUString_ConcatAndDel(&ret, tmp); return ret; }