quantumlib / qsim

Schrödinger and Schrödinger-Feynman simulators for quantum circuits.
Apache License 2.0
454 stars 151 forks source link

Fix expectation values. #578

Closed Hosseinberg closed 1 year ago

Hosseinberg commented 1 year ago

The coefficient of the identity operators is now included in the expectation value calculation. The following example uses three different methods to calculate the expectation value. qsimcirq discards the coefficient of the identity operator. This PR resolves this issue.

import cirq
import qsimcirq

objs = [(1.5, 'IIIIIII'), (-0.3, 'XZXIXII')]
num_qubits = 7
moments = 9
density = 0.95
qubits = cirq.LineQubit.range(num_qubits)
cirq_circuit = cirq.testing.random_circuit(qubits=qubits,
                                      n_moments=moments,
                                      op_density=density)

hamiltonian = 0
for w, pauli in objs:
    pauli = pauli[::-1]
    hamiltonian += float(w) * cirq.PauliString(
        cirq.I(cirq.LineQubit(i)) if p == 'I' else
        cirq.X(cirq.LineQubit(i)) if p == 'X' else
        cirq.Y(cirq.LineQubit(i)) if p == 'Y' else
        cirq.Z(cirq.LineQubit(i)) if p == 'Z' else
        None  
        for i, p in enumerate(pauli))

energy_ham = hamiltonian.expectation_from_state_vector(
    state_vector= cirq.final_state_vector(cirq_circuit), 
    qubit_map={q: i for i, q in enumerate(qubits)},
    atol=0.01)

qsimSim = qsimcirq.QSimSimulator()
qsimcirq_result = qsimSim.simulate_expectation_values(cirq_circuit, hamiltonian) 

cirqSim = cirq.Simulator()
cirq_result = cirqSim.simulate_expectation_values(cirq_circuit, hamiltonian)  

print(f'energy_ham = {energy_ham}')
print(f'qsimcirq_result = {qsimcirq_result}')
print(f'cirq_result = {cirq_result}')
95-martin-orion commented 1 year ago

Is this a duplicate of #577? qsim hasn't had a release since that PR, so you may need to clone and build locally to see it effects. If this isn't feasible for you I can package a dev release later this week.

Hosseinberg commented 1 year ago

@95-martin-orion I believe this is not a duplicate of #577 since even after cloning and building locally the issue still exists. However, the suggested commit 3841701 will resolve the issue.

Hosseinberg commented 1 year ago

@95-martin-orion I'm getting an error in the formatting check. Which Python code formatter should I use to ensure that it passes the format check?

95-martin-orion commented 1 year ago

@95-martin-orion I'm getting an error in the formatting check. Which Python code formatter should I use to ensure that it passes the format check?

Formatting is checked with check/format-incremental, which uses black~=22.3.0. It should be possible to run this script locally.

From the logs, it looks like there's trailing whitespace on the marked lines.