Skip to content

Fix #929 Raise error for non-physical terms #1086

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 3, 2025
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ def linearize_term(term, n_orbitals):
r = term[2][0]
s = term[3][0]
return 1 + n_orbitals**2 + p + q * n_orbitals + r * n_orbitals**2 + s * n_orbitals**3
raise ValueError(
'Expect one-body (2 terms) or two-body (4 terms) operator but got {} terms. '.format(
len(term)
)
)


def unlinearize_term(index, n_orbitals):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import unittest
import numpy

from openfermion.ops.operators import FermionOperator
from openfermion.chem import MolecularData
from openfermion.config import DATA_DIRECTORY
from openfermion.transforms.opconversions import get_fermion_operator
Expand Down Expand Up @@ -59,6 +60,11 @@ def test_linearize_term(self):
self.assertFalse(index in past_terms)
past_terms.add(index)

def test_error_with_non_physical_term(self):
non_physical_operator = FermionOperator((0, 1))
with self.assertRaises(ValueError):
linearize_term(non_physical_operator.terms, self.n_orbitals)

def test_unlinearize_term_consistency(self):
for term, _ in self.fermion_hamiltonian.terms.items():
index = linearize_term(term, self.n_orbitals)
Expand Down
Loading