tequilahub / tequila

A High-Level Abstraction Framework for Quantum Algorithms
MIT License
369 stars 103 forks source link

Discrepancy between VQE optimization and simulation results #309

Closed dariavh closed 1 year ago

dariavh commented 1 year ago

Describe the bug I optimized the expectation value of a simple toy Hamiltonian over a quantum circuit with four adjustable variables and got an optimal VQE energy of approx. -1.645. When I try to simulate the expectation value of the same Hamiltonian with the optimal VQE parameters, I get a different value from the optimal VQE energy. I'm not sure if I might be overlooking something fundamental or if there's a potential issue in my approach.

To Reproduce Steps to reproduce the behavior:

import tequila as tq

### Generate unitary circuit.
a = tq.Variable(name="a")*tq.numpy.pi
b = tq.Variable(name="b")*tq.numpy.pi
c = tq.Variable(name="c")*tq.numpy.pi
d = tq.Variable(name='d')*tq.numpy.pi

U1 = tq.gates.H(target=[0])
U1 += tq.gates.H(target=1)
U1 += tq.gates.Ry(target=0, angle=a)
U1 += tq.gates.Rz(target=1, angle=b)
U1 += tq.gates.Z(target=1,control=0)
U1 += tq.gates.Rx(target=0, angle=c)
U1 += tq.gates.Rx(target=1,angle=d)
U1 += tq.gates.Z(target=1,control=0)

### Once we have a circuit, we pick a simple toy Hamiltonian to optimize over.
H1 = (tq.paulis.Y(0)+tq.paulis.Qm(0))*tq.paulis.X(1)
O1 = tq.ExpectationValue(U=U1,H=H1)

# Optimize.
result = tq.minimize(objective=O1, method="COBYLA", samples=1000,
                    initial_values={k: np.random.rand() for k in O1.extract_variables()},
                    maxiter=100000, backend="qulacs")
print("The VQE outcome is: {:+2.8}f".format(result.energy))    

### Simulate.
print( tq.simulate(O1, variables=result.variables), result.energy )

This code block prints:

The VQE outcome is: -1.645f
(-1.6060566132207432, -1.6450000000000002)

Expected behavior I expect the last line in the code block to print two identical expectation values.

Computer:

kottmanj commented 1 year ago

Hi Daria,

the reason is the error resulting from the finite sampling of the expectation value.

energy = tq.compile(E)
exact_expectation_value = energy(variables)
finite_sampling_value1 = energy(variables, samples=1000)
finite_sampling_value2 = energy(variables, samples=1000)

the finite_sampling_valueX results will fluctuate around exact_expectation_value.

It depends a bit, on what you are interested in with the current simulation, but in general, I would recommend exact simulation: Faster, and you get a deterministic result corresponding to the samples-->infinity limit.

As a ballpark number, I think most experiments use ~10k samples.

Hope that helps.

dariavh commented 1 year ago

Hi Jakob,

The finite sampling is just something I am testing out for a research idea 🙂thank you for the prompt reply and resolving my issue!