Skip to content

Commit

Permalink
Refactor: Collect non-I factors in a term first
Browse files Browse the repository at this point in the history
  • Loading branch information
chmwzc committed Dec 18, 2024
1 parent 2ce694e commit 2c1a6a8
Showing 1 changed file with 7 additions and 14 deletions.
21 changes: 7 additions & 14 deletions src/qibo/hamiltonians/hamiltonians.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 2c1a6a8

Please sign in to comment.