How to create Ising Hamiltonian and implement it with qiskit (the output should be in the form of WeightedPauliOperator) for the following problem:

$$ H = A \big(K - \sum_{i}^{N} t_i x_i \big)^2\\ x_i=\{0,1\}\\ t_i \in \mathbb{N}_{>0}\\ K\in \mathbb{N}\\ A \in \mathbb{R}_{>0}\\ $$

I want to choose any number of variables $x_i$, that the sum $\sum_{i}^{N} t_i x_i$ will equal exactly $K$.


1 Answer 1


You can use Qiskit's new optimization module. This allows you to use docplex to build your model:

# required imports
from docplex.mp.model import Model
from qiskit.optimization.problems import QuadraticProgram
from qiskit.optimization.converters import QuadraticProgramToIsing

# specify problem
n = 3
a = 1.0
k = 2
t = range(1, n+1)

# build model with docplex
mdl = Model()
x = [mdl.binary_var() for i in range(n)]
objective = a*(k - mdl.sum(t[i]*x[i] for i in range(n)))**2

# convert to Qiskit's quadratic program
qp = QuadraticProgram()

# convert to Ising Hamiltonian
qp2ising = QuadraticProgramToIsing()
H, offset = qp2ising.encode(qp)
print('Offset:', offset)
print('Ising Hamiltonian:')

Offset: 4.5

Ising Hamiltonian:

IIZ (-1+0j)

IZI (-2+0j)

ZII (-3+0j)

IZZ (1+0j)

ZIZ (1.5+0j)

ZZI (3+0j)

You can find some tutorials introducing the functionality here: https://qiskit.org/documentation/tutorials/optimization/index.html or here https://github.com/Qiskit/qiskit-tutorials/tree/master/tutorials/optimization

  • $\begingroup$ Thanks for the answer! Can you please explain to me one more thing. To run optimization problem (for example with VQE algorithm) it is necessary to get the problem in the form of WeightedPauliOperator. What exactly this structure represent? And how WeightedPauliOperator is related to Ising Hamiltonian? $\endgroup$
    – user10234
    May 21, 2020 at 21:07
  • 1
    $\begingroup$ The WeightedPauliOperator is a possible way to represent an Ising Hamiltonian, e.g. in contrast to the MatrixOperator. If you want to use VQE or QAOA to actually approximate the ground state, then Qiskit does the translation for you and you can directly use the MinimumEigenOptimizer and give it a QuadraticProgram. See this tutorial on QAOA: github.com/Qiskit/qiskit-tutorials/blob/master/tutorials/… For VQE, just pass VQE as a MinimumEigenSolver instead of QAOA. $\endgroup$ May 24, 2020 at 10:07
  • $\begingroup$ This is late, but QuadraticProgramToIsing() is no longer included in the Qiskit library. Has it been obsolete? $\endgroup$ Sep 1, 2023 at 8:33
  • $\begingroup$ @Alternative7 it has been moved to QuadraticProgram().to_ising() (github.com/qiskit-community/qiskit-optimization/blob/…) $\endgroup$ Sep 2, 2023 at 9:35
  • $\begingroup$ @StefanWoerner Thanks a lot! $\endgroup$ Sep 3, 2023 at 10:51

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.