diff --git a/CHANGELOG.md b/CHANGELOG.md index 286e3b8df..85433f11c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - #474, #564: Added `FocusedPauliFlow` and `FocusedGFlow` classes to encapsulate operations specific to focused flows. Flow-finding algorithms return focused flows by construction. Having dedicated classes removes the need to dynamically recheck that a flow is focused during circuit extraction. +- #651: + - Added new class `ExtendedCausalFlow`. + - Added methods `OpenGraph.to_extendedcausalflow`, `XZCorrections.to_extendedcausalflow`, and `Pattern.to_extendedcausalflow`. + ### Fixed - Fixed incorrect Clifford signs during circuit extraction for input vertices measured in negative Pauli X or Y bases. @@ -46,6 +50,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - #626, #635: The `domain` argument of the `X` and `Z` commands is now mandatory. Previously, it defaulted to the empty set, so that `X(1)` silently had no effect; write `X(1, set())` to state this explicitly. +- #651: + - The default space minimization heuristic `SpaceMinimizationHeuristics.extended_causal_flow` + replaces `causal_flow`, and is optimal for patterns with extended causal flow. + - The specific implementation of `CausalFlow.to_xzcorrections` is removed since it was equivalent to that in its parent class, `GFlow`. + - `OpenGraph.to_pattern` and `Pattern.draw` attempt to extract an extended causal flow rather than a causal flow. + ## [0.4.1] - 2026-10-13 ### Added diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index ce0364ca0..309466a82 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -1,22 +1,30 @@ -"""Causal flow finding algorithm. +"""Causal flow and extended causal flow finding algorithms. -This module implements Algorithm 1 from Ref. [1]. For a given labelled open graph (G, I, O, meas_plane), this algorithm finds a causal flow [2] in polynomial time with the number of nodes, :math:`O(N^2)`. +This module implements Algorithm 1 from Ref. [1] and an adaptation of it to extended causal flows [3]. For a given labelled open graph (G, I, O, meas_plane), these algorithms find a causal flow [2] or an extended causal flow [3] in polynomial time with the number of nodes, :math:`O(N^2)`. References ---------- [1] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 [2] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212) +[3] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 """ from __future__ import annotations from typing import TYPE_CHECKING -from graphix.flow.core import CausalFlow +from graphix.flow.core import CausalFlow, ExtendedCausalFlow from graphix.fundamentals import Plane if TYPE_CHECKING: - from graphix.opengraph import OpenGraph, _PM_co + from collections.abc import Set as AbstractSet + from typing import TypeAlias, TypeVar + + from graphix.fundamentals import AbstractPlanarMeasurement + from graphix.opengraph import OpenGraph + + FlowArguments: TypeAlias = tuple[dict[int, frozenset[int]], tuple[frozenset[int], ...]] + _PM_co = TypeVar("_PM_co", bound=AbstractPlanarMeasurement, covariant=True) def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: @@ -30,12 +38,12 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: Returns ------- CausalFlow[_PM_co] | None - A causal flow object if the open graph has causal flow, `None` otherwise. + A causal flow object if the open graph has causal flow, ``None`` otherwise. Notes ----- - See Definition 2, Theorem 1 and Algorithm 1 in Ref. [1]. - - The open graph instance must be of parametric type `Measurement` or `Plane` since the causal flow is only defined on open graphs with :math:`XY` measurements. + - Causal flow is only defined on open graphs with :math:`XY` measurements: ``None`` is returned if some measurement is in the :math:`XZ` or :math:`YZ` plane. Measurements are labelled by :meth:`AbstractPlanarMeasurement.to_plane`. References ---------- @@ -45,10 +53,81 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: if measurement.to_plane() in {Plane.XZ, Plane.YZ}: return None + flow_args = _find_flow(og) + if flow_args is None: + return None + return CausalFlow(og, *flow_args) + + +def find_ecflow(og: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co] | None: + """Return the extended causal flow of the input open graph if it exists. + + Parameters + ---------- + og : OpenGraph[_PM_co] + Open graph whose extended causal flow is calculated. + + Returns + ------- + ExtendedCausalFlow[_PM_co] | None + An extended causal flow object if the open graph has extended causal flow, ``None`` otherwise. + + Notes + ----- + - See Definition 10 in Ref. [1]. The algorithm is an adaptation of Algorithm 1 in Ref. [2] where, at each step, a :math:`YZ`-measured node is self-corrected and added to the current layer as soon as all its neighbors have been corrected. :math:`YZ`-measured nodes never correct other nodes. + - Extended causal flow is only defined on open graphs with :math:`XY` and :math:`YZ` measurements: ``None`` is returned if some measurement is in the :math:`XZ` plane. Measurements are labelled by :meth:`AbstractPlanarMeasurement.to_plane`. + + References + ---------- + [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + [2] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 + """ + yz_candidates: set[int] = set() + for node, measurement in og.measurements.items(): + plane = measurement.to_plane() + if plane == Plane.XZ: + return None + if plane == Plane.YZ: + yz_candidates.add(node) + + flow_args = _find_flow(og, yz_candidates) + if flow_args is None: + return None + return ExtendedCausalFlow(og, *flow_args) + + +def _find_flow(og: OpenGraph[_PM_co], yz_candidates: AbstractSet[int] | None = None) -> FlowArguments | None: + """Compute the correction function and the partial order layers of a causal or an extended causal flow. + + This is the routine shared by :func:`find_cflow` and :func:`find_ecflow`. Nodes not in ``yz_candidates`` are treated as :math:`XY`-measured nodes and are corrected by a single neighbor, as in a causal flow. Nodes in ``yz_candidates`` are treated as :math:`YZ`-measured nodes: they are corrected by themselves and never correct other nodes. + + Parameters + ---------- + og : OpenGraph[_PM_co] + Open graph whose flow is calculated. The caller is responsible for discarding open graphs with measurements in the :math:`XZ` plane (and in the :math:`YZ` plane when looking for a causal flow). + yz_candidates : AbstractSet[int] | None, optional + Non-output nodes measured in the :math:`YZ` plane. The set is not modified. If ``None`` (default), it is considered to be empty. + + Returns + ------- + FlowArguments | None + A tuple ``(correction_function, partial_order_layers)`` used to instantiate a :class:`CausalFlow` or an :class:`ExtendedCausalFlow` if the flow exists, ``None`` otherwise. + + Notes + ----- + See Definition 2, Theorem 1 and Algorithm 1 in Ref. [1] for causal flow, and Definition 10 in Ref. [2] for extended causal flow. + + References + ---------- + [1] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 + [2] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + """ + yz_candidates = set(yz_candidates) if yz_candidates is not None else set() + graph_nodes = set(og.graph.nodes) corrected_nodes = set(og.output_nodes) - corrector_candidates = corrected_nodes - set(og.input_nodes) - non_input_nodes = og.graph.nodes - set(og.input_nodes) + iset = set(og.input_nodes) + corrector_candidates = corrected_nodes - iset cf: dict[int, frozenset[int]] = {} # Output nodes are always in layer 0. @@ -58,25 +137,29 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: while corrected_nodes != graph_nodes: corrected_nodes_new: set[int] = set() corrector_nodes_new: set[int] = set() - curr_layer: set[int] = set() - - non_corrected_nodes = og.graph.nodes - corrected_nodes for p in corrector_candidates: - non_corrected_neighbors = og.neighbors({p}) & non_corrected_nodes + non_corrected_neighbors = og.neighbors({p}) - corrected_nodes if len(non_corrected_neighbors) == 1: (q,) = non_corrected_neighbors - cf[q] = frozenset({p}) - curr_layer.add(q) - corrected_nodes_new |= {q} - corrector_nodes_new |= {p} + if og.measurements[q].to_plane() == Plane.XY: + cf[q] = frozenset({p}) + corrected_nodes_new.add(q) + corrector_nodes_new.add(p) - layers.append(frozenset(curr_layer)) + for q in yz_candidates - corrected_nodes_new: + if og.neighbors({q}) <= corrected_nodes: + cf[q] = frozenset({q}) + corrected_nodes_new.add(q) if len(corrected_nodes_new) == 0: return None + layers.append(frozenset(corrected_nodes_new)) corrected_nodes |= corrected_nodes_new - corrector_candidates = (corrector_candidates - corrector_nodes_new) | (corrected_nodes_new & non_input_nodes) + yz_candidates -= corrected_nodes_new + corrector_candidates = (corrector_candidates - corrector_nodes_new) | { + q for q in corrected_nodes_new if q not in iset and q not in cf[q] + } - return CausalFlow(og, cf, tuple(layers)) + return cf, tuple(layers) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index b575189df..951bc6744 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -249,6 +249,41 @@ def to_causalflow(self: XZCorrections[_PM_co]) -> CausalFlow[_PM_co]: cf.check_well_formed() # Raises a ``FlowError`` if the partial order and the correction function are not compatible, if a measured node is corrected by more than one node, or if nodes are not measured on the XY plane. return cf + def to_extendedcausalflow(self: XZCorrections[_PM_co]) -> ExtendedCausalFlow[_PM_co]: + r"""Extract an extended causal flow from XZ-corrections. + + This method does not invoke the flow-extraction routine on the underlying open graph. + Instead, it assigns the ``x_corrections`` mapping to the correction function of the + :math:`XY`-measured nodes, makes the :math:`YZ`-measured nodes self-corrected (their + X-corrections, if any, are added to their correction set), and verifies that the result + is compatible with the intrinsic partial order of the XZ-corrections. + + Returns + ------- + ExtendedCausalFlow[_PM_co] + + Raises + ------ + FlowError + If the resulting correction function is incompatible with the partial order of the + XZ-corrections, if a measured node is corrected by more than one node, or if the + open graph contains measurements in the :math:`XZ` plane. + + Notes + ----- + - See Definition 10 in Ref. [1]. + - Only the ``x_corrections`` mapping and the partial order are used to build the flow, + the ``z_corrections`` mapping is not checked against the flow. + + References + ---------- + [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + """ + correction_function = _reconstruct_correction_function(self) + ecf = ExtendedCausalFlow(self.og, correction_function, self.partial_order_layers) + ecf.check_well_formed() # Raises a ``FlowError`` if the partial order and the correction function are not compatible. + return ecf + def to_gflow(self: XZCorrections[_PM_co]) -> GFlow[_PM_co]: r"""Extract a gflow from XZ-corrections. @@ -270,16 +305,7 @@ def to_gflow(self: XZCorrections[_PM_co]) -> GFlow[_PM_co]: ---------- [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). """ - correction_function: dict[int, set[int]] = {} - - for i, meas in self.og.measurements.items(): - corrections = set(self.x_corrections.get(i, set())) - - if meas.to_plane() in {Plane.XZ, Plane.YZ}: - corrections.add(i) - - correction_function[i] = corrections - + correction_function = _reconstruct_correction_function(self) gf = GFlow(self.og, correction_function, self.partial_order_layers) gf.check_well_formed() # Raises a ``FlowError`` if the partial order and the correction function are not compatible. return gf @@ -586,7 +612,7 @@ def with_parameters( @dataclass(frozen=True) class PauliFlow(Parameterizable, Simulable[_AM_co], Generic[_AM_co]): - """An unmutable dataclass providing a representation of a Pauli flow. + r"""An unmutable dataclass providing a representation of a Pauli flow. The methods :meth:`OpenGraph.to_pauliflow` and :meth:`Pattern.to_pauliflow` return well-formed Pauli flows by @@ -597,7 +623,7 @@ class PauliFlow(Parameterizable, Simulable[_AM_co], Generic[_AM_co]): correction function may not be valid, and the layers may be incompatible with the open graph or the corrections. The caller is responsible for ensuring that the provided attributes form a - well-formed Pauli flow. The :meth`:check_well_formed` method can + well-formed Pauli flow. The :meth:`check_well_formed` method can be called to explicitly verify that the flow is well-formed. Attributes @@ -611,9 +637,36 @@ class PauliFlow(Parameterizable, Simulable[_AM_co], Generic[_AM_co]): Notes ----- - - See Definition 5 in Ref. [1] for a definition of Pauli flow. - - - The flow's correction function defines a partial order (see Def. 2.8 and 2.9, Lemma 2.11 and Theorem 2.12 in Ref. [2]), therefore, only ``og`` and ``correction_function`` are necessary to initialize an ``PauliFlow`` instance (see :func:`PauliFlow.from_correctionmatrix_or_none`). However, flow-finding algorithms generate a partial order in a layer form, which is necessary to extract the flow's XZ-corrections, so it is stored as an attribute. + A Pauli flow on an open graph :math:`(G, I, O, \lambda)` is a pair :math:`(p, \prec)`, where + :math:`p: O^c \to 2^{I^c}` is the correction function and :math:`\prec` is a strict partial + order on the nodes of the open graph, such that, for all :math:`i \in O^c`: + + - If :math:`j \in p(i), i \neq j, \lambda(j) \notin \{X, Y\}`, then :math:`i \prec j` (P1). + - If :math:`j \in Odd(p(i)), i \neq j, \lambda(j) \notin \{Y, Z\}`, then :math:`i \prec j` (P2). + - If :math:`\neg (i \prec j), i \neq j, \lambda(j) = Y`, then either :math:`j \notin p(i)` and :math:`j \in Odd(p(i))` or :math:`j \in p(i)` and :math:`j \notin Odd(p(i))` (P3). + - If :math:`\lambda(i) = XY`, then :math:`i \notin p(i)` and :math:`i \in Odd(p(i))` (P4). + - If :math:`\lambda(i) = XZ`, then :math:`i \in p(i)` and :math:`i \in Odd(p(i))` (P5). + - If :math:`\lambda(i) = YZ`, then :math:`i \in p(i)` and :math:`i \notin Odd(p(i))` (P6). + - If :math:`\lambda(i) = X`, then :math:`i \in Odd(p(i))` (P7). + - If :math:`\lambda(i) = Z`, then :math:`i \in p(i)` (P8). + - If :math:`\lambda(i) = Y`, then either :math:`i \notin p(i)` and :math:`i \in Odd(p(i))` or :math:`i \in p(i)` and :math:`i \notin Odd(p(i))` (P9), + + where :math:`\lambda(i)` is the measurement plane or axis of node :math:`i` (see + :meth:`node_measurement_label`) and :math:`Odd(s)` is the odd neighbourhood of the set + :math:`s` in the open graph. See Definition 5 in Ref. [1] or Definition 2.4 in Ref. [2]. + The names in brackets are those of + :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and + :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`. + + In addition, the following general properties are required for the attributes to + represent a flow. They are shared by all the flow classes: + + - The domain of the correction function is :math:`O^c`, the non-output nodes of the open graph. + - The image of the correction function is a subset of :math:`I^c`, the non-input nodes of the open graph. + - The nodes in the partial order layers are the nodes of the open graph, and each node appears in exactly one layer. + - The first layer of the partial order layers is :math:`O`, the output nodes of the open graph, if there are any. + + The flow's correction function defines a partial order (see Def. 2.8 and 2.9, Lemma 2.11 and Theorem 2.12 in Ref. [2]), therefore, only ``og`` and ``correction_function`` are necessary to initialize an ``PauliFlow`` instance (see :func:`PauliFlow.from_correctionmatrix_or_none`). However, flow-finding algorithms generate a partial order in a layer form, which is necessary to extract the flow's XZ-corrections, so it is stored as an attribute. References ---------- @@ -687,65 +740,30 @@ def is_well_formed(self) -> bool: return True def check_well_formed(self) -> None: - r"""Verify that the Pauli flow is well-formed. + """Verify that the flow is well-formed. + + This method checks the validity of the flow, and, if ``self`` is an instance of + :class:`FocusedPauliFlow`, that the flow is focused. See the class docstring for the + flow definition. Use :meth:`check_flow_properties` to check only flow validity. Raises ------ FlowError - if the Pauli flow is not well-formed. - - Notes - ----- - This method checks that the instance is indeed a valid Pauli - flow. Moreover, if ``self`` is an instance of - :class:`FocusedPauliFlow`, it also checks that the flow is - focused. Use :meth:`check_flow_properties` to check only flow - properties. + If the flow is not well-formed. """ self.check_flow_properties() def check_flow_properties(self) -> None: - r"""Verify that the Pauli flow satisfies the flow properties. + """Verify that the flow satisfies the flow properties. + + This method checks the validity of the flow, see the class docstring for the flow + definition. It does not check whether the flow is focused, even if ``self`` is an + instance of :class:`FocusedPauliFlow`. Raises ------ FlowError - if the Pauli flow does not satisfy the flow properties. - - Notes - ----- - This method checks the properties for the instance to be a - valid Pauli flow. It does not check whether the flow is - focused, even if ``self`` is an instance of - :class:`FocusedPauliFlow`. By contrast, - :meth:`check_well_formed` checks that the flow is valid and, - for instances of :class:`FocusedPauliFlow`, also checks that - the flow is focused. - - General properties of flows: - - The domain of the correction function is :math:`O^c`, the non-output nodes of the open graph. - - The image of the correction function is a subset of :math:`I^c`, the non-input nodes of the open graph. - - The nodes in the partial order are the nodes in the open graph. - - The first layer of the partial order layers contains the outputs of the open graph if there are any. - - Specific properties of Pauli flows: - - If :math:`j \in p(i), i \neq j, \lambda(j) \notin \{X, Y\}`, then :math:`i \prec j` (P1). - - If :math:`j \in Odd(p(i)), i \neq j, \lambda(j) \notin \{Y, Z\}`, then :math:`i \prec j` (P2). - - If :math:`neg i \prec j, i \neq j, \lambda(j) = Y`, then either :math:`j \notin p(i)` and :math:`j \in Odd((p(i)))` or :math:`j \in p(i)` and :math:`j \notin Odd((p(i)))` (P3). - - If :math:`\lambda(i) = XY`, then :math:`i \notin p(i)` and :math:`i \in Odd((p(i)))` (P4). - - If :math:`\lambda(i) = XZ`, then :math:`i \in p(i)` and :math:`i \in Odd((p(i)))` (P5). - - If :math:`\lambda(i) = YZ`, then :math:`i \in p(i)` and :math:`i \notin Odd((p(i)))` (P6). - - If :math:`\lambda(i) = X`, then :math:`i \in Odd((p(i)))` (P7). - - If :math:`\lambda(i) = Z`, then :math:`i \in p(i)` (P8). - - If :math:`\lambda(i) = Y`, then either :math:`i \notin p(i)` and :math:`i \in Odd((p(i)))` or :math:`i \in p(i)` and :math:`i \notin Odd((p(i)))` (P9), - where :math:`i \in O^c`, :math:`c` is the correction function, :math:`prec` denotes the partial order, :math:`\lambda(i)` is the measurement plane or axis of node :math:`i`, and :math:`Odd(s)` is the odd neighbourhood of the set :math:`s` in the open graph. - - See Definition 5 in Ref. [1] or Definition 2.4 in Ref. [2]. - - References - ---------- - [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). - [2] Mitosek and Backens, 2024 (arXiv:2410.23439). + If the flow does not satisfy the flow properties. """ _check_flow_general_properties(self) @@ -1031,9 +1049,15 @@ class FocusedPauliFlow(PauliFlow[_AM_co], Generic[_AM_co]): or the corrections, and the flow, if any, may not be focused. The caller is responsible for ensuring that the provided attributes form a well-formed and focused Pauli flow. The - :meth`:check_well_formed` method can be called to explicitly - verify that the flow is well-formed, and the `is_focused` method - can be called to explicitly verify that the flow is focused. + :meth:`check_well_formed` method can be called to explicitly + verify that the flow is well-formed and focused, and the + :meth:`is_focused` method can be called to explicitly verify that + the flow is focused. + + Notes + ----- + See :class:`PauliFlow` for the definition of Pauli flow and :meth:`PauliFlow.is_focused` + for the definition of focused Pauli flow. """ @classmethod @@ -1065,10 +1089,18 @@ def from_correctionmatrix_or_none(cls, correction_matrix: CorrectionMatrix[_AM_c return cls(correction_matrix.aog.og, correction_function, partial_order_layers) + @override def check_well_formed(self) -> None: - """Verify that the Pauli flow is well-formed and focused. + """Verify that the flow is well-formed and focused. + + This method checks the validity of the flow and that the flow is focused. See the class + docstring for the flow definition. - See :meth:`PauliFlow.check_well_formed` and :meth:`PauliFlow.is_focused` for details. + Raises + ------ + FlowError + If the flow is not well-formed. A ``FlowGenericError`` with reason ``NotFocused`` is + raised if the flow is valid but not focused. """ super().check_well_formed() if not self.is_focused(): @@ -1138,12 +1170,13 @@ def extract_circuit(self: FocusedPauliFlow[Measurement], *, stacklevel: int = 1) @dataclass(frozen=True) class GFlow(PauliFlow[_PM_co], Generic[_PM_co]): - """An unmutable subclass of ``PauliFlow`` providing a representation of a generalised flow (gflow). + r"""An unmutable subclass of ``PauliFlow`` providing a representation of a generalised flow (gflow). This class differs from its parent class in the following: - It cannot be constructed from ``OpenGraph[Axis]`` instances, since the gflow is only defined for planar measurements. + - Measurements are labelled by their plane (see :meth:`GFlow.node_measurement_label`). - The extraction of XZ-corrections from the gflow does not require knowledge on the partial order. - - The method :func:`GFlow.is_well_formed` verifies the definition of gflow (Definition 2.36 in Ref. [1]). + - The methods :meth:`check_well_formed` and :meth:`check_flow_properties` verify the definition of gflow below. The methods :meth:`OpenGraph.to_gflow` and :meth:`Pattern.to_gflow` return well-formed gflows by @@ -1154,9 +1187,29 @@ class GFlow(PauliFlow[_PM_co], Generic[_PM_co]): correction function may not be valid, and the layers may be incompatible with the open graph or the corrections. The caller is responsible for ensuring that the provided attributes form a - well-formed gflow. The :meth`:check_well_formed` method can be + well-formed gflow. The :meth:`check_well_formed` method can be called to explicitly verify that the flow is well-formed. + Notes + ----- + A gflow on an open graph :math:`(G, I, O, \lambda)` with planar measurements is a pair + :math:`(g, \prec)`, where :math:`g: O^c \to 2^{I^c}` is the correction function and + :math:`\prec` is a strict partial order on the nodes of the open graph, such that, for all + :math:`i \in O^c`: + + - If :math:`j \in g(i), i \neq j`, then :math:`i \prec j` (G1). + - If :math:`j \in Odd(g(i)), i \neq j`, then :math:`i \prec j` (G2). + - If :math:`\lambda(i) = XY`, then :math:`i \notin g(i)` and :math:`i \in Odd(g(i))` (G3). + - If :math:`\lambda(i) = XZ`, then :math:`i \in g(i)` and :math:`i \in Odd(g(i))` (G4). + - If :math:`\lambda(i) = YZ`, then :math:`i \in g(i)` and :math:`i \notin Odd(g(i))` (G5), + + where :math:`\lambda(i)` is the measurement plane of node :math:`i` and :math:`Odd(s)` is + the odd neighbourhood of the set :math:`s` in the open graph. See Definition 2.36 in Ref. [1]. + The names in brackets are those of + :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and + :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`. The general properties + of flows listed in :class:`PauliFlow` are also required. + References ---------- [1] Backens et al., Quantum 5, 421 (2021), doi.org/10.22331/q-2021-03-25-421 @@ -1197,41 +1250,16 @@ def to_xzcorrections(self) -> XZCorrections[_PM_co]: @override def check_flow_properties(self) -> None: - r"""Verify that the generalised flow satisfies the flow properties. + """Verify that the flow satisfies the flow properties. + + This method checks the validity of the flow, see the class docstring for the flow + definition. It does not check whether the flow is focused, even if ``self`` is an + instance of :class:`FocusedGFlow`. Raises ------ FlowError - if the gflow does not satisfy the flow properties. - - Notes - ----- - This method checks the properties for the instance to be a - valid generalised flow. It does not check whether the flow is - focused, even if ``self`` is an instance of - :class:`FocusedGFlow`. By contrast, :meth:`check_well_formed` - checks that the flow is valid and, for instances of - :class:`FocusedGFlow`, also checks that the flow is focused. - - General properties of flows: - - The domain of the correction function is :math:`O^c`, the non-output nodes of the open graph. - - The image of the correction function is a subset of :math:`I^c`, the non-input nodes of the open graph. - - The nodes in the partial order are the nodes in the open graph. - - The first layer of the partial order layers contains the outputs of the open graph if there are any. - - Specific properties of gflows: - - If :math:`j \in g(i), i \neq j`, then :math:`i \prec j` (G1). - - If :math:`j \in Odd(g(i)), i \neq j`, then :math:`i \prec j` (G2). - - If :math:`\lambda(i) = XY`, then :math:`i \notin g(i)`` and :math:`i \in Odd((g(i)))` (G3). - - If :math:`\lambda(i) = XZ`, then :math:`i \in g(i)`` and :math:`i \in Odd((g(i)))` (G4). - - If :math:`\lambda(i) = YZ`, then :math:`i \in g(i)`` and :math:`i \notin Odd((g(i)))` (G5), - where :math:`i \in O^c`, :math:`g` is the correction function, :math:`prec` denotes the partial order, :math:`\lambda(i)` is the measurement plane of node :math:`i`, and :math:`Odd(s)` is the odd neighbourhood of the set :math:`s` in the open graph. - - See Definition 2.36 in Ref. [1]. - - References - ---------- - [1] Backens et al., Quantum 5, 421 (2021), doi.org/10.22331/q-2021-03-25-421 + If the flow does not satisfy the flow properties. """ _check_flow_general_properties(self) @@ -1357,9 +1385,15 @@ class FocusedGFlow(GFlow[_PM_co], FocusedPauliFlow[_PM_co], Generic[_PM_co]): the corrections, and the flow, if any, may not be focused. The caller is responsible for ensuring that the provided attributes form a well-formed and focused gflow. The - :meth`:check_well_formed` method can be called to explicitly - verify that the flow is well-formed, and the `is_focused` method - can be called to explicitly verify that the flow is focused. + :meth:`check_well_formed` method can be called to explicitly + verify that the flow is well-formed and focused, and the + :meth:`is_focused` method can be called to explicitly verify that + the flow is focused. + + Notes + ----- + See :class:`GFlow` for the definition of gflow and :meth:`PauliFlow.is_focused` for the + definition of focused flow. """ @override @@ -1368,91 +1402,76 @@ def to_focused(self) -> FocusedGFlow[_PM_co]: @dataclass(frozen=True) -class CausalFlow(GFlow[_PM_co], Generic[_PM_co]): - """An unmutable subclass of ``GFlow`` providing a representation of a causal flow. +class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): + r"""An unmutable subclass of ``GFlow`` providing a representation of an extended causal flow. + + Extended causal flows are defined on open graphs with :math:`XY` and :math:`YZ` + measurements only (Definition 10 in Ref. [1]). The correction set of an :math:`XY`-measured + node :math:`i` is a single neighbor of :math:`i`, as in a causal flow, and the correction set + of a :math:`YZ`-measured node :math:`i` is :math:`\{i\}`. An extended causal flow is therefore + a gflow, and causal flows are extended causal flows on open graphs with :math:`XY` measurements only. This class differs from its parent class in the following: - - The extraction of XZ-corrections from the causal flow does assumes that correction sets have one element only. - - The method :func:`CausalFlow.is_well_formed` verifies the definition of causal flow (Definition 2 in Ref. [1]). + - The method :meth:`check_well_formed` verifies the definition of extended causal flow below. + - XZ-corrections are computed as for gflows (see :meth:`GFlow.to_xzcorrections`). - The methods :meth:`OpenGraph.to_causalflow` and - :meth:`Pattern.to_causalflow` return well-formed causal flows by - construction. + The methods :meth:`OpenGraph.to_extendedcausalflow` and + :meth:`XZCorrections.to_extendedcausalflow` return well-formed + extended causal flows by construction. - No well-formedness checks are performed when instantiating a - ``CausalFlow`` object directly by calling the constructor: the - correction function may not be valid, and the layers may be + No well-formedness checks are performed when instantiating an + ``ExtendedCausalFlow`` object directly by calling the constructor: + the correction function may not be valid, and the layers may be incompatible with the open graph or the corrections. The caller is responsible for ensuring that the provided attributes form a - well-formed causal flow. The :meth`:check_well_formed` method can - be called to explicitly verify that the flow is well-formed. + well-formed extended causal flow. The :meth:`check_well_formed` + method can be called to explicitly verify that the flow is + well-formed. + + Notes + ----- + An extended causal flow on an open graph :math:`(G, I, O, \lambda)` with :math:`XY` and + :math:`YZ` measurements is a pair :math:`(e, \prec)`, where :math:`e: O^c \to I^c` is + the correction function and :math:`\prec` is a strict partial order on the nodes of the open + graph, such that, for all :math:`i \in O^c`: + + - :math:`e(i)` has one element only (C0). + - If :math:`\lambda(i) = XY`, then :math:`i \sim e(i)` (C1). + - If :math:`\lambda(i) = YZ`, then :math:`e(i) = \{i\}` (CYZ). + - If :math:`\lambda(i) = XY`, then :math:`i \prec e(i)` (C2). + - For all :math:`k \in N_G(e(i)) \setminus \{i\}`, :math:`i \prec k` (C3), + + where :math:`\lambda(i)` is the measurement plane of node :math:`i` and :math:`N_G(s)` is the + neighbourhood of the set :math:`s` in the graph. The names in brackets are those of + :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and + :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`. The general properties + of flows listed in :class:`PauliFlow` are also required. Since the image of the correction + function is a subset of the non-input nodes, condition (CYZ) implies that + :math:`YZ`-measured nodes cannot be inputs. Open graphs with :math:`XZ` measurements do + not have extended causal flow. + + See Definition 10 in Ref. [1], where condition (CYZ) is introduced. Conditions (C0)-(C3) + are those of causal flow, see Definition 2 in Ref. [2]. References ---------- - [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). - + [1] Miriam Backens and Simon Perdrix, Completeness for flow-preserving rewrite rules, 2026 (arXiv:2608.13035). + [2] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). """ - _CF_PREFIX: str = "c" # Correction function prefix for printing + _CF_PREFIX: str = "e" # Correction function prefix for printing @override - def to_xzcorrections(self) -> XZCorrections[_PM_co]: - r"""Compute the XZ-corrections induced by the causal flow encoded in ``self``. - - Returns - ------- - XZCorrections[_PM_co] - - Notes - ----- - This function partially implements Theorem 1 in Ref. [1]. The generated XZ-corrections can be used to obtain a robustly deterministic pattern on the underlying open graph. - - References - ---------- - [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). - """ - x_corrections: dict[int, AbstractSet[int]] = {} # {domain: nodes} - z_corrections: dict[int, AbstractSet[int]] = {} # {domain: nodes} - - for measured_node, correcting_set in self.correction_function.items(): - # Conditionals avoid storing empty correction sets - if x_corrected_nodes := correcting_set: - x_corrections[measured_node] = frozenset(x_corrected_nodes) - if z_corrected_nodes := self.og.neighbors(correcting_set) - {measured_node}: - z_corrections[measured_node] = frozenset(z_corrected_nodes) - - return XZCorrections(self.og, x_corrections, z_corrections, self.partial_order_layers) - def check_well_formed(self) -> None: - r"""Verify if the causal flow is well formed. + """Verify that the flow is well-formed. + + This method checks the validity of the flow, see the class docstring for the flow + definition. Raises ------ FlowError - if the causal flow is not well formed. - - Notes - ----- - General properties of flows: - - The domain of the correction function is :math:`O^c`, the non-output nodes of the open graph. - - The image of the correction function is a subset of :math:`I^c`, the non-input nodes of the open graph. - - The nodes in the partial order are the nodes in the open graph. - - The first layer of the partial order layers is :math:`O`, the output nodes of the open graph. This is guaranteed because open graphs without outputs do not have flow, unless it is an empty open graph. - - Specific properties of causal flows: - - Correction sets have one element only (C0), - - :math:`i \sim c(i)` (C1), - - :math:`i \prec c(i)` (C2), - - :math:`\forall k \in N_G(c(i)) \setminus \{i\}, i \prec k` (C3), - where :math:`i \in O^c`, :math:`c` is the correction function and :math:`prec` denotes the partial order. - - Causal flows are defined on open graphs with XY measurements only. - - See Definition 2 in Ref. [1]. - - References - ---------- - [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). + If the flow is not well-formed. """ _check_flow_general_properties(self) @@ -1474,23 +1493,27 @@ def check_well_formed(self) -> None: if len(correction_set) != 1: raise FlowPropositionError(FlowPropositionErrorReason.C0, node=node, correction_set=correction_set) - meas = self.node_measurement_label(node) - if meas != Plane.XY: - raise FlowGenericError(FlowGenericErrorReason.XYPlane) - neighbors = self.og.neighbors(correction_set) - if node not in neighbors: - raise FlowPropositionError(FlowPropositionErrorReason.C1, node=node, correction_set=correction_set) - - # If some nodes of the correction set are in the past or in the present of the current node, they cannot be in its future, so the flow is incorrrect. - if correction_set & past_and_present_nodes: - raise FlowPropositionOrderError( - FlowPropositionOrderErrorReason.C2, - node=node, - correction_set=correction_set, - past_and_present_nodes=past_and_present_nodes, - ) + meas = self.node_measurement_label(node) + match meas: + case Plane.XY: + if node not in neighbors: + raise FlowPropositionError( + FlowPropositionErrorReason.C1, node=node, correction_set=correction_set + ) + # If some nodes of the correction set are in the past or in the present of the current node, they cannot be in its future, so the flow is incorrrect. + if correction_set & past_and_present_nodes: + raise FlowPropositionOrderError( + FlowPropositionOrderErrorReason.C2, + node=node, + correction_set=correction_set, + past_and_present_nodes=past_and_present_nodes, + ) + case Plane.YZ: + self._check_yzplane(node) + case Plane.XZ: + raise FlowGenericError(FlowGenericErrorReason.XZPlane) if (neighbors - {node}) & past_and_present_nodes: raise FlowPropositionOrderError( @@ -1505,6 +1528,87 @@ def check_well_formed(self) -> None: if {*o_set, *past_and_present_nodes} != set(self.og.graph.nodes): raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) + def _check_yzplane(self, node: int) -> None: + """Verify condition (CYZ) for a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. + + Parameters + ---------- + node : int + A non-output node measured in the :math:`YZ` plane. Its correction set is assumed to have one element only (condition (C0) is checked beforehand). + + Raises + ------ + FlowPropositionError + With reason ``CYZ`` if ``node`` is not its own corrector. + """ + correction_set = set(self.correction_function[node]) + if node not in correction_set: + raise FlowPropositionError(FlowPropositionErrorReason.CYZ, node=node, correction_set=correction_set) + + +@dataclass(frozen=True) +class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): + r"""An unmutable subclass of ``ExtendedCausalFlow`` providing a representation of a causal flow. + + A causal flow is an extended causal flow on an open graph with :math:`XY` measurements only. + + This class differs from its parent class in the following: + - The method :meth:`check_well_formed` verifies the definition of causal flow below: + open graphs with measurements in the :math:`XZ` or :math:`YZ` planes are rejected. + + The methods :meth:`OpenGraph.to_causalflow` and + :meth:`Pattern.to_causalflow` return well-formed causal flows by + construction. + + No well-formedness checks are performed when instantiating a + ``CausalFlow`` object directly by calling the constructor: the + correction function may not be valid, and the layers may be + incompatible with the open graph or the corrections. The caller is + responsible for ensuring that the provided attributes form a + well-formed causal flow. The :meth:`check_well_formed` method can + be called to explicitly verify that the flow is well-formed. + + Notes + ----- + A causal flow on an open graph :math:`(G, I, O, \lambda)` with :math:`XY` measurements only + is a pair :math:`(c, \prec)`, where :math:`c: O^c \to I^c` is the correction function + and :math:`\prec` is a strict partial order on the nodes of the open graph, such that, for + all :math:`i \in O^c`: + + - :math:`c(i)` has one element only (C0). + - :math:`i \sim c(i)` (C1). + - :math:`i \prec c(i)` (C2). + - For all :math:`k \in N_G(c(i)) \setminus \{i\}`, :math:`i \prec k` (C3), + + where :math:`N_G(s)` is the neighbourhood of the set :math:`s` in the graph. The names in + brackets are those of :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and + :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`. The general properties + of flows listed in :class:`PauliFlow` are also required. See Definition 2 in Ref. [1]. + + References + ---------- + [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). + + """ + + _CF_PREFIX: str = "c" # Correction function prefix for printing + + @override + def _check_yzplane(self, node: int) -> None: + """Handle a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. + + Parameters + ---------- + node : int + A non-output node measured in the :math:`YZ` plane. + + Raises + ------ + FlowGenericError + Always, with reason ``YZPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. + """ + raise FlowGenericError(FlowGenericErrorReason.YZPlane) + def _corrections_to_dag( x_corrections: Mapping[int, AbstractSet[int]], z_corrections: Mapping[int, AbstractSet[int]] @@ -1772,6 +1876,21 @@ def row_at(g: int) -> list[int]: return correction_set +def _reconstruct_correction_function(xz: XZCorrections[AbstractPlanarMeasurement]) -> dict[int, set[int]]: + """Reconstruct an extended causal flow or a gflow correction function from XZ-corrections. + + See :meth:`XZCorrections.to_extendedcausalflow` and :meth:`XZCorrections.to_gflow`. + """ + correction_function: dict[int, set[int]] = {} + for i, meas in xz.og.measurements.items(): + corrections = set(xz.x_corrections.get(i, set())) + if meas.to_plane() in {Plane.XZ, Plane.YZ}: + corrections.add(i) + correction_function[i] = corrections + + return correction_function + + def _reconstruct_pauli_correction_function(xz: XZCorrections[AbstractMeasurement]) -> dict[int, set[int]]: """Reconstruct a Pauli-flow correction function from XZ-corrections. diff --git a/graphix/flow/exceptions.py b/graphix/flow/exceptions.py index 46e4c52cc..ad343e33d 100644 --- a/graphix/flow/exceptions.py +++ b/graphix/flow/exceptions.py @@ -20,7 +20,10 @@ class FlowPropositionErrorReason(Enum): """A correction set in a causal flow has more than one element.""" C1 = enum.auto() - """Causal flow (C1). A node and its corrector must be neighbors.""" + """Causal flow (C1). A node and its corrector must be neighbors. For extended causal flows, this is condition (C.XY) of Definition 10 in [BP26] and only applies to nodes measured on plane XY.""" + + CYZ = enum.auto() + """Extended causal flow (C.YZ). Nodes measured on plane YZ must be their own corrector (Definition 10 in [BP26]).""" G3 = enum.auto() """Gflow (G3). Nodes measured on plane XY cannot be in their own correcting set and must belong to the odd neighbourhood of their own correcting set.""" @@ -84,8 +87,11 @@ class FlowGenericErrorReason(Enum): IncorrectCorrectionFunctionImage = enum.auto() """The image of the correction function is not a subset of non-input nodes (prepared qubits) of the open graph.""" - XYPlane = enum.auto() - "A causal flow is defined on an open graphs with non-XY measurements." + YZPlane = enum.auto() + "A causal flow is defined on an open graph with YZ measurements." + + XZPlane = enum.auto() + "A causal flow or extended causal flow is defined on an open graph with XZ measurements." NoPauliFlow = enum.auto() """No Pauli flow is compatible with the given XZ-corrections: the GF(2) system that reconstructs the correction function has no solution for at least one measured node.""" @@ -153,7 +159,7 @@ class XZCorrectionsError(Exception): @dataclass class FlowPropositionError(FlowError): - """Exception subclass to handle violations of the flow-definition propositions which concern the correction function only (C0, C1, G1, G3, G4, G5, P4, P5, P6, P7, P8, P9).""" + """Exception subclass to handle violations of the flow-definition propositions which concern the correction function only (C0, C1, CYZ, G1, G3, G4, G5, P4, P5, P6, P7, P8, P9).""" reason: FlowPropositionErrorReason node: int @@ -167,6 +173,8 @@ def __str__(self) -> str: return f"Correction set c({self.node}) = {self.correction_set} has more than one element." case FlowPropositionErrorReason.C1: return f"{self.reason.name}: a node and its corrector must be neighbors. {error_help}" + case FlowPropositionErrorReason.CYZ: + return f"{self.reason.name}: nodes measured on plane YZ must be their own corrector. {error_help}" case FlowPropositionErrorReason.G3 | FlowPropositionErrorReason.P4: return f"{self.reason.name}: nodes measured on plane XY cannot be in their own correcting set and must belong to the odd neighbourhood of their own correcting set.\n{error_help}" case FlowPropositionErrorReason.G4 | FlowPropositionErrorReason.P5: @@ -225,8 +233,10 @@ def __str__(self) -> str: return "The domain of the correction function must be the set of non-output nodes (measured qubits) of the open graph." case FlowGenericErrorReason.IncorrectCorrectionFunctionImage: return "The image of the correction function must be a subset of non-input nodes (prepared qubits) of the open graph." - case FlowGenericErrorReason.XYPlane: - return "Causal flow is only defined on open graphs with XY measurements." + case FlowGenericErrorReason.YZPlane: + return "Causal flow is not defined on open graphs with YZ measurements." + case FlowGenericErrorReason.XZPlane: + return "Causal flow and extended causal flows are not defined on open graphs with XZ measurements." case FlowGenericErrorReason.NoPauliFlow: return "No Pauli flow is compatible with the XZ-corrections: the GF(2) system that reconstructs the correction function has no solution for at least one measured node." case FlowGenericErrorReason.NotFocused: diff --git a/graphix/opengraph.py b/graphix/opengraph.py index 9eb9f5877..38847438d 100644 --- a/graphix/opengraph.py +++ b/graphix/opengraph.py @@ -13,7 +13,7 @@ from typing_extensions import override from graphix.clifford import Clifford -from graphix.flow._find_cflow import find_cflow +from graphix.flow._find_cflow import find_cflow, find_ecflow from graphix.flow._find_gpflow import AlgebraicOpenGraph, PlanarAlgebraicOpenGraph, compute_correction_matrix from graphix.flow.core import FocusedGFlow, FocusedPauliFlow from graphix.fundamentals import AbstractMeasurement, AbstractPlanarMeasurement @@ -29,6 +29,7 @@ from graphix import CausalFlow, Pattern, PauliFlow from graphix.circ_ext.extraction import CliffordMap, PauliExponentialDAG + from graphix.flow.core import ExtendedCausalFlow from graphix.parameter import ExpressionOrSupportsFloat, Parameter from graphix.transpiler import Circuit from graphix.visualization import DrawKwargs @@ -139,7 +140,7 @@ def to_pattern(self: OpenGraph[Measurement], *, stacklevel: int = 1) -> Pattern: except TypeError: flow: PauliFlow[Measurement] | None = None else: - flow = bloch_case.to_causalflow_or_none() + flow = bloch_case.to_extendedcausalflow_or_none() if flow is None: flow = self.to_pauliflow_or_none(stacklevel=stacklevel + 1) if flow is not None: @@ -404,6 +405,31 @@ def to_causalflow(self: OpenGraph[_PM_co]) -> CausalFlow[_PM_co]: raise OpenGraphError("The open graph does not have a causal flow.") return cf + def to_extendedcausalflow(self: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co]: + """Try to extract an extended causal flow on the open graph. + + This method is a wrapper over :func:`OpenGraph.to_extendedcausalflow_or_none` with a single return type. + + Returns + ------- + ExtendedCausalFlow[_PM_co] + An extended causal flow object if the open graph has extended causal flow. + + Raises + ------ + OpenGraphError + If the open graph does not have an extended causal flow. + + See Also + -------- + :func:`OpenGraph.to_extendedcausalflow_or_none` + + """ + ecf = self.to_extendedcausalflow_or_none() + if ecf is None: + raise OpenGraphError("The open graph does not have an extended causal flow.") + return ecf + def to_gflow(self: OpenGraph[_PM_co]) -> FocusedGFlow[_PM_co]: r"""Try to extract a maximally delayed generalised flow (gflow) on the open graph. @@ -473,7 +499,7 @@ def to_causalflow_or_none(self: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: Returns ------- CausalFlow[_PM_co] | None - A causal flow object if the open graph has causal flow or ``None`` otherwise. + A causal flow object if the open graph has causal flow or ``None`` otherwise. See Also -------- @@ -490,6 +516,35 @@ def to_causalflow_or_none(self: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: """ return find_cflow(self) + def to_extendedcausalflow_or_none(self: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co] | None: + """Return an extended causal flow on the open graph if it exists. + + As for gflow, measurements (including Bloch measurements with a + Pauli angle) are labelled by their plane. In particular, Pauli + measurements must be converted into Bloch measurements first, e.g., + with :meth:`OpenGraph.to_bloch`. + + Returns + ------- + ExtendedCausalFlow[_PM_co] | None + An extended causal flow object if the open graph has extended causal flow or ``None`` otherwise. + + See Also + -------- + :func:`OpenGraph.to_extendedcausalflow` + + Notes + ----- + - The extended causal flow is only defined on open graphs with :math:`XY` and :math:`YZ` measurements: ``None`` is returned if some measurement is in the :math:`XZ` plane. See Definition 10 in Ref. [1]. + - This function implements an adaptation of the algorithm presented in Ref. [2] with polynomial complexity on the number of nodes, :math:`O(N^2)`. + + References + ---------- + [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + [2] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 + """ + return find_ecflow(self) + def to_gflow_or_none(self: OpenGraph[_PM_co]) -> FocusedGFlow[_PM_co] | None: r"""Return a maximally delayed Pauli on the open graph if it exists. diff --git a/graphix/pattern.py b/graphix/pattern.py index 4088bc4b8..5e409fee4 100644 --- a/graphix/pattern.py +++ b/graphix/pattern.py @@ -48,7 +48,7 @@ from graphix.clifford import Clifford from graphix.command import CommandType - from graphix.flow.core import CausalFlow, GFlow, PauliFlow, XZCorrections + from graphix.flow.core import CausalFlow, ExtendedCausalFlow, GFlow, PauliFlow, XZCorrections from graphix.opengraph import OpenGraph from graphix.parameter import ExpressionOrSupportsFloat, Parameter from graphix.space_minimization import SpaceMinimizationHeuristic @@ -1055,7 +1055,6 @@ def to_causalflow(self) -> CausalFlow[BlochMeasurement]: FlowError If the pattern: - Contains measurements in forbidden planes (XZ or YZ), - - Is empty, or - Induces a correction function and a partial order which fail the well-formedness checks for a valid causal flow. ValueError If `N` commands in the pattern do not represent a :math:`|+\rangle` state or if the pattern corrections form closed loops. @@ -1067,6 +1066,31 @@ def to_causalflow(self) -> CausalFlow[BlochMeasurement]: """ return self.to_xzcorrections().downcast_bloch().to_causalflow() + def to_extendedcausalflow(self) -> ExtendedCausalFlow[BlochMeasurement]: + r"""Extract the extended causal flow structure from the current measurement pattern. + + This method does not call the flow-extraction routine on the underlying open graph, but constructs the flow from the pattern corrections instead. + + Returns + ------- + ExtendedCausalFlow[Measurement] + The extended causal flow associated with the current pattern. + + Raises + ------ + FlowError + If the pattern: + - Contains measurements in XZ planes, + - Induces a correction function and a partial order which fail the well-formedness checks for a valid extended causal flow. + ValueError + If `N` commands in the pattern do not represent a :math:`|+\rangle` state or if the pattern corrections form closed loops. + + Notes + ----- + See notes in :meth:`to_causalflow`. + """ + return self.to_xzcorrections().downcast_bloch().to_extendedcausalflow() + def to_gflow(self) -> GFlow[BlochMeasurement]: r"""Extract the generalized flow (gflow) structure from the current measurement pattern. @@ -1449,7 +1473,7 @@ def draw( try: # We first try to extract a causal flow because the plotting # algorithm for causal flows yields nicer plots. - flow = xzcorrections.downcast_bloch().to_causalflow() + flow = xzcorrections.downcast_bloch().to_extendedcausalflow() except (TypeError, FlowError): try: # If the pattern is not consistent with a Pauli flow, diff --git a/graphix/space_minimization.py b/graphix/space_minimization.py index 01580de93..a6d511070 100644 --- a/graphix/space_minimization.py +++ b/graphix/space_minimization.py @@ -186,17 +186,34 @@ class SpaceMinimizationHeuristics: """Predefined heuristics.""" @staticmethod - def causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: - """Use the causal flow layer to minimize space. - - This minimization heuristic is optimal but requires the pattern to have a causal flow. + def extended_causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: + """Use the extended causal flow layers to minimize space. + + This minimization heuristic is optimal but requires the + corrections of the pattern to be induced by an extended causal + flow (see :meth:`XZCorrections.to_extendedcausalflow`). This + includes patterns whose corrections are induced by a causal flow. + + Parameters + ---------- + pattern : StandardizedPattern + The pattern whose measurement order is optimized. + + Returns + ------- + SpaceMinimizationHeuristicResult | None + The measurement order given by the layers of the extended + causal flow, from the first to the last measured layer + (marked as known to be optimal), or + ``None`` if the corrections of the pattern are not induced + by an extended causal flow. """ try: - cf = pattern.to_xzcorrections().downcast_bloch().to_causalflow() + ecf = pattern.to_xzcorrections().downcast_bloch().to_extendedcausalflow() except (TypeError, FlowError, ValueError): return None else: - meas_order = tuple(chain(*reversed(cf.partial_order_layers[1:]))) + meas_order = tuple(chain(*reversed(ecf.partial_order_layers[1:]))) return SpaceMinimizationHeuristicResult(meas_order, True) @staticmethod @@ -239,7 +256,7 @@ def greedy_degree(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicRes DEFAULT_HEURISTICS: tuple[SpaceMinimizationHeuristic, ...] = ( - SpaceMinimizationHeuristics.causal_flow, + SpaceMinimizationHeuristics.extended_causal_flow, SpaceMinimizationHeuristics.greedy_degree, SpaceMinimizationHeuristics.order_unchanged, ) @@ -247,8 +264,8 @@ def greedy_degree(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicRes By default, the following heuristics will be tried in that order: -- :func:`causal_flow` gives an optimal measurement order, but only for - patterns with causal flow. +- :func:`extended_causal_flow` gives an optimal measurement order, but only for + patterns with extended causal flow (this includes patterns with causal flow). - :func:`greedy_degree` can improve but can also worsen the max space in some situations. @@ -267,11 +284,11 @@ def minimize_space( The default heuristics are as follows: - - If the pattern has a causal flow, then the layers of the flow - are used to provide an optimal measurement order for the - pattern. See :func:`causal_flow`. + - If the pattern has an extended causal flow, then the layers + of the flow are used to provide an optimal measurement order + for the pattern. See :func:`extended_causal_flow`. - - If the pattern has no causal flow, then a greedy algorithm is + - If the pattern has no extended causal flow, then a greedy algorithm is applied to choose at each step to measure the node with the minimal degree. This particular heuristic has no guarantee to produce an optimal pattern and can even increase the maximal diff --git a/graphix/visualization.py b/graphix/visualization.py index 15535fa0c..027f05b1c 100644 --- a/graphix/visualization.py +++ b/graphix/visualization.py @@ -16,7 +16,7 @@ import numpy.typing as npt from matplotlib import pyplot as plt -from graphix.flow.core import CausalFlow, PauliFlow, XZCorrections +from graphix.flow.core import ExtendedCausalFlow, PauliFlow, XZCorrections from graphix.measurements import PauliMeasurement from graphix.opengraph import OpenGraph @@ -650,7 +650,7 @@ def _compute_positions( obj: OpenGraph[AbstractMeasurement] | PauliFlow[AbstractMeasurement] | XZCorrections[AbstractMeasurement] - | CausalFlow[AbstractPlanarMeasurement], + | ExtendedCausalFlow[AbstractPlanarMeasurement], ) -> dict[int, _Point]: """Compute node positions dispatch.""" raise NotImplementedError @@ -784,8 +784,8 @@ def _( return {node: (l_max - layer_idx, index[pos[node][1]]) for layer_idx, layer in enumerate(pol) for node in layer} -@_compute_positions.register(CausalFlow) -def _(obj: CausalFlow[AbstractPlanarMeasurement]) -> dict[int, _Point]: +@_compute_positions.register(ExtendedCausalFlow) +def _(obj: ExtendedCausalFlow[AbstractPlanarMeasurement]) -> dict[int, _Point]: """Compute node positions for causal flow graph layout. Parameters diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 0faaece93..07b12d76a 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -9,6 +9,7 @@ from graphix.command import E, M, N, X, Z from graphix.flow.core import ( CausalFlow, + ExtendedCausalFlow, FocusedGFlow, FocusedPauliFlow, GFlow, @@ -525,10 +526,45 @@ def test_is_focused(self) -> None: bad_flow_focused.check_well_formed() assert exc_info.value.reason == FlowGenericErrorReason.NotFocused + def test_ecf_yz_node(self) -> None: + # 0 (XY, input) -> 2 (output), 1 (YZ) is a phase gadget on 2: 0 < 1 < 2. + og = OpenGraph( + graph=nx.Graph([(0, 2), (1, 2)]), + input_nodes=[0], + output_nodes=[2], + measurements={0: Plane.XY, 1: Plane.YZ}, + ) + ecf = og.to_extendedcausalflow() + ecf.check_well_formed() + assert ecf.correction_function == {0: {2}, 1: {1}} + assert [set(layer) for layer in ecf.partial_order_layers] == [{2}, {1}, {0}] + class TestXZCorrections: """Bundle for unit tests of :class:`XZCorrections`.""" + def test_to_extendedcausalflow(self) -> None: + # [0]-1-2-(3) with a YZ-measured node 4 attached to 1: extended causal flow but no causal flow. + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (2, 3), (1, 4)]), + input_nodes=[0], + output_nodes=[3], + measurements={0: Plane.XY, 1: Plane.XY, 2: Plane.XY, 4: Plane.YZ}, + ) + ecf_ref = og.to_extendedcausalflow() + corrections = ecf_ref.to_xzcorrections() + assert 4 not in corrections.x_corrections # The YZ-measured node has no X-correction. + + ecf = corrections.to_extendedcausalflow() + ecf.check_well_formed() + assert ecf.correction_function == {0: {1}, 1: {2}, 2: {3}, 4: {4}} + assert ecf.correction_function == ecf_ref.correction_function + assert ecf.partial_order_layers == ecf_ref.partial_order_layers + + # The same corrections are not induced by a causal flow (the YZ-measured node has no X-correction). + with pytest.raises(FlowError): + corrections.to_causalflow() + # See `:func: generate_causal_flow_0` def test_order_0(self) -> None: corrections = generate_causal_flow_0().to_xzcorrections() @@ -826,6 +862,14 @@ class TestIncorrectFlows: output_nodes=[3], measurements={0: Plane.XY, 1: Axis.X, 2: Plane.XY}, ) + # [0]-1-2-(3) with a YZ-measured node 4 attached to 1. A well-formed extended causal flow is + # c = {0: {1}, 1: {2}, 2: {3}, 4: {4}} with partial order layers [{3}, {2}, {1}, {4}, {0}]. + og_e = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (2, 3), (1, 4)]), + input_nodes=[0], + output_nodes=[3], + measurements={0: Plane.XY, 1: Plane.XY, 2: Plane.XY, 4: Plane.YZ}, + ) @pytest.mark.parametrize( "test_case", @@ -842,7 +886,7 @@ class TestIncorrectFlows: correction_function={0: {1}}, partial_order_layers=[{1}, {0}], ), - FlowGenericError(FlowGenericErrorReason.XYPlane), + FlowGenericError(FlowGenericErrorReason.XZPlane), ), # Incomplete correction function IncorrectFlowTestCase( @@ -956,6 +1000,121 @@ class TestIncorrectFlows: FlowPropositionOrderErrorReason.C3, node=0, correction_set={1}, past_and_present_nodes={0, 2} ), ), + # Correct extended causal flow checked as a causal flow (open graph with YZ measurements). + IncorrectFlowTestCase( + CausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {1}, {4}, {0}], + ), + FlowGenericError(FlowGenericErrorReason.YZPlane), + ), + # Extended causal flow on an open graph with XZ measurements. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=OpenGraph( + graph=nx.Graph([(0, 1)]), + input_nodes=[0], + output_nodes=[1], + measurements={0: Plane.XZ}, + ), + correction_function={0: {1}}, + partial_order_layers=[{1}, {0}], + ), + FlowGenericError(FlowGenericErrorReason.XZPlane), + ), + # Extended causal flow: YZ-measured input node (it should be in its own correction set). + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=OpenGraph( + graph=nx.Graph([(0, 1)]), + input_nodes=[0], + output_nodes=[1], + measurements={0: Plane.YZ}, + ), + correction_function={0: {0}}, + partial_order_layers=[{1}, {0}], + ), + FlowGenericError(FlowGenericErrorReason.IncorrectCorrectionFunctionImage), + ), + # Extended causal flow: incomplete correction function (missing YZ-measured node). + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}}, + partial_order_layers=[{3}, {2}, {1}, {4}, {0}], + ), + FlowGenericError(FlowGenericErrorReason.IncorrectCorrectionFunctionDomain), + ), + # Extended causal flow: C0 on a YZ-measured node. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {1, 4}}, + partial_order_layers=[{3}, {2}, {1}, {4}, {0}], + ), + FlowPropositionError(FlowPropositionErrorReason.C0, node=4, correction_set={1, 4}), + ), + # Extended causal flow: C1 on an XY-measured node. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {2}, 1: {2}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {1}, {4}, {0}], + ), + FlowPropositionError(FlowPropositionErrorReason.C1, node=0, correction_set={2}), + ), + # Extended causal flow: CYZ, the YZ-measured node is not its own corrector. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {1}}, + partial_order_layers=[{3}, {2}, {1}, {4}, {0}], + ), + FlowPropositionError(FlowPropositionErrorReason.CYZ, node=4, correction_set={1}), + ), + # Extended causal flow: C2 on an XY-measured node. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {4}, {0, 1}], + ), + FlowPropositionOrderError( + FlowPropositionOrderErrorReason.C2, node=0, correction_set={1}, past_and_present_nodes={0, 1} + ), + ), + # Extended causal flow: C3 on a YZ-measured node, its neighbor 1 is not in its future. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {1, 4}, {0}], + ), + FlowPropositionOrderError( + FlowPropositionOrderErrorReason.C3, node=4, correction_set={4}, past_and_present_nodes={0, 1, 4} + ), + ), + # Extended causal flow: C3, a YZ-measured node cannot correct another node. + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {4}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {4}, {1}, {0}], + ), + FlowPropositionOrderError( + FlowPropositionOrderErrorReason.C3, node=4, correction_set={4}, past_and_present_nodes={0, 1, 4} + ), + ), + # Extended causal flow: incomplete partial order (missing YZ-measured node). + IncorrectFlowTestCase( + ExtendedCausalFlow( + og=og_e, + correction_function={0: {1}, 1: {2}, 2: {3}, 4: {4}}, + partial_order_layers=[{3}, {2}, {1}, {0}], + ), + PartialOrderError(PartialOrderErrorReason.IncorrectNodes), + ), # G1 IncorrectFlowTestCase( GFlow( diff --git a/tests/test_opengraph.py b/tests/test_opengraph.py index 726d21bc3..e86b20875 100644 --- a/tests/test_opengraph.py +++ b/tests/test_opengraph.py @@ -34,6 +34,7 @@ class OpenGraphFlowTestCase(NamedTuple): og: OpenGraph[Measurement] has_cflow: bool + has_ecflow: bool has_gflow: bool has_pflow: bool @@ -71,7 +72,7 @@ def _og_0() -> OpenGraphFlowTestCase: output_nodes=[0, 1], measurements=meas, ) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -94,7 +95,7 @@ def _og_1() -> OpenGraphFlowTestCase: 4: Measurement.Y, }, ) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -118,7 +119,7 @@ def _og_2() -> OpenGraphFlowTestCase: 4: Measurement.XY(0.4), }, ) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -147,7 +148,7 @@ def _og_3() -> OpenGraphFlowTestCase: 3: Measurement.XY(0.3), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -173,7 +174,7 @@ def _og_4() -> OpenGraphFlowTestCase: 3: Measurement.YZ(0.3), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -197,7 +198,7 @@ def _og_5() -> OpenGraphFlowTestCase: 2: Measurement.XY(0.1), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -223,7 +224,7 @@ def _og_6() -> OpenGraphFlowTestCase: 3: Measurement.X, # X }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -244,7 +245,7 @@ def _og_7() -> OpenGraphFlowTestCase: 1: Measurement.YZ(0.5), # Y }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -270,7 +271,7 @@ def _og_8() -> OpenGraphFlowTestCase: 5: Measurement.YZ(0.1), # YZ }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -296,7 +297,7 @@ def _og_9() -> OpenGraphFlowTestCase: 5: Measurement.Y, # Y }, ) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -328,7 +329,7 @@ def _og_10() -> OpenGraphFlowTestCase: 4: Measurement.Z, # Z }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -354,7 +355,7 @@ def _og_11() -> OpenGraphFlowTestCase: 7: Measurement.X, }, ) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -373,7 +374,7 @@ def _og_12() -> OpenGraphFlowTestCase: output_nodes=[1, 3, 4], measurements={0: Measurement.XY(0.1), 2: Measurement.YZ(0.5)}, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -400,7 +401,7 @@ def _og_13() -> OpenGraphFlowTestCase: 5: Measurement.YZ(0.1), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -419,7 +420,7 @@ def _og_14() -> OpenGraphFlowTestCase: output_nodes=[1, 3, 4], measurements={0: Measurement.X, 2: Measurement.Z, 6: Measurement.XY(0.2)}, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -446,7 +447,7 @@ def _og_15() -> OpenGraphFlowTestCase: 5: Measurement.XY(0.1), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -465,7 +466,7 @@ def _og_16() -> OpenGraphFlowTestCase: output_nodes=[1, 3, 4], measurements={0: Measurement.XZ(0.1), 2: Measurement.Z, 6: Measurement.XY(0.2)}, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -499,7 +500,7 @@ def _og_17() -> OpenGraphFlowTestCase: 8: Measurement.XY(0.1), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -525,7 +526,7 @@ def _og_18() -> OpenGraphFlowTestCase: 7: Measurement.Z, }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=False) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) @register_open_graph_flow_test_case @@ -555,7 +556,7 @@ def _og_19() -> OpenGraphFlowTestCase: 7: Measurement.Z, }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -582,7 +583,7 @@ def _og_20() -> OpenGraphFlowTestCase: 0: Measurement.YZ(angle=0), }, ) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -595,7 +596,7 @@ def _og_21() -> OpenGraphFlowTestCase: https://github.com/TeamGraphix/graphix/issues/531 """ og: OpenGraph[Measurement] = OpenGraph(graph=nx.Graph(), input_nodes=[], output_nodes=[], measurements={}) - return OpenGraphFlowTestCase(og, has_cflow=True, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=True, has_ecflow=True, has_gflow=True, has_pflow=True) @register_open_graph_flow_test_case @@ -613,7 +614,7 @@ def _og_22() -> OpenGraphFlowTestCase: https://github.com/TeamGraphix/graphix/issues/531#issuecomment-4797042493 """ og = OpenGraph(nx.complete_graph(3), (), (), dict.fromkeys(range(3), Measurement.Z)) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=False, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=True) @register_open_graph_flow_test_case @@ -632,7 +633,77 @@ def _og_23() -> OpenGraphFlowTestCase: https://github.com/TeamGraphix/graphix/issues/531#issuecomment-4797042493 """ og = OpenGraph(nx.empty_graph(2), (), (), {0: Measurement.YZ(0.3), 1: Measurement.YZ(0.25)}) - return OpenGraphFlowTestCase(og, has_cflow=False, has_gflow=True, has_pflow=True) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=True, has_gflow=True, has_pflow=True) + + +@register_open_graph_flow_test_case +def _og_24() -> OpenGraphFlowTestCase: + r"""Generate open graph with adjacent YZ. + + Structure: + + 0-1-(2) + |____| + """ + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (0, 2)]), + input_nodes=[], + output_nodes=[2], + measurements={0: Measurement.YZ(0.3), 1: Measurement.YZ(0.3)}, + ) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) + + +@register_open_graph_flow_test_case +def _og_25() -> OpenGraphFlowTestCase: + r"""Generate open graph. YZ can't correct. + + Structure: + + [0]-1-(2) + |_____| + """ + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (0, 2)]), + input_nodes=[0], + output_nodes=[2], + measurements={0: Measurement.XY(0.3), 1: Measurement.YZ(0.3)}, + ) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) + + +@register_open_graph_flow_test_case +def _og_26() -> OpenGraphFlowTestCase: + r"""Generate open graph. + + Structure: + + 0-(2)-1 + """ + og = OpenGraph( + graph=nx.Graph([(0, 2), (1, 2)]), + input_nodes=[], + output_nodes=[2], + measurements={0: Measurement.XY(0.3), 1: Measurement.YZ(0.3)}, + ) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=True, has_gflow=True, has_pflow=True) + + +@register_open_graph_flow_test_case +def _og_27() -> OpenGraphFlowTestCase: + r"""Generate open graph. + + Structure: + + 0-(2)-1 + """ + og = OpenGraph( + graph=nx.Graph([(0, 2), (1, 2)]), + input_nodes=[], + output_nodes=[2], + measurements={0: Measurement.XY(0.3), 1: Measurement.XY(0.3)}, + ) + return OpenGraphFlowTestCase(og, has_cflow=False, has_ecflow=False, has_gflow=False, has_pflow=False) class OpenGraphComposeTestCase(NamedTuple): @@ -1098,6 +1169,21 @@ def test_cflow(self, test_case: OpenGraphFlowTestCase, fx_rng: Generator) -> Non with pytest.raises(OpenGraphError, match=r"The open graph does not have a causal flow."): og.to_causalflow() + @pytest.mark.parametrize("test_case", OPEN_GRAPH_FLOW_TEST_CASES) + def test_ecflow(self, test_case: OpenGraphFlowTestCase, fx_rng: Generator) -> None: + og = test_case.og.to_bloch() + + if test_case.has_ecflow: + ecf = og.to_extendedcausalflow() + ecf.check_well_formed() + xz = ecf.to_xzcorrections() + xz.check_well_formed() + pattern = xz.to_pattern() + assert check_determinism(pattern, fx_rng) + else: + with pytest.raises(OpenGraphError, match=r"The open graph does not have an extended causal flow."): + og.to_extendedcausalflow() + @pytest.mark.parametrize("test_case", OPEN_GRAPH_FLOW_TEST_CASES) @pytest.mark.filterwarnings("ignore:Non-Pauli measurement on an isolated node was removed.") def test_gflow(self, test_case: OpenGraphFlowTestCase, fx_rng: Generator) -> None: diff --git a/tests/test_pattern.py b/tests/test_pattern.py index bfbce7f15..e3472ce71 100644 --- a/tests/test_pattern.py +++ b/tests/test_pattern.py @@ -819,6 +819,7 @@ def test_partial_order_layers_results(self) -> None: class PatternFlowTestCase(NamedTuple): pattern: Pattern has_cflow: bool + has_ecflow: bool has_gflow: bool PATTERN_FLOW_TEST_CASES: list[PatternFlowTestCase] = [ # noqa: RUF012 @@ -865,24 +866,28 @@ class PatternFlowTestCase(NamedTuple): output_nodes=[6, 7], ), has_cflow=True, + has_ecflow=True, has_gflow=True, ), PatternFlowTestCase( # No measurements or corrections Pattern(input_nodes=[0, 1], cmds=[E((0, 1))]), has_cflow=True, + has_ecflow=True, has_gflow=True, ), PatternFlowTestCase( # Disconnected nodes and unordered outputs Pattern(input_nodes=[2], cmds=[N(0), N(1), E((0, 1)), M(0), X(1, {0})], output_nodes=[2, 1]), has_cflow=True, + has_ecflow=True, has_gflow=True, ), PatternFlowTestCase( # Pattern with XZ measurements. Pattern(cmds=[N(0), N(1), E((0, 1)), M(0, Measurement.XZ(0.3)), Z(1, {0}), X(1, {0})], output_nodes=[1]), has_cflow=False, + has_ecflow=False, has_gflow=True, ), PatternFlowTestCase( @@ -914,18 +919,40 @@ class PatternFlowTestCase(NamedTuple): output_nodes=[4, 5, 6], ), has_cflow=False, + has_ecflow=False, has_gflow=True, ), PatternFlowTestCase( # Non-deterministic pattern Pattern(input_nodes=[0], cmds=[N(1), E((0, 1)), M(0, Measurement.XY(0.3))]), has_cflow=False, + has_ecflow=False, has_gflow=False, ), PatternFlowTestCase( # Empty pattern Pattern(), has_cflow=True, + has_ecflow=True, + has_gflow=True, + ), + PatternFlowTestCase( + Pattern( + cmds=[ + N(0), + N(1), + N(2), + E(0, 2), + E(2, 1), + M(0, Measurement.XY(0.3)), + Z(1, {0}), + X(2, {0}), + M(1, Measurement.YZ(0.3)), + Z(2, {1}), + ] + ), + has_cflow=False, + has_ecflow=True, has_gflow=True, ), ] @@ -946,6 +973,22 @@ def test_to_causalflow_rnd_circuit(self, fx_bg: PCG64, jumps: int) -> None: s_test = f_test.simulate(rng=rng) assert s_ref.isclose(s_test) + # Extract extended causal flow from random circuits + @pytest.mark.parametrize("jumps", range(1, 11)) + def test_to_extendedcausalflow_rnd_circuit(self, fx_bg: PCG64, jumps: int) -> None: + """Tests the round trip Pattern -> XZCorrections -> ExtendedCausalFlow -> XZCorrections -> Pattern.""" + rng = Generator(fx_bg.jumped(jumps)) + nqubits = 2 + depth = 2 + circuit_1 = rand_circuit(nqubits, depth, rng, use_ccx=False) + p_ref = circuit_1.transpile().pattern + p_ref.infer_pauli_measurements() + f_test = p_ref.to_bloch().to_extendedcausalflow() + + s_ref = p_ref.simulate(rng=rng) + s_test = f_test.simulate(rng=rng) + assert s_ref.isclose(s_test) + # Extract gflow from random circuits @pytest.mark.parametrize("jumps", range(1, 11)) def test_to_gflow_rnd_circuit(self, fx_bg: PCG64, jumps: int) -> None: @@ -992,6 +1035,20 @@ def test_to_causalflow(self, fx_rng: Generator, test_case: PatternFlowTestCase) with pytest.raises(FlowError): test_case.pattern.to_causalflow() + @pytest.mark.parametrize("test_case", PATTERN_FLOW_TEST_CASES) + def test_to_extendedcausalflow(self, fx_rng: Generator, test_case: PatternFlowTestCase) -> None: + if test_case.has_ecflow: + alpha = 2 * np.pi * fx_rng.random() + s_ref = test_case.pattern.simulate(input_state=PlanarState(Plane.XZ, alpha), rng=fx_rng) + + f_test = test_case.pattern.to_bloch().to_extendedcausalflow() + s_test = f_test.simulate(input_state=PlanarState(Plane.XZ, alpha), rng=fx_rng) + + assert s_ref.isclose(s_test) + else: + with pytest.raises(FlowError): + test_case.pattern.to_extendedcausalflow() + @pytest.mark.parametrize("test_case", PATTERN_FLOW_TEST_CASES) def test_to_gflow(self, fx_rng: Generator, test_case: PatternFlowTestCase) -> None: """Tests the round trip Pattern -> XZCorrections -> GFlow -> XZCorrections -> Pattern.""" @@ -1046,6 +1103,30 @@ def test_extract_cflow_og(self, fx_rng: Generator) -> None: assert s_ref.isclose(s_test) + # From open graph + def test_extract_ecflow_og(self, fx_rng: Generator) -> None: + alpha = 2 * np.pi * fx_rng.random() + + og = OpenGraph( + graph=nx.Graph([(1, 3), (2, 4), (3, 4), (3, 5), (4, 6), (4, 7)]), + input_nodes=[1, 2], + output_nodes=[6, 5], + measurements={ + 1: Measurement.XY(0.1), + 2: Measurement.XY(0.2), + 3: Measurement.XY(0.3), + 4: Measurement.XY(0.4), + 7: Measurement.YZ(0.3), + }, + ) + p_ref = og.to_extendedcausalflow().to_pattern() + s_ref = p_ref.simulate(input_state=PlanarState(Plane.XZ, alpha), rng=fx_rng) + + f_test = p_ref.to_extendedcausalflow() + s_test = f_test.simulate(input_state=PlanarState(Plane.XZ, alpha), rng=fx_rng) + + assert s_ref.isclose(s_test) + # From open graph def test_to_gflow_og(self, fx_rng: Generator) -> None: alpha = 2 * np.pi * fx_rng.random() diff --git a/tests/test_pretty_print.py b/tests/test_pretty_print.py index ed2189d14..2545a6a7a 100644 --- a/tests/test_pretty_print.py +++ b/tests/test_pretty_print.py @@ -189,6 +189,28 @@ def test_cflow_str() -> None: assert flow.to_unicode(multiline=True) == "c(3) = {5}\nc(4) = {6}\nc(1) = {3}\nc(2) = {4}\n{1, 2} ≺ {3, 4} ≺ {5, 6}" +def test_ecflow_str() -> None: + flow = example_og().to_bloch().to_extendedcausalflow() + + assert str(flow) == "e(3) = {5}, e(4) = {6}, e(1) = {3}, e(2) = {4}; {1, 2} < {3, 4} < {5, 6}" + + assert ( + flow.to_latex() + == r"e(3) = \{5\}, \;e(4) = \{6\}, \;e(1) = \{3\}, \;e(2) = \{4\}; \;\{1, 2\} \prec \{3, 4\} \prec \{5, 6\}" + ) + + assert flow.to_unicode() == "e(3) = {5}, e(4) = {6}, e(1) = {3}, e(2) = {4}; {1, 2} ≺ {3, 4} ≺ {5, 6}" + + assert flow.to_ascii(multiline=True) == "e(3) = {5}\ne(4) = {6}\ne(1) = {3}\ne(2) = {4}\n{1, 2} < {3, 4} < {5, 6}" + + assert ( + flow.to_latex(multiline=True) + == r"e(3) = \{5\},\\e(4) = \{6\},\\e(1) = \{3\},\\e(2) = \{4\};\\\{1, 2\} \prec \{3, 4\} \prec \{5, 6\}" + ) + + assert flow.to_unicode(multiline=True) == "e(3) = {5}\ne(4) = {6}\ne(1) = {3}\ne(2) = {4}\n{1, 2} ≺ {3, 4} ≺ {5, 6}" + + def test_gflow_str() -> None: flow = example_og().to_bloch().to_gflow() diff --git a/tests/test_space_minimization.py b/tests/test_space_minimization.py index e8312de58..7826791f7 100644 --- a/tests/test_space_minimization.py +++ b/tests/test_space_minimization.py @@ -1,8 +1,18 @@ from __future__ import annotations +from typing import TYPE_CHECKING + +import networkx as nx + from graphix import Pattern, command +from graphix.measurements import Measurement +from graphix.opengraph import OpenGraph +from graphix.optimization import StandardizedPattern from graphix.space_minimization import SpaceMinimizationHeuristics +if TYPE_CHECKING: + from numpy.random import Generator + def counter_example_issue_454(sz: int, depth: int) -> Pattern: block = Pattern(input_nodes=range(sz)) @@ -31,7 +41,7 @@ def test_minimize_space_deprecated() -> None: # former heuristics, without `keep_measurement_order_unchanged` p.minimize_space( [ - SpaceMinimizationHeuristics.causal_flow, + SpaceMinimizationHeuristics.extended_causal_flow, SpaceMinimizationHeuristics.greedy_degree, ] ) @@ -39,6 +49,30 @@ def test_minimize_space_deprecated() -> None: assert after > before +def test_minimize_space_extended_causal_flow(fx_rng: Generator) -> None: + # [0]-1-2-(3) with a YZ-measured node 4 attached to 1: extended causal flow but no causal flow. + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (2, 3), (1, 4)]), + input_nodes=[0], + output_nodes=[3], + measurements={0: Measurement.XY(0.1), 1: Measurement.XY(0.2), 2: Measurement.XY(0.3), 4: Measurement.YZ(0.4)}, + ) + assert og.to_causalflow_or_none() is None + p = og.to_extendedcausalflow().to_xzcorrections().to_pattern() + + result = SpaceMinimizationHeuristics.extended_causal_flow(StandardizedPattern.from_pattern(p)) + assert result is not None + assert result.known_optimal + assert result.new_order == (0, 4, 1, 2) + + state_ref = p.simulate(rng=fx_rng) + before = p.max_space() + p.minimize_space([SpaceMinimizationHeuristics.extended_causal_flow]) + assert p.max_space() < before + state = p.simulate(rng=fx_rng) + assert state.isclose(state_ref) + + def test_minimization_by_degree_edge_ordering() -> None: # Vertices in edges returned by `graph.edges()` are ordered by # index: for instance, the edge {1, 2} is represented as `(1, 2)`