Skip to content

Commit

Permalink
Fix stuff related to I terms
Browse files Browse the repository at this point in the history
  • Loading branch information
chmwzc committed Dec 17, 2024
1 parent 201812e commit 2ce694e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/qibo/hamiltonians/hamiltonians.py
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,13 @@ def expectation_from_circuit(self, circuit: "Circuit", nshots: int = 1000) -> fl
# build diagonal observable
Z_observables.append(
SymbolicHamiltonian(
prod([Z(q) for q in term.target_qubits]),
prod(
[
Z(factor.target_qubit)
for factor in term.factors
if factor.name[0] != "I"
]
),
nqubits=circuit.nqubits,
backend=self.backend,
)
Expand Down Expand Up @@ -649,7 +655,9 @@ def expectation_from_samples(self, freq: dict, qubit_map: list = None) -> float:
)
expvals = []
for term in self.terms:
qubits = term.target_qubits
qubits = {
factor.target_qubit for factor in term.factors if factor.name[0] != "I"
}
expvals.extend(
[
term.coefficient.real
Expand Down
2 changes: 1 addition & 1 deletion tests/test_hamiltonians.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def test_hamiltonian_expectation_from_circuit(backend):
backend.set_seed(12)

nshots = 4 * 10**6
observable = I(0) + X(0) * Z(1) + Y(0) * X(2) / 2 - Z(0) * (1 - Y(1)) ** 3
observable = I(0) * Z(1) + X(0) * Z(1) + Y(0) * X(2) / 2 - Z(0) * (1 - Y(1)) ** 3
exp, H, c = non_exact_expectation_test_setup(backend, observable)
exp_from_samples = H.expectation_from_circuit(c, nshots=nshots)
backend.assert_allclose(exp, exp_from_samples, atol=1e-2)
Expand Down

0 comments on commit 2ce694e

Please sign in to comment.