1

I'm following the tutorial on gradients in Qiskit. Suppose I have the following:

# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
params = [a, b]

Instantiate the Hamiltonian observable

H = 0.5 * X - 1 * Z

Combine the Hamiltonian observable and the state

op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)

value_dict = { a: np.pi / 4, b: np.pi}

state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)

state_grad_assigned = state_grad.assign_parameters(value_dict)

Here state_grad_assigned is an object of type ListOp. If I call state_grad_assigned.eval(), it will return the exact gradient vector of $\langle \psi(a, b) | H | \psi(a, b) \rangle$. However, I would like to evaluate that expression using a noisy backend, e.g. one from AerSimulator. How would I do that?

Alexey Uvarov
  • 684
  • 5
  • 14

1 Answers1

1

To run on a simulator (or backend) you can use the CircuitSampler. For the details of how that class can be used you can check out this related question: Evaluating expectation values of operators in Qiskit

In your case, your code would need to be modified something like

from qiskit_aer.backends import AerSimulator
from qiskit.opflow import CircuitSampler, AerPauliExpectation

simulator = AerSimulator() sampler = CircuitSampler(simulator)

state_grad = # ... like you had it before

now use the CircuitSampler to evaluate the gradient

for efficiency: don't manually bind the parameters, but let the sampler do it!

sampled = sampler.convert(state_grad, value_dict)

now call eval to evaluate the sampled circuits

result = sampled.eval()

Cryoris
  • 2,893
  • 6
  • 14