From 179813762b9f0042fa6d1bc58be0ee35d501242e Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Thu, 12 Nov 2026 11:58:22 +0100 Subject: [PATCH 01/19] Draft extended causal flow --- CHANGELOG.md | 3 + graphix/flow/_find_cflow.py | 235 +++++++++++++++++++++++++++++----- graphix/flow/core.py | 219 +++++++++++++++++++++++++++++++ graphix/flow/exceptions.py | 14 +- graphix/opengraph.py | 59 ++++++++- graphix/space_minimization.py | 40 +++++- tests/test_flow_core.py | 54 +++++++- 7 files changed, 584 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 286e3b8df..6d3b55513 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,9 @@ 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. +- #613: The default space minimization heuristic `SpaceMinimizationHeuristics.extended_causal_flow` + replaces `causal_flow`, and is optimal for patterns with extended 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..4764f64e9 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -10,13 +10,175 @@ from __future__ import annotations +import enum from typing import TYPE_CHECKING -from graphix.flow.core import CausalFlow -from graphix.fundamentals import Plane +from graphix.fundamentals import Axis, Plane if TYPE_CHECKING: - from graphix.opengraph import OpenGraph, _PM_co + from collections.abc import Mapping + from collections.abc import Set as AbstractSet + + import networkx as nx + + from graphix.flow.core import CausalFlow, ExtendedCausalFlow + from graphix.fundamentals import AbstractMeasurement + from graphix.opengraph import OpenGraph, _AM_co, _PM_co + + +class ECFlowLabel(enum.Flag): + """Labels that a measurement can take in an extended causal flow.""" + + NONE = 0 + XY = enum.auto() + YZ = enum.auto() + + +def ecflow_labels(measurement: AbstractMeasurement) -> ECFlowLabel: + """Return the labels that ``measurement`` can take in an extended causal flow. + + The labels follow the convention of Pauli flow (see + :meth:`~graphix.fundamentals.AbstractMeasurement.to_plane_or_axis`): a planar + measurement (e.g., a :class:`~graphix.measurements.BlochMeasurement`, even with a Pauli + angle) is labelled by its plane, and a Pauli measurement (e.g., an inferred + :class:`~graphix.measurements.PauliMeasurement`) can be labelled with any of the planes + :math:`XY` and :math:`YZ` that contain it. A Pauli :math:`X` (resp. :math:`Z`) + measurement is labelled :math:`XY` (resp. :math:`YZ`), and a Pauli :math:`Y` + measurement can be labelled either: the extended causal flow then determines the label, + :math:`YZ` if and only if the node is its own corrector. + + Parameters + ---------- + measurement : AbstractMeasurement + A measurement, a plane or an axis. + + Returns + ------- + ECFlowLabel + The allowed labels (``ECFlowLabel.NONE`` for :math:`XZ`-measurements). + """ + match measurement.to_plane_or_axis(): + case Plane.XY | Axis.X: + return ECFlowLabel.XY + case Plane.YZ | Axis.Z: + return ECFlowLabel.YZ + case Axis.Y: + return ECFlowLabel.XY | ECFlowLabel.YZ + case _: + return ECFlowLabel.NONE + + +def ecflow_label_sets(measurements: Mapping[int, AbstractMeasurement]) -> tuple[set[int], set[int]] | None: + """Return the nodes that can be labelled :math:`XY` and those that can be labelled :math:`YZ`. + + Parameters + ---------- + measurements : Mapping[int, AbstractMeasurement] + The measurements of the measured nodes. + + Returns + ------- + tuple[set[int], set[int]] | None + The pair ``(xy_nodes, yz_nodes)`` (Pauli :math:`Y`-measured nodes belong to both), + or ``None`` if some node cannot be labelled (:math:`XZ`-measurement). + """ + xy_nodes: set[int] = set() + yz_nodes: set[int] = set() + for node, measurement in measurements.items(): + labels = ecflow_labels(measurement) + if not labels: + return None + if ECFlowLabel.XY in labels: + xy_nodes.add(node) + if ECFlowLabel.YZ in labels: + yz_nodes.add(node) + return xy_nodes, yz_nodes + + +def find_ecflow_layers( + graph: nx.Graph[int], + input_nodes: AbstractSet[int], + output_nodes: AbstractSet[int], + xy_nodes: AbstractSet[int], + yz_nodes: AbstractSet[int] = frozenset(), +) -> tuple[dict[int, frozenset[int]], list[frozenset[int]]] | None: + r"""Compute the correction function and layers of a maximally delayed (extended) causal flow. + + The graph is traversed backward from the outputs: + + - a node ``q`` of ``xy_nodes`` is corrected by a node ``p`` which is neither an input nor + self-corrected, and whose only uncorrected neighbour is ``q``: this is condition (C.XY) + of Definition 10 in Ref. [1] (reported as :attr:`~graphix.flow.exceptions.FlowPropositionErrorReason.C1`); + - a non-input node ``q`` of ``yz_nodes`` is self-corrected as soon as all its neighbours are + corrected: this is condition (C.YZ) of Definition 10 in Ref. [1] (reported as + :attr:`~graphix.flow.exceptions.FlowPropositionErrorReason.CYZ`), and + :math:`R_f` requires ``q`` to precede all its neighbours. + + A node may belong to both ``xy_nodes`` and ``yz_nodes`` (e.g., a Pauli :math:`Y` + measurement): it is then labelled :math:`XY` if possible, which is never worse since an + :math:`XY`-node can correct other nodes. Self-corrected nodes (``q`` in ``cf[q]``) are the + nodes labelled :math:`YZ`. + + Parameters + ---------- + graph : nx.Graph[int] + Underlying graph. + input_nodes : AbstractSet[int] + Input nodes. + output_nodes : AbstractSet[int] + Output nodes. + xy_nodes : AbstractSet[int] + Measured nodes that can be labelled :math:`XY`. + yz_nodes : AbstractSet[int] + Measured nodes that can be labelled :math:`YZ`. + + Returns + ------- + tuple[dict[int, frozenset[int]], list[frozenset[int]]] | None + The correction function and the partial-order layers (outputs first), or ``None`` if no + (extended) causal flow exists. + + References + ---------- + [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + """ + graph_nodes = set(graph.nodes) + corrected_nodes = set(output_nodes) + corrector_candidates = corrected_nodes - input_nodes + yz_candidates = set(yz_nodes) - input_nodes + + cf: dict[int, frozenset[int]] = {} + # Output nodes are always in layer 0. + # If the open graph has causal flow, it must have outputs (unless it is an empty open graph). + layers: list[frozenset[int]] = [frozenset(output_nodes)] if output_nodes else [] + + while corrected_nodes != graph_nodes: + corrected_nodes_new: set[int] = set() + corrector_nodes_new: set[int] = set() + + for p in corrector_candidates: + match [*(set(graph.neighbors(p)) - corrected_nodes)]: + case [q] if q in xy_nodes: + cf[q] = frozenset({p}) + corrected_nodes_new.add(q) + corrector_nodes_new.add(p) + + for q in yz_candidates - corrected_nodes_new: + if set(graph.neighbors(q)) <= corrected_nodes: + cf[q] = frozenset({q}) + corrected_nodes_new.add(q) + + if not corrected_nodes_new: + return None + + layers.append(frozenset(corrected_nodes_new)) + corrected_nodes |= corrected_nodes_new + yz_candidates -= corrected_nodes_new + # Self-corrected nodes can never correct another node: the corrected node would be both before and after them. + corrector_candidates = (corrector_candidates - corrector_nodes_new) | { + q for q in corrected_nodes_new if q not in input_nodes and q not in cf[q] + } + return cf, layers def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: @@ -41,42 +203,51 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: ---------- [1] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 """ + from graphix.flow.core import CausalFlow # noqa: PLC0415 (circular import) + for measurement in og.measurements.values(): if measurement.to_plane() in {Plane.XZ, Plane.YZ}: return None - 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) - - cf: dict[int, frozenset[int]] = {} - # Output nodes are always in layer 0. - # If the open graph has causal flow, it must have outputs (unless it is an empty open graph). - layers: list[frozenset[int]] = [frozenset(og.output_nodes)] if og.output_nodes else [] - - while corrected_nodes != graph_nodes: - corrected_nodes_new: set[int] = set() - corrector_nodes_new: set[int] = set() - curr_layer: set[int] = set() + result = find_ecflow_layers(og.graph, set(og.input_nodes), set(og.output_nodes), og.measurements.keys()) + if result is None: + return None + cf, layers = result + return CausalFlow(og, cf, tuple(layers)) - non_corrected_nodes = og.graph.nodes - corrected_nodes - for p in corrector_candidates: - non_corrected_neighbors = og.neighbors({p}) & non_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} +def find_ecflow(og: OpenGraph[_AM_co]) -> ExtendedCausalFlow[_AM_co] | None: + """Return the extended causal flow of the input open graph if it exists. - layers.append(frozenset(curr_layer)) + Parameters + ---------- + og : OpenGraph[_AM_co] + Open graph whose extended causal flow is calculated. - if len(corrected_nodes_new) == 0: - return None + Returns + ------- + ExtendedCausalFlow[_AM_co] | None + An extended causal flow object if the open graph has extended causal flow, `None` otherwise. - corrected_nodes |= corrected_nodes_new - corrector_candidates = (corrector_candidates - corrector_nodes_new) | (corrected_nodes_new & non_input_nodes) + Notes + ----- + The algorithm is derived from Algorithm 1 in Ref. [1], see :func:`find_ecflow_layers`. + Pauli measurements (i.e., measurements interpreted as axes, such as inferred + :class:`~graphix.measurements.PauliMeasurement`) can be labelled with any plane + containing them, see :func:`ecflow_labels`. - return CausalFlow(og, cf, tuple(layers)) + 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 + """ + from graphix.flow.core import ExtendedCausalFlow # noqa: PLC0415 (circular import) + + label_sets = ecflow_label_sets(og.measurements) + if label_sets is None: + return None + result = find_ecflow_layers(og.graph, set(og.input_nodes), set(og.output_nodes), *label_sets) + if result is None: + return None + cf, layers = result + return ExtendedCausalFlow(og, cf, tuple(layers)) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index b575189df..955e4989a 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -16,6 +16,7 @@ from typing_extensions import override from graphix._linalg import MatGF2, solve_f2_linear_system +from graphix.circ_ext.ecflow import ecflow_to_circuit from graphix.circ_ext.extraction import ( CliffordMap, ExtractionResult, @@ -23,6 +24,7 @@ extraction_ps_from_corrected_node, ) from graphix.command import C, E, M, N, X, Z +from graphix.flow._find_cflow import ECFlowLabel, ecflow_labels from graphix.flow._find_gpflow import ( CorrectionMatrix, compute_partial_order_layers, @@ -64,6 +66,7 @@ from graphix.opengraph import OpenGraph from graphix.parameter import ExpressionOrSupportsFloat, Parameter from graphix.pattern import Pattern + from graphix.transpiler import Circuit from graphix.visualization import DrawKwargs @@ -249,6 +252,42 @@ 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) -> ExtendedCausalFlow[_AM_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, and + verifies that the result is compatible with the intrinsic partial order of the + XZ-corrections. A ``FlowError`` is raised otherwise, or if the open graph contains + measurements in the XZ plane. + + Returns + ------- + ExtendedCausalFlow[_AM_co] + + Notes + ----- + See Definition 10 in Ref. [1]. Pauli measurements are labelled as in + :meth:`ExtendedCausalFlow.node_measurement_label`: a Pauli :math:`Y`-measured + node with an X-correction is labelled :math:`XY`, otherwise :math:`YZ`. + + References + ---------- + [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 + """ + correction_function: dict[int, set[int]] = {} + for i, meas in self.og.measurements.items(): + x_corrections = set(self.x_corrections.get(i, set())) + labels = ecflow_labels(meas) + # A node that can be labelled XY and has an X-correction is labelled XY. + correction_function[i] = ( + x_corrections if ECFlowLabel.XY in labels and (x_corrections or ECFlowLabel.YZ not in labels) else {i} + ) + ecf = ExtendedCausalFlow(self.og, correction_function, self.partial_order_layers) + ecf.check_well_formed() + return ecf + def to_gflow(self: XZCorrections[_PM_co]) -> GFlow[_PM_co]: r"""Extract a gflow from XZ-corrections. @@ -1367,6 +1406,186 @@ def to_focused(self) -> FocusedGFlow[_PM_co]: return self +@dataclass(frozen=True) +class ExtendedCausalFlow(PauliFlow[_AM_co], Generic[_AM_co]): + """An unmutable subclass of ``PauliFlow`` providing a representation of an extended causal flow. + + Extended causal flows are defined on labelled open graphs with :math:`XY` and :math:`YZ` + labels only (Definition 10 in Ref. [1]). Following the convention of Pauli flow, planar + measurements are labelled by their plane, and Pauli measurements can be labelled with any + of the planes :math:`XY` and :math:`YZ` that contain them (see + :meth:`ExtendedCausalFlow.node_measurement_label`). This is why this class derives from + ``PauliFlow`` rather than ``GFlow``: an extended causal flow is a gflow on the labelled + open graph, but a Pauli :math:`Y` measurement may be labelled :math:`YZ`. + + This class differs from its parent class in the following: + - The method :func:`ExtendedCausalFlow.check_well_formed` verifies the definition of extended causal flow (Definition 10 in Ref. [1]). + - XZ-corrections are computed as for gflows: :math:`R_f` already puts every corrected node in the future of the measured node. + + References + ---------- + [1] Miriam Backens and Simon Perdrix, Completeness for flow-preserving rewrite rules, 2026 (arXiv:2608.13035). + """ + + _CF_PREFIX: str = "c" # Correction function prefix for printing + + @override + def to_xzcorrections(self) -> XZCorrections[_AM_co]: + r"""Compute the XZ-corrections induced by the extended causal flow encoded in ``self``. + + For a measured node :math:`v` with corrector :math:`c = f(v)`, the X-correction is + applied on :math:`c` if :math:`c \neq v` and the Z-corrections on + :math:`N(c) \setminus \{v\}`. + + Returns + ------- + XZCorrections[_AM_co] + """ + x_corrections: dict[int, AbstractSet[int]] = {} + z_corrections: dict[int, AbstractSet[int]] = {} + for measured_node, correcting_set in self.correction_function.items(): + if x_corrected_nodes := correcting_set - {measured_node}: + x_corrections[measured_node] = frozenset(x_corrected_nodes) + if z_corrected_nodes := self.og.odd_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 to_circuit(self: ExtendedCausalFlow[Measurement]) -> Circuit: + """Extract a circuit from the extended causal flow. + + Chains of the flow become wires, :math:`XY`-measurements become :math:`J` gates, + edges become :math:`CZ` gates and :math:`YZ`-measurements become phase gadgets + (multi-qubit :math:`Z` rotations), see :func:`graphix.circ_ext.ecflow.ecflow_to_circuit`. + + Returns + ------- + Circuit + A circuit implementing the same unitary as the flow, up to a global phase. + """ + return ecflow_to_circuit(self) + + @override + def node_measurement_label(self, node: int) -> Plane: + """Get the label of a given node in the extended causal flow. + + Planar measurements are labelled by their plane. Pauli measurements can be labelled + with any of the planes :math:`XY` and :math:`YZ` that contain them (see + :func:`~graphix.flow._find_cflow.ecflow_labels`): a node that can take both labels + (Pauli :math:`Y`) is labelled :math:`YZ` if and only if it is its own corrector. + Nodes that cannot be labelled are reported as :math:`XZ`. + + Parameters + ---------- + node : int + + Returns + ------- + Plane + """ + labels = ecflow_labels(self.og.measurements[node]) + if labels == ECFlowLabel.XY | ECFlowLabel.YZ: + return Plane.YZ if node in self.correction_function[node] else Plane.XY + if labels == ECFlowLabel.XY: + return Plane.XY + if labels == ECFlowLabel.YZ: + return Plane.YZ + return Plane.XZ + + def check_well_formed(self) -> None: + r"""Verify if the extended causal flow is well formed. + + Raises + ------ + FlowError + if the extended 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 extended causal flows (the names in brackets are those of + :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and + :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`): + - Correction sets have one element only (C0), + - (C.XY) if :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1), + - (C.YZ) if :math:`\lambda(i) = YZ`, then :math:`c(i) = i` (CYZ), + - :math:`R_c^*` is a strict partial order, i.e., :math:`i \prec c(i)` if :math:`c(i) \neq i` (C2), + and :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. + + Extended causal flows are defined on open graphs with XY and YZ measurements only. + + See Definition 10 in Ref. [1], where conditions (C.XY) and (C.YZ) are introduced; (C0)-(C3) + are the conditions of causal flow, see Definition 2 in Ref. [2]. + + References + ---------- + [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). + """ + _check_flow_general_properties(self) + + o_set = set(self.og.output_nodes) + oc_set = set(self.og.measurements) + + layer_idx = len(self.partial_order_layers) - 1 + past_and_present_nodes: set[int] = set() + shift = 1 if o_set else 0 + for layer in reversed(self.partial_order_layers[shift:]): + if not oc_set.issuperset(layer) or not layer or layer & past_and_present_nodes: + raise PartialOrderLayerError(PartialOrderLayerErrorReason.NthLayer, layer_index=layer_idx, layer=layer) + + past_and_present_nodes.update(layer) + + for node in layer: + correction_set = set(self.correction_function[node]) + + if len(correction_set) != 1: + raise FlowPropositionError(FlowPropositionErrorReason.C0, node=node, correction_set=correction_set) + + neighbors = self.og.neighbors(correction_set) + + meas = self.node_measurement_label(node) + match meas: + case Plane.XZ: + raise FlowGenericError(FlowGenericErrorReason.XZPlane) + 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: + if node not in correction_set: + raise FlowPropositionError( + FlowPropositionErrorReason.CYZ, node=node, correction_set=correction_set + ) + + if (neighbors - {node}) & past_and_present_nodes: + raise FlowPropositionOrderError( + FlowPropositionOrderErrorReason.C3, + node=node, + correction_set=correction_set, + past_and_present_nodes=past_and_present_nodes, + ) + + layer_idx -= 1 + + if {*o_set, *past_and_present_nodes} != set(self.og.graph.nodes): + raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) + + @dataclass(frozen=True) class CausalFlow(GFlow[_PM_co], Generic[_PM_co]): """An unmutable subclass of ``GFlow`` providing a representation of a causal flow. diff --git a/graphix/flow/exceptions.py b/graphix/flow/exceptions.py index 46e4c52cc..15d23eedb 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.""" @@ -87,6 +90,9 @@ class FlowGenericErrorReason(Enum): XYPlane = enum.auto() "A causal flow is defined on an open graphs with non-XY measurements." + XZPlane = enum.auto() + "An 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: @@ -227,6 +235,8 @@ def __str__(self) -> str: 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.XZPlane: + return "Extended causal flow is only defined on open graphs without 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..ef457be09 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 @@ -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) -> ExtendedCausalFlow[_AM_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[_AM_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` + + """ + cf = self.to_extendedcausalflow_or_none() + if cf is None: + raise OpenGraphError("The open graph does not have an extended causal flow.") + return cf + 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) -> ExtendedCausalFlow[_AM_co] | None: + """Return an extended causal flow on the open graph if it exists. + + As for Pauli flow, planar measurements (including Bloch measurements + with a Pauli angle) are labelled by their plane, and Pauli + measurements (e.g., inferred with :meth:`OpenGraph.infer_pauli_measurements`) + can be labelled with any of the planes :math:`XY` and :math:`YZ` that + contain them. + + Returns + ------- + ExtendedCausalFlow[_AM_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 measurements that can be labelled :math:`XY` or :math:`YZ`: there is none if some measurement is in the :math:`XZ` plane (and not a Pauli measurement). + - This function implements an adaptation of the algorithm presented in Ref. [1] with polynomial complexity on 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 + """ + 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/space_minimization.py b/graphix/space_minimization.py index 01580de93..d5998c90a 100644 --- a/graphix/space_minimization.py +++ b/graphix/space_minimization.py @@ -10,6 +10,7 @@ import graphix from graphix import command from graphix.command import CommandKind +from graphix.flow._find_cflow import ecflow_label_sets, find_ecflow_layers from graphix.flow.exceptions import FlowError if TYPE_CHECKING: @@ -185,6 +186,39 @@ class SpaceMinimizationHeuristicResult: class SpaceMinimizationHeuristics: """Predefined heuristics.""" + @staticmethod + def extended_causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: + """Use an extended causal flow to minimize space. + + The measurement order follows the layers of a maximally delayed extended causal flow + of the pattern's open graph (see :func:`~graphix.flow._find_cflow.find_ecflow_layers`). + Pauli measurements are labelled as in :func:`~graphix.flow._find_cflow.ecflow_labels`. + + Since every measurement only activates its corrector (or, for :math:`YZ`-measured + nodes, the node itself), the number of active nodes stays at most one more than the + number of chains of the flow: this heuristic is optimal, and subsumes + :func:`causal_flow`. It returns ``None`` if the open graph has no extended causal flow + or if the dependencies of the pattern are not compatible with the layers (i.e., the + corrections of the pattern were not derived from the same flow). + """ + label_sets = ecflow_label_sets({m.node: m.measurement for m in pattern.m_list}) + if label_sets is None: + return None + graph = pattern.graph() + result = find_ecflow_layers(graph, set(pattern.input_nodes), set(pattern.output_nodes), *label_sets) + if result is None: + return None + _correction_function, layers = result + layer_index = {node: index for index, layer in enumerate(layers) for node in layer} + for node, domain in _extract_dependency(pattern).items(): + if node in layer_index and any( + layer_index[dependency] <= layer_index[node] for dependency in domain if dependency in layer_index + ): + return None + # Earliest nodes first: the last layer is measured first, and the first layer contains the outputs. + meas_order = tuple(chain.from_iterable(reversed(layers[1:] if pattern.output_nodes else layers))) + return SpaceMinimizationHeuristicResult(meas_order, True) + @staticmethod def causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: """Use the causal flow layer to minimize space. @@ -239,7 +273,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 +281,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. diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 0faaece93..509397536 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -5,7 +5,9 @@ import networkx as nx import pytest +from numpy.random import Generator +from graphix import Circuit from graphix.command import E, M, N, X, Z from graphix.flow.core import ( CausalFlow, @@ -38,12 +40,13 @@ from graphix.opengraph import OpenGraph from graphix.parameter import Placeholder from graphix.pattern import Pattern +from graphix.random_objects import rand_circuit from graphix.states import PlanarState if TYPE_CHECKING: from collections.abc import Mapping - from numpy.random import Generator + from numpy.random import PCG64 def generate_causal_flow_0() -> CausalFlow[Plane]: @@ -1236,3 +1239,52 @@ def test_xzc_well_formed(self, test_case: IncorrectXZCTestCase) -> None: for field in fields(exc_info.value): attr = field.name assert getattr(exc_info.value, attr) == getattr(test_case.exception, attr) + + +def test_ecf_yz_node() -> 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}] + + +def test_ecf_yz_cannot_correct() -> None: + # The only candidate corrector of 0 is the YZ node 1, which must precede 0. + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2)]), + input_nodes=[0], + output_nodes=[2], + measurements={0: Plane.XY, 1: Plane.YZ}, + ) + assert og.to_extendedcausalflow_or_none() is None + + +def test_ecf_adjacent_yz() -> None: + og = OpenGraph( + graph=nx.Graph([(0, 1), (1, 2), (0, 2)]), + input_nodes=[], + output_nodes=[2], + measurements={0: Plane.YZ, 1: Plane.YZ}, + ) + assert og.to_extendedcausalflow_or_none() is None + + +def test_cflow_none_still_returned() -> None: + # Regression: `find_cflow` must return None (not raise) when there is no causal flow. + # Browne et al. 2007, Fig. 2: gflow but no causal flow. + og = OpenGraph( + graph=nx.Graph([(0, 3), (0, 5), (1, 3), (1, 4), (1, 5), (2, 4), (2, 5)]), + input_nodes=[0, 1, 2], + output_nodes=[3, 4, 5], + measurements=dict.fromkeys([0, 1, 2], Plane.XY), + ) + assert og.to_causalflow_or_none() is None + assert og.to_extendedcausalflow_or_none() is None + From f9741c5c635630059d8ca571650b83f67f8230de Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 13:09:12 +0100 Subject: [PATCH 02/19] Remove refs to circuit extraction --- graphix/flow/core.py | 17 +---------------- graphix/opengraph.py | 6 +++--- tests/test_flow_core.py | 1 - 3 files changed, 4 insertions(+), 20 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 955e4989a..262d24452 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -16,7 +16,6 @@ from typing_extensions import override from graphix._linalg import MatGF2, solve_f2_linear_system -from graphix.circ_ext.ecflow import ecflow_to_circuit from graphix.circ_ext.extraction import ( CliffordMap, ExtractionResult, @@ -1446,24 +1445,10 @@ def to_xzcorrections(self) -> XZCorrections[_AM_co]: for measured_node, correcting_set in self.correction_function.items(): if x_corrected_nodes := correcting_set - {measured_node}: x_corrections[measured_node] = frozenset(x_corrected_nodes) - if z_corrected_nodes := self.og.odd_neighbors(correcting_set) - {measured_node}: + 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 to_circuit(self: ExtendedCausalFlow[Measurement]) -> Circuit: - """Extract a circuit from the extended causal flow. - - Chains of the flow become wires, :math:`XY`-measurements become :math:`J` gates, - edges become :math:`CZ` gates and :math:`YZ`-measurements become phase gadgets - (multi-qubit :math:`Z` rotations), see :func:`graphix.circ_ext.ecflow.ecflow_to_circuit`. - - Returns - ------- - Circuit - A circuit implementing the same unitary as the flow, up to a global phase. - """ - return ecflow_to_circuit(self) - @override def node_measurement_label(self, node: int) -> Plane: """Get the label of a given node in the extended causal flow. diff --git a/graphix/opengraph.py b/graphix/opengraph.py index ef457be09..29f1f4670 100644 --- a/graphix/opengraph.py +++ b/graphix/opengraph.py @@ -425,10 +425,10 @@ def to_extendedcausalflow(self) -> ExtendedCausalFlow[_AM_co]: :func:`OpenGraph.to_extendedcausalflow_or_none` """ - cf = self.to_extendedcausalflow_or_none() - if cf is None: + ecf = self.to_extendedcausalflow_or_none() + if ecf is None: raise OpenGraphError("The open graph does not have an extended causal flow.") - return cf + 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. diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 509397536..537347370 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -1287,4 +1287,3 @@ def test_cflow_none_still_returned() -> None: ) assert og.to_causalflow_or_none() is None assert og.to_extendedcausalflow_or_none() is None - From 636a618121bf309fb67f1e50a2ab1c02aca2b23f Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 13:40:00 +0100 Subject: [PATCH 03/19] Adapt finding flow algorithm --- graphix/flow/_find_cflow.py | 40 +++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index ce0364ca0..d45eb7534 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -41,14 +41,21 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: ---------- [1] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 """ - for measurement in og.measurements.values(): - if measurement.to_plane() in {Plane.XZ, Plane.YZ}: + yz_candidates: set[int] = set() + + for node, measurement in og.measurements.items(): + plane = measurement.to_plane() + if plane == Plane.XZ: return None + elif plane == Plane.YZ: + yz_candidates.add(node) + + flow = ExtendedCausalFlow if yz_candidates else CausalFlow 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 +65,28 @@ 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 flow(og, cf, tuple(layers)) From ea9e19bd3bfc898cf488033caa75cbb1fd1b8786 Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 14:56:43 +0100 Subject: [PATCH 04/19] Tests passing, simple extraction algorithm --- graphix/flow/_find_cflow.py | 195 +++++----------------------------- graphix/flow/core.py | 72 +++---------- graphix/opengraph.py | 4 +- graphix/space_minimization.py | 34 +----- tests/test_flow_core.py | 4 - tests/test_opengraph.py | 134 ++++++++++++++++++----- 6 files changed, 154 insertions(+), 289 deletions(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index 58272822d..8cd4d4ee6 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -10,178 +10,48 @@ from __future__ import annotations -import enum from typing import TYPE_CHECKING -from graphix.fundamentals import Axis, Plane +from graphix.flow.core import CausalFlow, ExtendedCausalFlow +from graphix.fundamentals import Plane if TYPE_CHECKING: - from collections.abc import Mapping - from collections.abc import Set as AbstractSet + from typing import TypeAlias, TypeVar - import networkx as nx + from graphix.opengraph import OpenGraph + from graphix.fundamentals import AbstractPlanarMeasurement - from graphix.flow.core import CausalFlow, ExtendedCausalFlow - from graphix.fundamentals import AbstractMeasurement - from graphix.opengraph import OpenGraph, _AM_co, _PM_co + FlowArguments: TypeAlias = tuple[dict[int, frozenset[int]], tuple[frozenset[int], ...]] + _PM_co = TypeVar("_PM_co", bound=AbstractPlanarMeasurement, covariant=True) -class ECFlowLabel(enum.Flag): - """Labels that a measurement can take in an extended causal flow.""" - - NONE = 0 - XY = enum.auto() - YZ = enum.auto() - - -def ecflow_labels(measurement: AbstractMeasurement) -> ECFlowLabel: - """Return the labels that ``measurement`` can take in an extended causal flow. - - The labels follow the convention of Pauli flow (see - :meth:`~graphix.fundamentals.AbstractMeasurement.to_plane_or_axis`): a planar - measurement (e.g., a :class:`~graphix.measurements.BlochMeasurement`, even with a Pauli - angle) is labelled by its plane, and a Pauli measurement (e.g., an inferred - :class:`~graphix.measurements.PauliMeasurement`) can be labelled with any of the planes - :math:`XY` and :math:`YZ` that contain it. A Pauli :math:`X` (resp. :math:`Z`) - measurement is labelled :math:`XY` (resp. :math:`YZ`), and a Pauli :math:`Y` - measurement can be labelled either: the extended causal flow then determines the label, - :math:`YZ` if and only if the node is its own corrector. - - Parameters - ---------- - measurement : AbstractMeasurement - A measurement, a plane or an axis. - - Returns - ------- - ECFlowLabel - The allowed labels (``ECFlowLabel.NONE`` for :math:`XZ`-measurements). - """ - match measurement.to_plane_or_axis(): - case Plane.XY | Axis.X: - return ECFlowLabel.XY - case Plane.YZ | Axis.Z: - return ECFlowLabel.YZ - case Axis.Y: - return ECFlowLabel.XY | ECFlowLabel.YZ - case _: - return ECFlowLabel.NONE - - -def ecflow_label_sets(measurements: Mapping[int, AbstractMeasurement]) -> tuple[set[int], set[int]] | None: - """Return the nodes that can be labelled :math:`XY` and those that can be labelled :math:`YZ`. - - Parameters - ---------- - measurements : Mapping[int, AbstractMeasurement] - The measurements of the measured nodes. - - Returns - ------- - tuple[set[int], set[int]] | None - The pair ``(xy_nodes, yz_nodes)`` (Pauli :math:`Y`-measured nodes belong to both), - or ``None`` if some node cannot be labelled (:math:`XZ`-measurement). - """ - xy_nodes: set[int] = set() - yz_nodes: set[int] = set() - for node, measurement in measurements.items(): - labels = ecflow_labels(measurement) - if not labels: +def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: + for measurement in og.measurements.values(): + if measurement.to_plane() in {Plane.XZ, Plane.YZ}: return None - if ECFlowLabel.XY in labels: - xy_nodes.add(node) - if ECFlowLabel.YZ in labels: - yz_nodes.add(node) - return xy_nodes, yz_nodes - - -def find_ecflow_layers( - graph: nx.Graph[int], - input_nodes: AbstractSet[int], - output_nodes: AbstractSet[int], - xy_nodes: AbstractSet[int], - yz_nodes: AbstractSet[int] = frozenset(), -) -> tuple[dict[int, frozenset[int]], list[frozenset[int]]] | None: - r"""Compute the correction function and layers of a maximally delayed (extended) causal flow. - - The graph is traversed backward from the outputs: - - - a node ``q`` of ``xy_nodes`` is corrected by a node ``p`` which is neither an input nor - self-corrected, and whose only uncorrected neighbour is ``q``: this is condition (C.XY) - of Definition 10 in Ref. [1] (reported as :attr:`~graphix.flow.exceptions.FlowPropositionErrorReason.C1`); - - a non-input node ``q`` of ``yz_nodes`` is self-corrected as soon as all its neighbours are - corrected: this is condition (C.YZ) of Definition 10 in Ref. [1] (reported as - :attr:`~graphix.flow.exceptions.FlowPropositionErrorReason.CYZ`), and - :math:`R_f` requires ``q`` to precede all its neighbours. - - A node may belong to both ``xy_nodes`` and ``yz_nodes`` (e.g., a Pauli :math:`Y` - measurement): it is then labelled :math:`XY` if possible, which is never worse since an - :math:`XY`-node can correct other nodes. Self-corrected nodes (``q`` in ``cf[q]``) are the - nodes labelled :math:`YZ`. - - Parameters - ---------- - graph : nx.Graph[int] - Underlying graph. - input_nodes : AbstractSet[int] - Input nodes. - output_nodes : AbstractSet[int] - Output nodes. - xy_nodes : AbstractSet[int] - Measured nodes that can be labelled :math:`XY`. - yz_nodes : AbstractSet[int] - Measured nodes that can be labelled :math:`YZ`. - - Returns - ------- - tuple[dict[int, frozenset[int]], list[frozenset[int]]] | None - The correction function and the partial-order layers (outputs first), or ``None`` if no - (extended) causal flow exists. - References - ---------- - [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 - """ - graph_nodes = set(graph.nodes) - corrected_nodes = set(output_nodes) - corrector_candidates = corrected_nodes - input_nodes - yz_candidates = set(yz_nodes) - input_nodes + flow_args = _find_flow(og) + if flow_args is None: + return None + return CausalFlow(og, *flow_args) - cf: dict[int, frozenset[int]] = {} - # Output nodes are always in layer 0. - # If the open graph has causal flow, it must have outputs (unless it is an empty open graph). - layers: list[frozenset[int]] = [frozenset(output_nodes)] if output_nodes else [] - while corrected_nodes != graph_nodes: - corrected_nodes_new: set[int] = set() - corrector_nodes_new: set[int] = set() - - for p in corrector_candidates: - match [*(set(graph.neighbors(p)) - corrected_nodes)]: - case [q] if q in xy_nodes: - cf[q] = frozenset({p}) - corrected_nodes_new.add(q) - corrector_nodes_new.add(p) - - for q in yz_candidates - corrected_nodes_new: - if set(graph.neighbors(q)) <= corrected_nodes: - cf[q] = frozenset({q}) - corrected_nodes_new.add(q) - - if not corrected_nodes_new: +def find_ecflow(og: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co] | None: + 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) - layers.append(frozenset(corrected_nodes_new)) - corrected_nodes |= corrected_nodes_new - yz_candidates -= corrected_nodes_new - # Self-corrected nodes can never correct another node: the corrected node would be both before and after them. - corrector_candidates = (corrector_candidates - corrector_nodes_new) | { - q for q in corrected_nodes_new if q not in input_nodes and q not in cf[q] - } - return cf, layers + flow_args = _find_flow(og, yz_candidates) + if flow_args is None: + return None + return ExtendedCausalFlow(og, *flow_args) -def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: +def _find_flow(og: OpenGraph[_PM_co], yz_candidates: set[int] | None = None) -> FlowArguments | None: """Return the causal flow of the input open graph if it exists. Parameters @@ -203,16 +73,7 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: ---------- [1] 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 - elif plane == Plane.YZ: - yz_candidates.add(node) - - flow = ExtendedCausalFlow if yz_candidates else CausalFlow + yz_candidates = yz_candidates or set() graph_nodes = set(og.graph.nodes) corrected_nodes = set(og.output_nodes) @@ -252,4 +113,4 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: q for q in corrected_nodes_new if q not in iset and q not in cf[q] } - return flow(og, cf, tuple(layers)) + return cf, tuple(layers) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 262d24452..c7bc578c4 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -23,7 +23,6 @@ extraction_ps_from_corrected_node, ) from graphix.command import C, E, M, N, X, Z -from graphix.flow._find_cflow import ECFlowLabel, ecflow_labels from graphix.flow._find_gpflow import ( CorrectionMatrix, compute_partial_order_layers, @@ -65,7 +64,6 @@ from graphix.opengraph import OpenGraph from graphix.parameter import ExpressionOrSupportsFloat, Parameter from graphix.pattern import Pattern - from graphix.transpiler import Circuit from graphix.visualization import DrawKwargs @@ -251,7 +249,7 @@ 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) -> ExtendedCausalFlow[_AM_co]: + 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. @@ -276,15 +274,17 @@ def to_extendedcausalflow(self) -> ExtendedCausalFlow[_AM_co]: [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 """ correction_function: dict[int, set[int]] = {} + for i, meas in self.og.measurements.items(): - x_corrections = set(self.x_corrections.get(i, set())) - labels = ecflow_labels(meas) - # A node that can be labelled XY and has an X-correction is labelled XY. - correction_function[i] = ( - x_corrections if ECFlowLabel.XY in labels and (x_corrections or ECFlowLabel.YZ not in labels) else {i} - ) + corrections = set(self.x_corrections.get(i, set())) + + if meas.to_plane() == Plane.YZ: + corrections.add(i) + + correction_function[i] = corrections + ecf = ExtendedCausalFlow(self.og, correction_function, self.partial_order_layers) - ecf.check_well_formed() + 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]: @@ -1406,7 +1406,7 @@ def to_focused(self) -> FocusedGFlow[_PM_co]: @dataclass(frozen=True) -class ExtendedCausalFlow(PauliFlow[_AM_co], Generic[_AM_co]): +class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): """An unmutable subclass of ``PauliFlow`` providing a representation of an extended causal flow. Extended causal flows are defined on labelled open graphs with :math:`XY` and :math:`YZ` @@ -1428,54 +1428,6 @@ class ExtendedCausalFlow(PauliFlow[_AM_co], Generic[_AM_co]): _CF_PREFIX: str = "c" # Correction function prefix for printing - @override - def to_xzcorrections(self) -> XZCorrections[_AM_co]: - r"""Compute the XZ-corrections induced by the extended causal flow encoded in ``self``. - - For a measured node :math:`v` with corrector :math:`c = f(v)`, the X-correction is - applied on :math:`c` if :math:`c \neq v` and the Z-corrections on - :math:`N(c) \setminus \{v\}`. - - Returns - ------- - XZCorrections[_AM_co] - """ - x_corrections: dict[int, AbstractSet[int]] = {} - z_corrections: dict[int, AbstractSet[int]] = {} - for measured_node, correcting_set in self.correction_function.items(): - if x_corrected_nodes := correcting_set - {measured_node}: - 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) - - @override - def node_measurement_label(self, node: int) -> Plane: - """Get the label of a given node in the extended causal flow. - - Planar measurements are labelled by their plane. Pauli measurements can be labelled - with any of the planes :math:`XY` and :math:`YZ` that contain them (see - :func:`~graphix.flow._find_cflow.ecflow_labels`): a node that can take both labels - (Pauli :math:`Y`) is labelled :math:`YZ` if and only if it is its own corrector. - Nodes that cannot be labelled are reported as :math:`XZ`. - - Parameters - ---------- - node : int - - Returns - ------- - Plane - """ - labels = ecflow_labels(self.og.measurements[node]) - if labels == ECFlowLabel.XY | ECFlowLabel.YZ: - return Plane.YZ if node in self.correction_function[node] else Plane.XY - if labels == ECFlowLabel.XY: - return Plane.XY - if labels == ECFlowLabel.YZ: - return Plane.YZ - return Plane.XZ - def check_well_formed(self) -> None: r"""Verify if the extended causal flow is well formed. @@ -1572,7 +1524,7 @@ def check_well_formed(self) -> None: @dataclass(frozen=True) -class CausalFlow(GFlow[_PM_co], Generic[_PM_co]): +class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): """An unmutable subclass of ``GFlow`` providing a representation of a causal flow. This class differs from its parent class in the following: diff --git a/graphix/opengraph.py b/graphix/opengraph.py index 29f1f4670..99fe8603e 100644 --- a/graphix/opengraph.py +++ b/graphix/opengraph.py @@ -405,7 +405,7 @@ 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) -> ExtendedCausalFlow[_AM_co]: + 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. @@ -516,7 +516,7 @@ def to_causalflow_or_none(self: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: """ return find_cflow(self) - def to_extendedcausalflow_or_none(self) -> ExtendedCausalFlow[_AM_co] | None: + 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 Pauli flow, planar measurements (including Bloch measurements diff --git a/graphix/space_minimization.py b/graphix/space_minimization.py index d5998c90a..2b5fba301 100644 --- a/graphix/space_minimization.py +++ b/graphix/space_minimization.py @@ -10,7 +10,6 @@ import graphix from graphix import command from graphix.command import CommandKind -from graphix.flow._find_cflow import ecflow_label_sets, find_ecflow_layers from graphix.flow.exceptions import FlowError if TYPE_CHECKING: @@ -188,36 +187,7 @@ class SpaceMinimizationHeuristics: @staticmethod def extended_causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: - """Use an extended causal flow to minimize space. - - The measurement order follows the layers of a maximally delayed extended causal flow - of the pattern's open graph (see :func:`~graphix.flow._find_cflow.find_ecflow_layers`). - Pauli measurements are labelled as in :func:`~graphix.flow._find_cflow.ecflow_labels`. - - Since every measurement only activates its corrector (or, for :math:`YZ`-measured - nodes, the node itself), the number of active nodes stays at most one more than the - number of chains of the flow: this heuristic is optimal, and subsumes - :func:`causal_flow`. It returns ``None`` if the open graph has no extended causal flow - or if the dependencies of the pattern are not compatible with the layers (i.e., the - corrections of the pattern were not derived from the same flow). - """ - label_sets = ecflow_label_sets({m.node: m.measurement for m in pattern.m_list}) - if label_sets is None: - return None - graph = pattern.graph() - result = find_ecflow_layers(graph, set(pattern.input_nodes), set(pattern.output_nodes), *label_sets) - if result is None: - return None - _correction_function, layers = result - layer_index = {node: index for index, layer in enumerate(layers) for node in layer} - for node, domain in _extract_dependency(pattern).items(): - if node in layer_index and any( - layer_index[dependency] <= layer_index[node] for dependency in domain if dependency in layer_index - ): - return None - # Earliest nodes first: the last layer is measured first, and the first layer contains the outputs. - meas_order = tuple(chain.from_iterable(reversed(layers[1:] if pattern.output_nodes else layers))) - return SpaceMinimizationHeuristicResult(meas_order, True) + pass @staticmethod def causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: @@ -226,7 +196,7 @@ def causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResul This minimization heuristic is optimal but requires the pattern to have a causal flow. """ try: - cf = pattern.to_xzcorrections().downcast_bloch().to_causalflow() + cf = pattern.to_xzcorrections().downcast_bloch().to_extendedcausalflow() except (TypeError, FlowError, ValueError): return None else: diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 537347370..54c5d184d 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -7,7 +7,6 @@ import pytest from numpy.random import Generator -from graphix import Circuit from graphix.command import E, M, N, X, Z from graphix.flow.core import ( CausalFlow, @@ -40,14 +39,11 @@ from graphix.opengraph import OpenGraph from graphix.parameter import Placeholder from graphix.pattern import Pattern -from graphix.random_objects import rand_circuit from graphix.states import PlanarState if TYPE_CHECKING: from collections.abc import Mapping - from numpy.random import PCG64 - def generate_causal_flow_0() -> CausalFlow[Plane]: """Generate causal flow on linear open graph. diff --git a/tests/test_opengraph.py b/tests/test_opengraph.py index 726d21bc3..eb70e8777 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. YZ can't correct. + + 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. YZ can't correct. + + 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: From 64ac80e028227fc4749f9f8251f1df6440f02d9f Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 17:30:23 +0100 Subject: [PATCH 05/19] Replace causal flow by extended causal flow in minimization heuristics --- graphix/flow/_find_cflow.py | 2 +- graphix/space_minimization.py | 20 ++++++++----------- tests/test_flow_core.py | 34 -------------------------------- tests/test_space_minimization.py | 2 +- 4 files changed, 10 insertions(+), 48 deletions(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index 8cd4d4ee6..2699815a3 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -18,8 +18,8 @@ if TYPE_CHECKING: from typing import TypeAlias, TypeVar - from graphix.opengraph import OpenGraph 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) diff --git a/graphix/space_minimization.py b/graphix/space_minimization.py index 2b5fba301..e56d4460a 100644 --- a/graphix/space_minimization.py +++ b/graphix/space_minimization.py @@ -187,20 +187,16 @@ class SpaceMinimizationHeuristics: @staticmethod def extended_causal_flow(pattern: StandardizedPattern) -> SpaceMinimizationHeuristicResult | None: - pass + """Use the extended causal flow layers to minimize space. - @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. + This minimization heuristic is optimal but requires the pattern to have an extended causal flow. """ try: - cf = pattern.to_xzcorrections().downcast_bloch().to_extendedcausalflow() + 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 @@ -271,11 +267,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/tests/test_flow_core.py b/tests/test_flow_core.py index 54c5d184d..723dd1c39 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -1249,37 +1249,3 @@ def test_ecf_yz_node() -> None: 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}] - - -def test_ecf_yz_cannot_correct() -> None: - # The only candidate corrector of 0 is the YZ node 1, which must precede 0. - og = OpenGraph( - graph=nx.Graph([(0, 1), (1, 2)]), - input_nodes=[0], - output_nodes=[2], - measurements={0: Plane.XY, 1: Plane.YZ}, - ) - assert og.to_extendedcausalflow_or_none() is None - - -def test_ecf_adjacent_yz() -> None: - og = OpenGraph( - graph=nx.Graph([(0, 1), (1, 2), (0, 2)]), - input_nodes=[], - output_nodes=[2], - measurements={0: Plane.YZ, 1: Plane.YZ}, - ) - assert og.to_extendedcausalflow_or_none() is None - - -def test_cflow_none_still_returned() -> None: - # Regression: `find_cflow` must return None (not raise) when there is no causal flow. - # Browne et al. 2007, Fig. 2: gflow but no causal flow. - og = OpenGraph( - graph=nx.Graph([(0, 3), (0, 5), (1, 3), (1, 4), (1, 5), (2, 4), (2, 5)]), - input_nodes=[0, 1, 2], - output_nodes=[3, 4, 5], - measurements=dict.fromkeys([0, 1, 2], Plane.XY), - ) - assert og.to_causalflow_or_none() is None - assert og.to_extendedcausalflow_or_none() is None diff --git a/tests/test_space_minimization.py b/tests/test_space_minimization.py index e8312de58..f9280027e 100644 --- a/tests/test_space_minimization.py +++ b/tests/test_space_minimization.py @@ -31,7 +31,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, ] ) From 58035b18babec22bb8adf1f320f5e1b466414621 Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 17:56:50 +0100 Subject: [PATCH 06/19] Refactor exceptions --- graphix/flow/core.py | 129 +++++----------------------------------- tests/test_flow_core.py | 30 +++++----- 2 files changed, 31 insertions(+), 128 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index c7bc578c4..7eff45a4e 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1488,8 +1488,6 @@ def check_well_formed(self) -> None: meas = self.node_measurement_label(node) match meas: - case Plane.XZ: - raise FlowGenericError(FlowGenericErrorReason.XZPlane) case Plane.XY: if node not in neighbors: raise FlowPropositionError( @@ -1504,10 +1502,9 @@ def check_well_formed(self) -> None: past_and_present_nodes=past_and_present_nodes, ) case Plane.YZ: - if node not in correction_set: - raise FlowPropositionError( - FlowPropositionErrorReason.CYZ, node=node, correction_set=correction_set - ) + self._check_yzplane(node) + case Plane.XZ: + self._check_xzplane() if (neighbors - {node}) & past_and_present_nodes: raise FlowPropositionOrderError( @@ -1522,6 +1519,14 @@ def check_well_formed(self) -> None: if {*o_set, *past_and_present_nodes} != set(self.og.graph.nodes): raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) + def _check_xzplane(self) -> None: + raise FlowGenericError(FlowGenericErrorReason.XZPlane) + + def _check_yzplane(self, node: int) -> None: + 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]): @@ -1552,114 +1557,12 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): _CF_PREFIX: str = "c" # 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. - - 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. + def _check_xzplane(self) -> None: + raise FlowGenericError(FlowGenericErrorReason.XYPlane) - 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). - """ - _check_flow_general_properties(self) - - o_set = set(self.og.output_nodes) - oc_set = set(self.og.measurements) - - layer_idx = len(self.partial_order_layers) - 1 - past_and_present_nodes: set[int] = set() - shift = 1 if o_set else 0 - for layer in reversed(self.partial_order_layers[shift:]): - if not oc_set.issuperset(layer) or not layer or layer & past_and_present_nodes: - raise PartialOrderLayerError(PartialOrderLayerErrorReason.NthLayer, layer_index=layer_idx, layer=layer) - - past_and_present_nodes.update(layer) - - for node in layer: - correction_set = set(self.correction_function[node]) - - 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, - ) - - if (neighbors - {node}) & past_and_present_nodes: - raise FlowPropositionOrderError( - FlowPropositionOrderErrorReason.C3, - node=node, - correction_set=correction_set, - past_and_present_nodes=past_and_present_nodes, - ) - - layer_idx -= 1 - - if {*o_set, *past_and_present_nodes} != set(self.og.graph.nodes): - raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) + @override + def _check_yzplane(self, node: int) -> None: + raise FlowGenericError(FlowGenericErrorReason.XYPlane) def _corrections_to_dag( diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 723dd1c39..3ce07ec4e 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -5,7 +5,6 @@ import networkx as nx import pytest -from numpy.random import Generator from graphix.command import E, M, N, X, Z from graphix.flow.core import ( @@ -44,6 +43,8 @@ if TYPE_CHECKING: from collections.abc import Mapping + from numpy.random import Generator + def generate_causal_flow_0() -> CausalFlow[Plane]: """Generate causal flow on linear open graph. @@ -524,6 +525,19 @@ 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`.""" @@ -1235,17 +1249,3 @@ def test_xzc_well_formed(self, test_case: IncorrectXZCTestCase) -> None: for field in fields(exc_info.value): attr = field.name assert getattr(exc_info.value, attr) == getattr(test_case.exception, attr) - - -def test_ecf_yz_node() -> 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}] From 6dd9906020079ed04b598324b90c6b149d3aa187 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:06:57 +0000 Subject: [PATCH 07/19] Update extended causal flow docstrings and test ExtendedCausalFlow.check_well_formed - Add numpy-style docstrings to find_cflow, find_ecflow and _find_flow, and make _find_flow copy yz_candidates instead of mutating the caller's set. - Fix stale ExtendedCausalFlow/CausalFlow docstrings: ExtendedCausalFlow derives from GFlow and labels measurements by plane (no Pauli labelling), CausalFlow derives from ExtendedCausalFlow and no longer overrides to_xzcorrections. Restore a causal-flow-specific CausalFlow.check_well_formed docstring and document _check_xzplane and _check_yzplane. - Fix return types (_AM_co -> _PM_co), add Raises sections, and update references in XZCorrections.to_extendedcausalflow, OpenGraph.to_extendedcausalflow(_or_none) and SpaceMinimizationHeuristics.extended_causal_flow. - Add ExtendedCausalFlow cases to TestIncorrectFlows (XZPlane, YZ input, domain, C0, C1, CYZ, C2, C3, incomplete order) and a CausalFlow case on an open graph with YZ measurements. Co-Authored-By: Claude Opus 5.5 --- graphix/flow/_find_cflow.py | 69 +++++++++++++--- graphix/flow/core.py | 151 +++++++++++++++++++++++++++------- graphix/flow/exceptions.py | 2 +- graphix/opengraph.py | 20 ++--- graphix/space_minimization.py | 19 ++++- tests/test_flow_core.py | 124 ++++++++++++++++++++++++++++ 6 files changed, 335 insertions(+), 50 deletions(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index 2699815a3..43665c81e 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -1,11 +1,12 @@ -"""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 @@ -16,6 +17,7 @@ from graphix.fundamentals import Plane if TYPE_CHECKING: + from collections.abc import Set as AbstractSet from typing import TypeAlias, TypeVar from graphix.fundamentals import AbstractPlanarMeasurement @@ -26,6 +28,27 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: + """Return the causal flow of the input open graph if it exists. + + Parameters + ---------- + og : OpenGraph[_PM_co] + Open graph whose causal flow is calculated. + + Returns + ------- + CausalFlow[_PM_co] | None + 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]. + - 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 + ---------- + [1] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 + """ for measurement in og.measurements.values(): if measurement.to_plane() in {Plane.XZ, Plane.YZ}: return None @@ -37,6 +60,28 @@ def find_cflow(og: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: 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() @@ -51,29 +96,33 @@ def find_ecflow(og: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co] | None: return ExtendedCausalFlow(og, *flow_args) -def _find_flow(og: OpenGraph[_PM_co], yz_candidates: set[int] | None = None) -> FlowArguments | None: - """Return the causal flow of the input open graph if it exists. +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 causal flow is calculated. + 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 and the routine looks for a causal flow. Returns ------- - CausalFlow[_PM_co] | None - A causal flow object if the open graph has causal flow, `None` otherwise. + 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. ``correction_function`` maps each non-output node to its (single-element) correction set, and ``partial_order_layers[0]`` is the set of output nodes. 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. + 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 = yz_candidates or set() + 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) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 7eff45a4e..c5a1f4bf4 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -254,20 +254,27 @@ def to_extendedcausalflow(self: XZCorrections[_PM_co]) -> ExtendedCausalFlow[_PM 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, and - verifies that the result is compatible with the intrinsic partial order of the - XZ-corrections. A ``FlowError`` is raised otherwise, or if the open graph contains - measurements in the XZ plane. + :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[_AM_co] + 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]. Pauli measurements are labelled as in - :meth:`ExtendedCausalFlow.node_measurement_label`: a Pauli :math:`Y`-measured - node with an X-correction is labelled :math:`XY`, otherwise :math:`YZ`. + - See Definition 10 in Ref. [1]. + - Measurements are labelled by their plane (see :meth:`GFlow.node_measurement_label`). + - 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 ---------- @@ -1407,19 +1414,32 @@ def to_focused(self) -> FocusedGFlow[_PM_co]: @dataclass(frozen=True) class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): - """An unmutable subclass of ``PauliFlow`` providing a representation of an extended causal flow. + r"""An unmutable subclass of ``GFlow`` providing a representation of an extended causal flow. - Extended causal flows are defined on labelled open graphs with :math:`XY` and :math:`YZ` - labels only (Definition 10 in Ref. [1]). Following the convention of Pauli flow, planar - measurements are labelled by their plane, and Pauli measurements can be labelled with any - of the planes :math:`XY` and :math:`YZ` that contain them (see - :meth:`ExtendedCausalFlow.node_measurement_label`). This is why this class derives from - ``PauliFlow`` rather than ``GFlow``: an extended causal flow is a gflow on the labelled - open graph, but a Pauli :math:`Y` measurement may be labelled :math:`YZ`. + Extended causal flows are defined on open graphs with :math:`XY` and :math:`YZ` + measurements only (Definition 10 in Ref. [1]). As for gflows, measurements are + labelled by their plane (see :meth:`GFlow.node_measurement_label`). 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 method :func:`ExtendedCausalFlow.check_well_formed` verifies the definition of extended causal flow (Definition 10 in Ref. [1]). - - XZ-corrections are computed as for gflows: :math:`R_f` already puts every corrected node in the future of the measured node. + - The method :meth:`ExtendedCausalFlow.check_well_formed` verifies the definition of extended causal flow (Definition 10 in Ref. [1]). + - XZ-corrections are computed as for gflows (see :meth:`GFlow.to_xzcorrections`). + + 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 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 extended causal flow. The :meth:`check_well_formed` + method can be called to explicitly verify that the flow is + well-formed. References ---------- @@ -1434,7 +1454,9 @@ def check_well_formed(self) -> None: Raises ------ FlowError - if the extended causal flow is not well formed. + If the extended causal flow is not well formed. In particular, a ``FlowGenericError`` + with reason ``XZPlane`` is raised if the open graph contains measurements in the + :math:`XZ` plane. Notes ----- @@ -1450,11 +1472,11 @@ def check_well_formed(self) -> None: - Correction sets have one element only (C0), - (C.XY) if :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1), - (C.YZ) if :math:`\lambda(i) = YZ`, then :math:`c(i) = i` (CYZ), - - :math:`R_c^*` is a strict partial order, i.e., :math:`i \prec c(i)` if :math:`c(i) \neq i` (C2), - and :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. + - :math:`i \prec c(i)` if :math:`\lambda(i) = XY` (C2), + - :math:`\forall k \in N_G(c(i)) \setminus \{i\}, i \prec k` (C3), + where :math:`i \in O^c`, :math:`\lambda(i)` is the measurement plane of :math:`i`, :math:`c` is the correction function and :math:`\prec` denotes the partial order. Conditions (C2) and (C3) state that the order induced by the correction function is compatible with the partial order. - Extended causal flows are defined on open graphs with XY and YZ measurements only. + Extended causal flows are defined on open graphs with XY and YZ measurements only. Since the image of the correction function is a subset of the non-input nodes, condition (C.YZ) implies that :math:`YZ`-measured nodes cannot be inputs. See Definition 10 in Ref. [1], where conditions (C.XY) and (C.YZ) are introduced; (C0)-(C3) are the conditions of causal flow, see Definition 2 in Ref. [2]. @@ -1520,9 +1542,28 @@ def check_well_formed(self) -> None: raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) def _check_xzplane(self) -> None: + """Handle a node measured in the :math:`XZ` plane in :meth:`check_well_formed`. + + Raises + ------ + FlowGenericError + Always, with reason ``XZPlane``, since extended causal flows are not defined on open graphs with :math:`XZ` measurements. + """ raise FlowGenericError(FlowGenericErrorReason.XZPlane) def _check_yzplane(self, node: int) -> None: + """Verify condition (C.YZ) 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) @@ -1530,11 +1571,12 @@ def _check_yzplane(self, node: int) -> None: @dataclass(frozen=True) class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): - """An unmutable subclass of ``GFlow`` providing a representation of a causal flow. + """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 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:`CausalFlow.check_well_formed` verifies the definition of causal flow (Definition 2 in Ref. [1]): 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 @@ -1545,7 +1587,7 @@ class CausalFlow(ExtendedCausalFlow[_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 causal flow. The :meth`:check_well_formed` method can + well-formed causal flow. The :meth:`check_well_formed` method can be called to explicitly verify that the flow is well-formed. References @@ -1554,14 +1596,67 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): """ - _CF_PREFIX: str = "c" # Correction function prefix for printing + @override + def check_well_formed(self) -> None: + r"""Verify if the causal flow is well formed. + + Raises + ------ + FlowError + If the causal flow is not well formed. In particular, a ``FlowGenericError`` + with reason ``XYPlane`` is raised if the open graph contains measurements in the + :math:`XZ` or :math:`YZ` planes. + + 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). + """ + super().check_well_formed() @override def _check_xzplane(self) -> None: + """Handle a node measured in the :math:`XZ` plane in :meth:`check_well_formed`. + + Raises + ------ + FlowGenericError + Always, with reason ``XYPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. + """ raise FlowGenericError(FlowGenericErrorReason.XYPlane) @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 ``XYPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. + """ raise FlowGenericError(FlowGenericErrorReason.XYPlane) diff --git a/graphix/flow/exceptions.py b/graphix/flow/exceptions.py index 15d23eedb..bcf4c20e0 100644 --- a/graphix/flow/exceptions.py +++ b/graphix/flow/exceptions.py @@ -88,7 +88,7 @@ class FlowGenericErrorReason(Enum): """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." + "A causal flow is defined on an open graph with non-XY measurements." XZPlane = enum.auto() "An extended causal flow is defined on an open graph with XZ measurements." diff --git a/graphix/opengraph.py b/graphix/opengraph.py index 99fe8603e..ad8f65999 100644 --- a/graphix/opengraph.py +++ b/graphix/opengraph.py @@ -412,7 +412,7 @@ def to_extendedcausalflow(self: OpenGraph[_PM_co]) -> ExtendedCausalFlow[_PM_co] Returns ------- - ExtendedCausalFlow[_AM_co] + ExtendedCausalFlow[_PM_co] An extended causal flow object if the open graph has extended causal flow. Raises @@ -519,15 +519,14 @@ def to_causalflow_or_none(self: OpenGraph[_PM_co]) -> CausalFlow[_PM_co] | None: 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 Pauli flow, planar measurements (including Bloch measurements - with a Pauli angle) are labelled by their plane, and Pauli - measurements (e.g., inferred with :meth:`OpenGraph.infer_pauli_measurements`) - can be labelled with any of the planes :math:`XY` and :math:`YZ` that - contain them. + 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[_AM_co] | None + ExtendedCausalFlow[_PM_co] | None An extended causal flow object if the open graph has extended causal flow or ``None`` otherwise. See Also @@ -536,12 +535,13 @@ def to_extendedcausalflow_or_none(self: OpenGraph[_PM_co]) -> ExtendedCausalFlow Notes ----- - - The extended causal flow is only defined on open graphs with measurements that can be labelled :math:`XY` or :math:`YZ`: there is none if some measurement is in the :math:`XZ` plane (and not a Pauli measurement). - - This function implements an adaptation of the algorithm presented in Ref. [1] with polynomial complexity on the number of nodes, :math:`O(N^2)`. + - 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] Mhalla and Perdrix, (2008), Finding Optimal Flows Efficiently, doi.org/10.1007/978-3-540-70575-8_70 + [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) diff --git a/graphix/space_minimization.py b/graphix/space_minimization.py index e56d4460a..a6d511070 100644 --- a/graphix/space_minimization.py +++ b/graphix/space_minimization.py @@ -189,7 +189,24 @@ class SpaceMinimizationHeuristics: 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 pattern to have an extended causal flow. + 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: ecf = pattern.to_xzcorrections().downcast_bloch().to_extendedcausalflow() diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 3ce07ec4e..a5bf6b64e 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, @@ -839,6 +840,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", @@ -969,6 +978,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.XYPlane), + ), + # 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 (C.XY) 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 (C.YZ), 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( From e24ed845468b3d83e0d8bb16e3663f737b78ed9e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:19:53 +0000 Subject: [PATCH 08/19] Address review and test extended causal flow extraction and space minimization - Simplify the yz_candidates description in _find_flow. - Explain why CausalFlow.check_well_formed is overridden. - Test XZCorrections.to_extendedcausalflow on an open graph with a YZ-measured node (round trip through XZ-corrections). - Test that the extended_causal_flow space minimization heuristic applies, is optimal and preserves semantics on a pattern without causal flow. Co-Authored-By: Claude Opus 5.5 --- graphix/flow/_find_cflow.py | 2 +- graphix/flow/core.py | 1 + tests/test_flow_core.py | 22 ++++++++++++++++++++++ tests/test_space_minimization.py | 30 ++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index 43665c81e..9ce8511a0 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -106,7 +106,7 @@ def _find_flow(og: OpenGraph[_PM_co], yz_candidates: AbstractSet[int] | None = N 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 and the routine looks for a causal flow. + Non-output nodes measured in the :math:`YZ` plane. The set is not modified. If ``None`` (default), it is considered to be empty. Returns ------- diff --git a/graphix/flow/core.py b/graphix/flow/core.py index c5a1f4bf4..11c76a1eb 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1630,6 +1630,7 @@ def check_well_formed(self) -> None: ---------- [1] Browne et al., 2007 New J. Phys. 9 250 (arXiv:quant-ph/0702212). """ + # Overridden only to provide the causal-flow-specific documentation above; the checks are those of the parent class. super().check_well_formed() @override diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index a5bf6b64e..43bd28e73 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -543,6 +543,28 @@ def test_ecf_yz_node(self) -> None: 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() diff --git a/tests/test_space_minimization.py b/tests/test_space_minimization.py index f9280027e..c59371f38 100644 --- a/tests/test_space_minimization.py +++ b/tests/test_space_minimization.py @@ -1,6 +1,12 @@ from __future__ import annotations +import networkx as nx +import numpy as np + 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 @@ -39,6 +45,30 @@ def test_minimize_space_deprecated() -> None: assert after > before +def test_minimize_space_extended_causal_flow() -> 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=np.random.default_rng(42)) + before = p.max_space() + p.minimize_space([SpaceMinimizationHeuristics.extended_causal_flow]) + assert p.max_space() < before + state = p.simulate(rng=np.random.default_rng(43)) + 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)` From 571ab66185046ffd6c596796faa7950255132248 Mon Sep 17 00:00:00 2001 From: matulni Date: Mon, 16 Nov 2026 18:31:43 +0100 Subject: [PATCH 09/19] Add methods pattern.to_extendedcausalflow --- graphix/opengraph.py | 2 +- graphix/pattern.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/graphix/opengraph.py b/graphix/opengraph.py index ad8f65999..38847438d 100644 --- a/graphix/opengraph.py +++ b/graphix/opengraph.py @@ -140,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: diff --git a/graphix/pattern.py b/graphix/pattern.py index 4088bc4b8..da871e7df 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 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, From efc68eb86d90885079772157b77fae439546da2c Mon Sep 17 00:00:00 2001 From: matulni Date: Tue, 17 Nov 2026 09:52:45 +0100 Subject: [PATCH 10/19] Fix docstrings --- graphix/flow/_find_cflow.py | 2 +- graphix/flow/core.py | 40 +++++++++++++++----------------- graphix/pattern.py | 2 +- tests/test_flow_core.py | 4 ++-- tests/test_opengraph.py | 4 ++-- tests/test_space_minimization.py | 12 ++++++---- 6 files changed, 33 insertions(+), 31 deletions(-) diff --git a/graphix/flow/_find_cflow.py b/graphix/flow/_find_cflow.py index 9ce8511a0..309466a82 100644 --- a/graphix/flow/_find_cflow.py +++ b/graphix/flow/_find_cflow.py @@ -111,7 +111,7 @@ def _find_flow(og: OpenGraph[_PM_co], yz_candidates: AbstractSet[int] | None = N 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. ``correction_function`` maps each non-output node to its (single-element) correction set, and ``partial_order_layers[0]`` is the set of output nodes. + A tuple ``(correction_function, partial_order_layers)`` used to instantiate a :class:`CausalFlow` or an :class:`ExtendedCausalFlow` if the flow exists, ``None`` otherwise. Notes ----- diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 11c76a1eb..e6c5f40eb 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -272,8 +272,7 @@ def to_extendedcausalflow(self: XZCorrections[_PM_co]) -> ExtendedCausalFlow[_PM Notes ----- - See Definition 10 in Ref. [1]. - - Measurements are labelled by their plane (see :meth:`GFlow.node_measurement_label`). - - Only the ``x_corrections`` mapping and the partial order are used to build the flow: + - 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 @@ -1110,6 +1109,7 @@ 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. @@ -1417,16 +1417,13 @@ 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]). As for gflows, measurements are - labelled by their plane (see :meth:`GFlow.node_measurement_label`). 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. + 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 method :meth:`ExtendedCausalFlow.check_well_formed` verifies the definition of extended causal flow (Definition 10 in Ref. [1]). - - XZ-corrections are computed as for gflows (see :meth:`GFlow.to_xzcorrections`). + This class differs from its parent class in the method :meth:`ExtendedCausalFlow.check_well_formed`. + XZ-corrections are computed as for gflows (see :meth:`GFlow.to_xzcorrections`). The methods :meth:`OpenGraph.to_extendedcausalflow` and :meth:`XZCorrections.to_extendedcausalflow` return well-formed @@ -1448,15 +1445,14 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): _CF_PREFIX: str = "c" # Correction function prefix for printing + @override def check_well_formed(self) -> None: r"""Verify if the extended causal flow is well formed. Raises ------ FlowError - If the extended causal flow is not well formed. In particular, a ``FlowGenericError`` - with reason ``XZPlane`` is raised if the open graph contains measurements in the - :math:`XZ` plane. + If the extended causal flow is not well formed. Notes ----- @@ -1464,21 +1460,22 @@ def check_well_formed(self) -> None: - 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. + - 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 extended causal flows (the names in brackets are those of :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`): - Correction sets have one element only (C0), - - (C.XY) if :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1), - - (C.YZ) if :math:`\lambda(i) = YZ`, then :math:`c(i) = i` (CYZ), + - if :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1), + - if :math:`\lambda(i) = YZ`, then :math:`c(i) = i` (CYZ), - :math:`i \prec c(i)` if :math:`\lambda(i) = XY` (C2), - :math:`\forall k \in N_G(c(i)) \setminus \{i\}, i \prec k` (C3), - where :math:`i \in O^c`, :math:`\lambda(i)` is the measurement plane of :math:`i`, :math:`c` is the correction function and :math:`\prec` denotes the partial order. Conditions (C2) and (C3) state that the order induced by the correction function is compatible with the partial order. + where :math:`i \in O^c`, :math:`\lambda(i)` is the measurement plane of :math:`i`, :math:`c` is the correction function and :math:`\prec` denotes the partial order. - Extended causal flows are defined on open graphs with XY and YZ measurements only. Since the image of the correction function is a subset of the non-input nodes, condition (C.YZ) implies that :math:`YZ`-measured nodes cannot be inputs. + Extended causal flows are defined on open graphs with XY and YZ measurements only. 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. - See Definition 10 in Ref. [1], where conditions (C.XY) and (C.YZ) are introduced; (C0)-(C3) + See Definition 10 in Ref. [1], where condition (CYZ) is introduced; (C0)-(C3) are the conditions of causal flow, see Definition 2 in Ref. [2]. References @@ -1576,7 +1573,8 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): 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:`CausalFlow.check_well_formed` verifies the definition of causal flow (Definition 2 in Ref. [1]): open graphs with measurements in the :math:`XZ` or :math:`YZ` planes are rejected. + - The method :meth:`CausalFlow.check_well_formed` verifies the definition of causal flow (Definition 2 in Ref. [1]): + 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 diff --git a/graphix/pattern.py b/graphix/pattern.py index da871e7df..5e409fee4 100644 --- a/graphix/pattern.py +++ b/graphix/pattern.py @@ -1081,7 +1081,7 @@ def to_extendedcausalflow(self) -> ExtendedCausalFlow[BlochMeasurement]: 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 causal flow. + - 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. diff --git a/tests/test_flow_core.py b/tests/test_flow_core.py index 43bd28e73..58653bf39 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -1055,7 +1055,7 @@ class TestIncorrectFlows: ), FlowPropositionError(FlowPropositionErrorReason.C0, node=4, correction_set={1, 4}), ), - # Extended causal flow: C1 (C.XY) on an XY-measured node. + # Extended causal flow: C1 on an XY-measured node. IncorrectFlowTestCase( ExtendedCausalFlow( og=og_e, @@ -1064,7 +1064,7 @@ class TestIncorrectFlows: ), FlowPropositionError(FlowPropositionErrorReason.C1, node=0, correction_set={2}), ), - # Extended causal flow: CYZ (C.YZ), the YZ-measured node is not its own corrector. + # Extended causal flow: CYZ, the YZ-measured node is not its own corrector. IncorrectFlowTestCase( ExtendedCausalFlow( og=og_e, diff --git a/tests/test_opengraph.py b/tests/test_opengraph.py index eb70e8777..e86b20875 100644 --- a/tests/test_opengraph.py +++ b/tests/test_opengraph.py @@ -674,7 +674,7 @@ def _og_25() -> OpenGraphFlowTestCase: @register_open_graph_flow_test_case def _og_26() -> OpenGraphFlowTestCase: - r"""Generate open graph. YZ can't correct. + r"""Generate open graph. Structure: @@ -691,7 +691,7 @@ def _og_26() -> OpenGraphFlowTestCase: @register_open_graph_flow_test_case def _og_27() -> OpenGraphFlowTestCase: - r"""Generate open graph. YZ can't correct. + r"""Generate open graph. Structure: diff --git a/tests/test_space_minimization.py b/tests/test_space_minimization.py index c59371f38..7826791f7 100644 --- a/tests/test_space_minimization.py +++ b/tests/test_space_minimization.py @@ -1,7 +1,8 @@ from __future__ import annotations +from typing import TYPE_CHECKING + import networkx as nx -import numpy as np from graphix import Pattern, command from graphix.measurements import Measurement @@ -9,6 +10,9 @@ 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)) @@ -45,7 +49,7 @@ def test_minimize_space_deprecated() -> None: assert after > before -def test_minimize_space_extended_causal_flow() -> None: +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)]), @@ -61,11 +65,11 @@ def test_minimize_space_extended_causal_flow() -> None: assert result.known_optimal assert result.new_order == (0, 4, 1, 2) - state_ref = p.simulate(rng=np.random.default_rng(42)) + 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=np.random.default_rng(43)) + state = p.simulate(rng=fx_rng) assert state.isclose(state_ref) From 6d4a24bb28856654ee7d498b0a95a7653a1f74f5 Mon Sep 17 00:00:00 2001 From: matulni Date: Tue, 17 Nov 2026 09:56:28 +0100 Subject: [PATCH 11/19] Up README --- CHANGELOG.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d3b55513..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,8 +50,11 @@ 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. -- #613: The default space minimization heuristic `SpaceMinimizationHeuristics.extended_causal_flow` +- #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 From bb2fb2c342b7d3e121c9d82416606352ef965df8 Mon Sep 17 00:00:00 2001 From: matulni Date: Tue, 17 Nov 2026 11:19:31 +0100 Subject: [PATCH 12/19] Refactor XZCorrections.to_gflow and XZCorrections.to_extendedcausalflow --- graphix/flow/core.py | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index e6c5f40eb..19c5ad9c1 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -279,16 +279,7 @@ def to_extendedcausalflow(self: XZCorrections[_PM_co]) -> ExtendedCausalFlow[_PM ---------- [1] Backens and Perdrix, (2026), Completeness for flow-preserving rewrite rules, arXiv:2608.13035 """ - 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() == Plane.YZ: - corrections.add(i) - - correction_function[i] = corrections - + 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 @@ -314,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 @@ -1925,6 +1907,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. From 6f8d4f8213eb2f5be76286b4fd3b97fc7f4396f2 Mon Sep 17 00:00:00 2001 From: matulni Date: Tue, 17 Nov 2026 11:31:12 +0100 Subject: [PATCH 13/19] Fix visualization error --- graphix/visualization.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 From 726caf86c80b543fc4e4d8566857b91df824dba7 Mon Sep 17 00:00:00 2001 From: matulni Date: Tue, 17 Nov 2026 11:37:45 +0100 Subject: [PATCH 14/19] Introduce YZPlane flow exception --- graphix/flow/core.py | 25 ++----------------------- graphix/flow/exceptions.py | 12 ++++++------ tests/test_flow_core.py | 4 ++-- 3 files changed, 10 insertions(+), 31 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 19c5ad9c1..61f8cf210 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1505,7 +1505,7 @@ def check_well_formed(self) -> None: case Plane.YZ: self._check_yzplane(node) case Plane.XZ: - self._check_xzplane() + raise FlowGenericError(FlowGenericErrorReason.XZPlane) if (neighbors - {node}) & past_and_present_nodes: raise FlowPropositionOrderError( @@ -1520,16 +1520,6 @@ def check_well_formed(self) -> None: if {*o_set, *past_and_present_nodes} != set(self.og.graph.nodes): raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) - def _check_xzplane(self) -> None: - """Handle a node measured in the :math:`XZ` plane in :meth:`check_well_formed`. - - Raises - ------ - FlowGenericError - Always, with reason ``XZPlane``, since extended causal flows are not defined on open graphs with :math:`XZ` measurements. - """ - raise FlowGenericError(FlowGenericErrorReason.XZPlane) - def _check_yzplane(self, node: int) -> None: """Verify condition (C.YZ) for a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. @@ -1613,17 +1603,6 @@ def check_well_formed(self) -> None: # Overridden only to provide the causal-flow-specific documentation above; the checks are those of the parent class. super().check_well_formed() - @override - def _check_xzplane(self) -> None: - """Handle a node measured in the :math:`XZ` plane in :meth:`check_well_formed`. - - Raises - ------ - FlowGenericError - Always, with reason ``XYPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. - """ - raise FlowGenericError(FlowGenericErrorReason.XYPlane) - @override def _check_yzplane(self, node: int) -> None: """Handle a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. @@ -1638,7 +1617,7 @@ def _check_yzplane(self, node: int) -> None: FlowGenericError Always, with reason ``XYPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. """ - raise FlowGenericError(FlowGenericErrorReason.XYPlane) + raise FlowGenericError(FlowGenericErrorReason.YZPlane) def _corrections_to_dag( diff --git a/graphix/flow/exceptions.py b/graphix/flow/exceptions.py index bcf4c20e0..ad343e33d 100644 --- a/graphix/flow/exceptions.py +++ b/graphix/flow/exceptions.py @@ -87,11 +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 graph with non-XY measurements." + YZPlane = enum.auto() + "A causal flow is defined on an open graph with YZ measurements." XZPlane = enum.auto() - "An extended causal flow is defined on an open graph with XZ measurements." + "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.""" @@ -233,10 +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 "Extended causal flow is only defined on open graphs without XZ measurements." + 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/tests/test_flow_core.py b/tests/test_flow_core.py index 58653bf39..07b12d76a 100644 --- a/tests/test_flow_core.py +++ b/tests/test_flow_core.py @@ -886,7 +886,7 @@ class TestIncorrectFlows: correction_function={0: {1}}, partial_order_layers=[{1}, {0}], ), - FlowGenericError(FlowGenericErrorReason.XYPlane), + FlowGenericError(FlowGenericErrorReason.XZPlane), ), # Incomplete correction function IncorrectFlowTestCase( @@ -1007,7 +1007,7 @@ class TestIncorrectFlows: correction_function={0: {1}, 1: {2}, 2: {3}, 4: {4}}, partial_order_layers=[{3}, {2}, {1}, {4}, {0}], ), - FlowGenericError(FlowGenericErrorReason.XYPlane), + FlowGenericError(FlowGenericErrorReason.YZPlane), ), # Extended causal flow on an open graph with XZ measurements. IncorrectFlowTestCase( From 89595b6524d87fb49dc3a74290fac5f4295154ae Mon Sep 17 00:00:00 2001 From: matulni Date: Thu, 19 Nov 2026 11:47:14 +0100 Subject: [PATCH 15/19] Add tests Pattern.to_extendedcausalflow --- tests/test_pattern.py | 81 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) 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() From c85af6b517aaca870a72922b4408cca58d5c76a4 Mon Sep 17 00:00:00 2001 From: matulni Date: Thu, 19 Nov 2026 11:48:42 +0100 Subject: [PATCH 16/19] Change prettyprinting of extended causal flow from 'c' to 'e' --- graphix/flow/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 61f8cf210..5e4399170 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1425,7 +1425,7 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): [1] Miriam Backens and Simon Perdrix, Completeness for flow-preserving rewrite rules, 2026 (arXiv:2608.13035). """ - _CF_PREFIX: str = "c" # Correction function prefix for printing + _CF_PREFIX: str = "e" # Correction function prefix for printing @override def check_well_formed(self) -> None: From 1efec454cf8058f51569cf99aa44587068d621dc Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 10:56:03 +0000 Subject: [PATCH 17/19] Move flow definitions to class docstrings - State the definition of each flow (Pauli flow, gflow, extended causal flow, causal flow) in the Notes section of its class docstring. The general properties shared by all flows are stated once, in PauliFlow, and referenced from the subclasses. - Shorten check_well_formed and check_flow_properties docstrings to say that they check flow validity and to refer to the class docstring for the definition. - Remove CausalFlow.check_well_formed, which was overridden only for its docstring. - Point the Focused* class docstrings to the flow and focus definitions, fix broken :meth: roles and the reason documented in CausalFlow._check_yzplane (YZPlane). Co-Authored-By: Claude Opus 5.5 --- graphix/flow/core.py | 324 +++++++++++++++++++++---------------------- 1 file changed, 156 insertions(+), 168 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 5e4399170..4a4ec7d55 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -612,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 @@ -623,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 @@ -637,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 ---------- @@ -713,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) @@ -1057,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 @@ -1093,9 +1091,16 @@ def from_correctionmatrix_or_none(cls, correction_matrix: CorrectionMatrix[_AM_c @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(): @@ -1165,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 @@ -1181,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 @@ -1224,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) @@ -1384,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 @@ -1404,8 +1411,9 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): 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 method :meth:`ExtendedCausalFlow.check_well_formed`. - XZ-corrections are computed as for gflows (see :meth:`GFlow.to_xzcorrections`). + This class differs from its parent class in the following: + - 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_extendedcausalflow` and :meth:`XZCorrections.to_extendedcausalflow` return well-formed @@ -1420,50 +1428,50 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): 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:`(c, \prec)`, where :math:`c: 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`: + + - :math:`c(i)` has one element only (C0). + - If :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1). + - If :math:`\lambda(i) = YZ`, then :math:`c(i) = \{i\}` (CYZ). + - If :math:`\lambda(i) = XY`, then :math:`i \prec c(i)` (C2). + - For all :math:`k \in N_G(c(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] 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 = "e" # Correction function prefix for printing @override def check_well_formed(self) -> None: - r"""Verify if the extended 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 extended 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 extended causal flows (the names in brackets are those of - :class:`~graphix.flow.exceptions.FlowPropositionErrorReason` and - :class:`~graphix.flow.exceptions.FlowPropositionOrderErrorReason`): - - Correction sets have one element only (C0), - - if :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1), - - if :math:`\lambda(i) = YZ`, then :math:`c(i) = i` (CYZ), - - :math:`i \prec c(i)` if :math:`\lambda(i) = XY` (C2), - - :math:`\forall k \in N_G(c(i)) \setminus \{i\}, i \prec k` (C3), - where :math:`i \in O^c`, :math:`\lambda(i)` is the measurement plane of :math:`i`, :math:`c` is the correction function and :math:`\prec` denotes the partial order. - - Extended causal flows are defined on open graphs with XY and YZ measurements only. 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. - - See Definition 10 in Ref. [1], where condition (CYZ) is introduced; (C0)-(C3) - are the conditions of causal flow, see Definition 2 in Ref. [2]. - - References - ---------- - [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). + If the flow is not well-formed. """ _check_flow_general_properties(self) @@ -1521,7 +1529,7 @@ def check_well_formed(self) -> None: raise PartialOrderError(PartialOrderErrorReason.IncorrectNodes) def _check_yzplane(self, node: int) -> None: - """Verify condition (C.YZ) for a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. + """Verify condition (CYZ) for a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. Parameters ---------- @@ -1540,12 +1548,12 @@ def _check_yzplane(self, node: int) -> None: @dataclass(frozen=True) class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): - """An unmutable subclass of ``ExtendedCausalFlow`` providing a representation of a causal flow. + 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:`CausalFlow.check_well_formed` verifies the definition of causal flow (Definition 2 in Ref. [1]): + - 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 @@ -1560,49 +1568,29 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): 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 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`: + + - :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). """ - @override - def check_well_formed(self) -> None: - r"""Verify if the causal flow is well formed. - - Raises - ------ - FlowError - If the causal flow is not well formed. In particular, a ``FlowGenericError`` - with reason ``XYPlane`` is raised if the open graph contains measurements in the - :math:`XZ` or :math:`YZ` planes. - - 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). - """ - # Overridden only to provide the causal-flow-specific documentation above; the checks are those of the parent class. - super().check_well_formed() - @override def _check_yzplane(self, node: int) -> None: """Handle a node measured in the :math:`YZ` plane in :meth:`check_well_formed`. @@ -1615,7 +1603,7 @@ def _check_yzplane(self, node: int) -> None: Raises ------ FlowGenericError - Always, with reason ``XYPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. + Always, with reason ``YZPlane``, since causal flows are only defined on open graphs with :math:`XY` measurements. """ raise FlowGenericError(FlowGenericErrorReason.YZPlane) From 200dc3eac82d575fd55401eb19860a81f0591ecf Mon Sep 17 00:00:00 2001 From: matulni Date: Thu, 19 Nov 2026 12:06:57 +0100 Subject: [PATCH 18/19] Fix mistakes in Claude's docstrings --- graphix/flow/core.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 4a4ec7d55..7d6571981 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1431,7 +1431,7 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): 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:`(c, \prec)`, where :math:`c: O^c \to 2^{I^c}` is + :math:`YZ` measurements 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`: @@ -1571,7 +1571,7 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): 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 2^{I^c}` is the correction function + 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`: From 8922c0cb1ce617da9e74eb746ef42457e0650d49 Mon Sep 17 00:00:00 2001 From: matulni Date: Thu, 19 Nov 2026 14:01:01 +0100 Subject: [PATCH 19/19] Fix errors flow pretty printing and add tests --- graphix/flow/core.py | 14 ++++++++------ tests/test_pretty_print.py | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/graphix/flow/core.py b/graphix/flow/core.py index 7d6571981..951bc6744 100644 --- a/graphix/flow/core.py +++ b/graphix/flow/core.py @@ -1431,15 +1431,15 @@ class ExtendedCausalFlow(GFlow[_PM_co], Generic[_PM_co]): 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:`(c, \prec)`, where :math:`c: O^c \to I^c` is + :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:`c(i)` has one element only (C0). - - If :math:`\lambda(i) = XY`, then :math:`i \sim c(i)` (C1). - - If :math:`\lambda(i) = YZ`, then :math:`c(i) = \{i\}` (CYZ). - - If :math:`\lambda(i) = XY`, then :math:`i \prec c(i)` (C2). - - For all :math:`k \in N_G(c(i)) \setminus \{i\}`, :math:`i \prec k` (C3), + - :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 @@ -1591,6 +1591,8 @@ class CausalFlow(ExtendedCausalFlow[_PM_co], Generic[_PM_co]): """ + _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`. 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()