# Copyright 2025 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Implements the pauli measurement.
"""
import uuid
from typing import override
import jax
import numpy as np
import pennylane as qp
from pennylane import math
from pennylane.capture import enabled as capture_enabled
from pennylane.capture.custom_primitives import QpPrimitive
from pennylane.compiler import compiler
from pennylane.core import QueuingManager
from pennylane.core.operator import Operator2, abstractify
from pennylane.typing import Wire
from pennylane.wires import Wires, WiresLike
from .measurement_value import MeasurementValue
_VALID_PAULI_CHARS = "XYZ"
class PauliMeasure(Operator2):
"""A Pauli product measurement."""
compilable_argnames = ("pauli_word", "postselect", "meas_uid")
# pylint: disable=too-many-arguments
def __init__(
self,
pauli_word: str,
wires: WiresLike,
postselect: int | None = None,
meas_uid: str | None = None,
):
if not all(c in _VALID_PAULI_CHARS for c in pauli_word):
raise ValueError(
f'The given Pauli word "{pauli_word}" contains characters that '
"are not allowed. Allowed characters are X, Y and Z."
)
super().__init__(pauli_word, wires=wires, postselect=postselect, meas_uid=meas_uid)
if len(pauli_word) != len(self.wires):
raise ValueError(
"The number of wires must be equal to the length of the Pauli "
f"word. The Pauli word {pauli_word} has length {len(pauli_word)} "
f"and {len(wires)} wires were given: {wires}."
)
@override
def label(self, decimals=None, base_label=None, cache=None, wire=None) -> str:
"""How the pauli-product measurement is represented in diagrams and drawings."""
postselect = "" if self.postselect is None else ("₁" if self.postselect == 1 else "₀")
if wire is None:
return f"┤↗{postselect}{self.pauli_word}├"
return f"┤↗{postselect}{self.pauli_word[self.wires.index(wire)]}├"
@override
def __repr__(self) -> str:
return f"PauliMeasure('{self.pauli_word}', wires={self.wires})"
@abstractify.register
@QueuingManager.stop_recording()
def _abstractify_pauli_measure(op: PauliMeasure):
# This is necessary so that an abstractified PauliMeasure would not have meas_uid
return PauliMeasure(op.pauli_word, Wire[len(op.wires)], postselect=op.postselect, meas_uid=None)
def _pauli_measure_impl(wires: WiresLike, pauli_word: str, postselect: int | None = None):
"""Concrete implementation of the pauli_measure primitive."""
measurement_id = str(uuid.uuid4())
measurement = PauliMeasure(pauli_word, wires, postselect, meas_uid=measurement_id)
return MeasurementValue([measurement])
pauli_measure_prim = QpPrimitive("pauli_measure")
@pauli_measure_prim.def_impl
def _pauli_measure_primitive_impl(*wires, pauli_word="", postselect=None):
wires = [w if math.is_tracer(w) else int(w) for w in wires]
return _pauli_measure_impl(wires, pauli_word=pauli_word, postselect=postselect)
@pauli_measure_prim.def_abstract_eval
def _pauli_measure_primitive_abstract_eval(*_, **__):
dtype = jax.numpy.int64 if jax.config.jax_enable_x64 else jax.numpy.int32
return jax.core.ShapedArray((), dtype)
_ARRAY_TYPES = (jax.numpy.ndarray, np.ndarray)
_NON_ARRAY_ITERABLES = (list, tuple, Wires, range, qp.capture.autograph.ag_primitives.PRange, set)
def _setup_wires(wires):
if isinstance(wires, _ARRAY_TYPES):
if wires.shape == ():
return (wires,)
return wires
if isinstance(wires, _NON_ARRAY_ITERABLES):
return tuple(wires)
return (wires,)
[docs]
def pauli_measure(pauli_word: str, wires: WiresLike, postselect: int | None = None):
"""Perform a Pauli product measurement.
A Pauli product measurement (PPM) is the measurement of a tensor product of Pauli observables (``X``, ``Y``, ``Z``, and ``I``).
The eigenvalue of this tensor product is one of 1 or -1, which is mapped to the 0 or 1 outcome of
the PPM, respectively. After the measurement, the state collapses to the superpositions of all
degenerate eigenstates corresponding to the measured eigenvalue.
.. note::
Circuits comprising ``pauli_measure`` are currently only executable with
:func:`~.qjit` and lightning qubit.
.. seealso::
For more information on Pauli product measurements, check out the
`Quantum Compilation hub <https://pennylane.ai/compilation/pauli-based-computation>`_ and
:func:`~.ppm_compilation` for compiling these circuits with ``qjit``.
Args:
pauli_word (str): The Pauli word to measure.
wires (Wires): The wires that the Pauli word acts on.
postselect (Optional[int]): The postselection value, one of ``0`` or ``1``. It determines which subspace of
degenerate eigenstates to postselect after a Pauli product measurement. ``None`` by default.
Returns:
MeasurementValue: A reference to the future result of the Pauli product measurement
Raises:
ValueError: if the Pauli word has characters other than X, Y and Z.
ValueError: if the number of wires does not match the length of the Pauli word.
**Example:**
The following example illustrates how to include a Pauli product measurement (PPM) in a circuit by specifying
the Pauli word and the wires it acts on.
.. code-block:: python
@qp.qnode(qp.device("null.qubit", wires=3))
def circuit():
qp.Hadamard(0)
qp.Hadamard(2)
ppm = qp.pauli_measure(pauli_word="XY", wires=[0, 2])
qp.cond(ppm, qp.X)(wires=1)
return qp.expval(qp.Z(0))
The ``X`` operation on wire ``1`` will be applied conditionally on the value of the PPM outcome:
>>> print(qp.draw(circuit)())
0: ──H─╭┤↗X├────┤ <Z>
1: ────│──────X─┤
2: ──H─╰┤↗Y├──║─┤
╚════╝
Additionally, the number of PPM operations in a circuit can be easily inspected with :func:`~.specs`:
>>> print(qp.specs(qp.qjit(circuit), level="top")()['resources'])
Quantum operations:
- Total: 4
- Hadamard: 2
- PPM-w2: 1
- PauliX: 1
Measurement processes:
- expval(PauliZ): 1
Total wires: 3
PBC Depths:
- Any commuting depth: 1
- Qubit disjoint depth: 1
"""
if capture_enabled():
wires = _setup_wires(wires)
return pauli_measure_prim.bind(*wires, pauli_word=pauli_word, postselect=postselect)
if active_jit := compiler.active_compiler():
available_eps = compiler.AvailableCompilers.names_entrypoints
ops_loader = available_eps[active_jit]["ops"].load()
return ops_loader.pauli_measure(pauli_word=pauli_word, wires=wires, postselect=postselect)
return _pauli_measure_impl(wires=wires, pauli_word=pauli_word, postselect=postselect)