I have a Hamiltonian as following $$ H= \sum_{i}^{n-1}(c_nX_iX_{i+1}+b_nZ_iZ_{i+1})+\sum_{i=1}^{n}b_nY$$ where $n:$ number of qubits.

I want to define this Hamiltonian in qiskit and use it as an observable to calculate the expectation value in an eigensolver. I have implemented it in OpenFermion:

def create_xy_hamiltonian(nqubit: int, cn: float, bn: float, r: float) -> Observable:
        nqubit: `int`, number of qubits
        cn: `float`, 0 - 1, coupling constant
        bn: `float`, 0 - 1, magnetic field
        r: `float`, 0 - 1, anisotropy param
        qulacs observable
    hami = QubitOperator()
    for i in range(nqubit-1):
        hami += (0.5*cn*(1+r)) * QubitOperator(f"X{i} X{i+1}")
        #hami += (0.5*cn*(1-r)) * QubitOperator(f"Y{i} Y{i+1}")
        hami += (0.5*cn*(1-r)) * QubitOperator(f"Z{i} Z{i+1}")
    for j in range(nqubit):
        hami += bn*QubitOperator(f"Y{j}")

    return (hami)```

1 Answer 1


In Qiskit, observables as usually defined as instances of SparsePauliOp class. Its newly added static method from_sparse_list() makes it easy to construct Hamiltonians where each term acts non-trivially on a very few number of qubits.

sparse_list = []
for m in range(num_qubits - 1):
    sparse_list.append(("XX", [m, m + 1], cn))
    sparse_list.append(("ZZ", [m, m + 1], bn))

for m in range(num_qubits):
    sparse_list.append(("Y", [m], bn))

hamiltonian = SparsePauliOp.from_sparse_list(sparse_list, num_qubits=num_qubits)

  • $\begingroup$ Thank you so much for your solution. Really appreciate it. $\endgroup$
    – Bakaneko
    Commented May 27 at 8:01

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.