qiboteam / qibo

A framework for quantum computing
https://qibo.science
Apache License 2.0
281 stars 55 forks source link

Combining `expectation_from_samples` with measurements in the Pauli X/Y basis #852

Open chmwzc opened 1 year ago

chmwzc commented 1 year ago

I've been trying to use the expectation_from_samples method under SymbolicHamiltonian together with measurements in the Pauli X/Y basis (#799). However, expectation_from_samples currently only accepts Hamiltonians with only Z's (link) and raises an error otherwise. Is this check still necessary, and can it be removed?

Sample code:

from qibo import models, gates

from qibo.symbols import X, Y
from qibo.hamiltonians import SymbolicHamiltonian

# Hamiltonian term
ham_term = X(0)*Y(1)
sym_ham = SymbolicHamiltonian(ham_term)

# Get the basis rotation gates and target qubits from the Hamiltonian term
qubits = [factor.target_qubit for factor in sym_ham.terms[0].factors]
basis = [type(factor.gate) for factor in sym_ham.terms[0].factors]

# Run the circuit to get the output frequencies
circuit = models.Circuit(2)
circuit.add(gates.M(*qubits, basis=basis))
result = circuit(nshots=100)
freq = result.frequencies(binary=True)

# Only works for Z terms, raises an error if ham_term has X/Y terms
sym_ham.expectation_from_samples(freq, qubit_map=qubits) 

Other than that, a minor documentation issue with expectation_from_samples: the lines under freq are missing 4 spaces😀

scarrazza commented 1 year ago

@AlejandroSopena are you looking into this and #719?

AlejandroSopena commented 1 year ago

I haven't looked at it in detail, but I can take care of it