OpenFermion icon indicating copy to clipboard operation
OpenFermion copied to clipboard

`QubitOperator` incompatible with `numpy==2.3.1`

Open andrijapau opened this issue 5 months ago • 1 comments

Describe the issue

This issue was encountered through our effort of dropping Python 3.10 support in pennylane (see PR). This change bumped our CI version of numpy from 2.2.6 to 2.3.1 which resulted in two of our qchem tests that use openfermion as the backend failing. After some investigation it seems that the SymbolicOperator class is incompatible with some changes introduced in 2.3.1.

What version of this software are you using?

1.7.1

How can the issue be reproduced?

The following code works with numpy==2.2.6 but fails with numpy==2.3.1,

import openfermion
import numpy as np

l = [0, 1, 0, 0, 1, 1]
x = np.count_nonzero(l)

openfermion.ops.QubitOperator(term=(), coefficient=(-1)**x)

The error message is,

    122 def __init__(self, term=None, coefficient=1.0):
    123     if not isinstance(coefficient, COEFFICIENT_TYPES):
--> 124        raise ValueError('Coefficient must be a numeric type. Got {}'.format(type(coefficient)))
    126     # Initialize the terms dictionary
    127     self.terms = {}

ValueError: Coefficient must be a numeric type. Got <class 'numpy.int64'>

A simple fix would be to use the numbers package instead of COEFFICIENT_TYPES,

import numbers
...
    def __init__(self, term=None, coefficient=1.0):
        if not isinstance(coefficient, numbers.Number):
            raise ValueError('Coefficient must be a numeric type. Got {}'.format(type(coefficient)))
...

andrijapau avatar Jul 25 '25 17:07 andrijapau

Thank you for the report. Yes, you're right that this needs to be done. In fact, I started doing exactly this kind of change (w.r.t. COEFFICIENNT_TYPES) but had not finished yet.

mhucka avatar Jul 25 '25 18:07 mhucka