Skip to content

Commit b6bc683

Browse files
sebergSwayamInSync
andauthored
ENH: Allow user-dtypes return views on .conjugate() (#31264)
This uses the fact that if something doesn't define an imag, then conjugate() should be defined as a simple view (similar to .real). This is a follow-up of a previous PR, where I didn't implement this isn't really backportable. With this, QuadDType for example does return a view (and a complex new-style dtype can opt out this). This doesn't yet support for .conjugate() to return a view for complex numbers (which would make a lot of sense and could be added but take a bit more effort). Co-authored-by: Swayam <[email protected]>
1 parent 12e16ab commit b6bc683

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

‎numpy/_core/src/multiarray/calculation.c‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -828,8 +828,8 @@ PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *o
828828
NPY_NO_EXPORT PyObject *
829829
PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out)
830830
{
831-
if (PyArray_ISCOMPLEX(self) || PyArray_ISOBJECT(self) ||
832-
PyArray_ISUSERDEF(self) || !NPY_DT_is_legacy(PyArray_DESCR(self))) {
831+
if (NPY_DT_SLOTS(NPY_DTYPE(PyArray_DTYPE(self)))->imag_meth != NULL) {
832+
/* The dtype has `arr.imag` so `conjugate` must exist (or error) */
833833
if (out == NULL) {
834834
return PyArray_GenericUnaryFunction(self,
835835
n_ops.conjugate);
@@ -841,12 +841,14 @@ PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out)
841841
}
842842
}
843843
else {
844-
PyArrayObject *ret;
845-
if (!PyArray_ISNUMBER(self)) {
844+
if (!NPY_DT_is_numeric(NPY_DTYPE(PyArray_DTYPE(self)))) {
846845
PyErr_SetString(PyExc_TypeError,
847-
"cannot conjugate non-numeric dtype");
846+
"cannot conjugate non-numeric dtype");
848847
return NULL;
849848
}
849+
850+
/* Numeric but no `.imag`: real-valued (or `.imag` should error) */
851+
PyArrayObject *ret;
850852
if (out) {
851853
if (PyArray_AssignArray(out, self,
852854
NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) {

‎numpy/_core/tests/test_custom_dtypes.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,12 @@ def test_flatiter_index(self, index):
373373
np.testing.assert_array_equal(
374374
arr.view(np.float64), arr2.view(np.float64))
375375

376+
def test_conjugate(self):
377+
# Also user dtype can just return self if conjugate should be no-op.
378+
arr = np.array([1.0, 2.0, 3.0], dtype=SF(1.0))
379+
assert arr.conjugate() is arr
380+
381+
376382
@pytest.mark.thread_unsafe(
377383
reason="_ScaledFloatTestDType setup is thread-unsafe (gh-29850)"
378384
)

0 commit comments

Comments
 (0)