From 2c1a6a85b282c8d9827dce4c86997c74461ab598 Mon Sep 17 00:00:00 2001 From: Wong Zi Cheng <70616433+chmwzc@users.noreply.github.com> Date: Wed, 18 Dec 2024 02:09:52 +0000 Subject: [PATCH] Refactor: Collect non-I factors in a term first --- src/qibo/hamiltonians/hamiltonians.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/src/qibo/hamiltonians/hamiltonians.py b/src/qibo/hamiltonians/hamiltonians.py index 59fbb40009..5bc78f5d30 100644 --- a/src/qibo/hamiltonians/hamiltonians.py +++ b/src/qibo/hamiltonians/hamiltonians.py @@ -584,31 +584,24 @@ def expectation_from_circuit(self, circuit: "Circuit", nshots: int = 1000) -> fl for term in self.terms: # store coefficient coefficients.append(term.coefficient) + # Only care about non-I terms + non_identity_factors = [ + factor for factor in term.factors if factor.name[0] != "I" + ] # build diagonal observable Z_observables.append( SymbolicHamiltonian( - prod( - [ - Z(factor.target_qubit) - for factor in term.factors - if factor.name[0] != "I" - ] - ), + prod(Z(factor.target_qubit) for factor in non_identity_factors), nqubits=circuit.nqubits, backend=self.backend, ) ) # Get the qubits we want to measure for each term - qubit_map = sorted( - factor.target_qubit - for factor in set(term.factors) - if factor.name[0] != "I" - ) + qubit_map = sorted(factor.target_qubit for factor in non_identity_factors) # prepare the measurement basis and append it to the circuit measurements = [ gates.M(factor.target_qubit, basis=factor.gate.__class__) - for factor in set(term.factors) - if factor.name[0] != "I" + for factor in non_identity_factors ] circ_copy = circuit.copy(True) circ_copy.add(measurements)