Skip to content

Commit

Permalink
fix the phase bug for trace
Browse files Browse the repository at this point in the history
  • Loading branch information
minhctran committed Jan 10, 2025
1 parent 6b21d84 commit f1dafb9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
17 changes: 15 additions & 2 deletions python/ffsim/protocols/trace_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ def trace(obj: Any, norb: int, nelec: tuple[int, int]) -> complex:
)


def _term_phase(op: tuple[tuple[bool, bool, int], ...]) -> int:
phase = 0
while len(op) > 0:
action, spin, orb = op[0]
conj_idx = op.index((not action, spin, orb))
phase += conj_idx - 1
op = op[1:conj_idx] + op[conj_idx + 1 :]
return (-1) ** phase


def _trace_term(
op: tuple[tuple[bool, bool, int], ...], norb: int, nelec: tuple[int, int]
) -> complex:
Expand Down Expand Up @@ -110,9 +120,12 @@ def _trace_term(
# the trace is nontrival and is a product of
# binom(#orbs not in the support of op, #elec on these orbs)
# for each spin species
# and a phase that depends on the ordering between the actions

return math.comb(norb - norb_alpha, n_alpha - nelec_alpha) * math.comb(
norb - norb_beta, n_beta - nelec_beta
return (
_term_phase(op)
* math.comb(norb - norb_alpha, n_alpha - nelec_alpha)
* math.comb(norb - norb_beta, n_beta - nelec_beta)
)


Expand Down
12 changes: 11 additions & 1 deletion tests/python/operators/fermion_operator_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,10 +645,20 @@ def test_mapping_methods():
}

def test_trace():
rng = np.random.default_rng(12345)
# compare for random_diagonal_coulomb_hamiltonian
norb = 50
nelec = (3, 3)
rng = np.random.default_rng(12345)
ham = ffsim.random.random_diagonal_coulomb_hamiltonian(norb, real=True, seed=rng)
t1 = ffsim.trace(ffsim.fermion_operator(ham), norb=norb, nelec=nelec)
t2 = ffsim.trace(ham, norb=norb, nelec=nelec)
np.testing.assert_allclose(t1, t2)

# compare for random_molecular_hamiltonian
norb = 20
nelec = (3, 3)
ham = ffsim.random.random_molecular_hamiltonian(norb, seed=rng, dtype=float)
t1 = ffsim.trace(ffsim.fermion_operator(ham), norb=norb, nelec=nelec)
t2 = ffsim.trace(ham, norb=norb, nelec=nelec)


0 comments on commit f1dafb9

Please sign in to comment.