From db3e53cf7c037903f1f6c2e1632315b72bf93483 Mon Sep 17 00:00:00 2001 From: thierry-martinez Date: Tue, 27 Oct 2026 14:05:00 +0100 Subject: [PATCH 1/5] Fix #636: `ApplyNoise` derives from `BaseCommand` `ApplyNoise` now derives from `BaseCommand`, like other commands. It implements `reindex`, which maps both its nodes and its domain, and uses the concise `repr` from `DataclassReprMixin`. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ graphix/noise_models/noise_model.py | 13 +++++++++---- tests/test_noise_model.py | 20 +++++++++++++++++++- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e88607cba..4262dc95e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,12 +27,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `E` command in patterns. - The pretty-printing (`repr`) of instructions and commands is updated to use notation without parentheses: `repr(E((0, 1))) == "E(0, 1)"`. +- #636: `ApplyNoise` now derives from `BaseCommand`, like other commands. In particular, it implements `reindex`. + ### Changed - #587: - Factorized instruction-validity checks in method `Circuit.add` via an instruction visitor. - Instruction methods of the `Circuit` class now return `self` allowing method chaining. + ## [0.4.1] - 2026-10-13 ### Added diff --git a/graphix/noise_models/noise_model.py b/graphix/noise_models/noise_model.py index 94b2237f1..08880ea7f 100644 --- a/graphix/noise_models/noise_model.py +++ b/graphix/noise_models/noise_model.py @@ -16,10 +16,10 @@ # override introduced in Python 3.12 from typing_extensions import override -from graphix.command import BaseM, CommandKind, Node, _KindChecker +from graphix.command import BaseCommand, BaseM, CommandKind, Node, _KindChecker if TYPE_CHECKING: - from collections.abc import Iterable + from collections.abc import Callable, Iterable from typing import TypeAlias from numpy.random import Generator @@ -42,8 +42,8 @@ def to_krauschannel(self) -> KrausChannel: """Return the Kraus channel describing the noise.""" -@dataclass -class ApplyNoise(_KindChecker): +@dataclass(repr=False) +class ApplyNoise(_KindChecker, BaseCommand): """Apply noise command. Parameters @@ -67,6 +67,11 @@ class ApplyNoise(_KindChecker): nodes: list[Node] domain: set[Node] | None = None + @override + def reindex(self, f: Callable[[Node], Node]) -> ApplyNoise: + domain = None if self.domain is None else set(map(f, self.domain)) + return ApplyNoise(self.noise, list(map(f, self.nodes)), domain) + if TYPE_CHECKING: CommandOrNoise: TypeAlias = CommandType | ApplyNoise diff --git a/tests/test_noise_model.py b/tests/test_noise_model.py index 7e3d28020..f7288410c 100644 --- a/tests/test_noise_model.py +++ b/tests/test_noise_model.py @@ -7,7 +7,7 @@ from graphix import Pattern from graphix.clifford import Clifford -from graphix.command import C, CommandKind, E, M, N, S, T, X, Z +from graphix.command import BaseCommand, C, CommandKind, E, M, N, S, T, X, Z from graphix.noise_models import ( AmplitudeDampingNoise, AmplitudeDampingNoiseModel, @@ -271,3 +271,21 @@ def test_amplitude_damping_command_rejects_signal() -> None: s_cmd = S(node=0) with pytest.raises(ValueError, match="Unexpected signal"): model.command(s_cmd) + + +def test_apply_noise_is_command() -> None: + noise = DepolarisingNoise(0.1) + cmd = ApplyNoise(noise=noise, nodes=[0, 1], domain={2}) + assert isinstance(cmd, BaseCommand) + assert repr(cmd) == f"ApplyNoise({noise!r}, [0, 1], {{2}})" + + +@pytest.mark.parametrize("domain", [None, {2, 3}]) +def test_apply_noise_reindex(domain: set[int] | None) -> None: + noise = DepolarisingNoise(0.1) + cmd = ApplyNoise(noise=noise, nodes=[0, 1], domain=domain) + reindexed = cmd.reindex(lambda node: node + 10) + expected_domain = None if domain is None else {node + 10 for node in domain} + assert reindexed == ApplyNoise(noise=noise, nodes=[10, 11], domain=expected_domain) + # The original command is left unchanged. + assert cmd == ApplyNoise(noise=noise, nodes=[0, 1], domain=domain) From 7b34b56c1fa53e0bbbffe81bd9b0740e61ef12e7 Mon Sep 17 00:00:00 2001 From: thierry-martinez Date: Wed, 4 Nov 2026 23:26:53 +0000 Subject: [PATCH 2/5] Make noise classes immutable dataclasses with a concise `repr` Following review: `DepolarisingNoise`, `TwoQubitDepolarisingNoise`, `AmplitudeDampingNoise` and `TwoQubitAmplitudeDampingNoise` are now frozen dataclasses using `DataclassReprMixin`, so that `repr(DepolarisingNoise(0.1)) == "DepolarisingNoise(0.1)"`, and they support value equality and hashing. The `Probability` descriptor does not combine with dataclasses: the descriptor itself is taken as the field default, and its `__set__` cannot assign the private field of a frozen instance. The probability is now checked in `__post_init__` with the new `graphix.utils.check_probability`. The tutorial, which used the descriptor in a dataclass and therefore failed, is updated accordingly. Since noise instances are immutable, `ApplyNoise.reindex` can share the noise with the original command; this is now documented. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/source/tutorial.rst | 15 ++++--- graphix/noise_models/amplitude_damping.py | 50 ++++++++++++----------- graphix/noise_models/depolarising.py | 50 ++++++++++++----------- graphix/noise_models/noise_model.py | 12 +++++- graphix/utils.py | 6 +++ tests/test_noise_model.py | 28 ++++++++++++- 7 files changed, 109 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4262dc95e..598cf69fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The pretty-printing (`repr`) of instructions and commands is updated to use notation without parentheses: `repr(E((0, 1))) == "E(0, 1)"`. - #636: `ApplyNoise` now derives from `BaseCommand`, like other commands. In particular, it implements `reindex`. + Noise classes (`DepolarisingNoise`, `TwoQubitDepolarisingNoise`, `AmplitudeDampingNoise`, `TwoQubitAmplitudeDampingNoise`) are now immutable (frozen dataclasses) with an eval-friendly `repr`: `repr(DepolarisingNoise(0.1)) == "DepolarisingNoise(0.1)"`. `graphix.utils.check_probability` validates probabilities. ### Changed diff --git a/docs/source/tutorial.rst b/docs/source/tutorial.rst index 312e8f3a4..3538a5e72 100644 --- a/docs/source/tutorial.rst +++ b/docs/source/tutorial.rst @@ -246,6 +246,7 @@ The statevector backend simulates the pattern ideally, without any noise. To run noisy simulations, we use a :class:`NoiseModel`, which transpiles ideal patterns into patterns containing some ``ApplyNoise`` commands. Each ``ApplyNoise`` command applies noise to certain qubits. The noise to be applied is described by an instance of :class:`Noise`, which is an abstract base class for classes that define a Kraus channel. +Noise instances are expected to be immutable, since they can be shared between several ``ApplyNoise`` commands: we define them as frozen dataclasses. In the following example, we apply dephasing noise to qubit preparation commands (denoted by ``N``) by defining a noise model, ``NoisyGraphState``, that transpiles ideal patterns by inserting an ``ApplyNoise`` command carrying a ``DephasingNoise`` after each ``N`` command. @@ -257,11 +258,15 @@ In the following example, we apply dephasing noise to qubit preparation commands from graphix.command import BaseM, CommandKind from graphix.channels import KrausChannel, dephasing_channel from graphix.noise_models.noise_model import ApplyNoise, CommandOrNoise, Noise, NoiseCommands, NoiseModel - from graphix.utils import Probability + from graphix.repr_mixins import DataclassReprMixin + from graphix.utils import check_probability - @dataclass - class DephasingNoise(Noise): - prob: Probability = Probability() + @dataclass(frozen=True, repr=False) + class DephasingNoise(DataclassReprMixin, Noise): + prob: float + + def __post_init__(self) -> None: + check_probability(self.prob) @property @typing_extensions.override @@ -274,7 +279,7 @@ In the following example, we apply dephasing noise to qubit preparation commands @dataclass class NoisyGraphState(NoiseModel): - p_z: Probability = Probability() + p_z: float = 0.0 @typing_extensions.override def input_nodes(self, nodes: Iterable[int]) -> NoiseCommands: diff --git a/graphix/noise_models/amplitude_damping.py b/graphix/noise_models/amplitude_damping.py index 57873dead..e638ec33c 100644 --- a/graphix/noise_models/amplitude_damping.py +++ b/graphix/noise_models/amplitude_damping.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING, assert_never import typing_extensions @@ -14,8 +15,9 @@ from graphix.command import BaseM, CommandKind from graphix.measurements import toggle_outcome from graphix.noise_models.noise_model import ApplyNoise, Noise, NoiseModel +from graphix.repr_mixins import DataclassReprMixin from graphix.rng import ensure_rng -from graphix.utils import Probability +from graphix.utils import check_probability if TYPE_CHECKING: from collections.abc import Iterable @@ -26,20 +28,21 @@ from graphix.noise_models.noise_model import CommandOrNoise -class AmplitudeDampingNoise(Noise): - """One-qubit amplitude damping noise with damping parameter ``prob``.""" +@dataclass(frozen=True, repr=False) +class AmplitudeDampingNoise(DataclassReprMixin, Noise): + r"""One-qubit amplitude damping noise with damping parameter ``prob``. - prob = Probability() + Parameters + ---------- + prob : float + Damping parameter :math:`\gamma` of the noise, between 0 and 1. + """ - def __init__(self, prob: float) -> None: - r"""Initialize one-qubit amplitude damping noise. + prob: float - Parameters - ---------- - prob : float - Damping parameter :math:`\\gamma` of the noise, between 0 and 1. - """ - self.prob = prob + def __post_init__(self) -> None: + """Check that ``prob`` is a probability.""" + check_probability(self.prob) @property @typing_extensions.override @@ -53,20 +56,21 @@ def to_krauschannel(self) -> KrausChannel: return amplitude_damping_channel(self.prob) -class TwoQubitAmplitudeDampingNoise(Noise): - """Two-qubit amplitude damping noise with damping parameter ``prob``.""" +@dataclass(frozen=True, repr=False) +class TwoQubitAmplitudeDampingNoise(DataclassReprMixin, Noise): + r"""Two-qubit amplitude damping noise with damping parameter ``prob``. - prob = Probability() + Parameters + ---------- + prob : float + Damping parameter :math:`\gamma` of the noise, between 0 and 1. + """ - def __init__(self, prob: float) -> None: - r"""Initialize two-qubit amplitude damping noise. + prob: float - Parameters - ---------- - prob : float - Damping parameter :math:`\\gamma` of the noise, between 0 and 1. - """ - self.prob = prob + def __post_init__(self) -> None: + """Check that ``prob`` is a probability.""" + check_probability(self.prob) @property @typing_extensions.override diff --git a/graphix/noise_models/depolarising.py b/graphix/noise_models/depolarising.py index bc400ccb3..1e9aea67b 100644 --- a/graphix/noise_models/depolarising.py +++ b/graphix/noise_models/depolarising.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import dataclass from typing import TYPE_CHECKING, assert_never import typing_extensions @@ -10,8 +11,9 @@ from graphix.command import BaseM, CommandKind from graphix.measurements import toggle_outcome from graphix.noise_models.noise_model import ApplyNoise, Noise, NoiseModel +from graphix.repr_mixins import DataclassReprMixin from graphix.rng import ensure_rng -from graphix.utils import Probability +from graphix.utils import check_probability if TYPE_CHECKING: from collections.abc import Iterable @@ -22,20 +24,21 @@ from graphix.noise_models.noise_model import CommandOrNoise -class DepolarisingNoise(Noise): - """One-qubit depolarising noise with probabibity ``prob``.""" +@dataclass(frozen=True, repr=False) +class DepolarisingNoise(DataclassReprMixin, Noise): + """One-qubit depolarising noise with probability ``prob``. - prob = Probability() + Parameters + ---------- + prob : float + Probability parameter of the noise, between 0 and 1. + """ - def __init__(self, prob: float) -> None: - """Initialize one-qubit depolarizing noise. + prob: float - Parameters - ---------- - prob : float - Probability parameter of the noise, between 0 and 1. - """ - self.prob = prob + def __post_init__(self) -> None: + """Check that ``prob`` is a probability.""" + check_probability(self.prob) @property @typing_extensions.override @@ -49,20 +52,21 @@ def to_krauschannel(self) -> KrausChannel: return depolarising_channel(self.prob) -class TwoQubitDepolarisingNoise(Noise): - """Two-qubits depolarising noise with probabibity ``prob``.""" +@dataclass(frozen=True, repr=False) +class TwoQubitDepolarisingNoise(DataclassReprMixin, Noise): + """Two-qubits depolarising noise with probability ``prob``. - prob = Probability() + Parameters + ---------- + prob : float + Probability parameter of the noise, between 0 and 1. + """ - def __init__(self, prob: float) -> None: - """Initialize two-qubit depolarizing noise. + prob: float - Parameters - ---------- - prob : float - Probability parameter of the noise, between 0 and 1. - """ - self.prob = prob + def __post_init__(self) -> None: + """Check that ``prob`` is a probability.""" + check_probability(self.prob) @property @typing_extensions.override diff --git a/graphix/noise_models/noise_model.py b/graphix/noise_models/noise_model.py index 08880ea7f..a53f8adff 100644 --- a/graphix/noise_models/noise_model.py +++ b/graphix/noise_models/noise_model.py @@ -30,7 +30,13 @@ class Noise(ABC): - """Abstract base class for noise.""" + """Abstract base class for noise. + + Noise instances are expected to be immutable: they can be shared + between several :class:`ApplyNoise` commands (in particular, the + command returned by :meth:`ApplyNoise.reindex` shares the noise of + the original command). + """ @property @abstractmethod @@ -69,6 +75,10 @@ class ApplyNoise(_KindChecker, BaseCommand): @override def reindex(self, f: Callable[[Node], Node]) -> ApplyNoise: + """Return a copy of the command with nodes and domain mapped by ``f``. + + The noise is not copied: since noise instances are immutable, it is shared with the original command. + """ domain = None if self.domain is None else set(map(f, self.domain)) return ApplyNoise(self.noise, list(map(f, self.nodes)), domain) diff --git a/graphix/utils.py b/graphix/utils.py index a490206da..76bf708b7 100644 --- a/graphix/utils.py +++ b/graphix/utils.py @@ -158,6 +158,12 @@ def __init__(self) -> None: super().__init__(minvalue=0, maxvalue=1) +def check_probability(value: float) -> None: + """Raise :class:`ValueError` if ``value`` is not a probability (between 0 and 1).""" + if not 0 <= value <= 1: + raise ValueError(f"Expected {value!r} to be a probability, between 0 and 1") + + Qubits: TypeAlias = int | tuple["Qubits", ...] diff --git a/tests/test_noise_model.py b/tests/test_noise_model.py index f7288410c..e7bfea885 100644 --- a/tests/test_noise_model.py +++ b/tests/test_noise_model.py @@ -1,5 +1,6 @@ from __future__ import annotations +import dataclasses from typing import TYPE_CHECKING import numpy as np @@ -277,7 +278,30 @@ def test_apply_noise_is_command() -> None: noise = DepolarisingNoise(0.1) cmd = ApplyNoise(noise=noise, nodes=[0, 1], domain={2}) assert isinstance(cmd, BaseCommand) - assert repr(cmd) == f"ApplyNoise({noise!r}, [0, 1], {{2}})" + assert repr(cmd) == "ApplyNoise(DepolarisingNoise(0.1), [0, 1], {2})" + + +@pytest.mark.parametrize( + "noise_class", + [DepolarisingNoise, TwoQubitDepolarisingNoise, AmplitudeDampingNoise, TwoQubitAmplitudeDampingNoise], +) +def test_noise_repr_and_immutability( + noise_class: type[ + DepolarisingNoise | TwoQubitDepolarisingNoise | AmplitudeDampingNoise | TwoQubitAmplitudeDampingNoise + ], +) -> None: + noise = noise_class(0.1) + expected = f"{noise_class.__name__}(0.1)" + assert repr(noise) == expected + assert str(noise) == expected + assert noise == noise_class(0.1) + assert hash(noise) == hash(noise_class(0.1)) + assert noise != noise_class(0.2) + with pytest.raises(dataclasses.FrozenInstanceError): + noise.prob = 0.2 # type: ignore[misc] + for prob in (-0.1, 1.1): + with pytest.raises(ValueError, match="to be a probability"): + noise_class(prob) @pytest.mark.parametrize("domain", [None, {2, 3}]) @@ -287,5 +311,7 @@ def test_apply_noise_reindex(domain: set[int] | None) -> None: reindexed = cmd.reindex(lambda node: node + 10) expected_domain = None if domain is None else {node + 10 for node in domain} assert reindexed == ApplyNoise(noise=noise, nodes=[10, 11], domain=expected_domain) + # The noise is shared, which is safe since it is immutable. + assert reindexed.noise is noise # The original command is left unchanged. assert cmd == ApplyNoise(noise=noise, nodes=[0, 1], domain=domain) From 41987198fc8b78415a9c243b46fe4a2d63bedf7c Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Thu, 5 Nov 2026 07:35:09 +0100 Subject: [PATCH 3/5] Validators are not used anymore --- graphix/utils.py | 70 +----------------------------------------------- 1 file changed, 1 insertion(+), 69 deletions(-) diff --git a/graphix/utils.py b/graphix/utils.py index 76bf708b7..8ceded0e2 100644 --- a/graphix/utils.py +++ b/graphix/utils.py @@ -5,19 +5,15 @@ import inspect import sys import typing -from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, SupportsInt, TypeAlias, TypeVar, cast, overload +from typing import TYPE_CHECKING, Any, ClassVar, Literal, SupportsInt, TypeAlias, TypeVar, cast import numpy as np import numpy.typing as npt # override introduced in Python 3.12 -from typing_extensions import override if TYPE_CHECKING: from collections.abc import Iterable, Iterator - from typing import Self _T = TypeVar("_T") @@ -94,70 +90,6 @@ def iter_empty(it: Iterator[_T]) -> bool: return all(False for _ in it) -_ValueT = TypeVar("_ValueT") - - -class Validator(ABC, Generic[_ValueT]): - """Descriptor to validate value. - - https://docs.python.org/3/howto/descriptor.html#custom-validators - """ - - def __set_name__(self, owner: object, name: str) -> None: - """Set private field name.""" - self.private_name = "_" + name - - @overload - def __get__(self, obj: None, objtype: type | None = None) -> Self: # access on class - ... - - @overload - def __get__(self, obj: object, objtype: type | None = None) -> _ValueT: # access on instance - ... - - def __get__(self, obj: object, objtype: object = None) -> _ValueT | Self: - """Get the validated value from the private field.""" - if obj is None: # access on the class, not an instance - return self - result: _ValueT = getattr(obj, self.private_name) - return result - - def __set__(self, obj: object, value: _ValueT) -> None: - """Validate and set the value in the private field.""" - self.validate(value) - setattr(obj, self.private_name, value) - - @abstractmethod - def validate(self, value: _ValueT) -> None: - """Validate the assigned value.""" - - -@dataclass -class BoundedFloat(Validator[float]): - """Descriptor to validate numbers with given bounds. - - https://docs.python.org/3/howto/descriptor.html#custom-validators - """ - - minvalue: float | None = None - maxvalue: float | None = None - - @override - def validate(self, value: float) -> None: - """Validate the assigned value.""" - if self.minvalue is not None and value < self.minvalue: - raise ValueError(f"Expected {value!r} to be at least {self.minvalue!r}") - if self.maxvalue is not None and value > self.maxvalue: - raise ValueError(f"Expected {value!r} to be no more than {self.maxvalue!r}") - - -class Probability(BoundedFloat): - """Descriptor for probability (between 0 and 1).""" - - def __init__(self) -> None: - super().__init__(minvalue=0, maxvalue=1) - - def check_probability(value: float) -> None: """Raise :class:`ValueError` if ``value`` is not a probability (between 0 and 1).""" if not 0 <= value <= 1: From 2421ac9ee498981f8cec2896b9c1342b520eb9c5 Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Thu, 5 Nov 2026 17:38:35 +0100 Subject: [PATCH 4/5] Fix reverse dependencies --- noxfile.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/noxfile.py b/noxfile.py index 58ade118e..ff18b5abd 100644 --- a/noxfile.py +++ b/noxfile.py @@ -106,7 +106,6 @@ class ReverseDependency: # Bumping to Python 3.15 requires qiskit-aer to support Python 3.15. # See Qiskit/qiskit-aer#2468 version_constraint=VersionRange(upper=Version("3.15")), - branch="refs/pull/27/head", ), "graphix-stim-compiler": ReverseDependency("https://github.com/TeamGraphix/graphix-stim-compiler"), "graphix-pyzx": ReverseDependency( @@ -127,7 +126,7 @@ class ReverseDependency: # Bumping to Python 3.15 requires qiskit-aer to support Python 3.15. # See Qiskit/qiskit-aer#2468 version_constraint=VersionRange(upper=Version("3.15")), - branch="refs/pull/45/head", + branch="refs/pull/48/head", ), "graphix-mqtbench": ReverseDependency("https://github.com/TeamGraphix/graphix-mqtbench", branch="refs/pull/7/head"), } From d1cf9e55ceb82f79dde3ade566fd9a73c9e3431d Mon Sep 17 00:00:00 2001 From: Thierry Martinez Date: Thu, 5 Nov 2026 19:39:55 +0100 Subject: [PATCH 5/5] Restored pin graphix-ibmq#27 --- noxfile.py | 1 + 1 file changed, 1 insertion(+) diff --git a/noxfile.py b/noxfile.py index ff18b5abd..7c60227e5 100644 --- a/noxfile.py +++ b/noxfile.py @@ -106,6 +106,7 @@ class ReverseDependency: # Bumping to Python 3.15 requires qiskit-aer to support Python 3.15. # See Qiskit/qiskit-aer#2468 version_constraint=VersionRange(upper=Version("3.15")), + branch="refs/pull/27/head", ), "graphix-stim-compiler": ReverseDependency("https://github.com/TeamGraphix/graphix-stim-compiler"), "graphix-pyzx": ReverseDependency(