You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Accept NumPy scalar coefficients across operator and representation types (#1361)
Fixes#1097.
The actual problem behind #1097 is that NumPy's scalar types aren't
subclasses of Python's `int`, `float`, or `complex`. `numpy.int64`,
`numpy.float32`, `numpy.complex64` and the rest all fail an
`isinstance(x, (int, float, complex))` check, which is the idiom the
coefficient validation uses in a few places. (The one that slips through
is `numpy.float64`, since it does subclass `float`, which is probably
why this went unnoticed for a while.)
The `SymbolicOperator` family already got fixed by adding
`numbers.Number` to its accepted types, so `FermionOperator`,
`QubitOperator` and so on are fine now. But the same `(int, float,
complex)` pattern shows up in other spots that the change didn't reach,
and those still reject NumPy scalars:
- `PolynomialTensor` (so `InteractionOperator`, `InteractionRDM`, ...)
- `DOCIHamiltonian`
- `MajoranaOperator`
- the `majorana_operator` builder in `special_operators.py`
This adds `numbers.Number` to each of them, matching the existing fix.
`numbers.Number` covers Python and NumPy numeric scalars equally, so a
coefficient behaves the same whether it came from Python or NumPy, and
the plain int/float/complex cases stay exactly as they were.
One thing worth calling out: dividing or multiplying a real-dtype tensor
by a complex scalar still raises, because NumPy won't do the in-place
cast from complex to float. That happens with a plain Python `complex`
too, so it's pre-existing and unrelated to this change, and I left it
alone.
Each affected module gets a test asserting that NumPy scalar
coefficients (`int64`, `float32`, `complex64`) give the same result as
the equivalent Python scalar, including the in-place operators on
`MajoranaOperator`. The tests fail on `main` and pass with this change.
0 commit comments