0
$\begingroup$

I save my (lenghty) Hamiltonian in a file as a string.

My naive attempt:

hamiltonian_string = read_hamiltonian_from_file()  # some function
hamiltonian = PauliOp(hamiltonian_string) 
TypeError: PauliOp can only be instantiated with Paulis, not <class 'str'>

But copy-pasting from the file into Jupyter notebook works (of course):

hamiltonian =  1*(X^X^X) - 2*(X^Z^X) + 3*(X^I^X)
print(type(hamiltonian))
<class 'qiskit.opflow.primitive_ops.pauli_sum_op.PauliSumOp'>

Is there a way to initiate a PauliOp from a string?

$\endgroup$

1 Answer 1

3
$\begingroup$

You can simply use Python's eval() function:

from qiskit.opflow import I, X, Y, Z

hamiltonian_string = '1*(X^X^X) - 2*(X^Z^X) + 3*(X^I^X)'
hamiltonian = eval(hamiltonian_string)
print(type(hamiltonian))

There are some security concerns regarding eval() you need to be aware of. See here for details.

$\endgroup$
1
  • $\begingroup$ Amazing, thank you! Works like a charm :) $\endgroup$ Mar 3, 2022 at 6:24

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.