qml.devices.preprocess.measurements_from_counts

measurements_from_counts(tape)[source]

Quantum function transform that replaces all terminal measurements from a tape with a single pennylane.counts() 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.counts(). The final output will return the initial requested measurements, calculated instead from the raw counts 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 counts measurement:

>>> (new_tape, ), fn = qml.devices.preprocess.measurements_from_counts(tape)
>>> new_tape.measurements
[CountsMP(wires=[0, 1], all_outcomes=False)]

The tape operations now include diagonalizing gates.

>>> new_tape.operations
[X(0), RY(1.23, wires=[1]), RX(1.5707963267948966, wires=[0])]

The tape is now compatible with a device backend that only supports counts. Executing the tape returns the raw counts:

>>> dev = qml.device("default.qubit")
>>> res = dev.execute(new_tape)
>>> res
{'00': 4, '01': 2, '10': 2, '11': 2}

And these can be post-processed to get the originally requested measurements:

>>> fn((res,))
[-0.19999999999999996, array([0.7, 0.3])]

Contents

Using PennyLane

Release news

Development

API

Internals