qiskit-community / qiskit-nature

Qiskit Nature is an open-source, quantum computing, framework for solving quantum mechanical natural science problems.
https://qiskit-community.github.io/qiskit-nature/
Apache License 2.0
291 stars 197 forks source link

The `commutator` methods break API by using `normal_order` #1298

Closed mrossinek closed 7 months ago

mrossinek commented 7 months ago

Environment

What is happening?

The methods provided by the qiskit_nature.second_q.operators.commutators module call .normal_order() even though they canNOT because this method is not part of the SparseLabelOp API. I am honestly very surprised how our linters did not catch this.

How can we reproduce the issue?

I found this while testing something with the MajoranaOp from #1270, but we can also reproduce it with the SpinOp which has no normal_order method.

from qiskit_nature.second_q.operators import SpinOp
from qiskit_nature.second_q.operators.commutators import commutator

op = SpinOp({"X_0": 1.0})

print(commutator(op, op))

This results in:

Traceback (most recent call last):
  File "/home/oss/Files/Dev/Qiskit/qiskit-nature/main/tmp-no.py", line 6, in <module>
    print(commutator(op, op))
  File "/home/oss/Files/Dev/Qiskit/qiskit-nature/main/qiskit_nature/second_q/operators/commutators.py", line 48, in commutator
    return (op_a @ op_b - op_b @ op_a).normal_order().simplify(atol=0)
AttributeError: 'SpinOp' object has no attribute 'normal_order'

What should happen?

The methods should work for any SparseLabelOp. This bug was introduced by #1210 which attempted to fix #1208.

@ftroisi we should figure out a different way of fixing that problem with the BosonicOp.

Any suggestions?

No response