Qiskit/qiskit-metapackage

Tensor product associativity issue

zodiacfireworks opened this issue · 1 comments

Informations

  • Qiskit version: 0.21.0
  • Python version: 3.8.13
  • Operating system: Ubuntu 20.04.4 LTS

What is the current behavior?

When I'm building the Heisenberg Hamiltonian for two qubits:

$$ \hat{H} = \frac{1}{2} \left( \hat{I}\otimes \hat{I} + \hat{\sigma}_x \otimes \hat{\sigma}_x + \hat{\sigma}_y \otimes \hat{\sigma}_y + \hat{\sigma}_z \otimes \hat{\sigma}_z \right) $$

whit Qiskit as

from qiskit.opflow import X, Y, Z, I

H = 0.5 * (I^I + X^X + Y^Y + Z^Z)
print(H)

I got the following result

0.5 * IIXYZ
+ 0.5 * IIXZZ
+ 0.5 * IIYYZ
+ 0.5 * IIYZZ
+ 0.5 * IXXYZ
+ 0.5 * IXXZZ
+ 0.5 * IXYYZ
+ 0.5 * IXYZZ

Steps to reproduce the problem

Fresh qiskit install and try to compute Heisenberg Hamiltonian for two qubits

What is the expected behavior?

For this snippet

from qiskit.opflow import X, Y, Z, I

H = 0.5 * (I^I + X^X + Y^Y + Z^Z)
print(H)

is expected an output of the form

0.5 * II
+ 0.5 * XX
+ 0.5 * YY
+ 0.5 * ZZ

Suggested solutions

I think this is due to the fast that the precedence rule between ^ and + operators is set in a way that the following equivalence is true

I^I + X^X == I^(I + X)^X

and not the "natrual" interpretarion

I^I + X^X == (I^I) + (X^X)

I'm not familiar with this implementation of operators in Qiskit but if someone can guide me I can help with a PR :)

Unfortunately, operator associativity is a fixed function of Python that we simply can't control. ^ binds less tightly than + in Python, so I^X + X^I is interpreted as I ^ (X+X) ^ I, and we can't affect that. You need to put brackets around the individual tensor-product terms to achieve the effect you want. There's a warning about this in the documentation for opflow.