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?

  • 1
    $\begingroup$ 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? $\endgroup$ Commented Oct 12, 2021 at 21:01
  • $\begingroup$ 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 $\endgroup$
    – jecado
    Commented Oct 13, 2021 at 14:31

1 Answer 1


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.

  • $\begingroup$ After the modification, the program output the exception dimension mismatch for the state to multiply the operator. $\endgroup$ Commented Oct 16, 2021 at 16:19
  • $\begingroup$ 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. $\endgroup$ Commented Oct 16, 2021 at 17:52
  • $\begingroup$ 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]? $\endgroup$ Commented Oct 17, 2021 at 3:13
  • $\begingroup$ Also, there seems have problems when the state is a density matrix after adding deplorizing noisy to the circuit. Each expectation will go to zero in this case. $\endgroup$ Commented Oct 17, 2021 at 5:16

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.