qml.devices.preprocess.measurements_from_samples¶
- measurements_from_samples(tape)[source]¶
Quantum function transform that replaces all terminal measurements from a tape with a single
pennylane.sample()
measurement, and adds postprocessing functions for each original measurement.This transform can be used to make tapes compatible with device backends that only return
pennylane.sample()
. The final output will return the initial requested measurements, calculated instead from the raw samples returned immediately after execution.The transform is only applied if the tape is being executed with shots.
Note
This transform diagonalizes all the operations on the tape. An error will be raised if non-commuting terms are encountered. To avoid non-commuting terms in circuit measurements, the
split_non_commuting
transform can be applied.- Parameters:
tape (QNode or QuantumTape or Callable) – A quantum circuit.
- Returns:
The transformed circuit as described in
qml.transform
.- Return type:
qnode (QNode) or quantum function (Callable) or tuple[List[QuantumTape], function]
Example
Consider the tape:
>>> ops = [qml.X(0), qml.RY(1.23, 1)] >>> measurements = [qml.expval(qml.Y(0)), qml.probs(wires=[1])] >>> tape = qml.tape.QuantumScript(ops, measurements, shots=10)
We can apply the transform to diagonalize and convert the two measurements to a single sample measurement:
>>> (new_tape, ), fn = qml.devices.preprocess.measurements_from_samples(tape) >>> new_tape.measurements [sample(wires=[0, 1])]
The tape operations now include diagonalizing gates.
>>> new_tape.operations [X(0), RY(1.23, wires=[1]), RX(1.5707963267948966, wires=[0])]
Executing the tape returns samples that can be post-processed to get the originally requested measurements:
>>> dev = qml.device("default.qubit") >>> res = dev.execute(new_tape) >>> res array([[1, 0], [0, 0], [0, 1], [1, 1], [0, 1], [1, 0], [0, 1], [1, 0], [1, 0], [1, 0]])
>>> fn((res,)) [-0.2, array([0.6, 0.4])]