Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
0f27921
trying to remove BackendState still causing problems
Dec 3, 2025
b88df05
trying to remove BackendState bad fixed version
Dec 3, 2025
4dc8ee5
Fixing typing.
Dec 10, 2025
003f71e
Fixed typing after removing backend state.
Dec 10, 2025
604110b
Introduce `BaseN` and `PrepareMethod` (#383)
thierry-martinez Dec 4, 2025
a0622f3
trying to remove BackendState still causing problems
Dec 3, 2025
87fdc74
Refactor of flow tools - `OpenGraph.isclose` (#374)
matulni Dec 2, 2025
7a29de2
Refactor of flow tools - `OpenGraph.compose` (#375)
matulni Dec 2, 2025
2e63924
Fix #349: ensure flow for patterns transpiled from circuit (#362)
thierry-martinez Dec 2, 2025
23294b2
Fixing typing.
Dec 10, 2025
67412d3
Refactor of flow tools - Verification of flow objects (#378)
matulni Dec 8, 2025
8f60ccb
Fixed typing after removing backend state.
Dec 10, 2025
9b4e078
trying to rebase
Dec 10, 2025
5d726e3
fixed rebasing and conflicts
Dec 10, 2025
97c1314
fixed changelog and vscode
Dec 10, 2025
0d70214
final fix of changelog
Dec 10, 2025
f595649
aligning changelog
Dec 10, 2025
bab5b19
Ruff fixes
Dec 10, 2025
8b04861
added change to CHANGELOG
Dec 10, 2025
e6e8e82
Merge branch 'master' into remove_backend_state
emlynsg Dec 10, 2025
5d84f4a
Merge branch 'master' into remove_backend_state
emlynsg Dec 15, 2025
99c01cd
Merge branch 'master' into remove_backend_state
emlynsg Dec 16, 2025
d14ae08
Fixed typing of str and Backend functions in and
Dec 16, 2025
aa53312
Final typing fix
Dec 16, 2025
cd26b44
Remove Any import.
Dec 16, 2025
9941608
Pushing again to check CI.
Dec 16, 2025
55febbe
Disabled qasm parser CI tests causing Graphix CI to fail.
Dec 16, 2025
3de41aa
Added qasm test back in.
emlynsg Jan 6, 2026
d76ef48
Merge branch 'master' into remove_backend_state
emlynsg Jan 6, 2026
a9f4889
Fixed merge from master.
emlynsg Jan 6, 2026
90d0185
Fixed merge from master.
emlynsg Jan 6, 2026
2bd5042
fixing added code
emlynsg Jan 7, 2026
d2651cc
Merge branch 'master' into remove_backend_state
emlynsg Jan 7, 2026
d98c98d
fixing CI
emlynsg Jan 7, 2026
28f28b9
Merge remote branch into remove_backend_state
emlynsg Jan 7, 2026
1a6f15c
fixing imports
emlynsg Jan 7, 2026
982db24
fixing typing in tests
emlynsg Jan 7, 2026
4118f5d
fixing typing in tests
emlynsg Jan 7, 2026
24ee532
fixed test typing
emlynsg Jan 8, 2026
89fc88d
fixed test typing
emlynsg Jan 8, 2026
2f46277
fixed test typing
emlynsg Jan 8, 2026
2b1feeb
fixed test typing
emlynsg Jan 8, 2026
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- #396: Removed generic `BackendState` from `graphix.sim` modules and methods in `graphix.pattern` and `graphix.simulator` modules.

- #374: Adapted existing method `graphix.opengraph.OpenGraph.isclose` to the new API introduced in #358.

- #375: Adapted existing method `graphix.opengraph.OpenGraph.compose` to the new API introduced in #358.
Expand Down
74 changes: 65 additions & 9 deletions graphix/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, SupportsFloat, TypeVar
from typing import TYPE_CHECKING, Literal, SupportsFloat, overload

import networkx as nx
from typing_extensions import assert_never
Expand All @@ -39,11 +39,20 @@
from numpy.random import Generator

from graphix.flow.core import CausalFlow, GFlow
from graphix.parameter import ExpressionOrSupportsFloat, Parameter
from graphix.sim import Backend, BackendState, Data


_StateT_co = TypeVar("_StateT_co", bound="BackendState", covariant=True)
from graphix.parameter import ExpressionOrSupportsComplex, ExpressionOrSupportsFloat, Parameter
from graphix.sim import (
Backend,
Data,
DensityMatrix,
DensityMatrixBackend,
Statevec,
StatevectorBackend,
_BackendLiteral,
_BuiltinBackendState,
)
from graphix.sim.base_backend import _StateT_co
from graphix.sim.tensornet import MBQCTensorNet, TensorNetworkBackend
from graphix.states import State


class Pattern:
Expand Down Expand Up @@ -1375,13 +1384,60 @@ def space_list(self) -> list[int]:
n_list.append(nodes)
return n_list

@overload
def simulate_pattern(
self,
backend: StatevectorBackend | Literal["statevector"] = "statevector",
input_state: State
| Statevec
| Iterable[State]
| Iterable[ExpressionOrSupportsComplex]
| Iterable[Iterable[ExpressionOrSupportsComplex]] = ...,
rng: Generator | None = ...,
**kwargs: Any,
) -> Statevec: ...

@overload
def simulate_pattern(
self,
backend: DensityMatrixBackend | Literal["densitymatrix"],
input_state: State
| DensityMatrix
| Iterable[State]
| Iterable[ExpressionOrSupportsComplex]
| Iterable[Iterable[ExpressionOrSupportsComplex]] = ...,
rng: Generator | None = ...,
**kwargs: Any,
) -> DensityMatrix: ...

@overload
def simulate_pattern(
self,
backend: TensorNetworkBackend | Literal["tensornetwork", "mps"],
input_state: State
| Iterable[State]
| Iterable[ExpressionOrSupportsComplex]
| Iterable[Iterable[ExpressionOrSupportsComplex]] = ...,
rng: Generator | None = ...,
**kwargs: Any,
) -> MBQCTensorNet: ...

@overload
def simulate_pattern(
self,
backend: Backend[_StateT_co],
input_state: Data = ...,
rng: Generator | None = ...,
**kwargs: Any,
) -> _StateT_co: ...

def simulate_pattern(
self,
backend: Backend[_StateT_co] | str = "statevector",
backend: Backend[_StateT_co] | _BackendLiteral = "statevector",
input_state: Data = BasicStates.PLUS,
rng: Generator | None = None,
**kwargs: Any,
) -> BackendState:
) -> _StateT_co | _BuiltinBackendState:
"""Simulate the execution of the pattern by using :class:`graphix.simulator.PatternSimulator`.

Available backend: ['statevector', 'densitymatrix', 'tensornetwork']
Expand All @@ -1403,7 +1459,7 @@ def simulate_pattern(

.. seealso:: :class:`graphix.simulator.PatternSimulator`
"""
sim = PatternSimulator(self, backend=backend, **kwargs)
sim: PatternSimulator[_StateT_co] = PatternSimulator(self, backend=backend, **kwargs)
sim.run(input_state, rng=rng)
return sim.backend.state

Expand Down
25 changes: 21 additions & 4 deletions graphix/sim/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,26 @@

from __future__ import annotations

from graphix.sim.base_backend import Backend, BackendState
from typing import Literal

from graphix.sim.base_backend import Backend
from graphix.sim.data import Data
from graphix.sim.density_matrix import DensityMatrix
from graphix.sim.statevec import Statevec
from graphix.sim.density_matrix import DensityMatrix, DensityMatrixBackend
from graphix.sim.statevec import Statevec, StatevectorBackend
from graphix.sim.tensornet import MBQCTensorNet, TensorNetworkBackend

_BuiltinBackendState = DensityMatrix | Statevec | MBQCTensorNet
_BuiltinBackend = DensityMatrixBackend | StatevectorBackend | TensorNetworkBackend
_BackendLiteral = Literal["statevector", "densitymatrix", "tensornetwork", "mps"]

__all__ = ["Backend", "BackendState", "Data", "DensityMatrix", "Statevec"]
__all__ = [
"Backend",
"Data",
"DensityMatrix",
"DensityMatrixBackend",
"Statevec",
"StatevectorBackend",
"_BackendLiteral",
"_BuiltinBackend",
"_BuiltinBackendState",
]
43 changes: 8 additions & 35 deletions graphix/sim/base_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

Matrix: TypeAlias = npt.NDArray[np.object_ | np.complex128]

_StateT_co = TypeVar("_StateT_co", covariant=True)


def tensordot(op: Matrix, psi: Matrix, axes: tuple[int | Sequence[int], int | Sequence[int]]) -> Matrix:
"""Tensor dot product that preserves the type of `psi`.
Expand Down Expand Up @@ -325,37 +327,7 @@ def __str__(self) -> str:
return "This backend does not support noise."


class BackendState(ABC):
"""
Abstract base class for representing the quantum state of a backend.

`BackendState` defines the interface for quantum state representations used by
various backend implementations. It provides a common foundation for different
simulation strategies, such as dense linear algebra or tensor network contraction.

Concrete subclasses must implement the storage and manipulation logic appropriate
for a specific backend and representation strategy.

Notes
-----
This class is abstract and cannot be instantiated directly.

Examples of concrete subclasses include:
- :class:`Statevec` (for pure states represented as state vectors)
- :class:`DensityMatrix` (for mixed states represented as density matrices)
- :class:`MBQCTensorNet` (for compressed representations using tensor networks)

See Also
--------
:class:`DenseState`, :class:`MBQCTensorNet`, :class:`Statevec`, :class:`DensityMatrix`
"""

@abstractmethod
def flatten(self) -> Matrix:
"""Return flattened state."""


class DenseState(BackendState):
class DenseState(ABC):
"""
Abstract base class for quantum states with full dense representations.

Expand All @@ -373,7 +345,7 @@ class DenseState(BackendState):
-----
This class is abstract and cannot be instantiated directly.

Not all :class:`BackendState` subclasses are dense. For example, :class:`MBQCTensorNet` is a
Not all internal states are dense. For example, :class:`MBQCTensorNet` is a
`BackendState` that represents the quantum state using a tensor network, rather than
a single dense array.

Expand All @@ -388,6 +360,10 @@ class DenseState(BackendState):
def nqubit(self) -> int:
"""Return the number of qubits."""

@abstractmethod
def flatten(self) -> Matrix:
"""Return flattened state."""

@abstractmethod
def add_nodes(self, nqubit: int, data: Data) -> None:
"""
Expand Down Expand Up @@ -527,9 +503,6 @@ def _op_mat_from_result(
return op_mat_complex


_StateT_co = TypeVar("_StateT_co", bound="BackendState", covariant=True)


@dataclass(frozen=True)
class Backend(Generic[_StateT_co]):
"""
Expand Down
4 changes: 2 additions & 2 deletions graphix/sim/tensornet.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from graphix.branch_selector import BranchSelector, RandomBranchSelector
from graphix.ops import Ops
from graphix.parameter import Expression
from graphix.sim.base_backend import Backend, BackendState
from graphix.sim.base_backend import Backend
from graphix.states import BasicStates, PlanarState

if TYPE_CHECKING:
Expand All @@ -39,7 +39,7 @@
PrepareState: TypeAlias = str | npt.NDArray[np.complex128]


class MBQCTensorNet(BackendState, TensorNetwork):
class MBQCTensorNet(TensorNetwork):
"""Tensor Network Simulator interface for MBQC patterns, using quimb.tensor.core.TensorNetwork."""

_dangling: dict[str, str]
Expand Down
Loading