-
Notifications
You must be signed in to change notification settings - Fork 61
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implemented expectation for non diagonal observbales
- Loading branch information
1 parent
e7276d8
commit e756691
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |