From 2ce694ea376b3a7bc091eba8f1f9eaa23d12991f Mon Sep 17 00:00:00 2001 From: Wong Zi Cheng <70616433+chmwzc@users.noreply.github.com> Date: Tue, 17 Dec 2024 04:17:39 +0000 Subject: [PATCH] Fix stuff related to I terms --- src/qibo/hamiltonians/hamiltonians.py | 12 ++++++++++-- tests/test_hamiltonians.py | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/qibo/hamiltonians/hamiltonians.py b/src/qibo/hamiltonians/hamiltonians.py index 6c68b71b7d..59fbb40009 100644 --- a/src/qibo/hamiltonians/hamiltonians.py +++ b/src/qibo/hamiltonians/hamiltonians.py @@ -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, ) @@ -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 diff --git a/tests/test_hamiltonians.py b/tests/test_hamiltonians.py index 94c4e189da..8806bd94bb 100644 --- a/tests/test_hamiltonians.py +++ b/tests/test_hamiltonians.py @@ -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)