Skip to content
Draft
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added
- **Fault distance of non-Clifford circuits (experimental).**
`tsim.experimental.shortest_errors(circuit, max_weight=k)` returns every
smallest set of faults that can flip an observable without flipping a
detector, like Stim's `shortest_graphlike_error` but exact and for circuits
with T gates. Each result gives the probability that the faults go undetected
and that they flip an observable, and explains each fault with
`stim.CircuitErrorLocation`s. An empty result proves the distance exceeds `k`.
The fault distance of d=5 T-state cultivation (3, as found by
[Chan et al.](https://arxiv.org/abs/2609.17706)) takes under a second, and
that of its Z-flagged version (4) takes 5 s.

### Changed
- The stabilizer-rank strategies compile components of the same shape once, and
no longer run components with a single output without compiling them. A
Expand Down
62 changes: 59 additions & 3 deletions src/tsim/core/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from dataclasses import dataclass
from fractions import Fraction
from typing import Literal, get_args
from typing import Literal, NamedTuple, get_args

import numpy as np
from zxparam import Domain, EdgeType, Graph, Phase, Vertex, VertexType
Expand Down Expand Up @@ -46,6 +46,23 @@
"""The classical outputs of a built graph (see ``GraphBuilder.build``)."""


class Site(NamedTuple):
"""Where a noise channel sits in the flattened circuit.

Attributes:
instruction: Index of its instruction in the flattened circuit.
start: Index of its first target in the instruction.
end: One past the index of its last target.
record: Index of the measurement record it flips, if it flips one.

"""

instruction: int
start: int
end: int
record: int


def error_phase(error_bit: int) -> Phase:
"""Return the phase of a noise spider for error bit ``error_bit`` (ID = bit)."""
return Phase(Fraction(0), frozenset({error_bit}))
Expand Down Expand Up @@ -90,7 +107,12 @@ def __init__(self) -> None:
self._first_vertex: dict[int, Vertex] = {}
self._last_vertex: dict[int, Vertex] = {}
self._channel_probs: list[np.ndarray] = []
self._channel_sites: list[Site] = []
self._chain_links: dict[int, list[tuple[int, Site]]] = {}
self._chain_sites: list[Site] = []
self._num_error_bits = 0
self.position: tuple[int, int, int] = (-1, 0, 0)
"""Instruction index and target range that the parser is at."""
self._correlated_error_probs: list[float] = []
self._chain_spiders: list[Vertex] = []
self._chain_toggles: list[set[int]] = []
Expand Down Expand Up @@ -126,6 +148,29 @@ def channel_probs(self) -> list[np.ndarray]:
self._check_finalized()
return list(self._channel_probs)

@property
def channel_sites(self) -> list[Site]:
"""Each noise channel's place in the flattened circuit.

A correlated-error chain is at its first link; ``chain_links`` has the
others.
"""
self._check_finalized()
return list(self._channel_sites)

@property
def chain_links(self) -> dict[int, list[tuple[int, Site]]]:
"""The links of each correlated-error chain, by channel.

A link is the channel outcome in which it alone fires, and its site.
"""
self._check_finalized()
return dict(self._chain_links)

def _site(self) -> Site:
"""Return the site of a channel added at the parser's position."""
return Site(*self.position, len(self._records))

@property
def num_error_bits(self) -> int:
"""The number of error bits, which are the error parameter IDs."""
Expand Down Expand Up @@ -358,6 +403,7 @@ def add_channel(self, probs: np.ndarray) -> int:
num_bits = channel_num_bits(probs)
first = self._num_error_bits
self._channel_probs.append(probs)
self._channel_sites.append(self._site())
self._num_error_bits += num_bits
return first

Expand Down Expand Up @@ -385,6 +431,7 @@ def correlated_error(
if type_ == "Z" or type_ == "Y":
self._chain_toggles[self._chain_spider(qubit, VertexType.Z)] ^= {term}
self._correlated_error_probs.append(p)
self._chain_sites.append(self._site())

def _chain_spider(self, qubit: int, vertex_type: VertexType) -> int:
"""Return the index of the pending chain's noise spider for a component.
Expand Down Expand Up @@ -431,6 +478,8 @@ def finalize_correlated_error(self) -> None:
if not probabilities:
return
spiders, toggles = self._chain_spiders, self._chain_toggles
sites = self._chain_sites
self._chain_sites = []
self._chain_spiders = []
self._chain_toggles = []
self._chain_runs = {}
Expand All @@ -445,19 +494,26 @@ def finalize_correlated_error(self) -> None:
"instructions approximate it to first order in p"
)
# NOTE: a chain that flips no spider, such as E(p) X0 X0, has no channel.
if 0 < c < k:
if c == 0:
return
if c < k:
masks = [0] * k
for bit, i in enumerate(live):
for term in toggles[i]:
masks[term] |= 1 << bit
first = self.add_channel(chain_error_probs(masks, probabilities, c))
for bit, i in enumerate(live):
self._graph.set_phase(spiders[i], error_phase(first + bit))
elif c > 0:
else:
masks = [1 << term for term in range(k)]
first = self.add_channel(correlated_error_probs(probabilities))
for i in live:
bits = frozenset(first + term for term in toggles[i])
self._graph.set_phase(spiders[i], Phase(Fraction(0), bits))
# NOTE: add_channel recorded the parser's position, which is past the chain.
channel = len(self._channel_sites) - 1
self._channel_sites[channel] = sites[0]
self._chain_links[channel] = list(zip(masks, sites, strict=True))

# -------------------------------------------------------------------------
# Detectors and observables
Expand Down
31 changes: 28 additions & 3 deletions src/tsim/core/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,21 @@ def _validate_r_pauli_targets(instruction: stim.CircuitInstruction) -> None:
seen = set()


def _product_ranges(instruction: stim.CircuitInstruction) -> list[tuple[int, int]]:
"""Return the target range ``(start, end)`` of each Pauli product."""
targets = instruction.targets_copy()
ranges = []
start = 0
for i in range(len(targets)):
if targets[i].is_combiner or (
i + 1 < len(targets) and targets[i + 1].is_combiner
):
continue
ranges.append((start, i + 1))
start = i + 1
return ranges


def _iter_pauli_products(
instruction: stim.CircuitInstruction,
) -> Iterator[tuple[list[tuple[Literal["X", "Y", "Z"], int]], bool]]:
Expand Down Expand Up @@ -166,8 +181,13 @@ def parse_stim_circuit(stim_circuit: stim.Circuit) -> GraphBuilder:
"""
builder = GraphBuilder()

for instruction in stim_circuit.flattened():
flattened = stim_circuit.flattened()
for index in range(len(flattened)):
instruction = flattened[index]
assert not isinstance(instruction, stim.CircuitRepeatBlock)
# NOTE: the builder records this position with each noise channel that
# the instruction adds; the loops below narrow it to the targets.
builder.position = (index, 0, len(instruction.targets_copy()))

name = instruction.name
if name == "SHIFT_COORDS":
Expand Down Expand Up @@ -217,7 +237,10 @@ def parse_stim_circuit(stim_circuit: stim.Circuit) -> GraphBuilder:
if name == "MPP":
args = instruction.gate_args_copy()
p = args[0] if args else 0
for paulis, invert in _iter_pauli_products(instruction):
products = _iter_pauli_products(instruction)
ranges = _product_ranges(instruction)
for (paulis, invert), (start, end) in zip(products, ranges, strict=True):
builder.position = (index, start, end)
mpp(builder, paulis, invert, p=p)
continue
if name in ("SPP", "SPP_DAG") and is_t_tag(instruction.tag):
Expand Down Expand Up @@ -247,7 +270,8 @@ def parse_stim_circuit(stim_circuit: stim.Circuit) -> GraphBuilder:
if name == "MPAD":
args = instruction.gate_args_copy()
p = args[0] if args else 0
for target in instruction.targets_copy():
for i_target, target in enumerate(instruction.targets_copy()):
builder.position = (index, i_target, i_target + 1)
mpad(builder, target.value, p=p)
continue
if name == "E" or name == "ELSE_CORRELATED_ERROR":
Expand Down Expand Up @@ -300,6 +324,7 @@ def parse_stim_circuit(stim_circuit: stim.Circuit) -> GraphBuilder:
for i_target in range(0, len(targets), num_qubits):
chunk = targets[i_target : i_target + num_qubits]
cc_chunk = is_classically_controlled[i_target : i_target + num_qubits]
builder.position = (index, i_target, i_target + num_qubits)
chunk_inverted = False
for j in range(num_qubits):
chunk_inverted ^= invert[i_target + j]
Expand Down
17 changes: 16 additions & 1 deletion src/tsim/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,27 @@
detector outcomes with a stabilizer rank decomposition.
- `SteaneEncoder` and `ColorEncoder5` encode a circuit transversally into the
[[7,1,3]] Steane code and the [[17,1,5]] color code.
- `shortest_errors` finds a circuit's fault distance: every smallest set of
faults that flips an observable without flipping a detector, as `LogicalError`s
of `Fault`s.
"""

from tsim.noise.faults import (
Fault as Fault,
LogicalError as LogicalError,
shortest_errors as shortest_errors,
)
from tsim.sampler import CompiledStateProbs as CompiledStateProbs
from tsim.utils.encoder import (
ColorEncoder5 as ColorEncoder5,
SteaneEncoder as SteaneEncoder,
)

__all__ = ["ColorEncoder5", "CompiledStateProbs", "SteaneEncoder"]
__all__ = [
"ColorEncoder5",
"CompiledStateProbs",
"Fault",
"LogicalError",
"SteaneEncoder",
"shortest_errors",
]
Loading
Loading