qiboteam / qibo

A full-stack framework for quantum computing.
https://qibo.science
Apache License 2.0
294 stars 60 forks source link

`SymbolicHamiltonian` as a callback leading to mismatched circuit sizes #1418

Open alhajri opened 3 months ago

alhajri commented 3 months ago

Describe the bug Facing an issue when using a SymbolicHamiltonian as a callback for a circuit. The issue occurs because SymbolicHamiltonian is assumes that it acts on the highest qubit number that any of its terms acts on, and there is no way to override this behavior. I will demonstrate:

To Reproduce

from qibo import hamiltonians, models, callbacks, matrices
import time
import numpy as np

L = 6

hxx = np.kron(matrices.X,matrices.X)

terms = [hamiltonians.terms.HamiltonianTerm(hxx, i, i+1) for i in range(L-1)]
H = hamiltonians.SymbolicHamiltonian()
H.terms = terms

P = hamiltonians.SymbolicHamiltonian()
P.terms = [hamiltonians.terms.HamiltonianTerm(matrices.Z, 0)]  

CallBack =[callbacks.Energy(P)]

start = time.time()

# Create evolution object using the above callbacks
evolve = models.StateEvolution(H, dt=1e-3,
                               callbacks=CallBack)
# Evolve for total time t=1
final_state = evolve(final_time=10,initial_state=np.ones(2 ** L) / np.sqrt(2 ** L))
end = time.time()
print('Time to completion = '+str(end - start)+' [sec]')

results in the following error:

[Qibo 0.2.10|ERROR|2024-08-08 11:50:52]: Cannot multiply Hamiltonian on 1 qubits to state of 6 qubits. ERROR:qibo.config:Cannot multiply Hamiltonian on 1 qubits to state of 6 qubits.

This can be 'fixed' by modifying the definition of P by artificially adding a term that acts on the final qubit. So replacing this line: P.terms = [hamiltonians.terms.HamiltonianTerm(matrices.Z, 0)] with this: P.terms = [hamiltonians.terms.HamiltonianTerm(matrices.Z, 0), hamiltonians.terms.HamiltonianTerm(0.0*matrices.I,L-1)]

This is quite inelegant in my opinion. Maybe there should be an optional parameter in SymbolicHamiltonian where I can specify how many qubits it acts on.

alecandido commented 3 months ago

I'm not sure I'd classify it as a bug, but rather a feature request.

Here you said that you have to pad the Hamiltonian yourself, while the alternative, more elegant, option would be to pad it with identities.

This is true, and it's usually intended that way, even when you are writing them in formulas. Still, it could be considered a notation extension (or even an abuse?). But I acknowledge it's convenient.

In any case, we're open to PRs, so feel free to propose the implementation. (and, if you agree with the classification, please switch label from bug to enhancement)