Skip to content

Commit 9ae2967

Browse files
committed
Fixed expectation_computational_basis_state and added test for non-normal-ordered operator
1 parent 460238f commit 9ae2967

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

src/openfermion/linalg/sparse_tools.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ def expectation_computational_basis_state(operator, computational_basis_state):
700700
If operator is a FermionOperator, it must be normal-ordered.
701701
computational_basis_state (scipy.sparse vector / list): normalized
702702
computational basis state (if scipy.sparse vector), or list of
703-
occupied orbitals.
703+
zeros and ones for occupied and unoccupied orbitals, respectively.
704704
705705
Returns:
706706
A real float giving expectation value.
@@ -714,6 +714,9 @@ def expectation_computational_basis_state(operator, computational_basis_state):
714714
if not isinstance(operator, FermionOperator):
715715
raise TypeError('operator must be a FermionOperator.')
716716

717+
if not operator.is_normal_ordered():
718+
raise ValueError('operator must be a normal ordered.')
719+
717720
occupied_orbitals = computational_basis_state
718721

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

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

735739
return expectation_value
736740

src/openfermion/linalg/sparse_tools_test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,17 @@ def test_expectation_qubit_operator_not_implemented(self):
727727
QubitOperator(), csc_matrix(([1], ([6], [0])), shape=(16, 1))
728728
)
729729

730+
def test_expectation_bad_operator_order(self):
731+
operator = (
732+
FermionOperator('2^ 2', 1.9)
733+
+ FermionOperator('2^ 1')
734+
+ FermionOperator('2^ 1 2 1^', -1.7)
735+
)
736+
state = [0, 1, 1]
737+
738+
with self.assertRaises(ValueError):
739+
expectation_computational_basis_state(operator, state)
740+
730741

731742
class ExpectationDualBasisOperatorWithPlaneWaveBasisState(unittest.TestCase):
732743
def setUp(self):

0 commit comments

Comments
 (0)