# Compute expectation value of an operator in openfermion

I am trying to compute the 2-electron reduced-density matrix (2-RDM) for a given quantum state with openfermion. The code is as follow

two_rdm = np.zeros((n_qubits,) * 4, dtype=complex)
psi =  = openfermion.haar_random_vector(2 ** n_qubits, random_seed).astype(numpy.complex64)
for i, j, k, l in itertools.product(range(n_qubits), repeat=4):
transformed_operator = jordan_wigner(
FermionOperator(((i, 1), (j, 1), (k, 0), (l, 0))))
two_rdm[i, j, k, l] = openfermion.linalg.expectation(transformed_operator, psi)


The problem is with the last line, which gives the following exception

TypeError: can only concatenate str (not "ABCMeta") to str


After examning the source code, I figured out that the problem is with the [operator * state][1]. Can anybody help to fix this?

• I think one would need more information in order to answer this question. Which line is throwing that exception? What sort of object is converter? You mention the package openfermion, but it looks like you're actually using Qiskit Nature? Oct 12 at 21:01
• If I had to guess, I'd say the normalization error you see is related to init_state. But it's hard to diagnose without a minimal working example: stackoverflow.com/help/minimal-reproducible-example Oct 13 at 14:31

From the openfermion documentation (see here), it says the operator must be a scipy.sparse matrix. So, replacing transformed_operator with get_sparse_matrix(transformed_operator, n_qubits=n_qubits) in the final line will give you a 2**n_qubits x 2**n_qubits dimensional sparse matrix, which should remove the error.
• After the modification, the program output the exception dimension mismatch for the state to multiply the operator. Oct 16 at 16:19
• I've edited my answer to something that should fix that problem. In get_sparse_matrix there is an optional argument n_qubits to specify the number of qubits you are working with. Oct 16 at 17:52
• Thanks for the answers. That really helps to fix the problem! I have one question about the quantum state of openfermion. The state is a $2^n$-length vector. I want to know what is the ordering of the vector. The first one, state[0] should be '0000' for a 4-qubit state. Then, is '1000' or '0001' the state[1]? Oct 17 at 3:13