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
result = job.result().get_counts()
# Compute average expectation value of the observable H Ising
for string,count in result.items():
    value+=count*sum([(~StateFn(string)@ op @ StateFn(string)).eval() for op in hamiltonian])

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

  • $\begingroup$ 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? $\endgroup$
    – ryanhill1
    May 4, 2022 at 17:26
  • $\begingroup$ 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) $\endgroup$ May 6, 2022 at 12:41

2 Answers 2


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())

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
  • $\begingroup$ 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. $\endgroup$ May 13, 2022 at 10:39
  • $\begingroup$ You can read about this here and here. $\endgroup$ May 13, 2022 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.