# Qiskit compute mean expectation value

I want to calculate the mean expectation value of an PauliSumOp within qiskit after I executed a QAOA Circuit. My approach is the following:

# Run and get counts
job=qiskit.execute(circuit,backend=simulator,shots=shots,optimization_level=0)
result = job.result().get_counts()
# Compute average expectation value of the observable H Ising
max_count=0
value=0
for string,count in result.items():
value+=count*sum([(~StateFn(string)@ op @ StateFn(string)).eval() for op in hamiltonian])
max_count+=count
expectation=value/max_count


Is this correct? I am especially concerned if StateFn(Bitstring) is a valid usage of qiskit in terms of StateFn("0101")=$$|0101\rangle$$

• Could you include the code where you define the hamiltonian variable? i.e. where you write for op in hamiltonian, could you show how you instantiate that PauliSumOp object? May 4 at 17:26
• The hamiltonian variable is instantiated by defining a Graph which is supposed to be solved within the MaxCut Problem. With following steps: max_cut = Maxcut(Graph) qp = max_cut.to_quadratic_program() hamiltonian=qp.to_ising() Returning the hamiltonian gives in my example: PauliSumOp(SparsePauliOp(['ZZII', 'IZZI', 'ZIIZ', 'IZIZ', 'IIZZ'], coeffs=[0.5+0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j]), coeff=1.0) May 6 at 12:41

Yes, StateFn(Bitstring) is a valid usage of qiskit in terms of StateFn("0101")=$$\left|0101\right\rangle$$. As an example:

>>> from qiskit.opflow import Plus, StateFn
>>> import numpy as np
>>> print(Plus.to_circuit())
┌───┐
q_0: ┤ H ├
└───┘
>>> v_zero_one = (StateFn("0") + StateFn("1")) / np.sqrt(2)
>>> print(v_zero_one)
DictStateFn({'0': 1.0, '1': 1.0}) * 0.7071067811865475
>>> np.allclose(Plus.to_matrix(), v_zero_one.to_matrix())
True


And yes, to me, the rest of your code looks correct for hamiltonian of type PauliSumOp.

Qiskit provides a high-level constructs that can be used to calculate the expectation value. You don't have to do this low-level calculations by yourself.

First, use ExpectationFactory[1] to get a suitable expectation algorithm based on your backend (simulator or actual quantum device) and operator type:

exp_converter = ExpectationFactory.build(hamiltonian, simulator)


Now, use this expectation converter[2] and CircuitSampler[3] to do the low-level calculations:

measurable_expression =  ~StateFn(hamiltonian) @ StateFn(circ)
expect_op = exp_converter.convert(measurable_expression)
sampled_op = CircuitSampler(simulator).convert(expect_op)
expectation_value = sampled_op.eval().real

• Is there any ressource to learn qiskit in a way to know these "tricks"? The tutorials and example notebooks were not covering such things, as far as I know. May 13 at 10:39