From e756691c6b1e9d749b94c293ec69ec4d13d22e07 Mon Sep 17 00:00:00 2001 From: BrunoLiegiBastonLiegi Date: Mon, 14 Oct 2024 17:48:50 +0200 Subject: [PATCH] feat: implemented expectation for non diagonal observbales --- src/qibo/hamiltonians/expectation.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/qibo/hamiltonians/expectation.py diff --git a/src/qibo/hamiltonians/expectation.py b/src/qibo/hamiltonians/expectation.py new file mode 100644 index 0000000000..333fdce40a --- /dev/null +++ b/src/qibo/hamiltonians/expectation.py @@ -0,0 +1,26 @@ +from math import prod + +from qibo import Circuit, gates, symbols +from qibo.config import raise_error +from qibo.hamiltonians import SymbolicHamiltonian + + +def Expectation(circuit: Circuit, observable: SymbolicHamiltonian) -> float: + if len(circuit.measurements) > 0: + raise_error(RuntimeError) + exp_val = 0.0 + for term in observable.terms: + Z_observable = SymbolicHamiltonian( + prod([symbols.Z(q) for q in term.target_qubits]), + nqubits=circuit.nqubits, + backend=observable.backend, + ) + measurements = [ + gates.M(factor.target_qubit, basis=factor.gate.__class__) + for factor in term.factors + ] + circ_copy = circuit.copy(True) + [circ_copy.add(m) for m in measurements] + freq = observable.backend.execute_circuit(circ_copy).frequencies() + exp_val += Z_observable.expectation_from_samples(freq) + return exp_val