Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/openfermion/linalg/sparse_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ def expectation_computational_basis_state(operator, computational_basis_state):
If operator is a FermionOperator, it must be normal-ordered.
computational_basis_state (scipy.sparse vector / list): normalized
computational basis state (if scipy.sparse vector), or list of
occupied orbitals.
zeros and ones for occupied and unoccupied orbitals, respectively.

Returns:
A real float giving expectation value.
Expand All @@ -714,6 +714,9 @@ def expectation_computational_basis_state(operator, computational_basis_state):
if not isinstance(operator, FermionOperator):
raise TypeError('operator must be a FermionOperator.')

if not operator.is_normal_ordered():
raise ValueError('operator must be a normal ordered.')

occupied_orbitals = computational_basis_state

if not isinstance(occupied_orbitals, list):
Expand All @@ -730,7 +733,8 @@ def expectation_computational_basis_state(operator, computational_basis_state):
expectation_value += operator.terms.get(((i, 1), (i, 0)), 0.0)

for j in range(i + 1, len(occupied_orbitals)):
expectation_value -= operator.terms.get(((j, 1), (i, 1), (j, 0), (i, 0)), 0.0)
if occupied_orbitals[j]:
expectation_value -= operator.terms.get(((j, 1), (i, 1), (j, 0), (i, 0)), 0.0)

return expectation_value

Expand Down
11 changes: 11 additions & 0 deletions src/openfermion/linalg/sparse_tools_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,17 @@ def test_expectation_qubit_operator_not_implemented(self):
QubitOperator(), csc_matrix(([1], ([6], [0])), shape=(16, 1))
)

def test_expectation_bad_operator_order(self):
operator = (
FermionOperator('2^ 2', 1.9)
+ FermionOperator('2^ 1')
+ FermionOperator('2^ 1 2 1^', -1.7)
)
state = [0, 1, 1]

with self.assertRaises(ValueError):
expectation_computational_basis_state(operator, state)


class ExpectationDualBasisOperatorWithPlaneWaveBasisState(unittest.TestCase):
def setUp(self):
Expand Down