Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- #624: CH gate is now supported (its support was missing as it is a standard OpenQASM gate).

- #637: Decompositions no longer drop global phases, which made controlled gates produced by `insert_control` wrong. `instruction_to_jcz` now keeps the global phase of `S`, `SDG`, `T`, `TDG`, `SX`, `SXDG`, `X`, `Y` and `Z`, and `decompose_ccx` now uses `T`, `TDG` and `S` gates as in Nielsen & Chuang instead of `RZ` rotations.
- #636, #639: `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.

- #637, #643: Decompositions no longer drop global phases, which made controlled gates produced by `insert_control` wrong. `instruction_to_jcz` now keeps the global phase of `S`, `SDG`, `T`, `TDG`, `SX`, `SXDG`, `X`, `Y` and `Z`, and `decompose_ccx` now uses `T`, `TDG` and `S` gates as in Nielsen & Chuang instead of `RZ` rotations.

- #645: Fix negative sign in circuit extraction strings

### Changed

Expand Down
15 changes: 10 additions & 5 deletions docs/source/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand All @@ -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:
Expand Down
50 changes: 27 additions & 23 deletions graphix/noise_models/amplitude_damping.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, assert_never

import typing_extensions
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
50 changes: 27 additions & 23 deletions graphix/noise_models/depolarising.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, assert_never

import typing_extensions
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
25 changes: 20 additions & 5 deletions graphix/noise_models/noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -42,8 +48,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
Expand All @@ -67,6 +73,15 @@ class ApplyNoise(_KindChecker):
nodes: list[Node]
domain: set[Node] | None = None

@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)
Comment thread
thierry-martinez marked this conversation as resolved.
Resolved


if TYPE_CHECKING:
CommandOrNoise: TypeAlias = CommandType | ApplyNoise
Expand Down
72 changes: 5 additions & 67 deletions graphix/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -94,68 +90,10 @@ 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:
raise ValueError(f"Expected {value!r} to be a probability, between 0 and 1")


Qubits: TypeAlias = int | tuple["Qubits", ...]
Expand Down
2 changes: 1 addition & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,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"),
}
Expand Down
Loading
Loading