Metadata-Version: 2.1
Name: qec-qem
Version: 0.1.0
Summary: Low-distance surface-code QEC simulation with Stim, plus zero-noise extrapolation (quantum error mitigation) of the logical error rate.
Keywords: quantum error correction,quantum error mitigation,surface code,stim,zero-noise extrapolation
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy >=1.21
Requires-Dist: pymatching >=2.0
Requires-Dist: scipy >=1.7
Requires-Dist: stim >=1.12
Provides-Extra: test
Requires-Dist: pytest ; extra == 'test'

# QEC-QEM (`qec_qem`)

Quantum error correction (QEC) with quantum error mitigation (QEM) for small
surface codes. It simulates a low-distance code with [Stim](https://github.com/quantumlib/Stim),
decodes with [PyMatching](https://github.com/oscarhiggott/PyMatching), and uses
zero-noise extrapolation (ZNE) to estimate the logical error rate at lower noise.

> **Status:** early release (0.1.x). The API may change.

## Contents
1. [The idea](#1-the-idea)
2. [Installation](#2-installation)
3. [Quick start](#3-quick-start)
4. [How a run works](#4-how-a-run-works)
5. [Configuration reference](#5-configuration-reference)
6. [Results reference](#6-results-reference)
7. [The extrapolation (ZNE)](#7-the-extrapolation-zne)
8. [Recipes](#8-recipes)
9. [Reproducibility](#9-reproducibility)
10. [Troubleshooting](#10-troubleshooting)
11. [Limitations](#11-limitations)
12. [Development](#12-development)

---

## 1. The idea

A surface-code logical qubit is built from many physical qubits. In the rotated
layout one logical qubit needs **2d² − 1** physical qubits for code distance `d`:

| distance d | 3 | 5 | 7 | 9 |
|---|---|---|---|---|
| physical qubits per logical qubit | 17 | 49 | 97 | 161 |

A larger `d` suppresses logical errors better, but its qubit cost grows with d².
**QEC-QEM keeps `d` small to lower that resource cost.** A small code leaves
*residual* logical errors, and QEC-QEM handles them in software with ZNE:

1. Simulate the small code at several **amplified** noise levels. Errors are
   frequent there, so they are cheap to measure.
2. Decode each run and record the logical result.
3. Fit how the result changes with the noise scale, and **extrapolate back down**
   to lower noise: to your real operating noise, or toward zero noise for logical
   expectation values.

You get an estimate of what the logical qubit would deliver with the residual
noise removed, from a code that needs few physical qubits.

Stim does all of the simulation. This package collects settings, calls Stim,
decodes, fits, and records everything. Because Stim can scale its noise rates
exactly, no gate folding or pulse stretching is needed.

## 2. Installation

```bash
pip install qec_qem          # PyPI shows the project as "qec-qem"
```

Requires Python 3.9+, `stim`, `pymatching`, `numpy`, `scipy` (installed automatically).
The import name is `qec_qem`.

## 3. Quick start

```python
from qec_qem import Config, CircuitArgs, SamplerArgs, ZNEArgs, run

p = 1e-3  # your real physical error rate (this is noise scale lambda = 1)

cfg = Config(
    circuit=CircuitArgs(
        distance=3,
        after_clifford_depolarization=p,
        before_round_data_depolarization=p,
        before_measure_flip_probability=p,
        after_reset_flip_probability=p,
    ),
    sampler=SamplerArgs(shots=200_000, seed=1),
    zne=ZNEArgs(target=1.0, models=("powerlaw", "polynomial")),
    lambdas=(2.0, 3.0, 4.0, 5.0),   # amplified noise levels to simulate
)

result = run(cfg)

for pt in result.points:
    print(pt.lam, pt.p_L, pt.stderr, pt.stats["num_qubits"])

z = result.zne
print("extrapolated p_L:", z.value, "CI:", z.ci_low, z.ci_high)
print("model spread:", z.model_spread)
print("warnings:", z.warnings)

result.to_json("result.json")   # full record of the run
```

This runs the code at noise rates 2p, 3p, 4p, 5p (200,000 shots each), fits the
logical error rate against the noise scale, and extrapolates to `lambda = 1`,
i.e. the rate `p` you actually care about.

## 4. How a run works

`run(cfg)` does the following for each noise scale `lambda` in `cfg.lambdas`:

| Step | What happens | Stim / library call |
|---|---|---|
| 1. Scale noise | Multiply the four base noise rates by `lambda` (or use your `noise_scale`). | none |
| 2. Build circuit | Generate the code circuit at the scaled rates. | `stim.Circuit.generated(...)` |
| 3. Build DEM | Turn the circuit into a detector error model. | `circuit.detector_error_model(...)` |
| 4. Build decoder | Build the decoder from the DEM. | `pymatching.Matching.from_detector_error_model(...)` |
| 5. Sample | Draw detection events and the true observable flips. | `circuit.compile_detector_sampler(seed=...)`, `.sample(...)` |
| 6. Decode | Predict the observable flips from the detection events. | `decoder.decode_batch(...)` |
| 7. Count | A shot **fails** if the prediction differs from the true flip. `p_L = failures / shots`. | none |

After all noise scales are done, the package fits the models in `zne.models` to
`p_L` versus `lambda` and evaluates them at `zne.target` (see section 7).

`p_L` is the probability that the logical observable is decoded wrongly over the
whole experiment of `rounds` rounds of syndrome extraction. Total shots simulated
is `len(lambdas) × sampler.shots`.

## 5. Configuration reference

Everything is set through `Config`. Each Stim call has its own section whose
field names match Stim's argument names. Every section has an `extra` dict that is
passed straight to the underlying call, so arguments added by newer Stim versions
are never blocked.

### `Config`
| Field | Default | Description |
|---|---|---|
| `circuit` | `CircuitArgs()` | Circuit generation settings. |
| `dem` | `DemArgs()` | Detector error model settings. |
| `sampler` | `SamplerArgs()` | Sampling settings. |
| `decoder` | `DecoderArgs()` | Decoder settings. |
| `zne` | `ZNEArgs()` | Extrapolation settings. |
| `lambdas` | `(2.0, 3.0, 4.0, 5.0)` | Noise scales to simulate. Must be positive and distinct. |
| `store_raw` | `False` | Keep raw detection events, observable flips, predictions and weights in the result (large). |
| `custom_circuit` | `None` | Your own `stim.Circuit`, or a `callable(lam) -> stim.Circuit`. Replaces the generated circuit. |
| `noise_scale` | `None` | Your own scaling function `callable(CircuitArgs, lam) -> dict` of the four noise rates. |

### `CircuitArgs` → `stim.Circuit.generated`
| Field | Default | Description |
|---|---|---|
| `code_task` | `"surface_code:rotated_memory_z"` | Stim code task, e.g. `surface_code:rotated_memory_x`, `surface_code:unrotated_memory_z`. Other Stim tasks (e.g. `repetition_code:memory`) are passed through. |
| `distance` | `3` | Code distance. |
| `rounds` | `None` | Syndrome-measurement rounds. `None` means the same as `distance`. |
| `after_clifford_depolarization` | `1e-3` | Depolarizing noise after each gate. |
| `before_round_data_depolarization` | `1e-3` | Depolarizing noise on data qubits before each round. |
| `before_measure_flip_probability` | `1e-3` | Probability a measurement result is flipped. |
| `after_reset_flip_probability` | `1e-3` | Probability a reset produces the wrong state. |
| `extra` | `{}` | Other keyword arguments for `Circuit.generated`. |

These four rates are your **base rates** (`lambda = 1`). The simulated rate at noise
scale `lambda` is `lambda ×` each of them.

### `DemArgs` → `circuit.detector_error_model`
| Field | Default |
|---|---|
| `decompose_errors` | `True` (PyMatching needs graph-like errors) |
| `flatten_loops` | `True` |
| `allow_gauge_detectors` | `False` |
| `approximate_disjoint_errors` | `False` (Stim also accepts a float) |
| `ignore_decomposition_failures` | `False` |
| `block_decomposition_from_introducing_remnant_edges` | `False` |
| `extra` | `{}` |

### `SamplerArgs` → `compile_detector_sampler` and `.sample`
| Field | Default | Description |
|---|---|---|
| `seed` | `None` | `None` picks a random seed. The seed actually used is always recorded. |
| `shots` | `100_000` | Shots **per noise scale**. |
| `separate_observables` | `True` | Must stay `True`; the decoder needs observables split from detectors. |
| `prepend_observables` | `False` | Must stay `False` when decoding. |
| `append_observables` | `False` | Must stay `False` when decoding. |
| `bit_packed` | `False` | Return bit-packed arrays (lower memory). |
| `extra` | `{}` | Other `.sample` arguments, e.g. `dtype` on newer Stim. |

### `DecoderArgs`
| Field | Default | Description |
|---|---|---|
| `decoder` | `"pymatching"` | Built-in decoder name. |
| `decoder_factory` | `None` | Your own decoder: `callable(dem)` returning an object with `decode_batch(...)`. |
| `from_dem_extra` | `{}` | Extra arguments for `Matching.from_detector_error_model`. |
| `return_weights` | `False` | Also return matching weights from `decode_batch`. |
| `bit_packed_shots` | `None` | `None` follows `sampler.bit_packed`. If set, must equal it. |
| `bit_packed_predictions` | `None` | `None` follows `sampler.bit_packed`. If set, must equal it. |
| `batch_size` | `None` | Sample and decode in batches of this size to limit memory. `None` is one batch. |
| `extra` | `{}` | Extra `decode_batch` arguments. |

### `ZNEArgs` (package settings, not Stim arguments)
| Field | Default | Description |
|---|---|---|
| `target` | `1.0` | Noise scale to extrapolate to. `1.0` is your base rates. |
| `models` | `("powerlaw",)` | Fit models. The first is the primary result; extra models give a spread. |
| `poly_order` | `2` | Degree for the `polynomial` model. |
| `quantity` | `"logical_error_rate"` | Or `"expectation"` (the value `1 − 2·p_L`). |
| `n_bootstrap` | `500` | Bootstrap resamples for the confidence interval. |
| `confidence` | `0.95` | Confidence level of the interval. |
| `threshold_guard` | `0.007` | Warn if any simulated physical rate exceeds this. |
| `bootstrap_seed` | `None` | Seed for the bootstrap. |

### Validation
`run()` raises `ValueError` before simulating if: `lambdas` is empty, contains
non-positive or duplicate values; `shots <= 0`; `separate_observables` is not
`True` or `prepend/append_observables` are set; the decoder bit-packing flags
disagree with `sampler.bit_packed`; `batch_size <= 0`; or a fixed
`stim.Circuit` is given together with more than one `lambda` (a fixed circuit
cannot be noise-scaled; pass a callable instead).

## 6. Results reference

`run()` returns a `RunResult`. Call `result.to_dict()` or `result.to_json(path)`
to export everything.

### `RunResult`
| Field | Description |
|---|---|
| `config` | The full configuration used (callables and circuits as text). |
| `versions` | Versions of `qec_qem`, Stim, PyMatching, NumPy, SciPy, Python. |
| `seed` | Base sampling seed. Noise scale number `i` uses `seed + i`. |
| `points` | List of `PointResult`, one per noise scale. |
| `zne` | The `ZNEResult`. |

### `PointResult` (one noise scale)
| Field | Description |
|---|---|
| `lam` | Noise scale. |
| `noise` | The four scaled rates passed to Stim (`None` for custom circuits). |
| `max_noise_rate` | Largest scaled rate (`None` for custom circuits). |
| `rounds` | Rounds used (`None` for custom circuits). |
| `seed` | Seed given to Stim's sampler for this point. |
| `shots`, `failures` | Shots run and logical failures. |
| `p_L`, `stderr` | Logical error rate and its binomial standard error. |
| `stats` | Circuit stats: `num_qubits`, `num_detectors`, `num_observables`, `num_measurements`, `num_ticks`. |
| `circuit_text`, `dem_text` | The Stim circuit and detector error model as text. |
| `decoder` | Decoder name (`"custom"` for a factory). |
| `raw` | With `store_raw=True`: dict of `det_events`, `obs_flips`, `predictions`, and `weights` (if requested). Otherwise `None`. |

### `ZNEResult`
| Field | Description |
|---|---|
| `primary_model` | Name of the first model that fitted. |
| `value`, `ci_low`, `ci_high` | Extrapolated value and confidence interval of the primary model. The interval is `None` if too few bootstrap fits succeeded. |
| `fits` | List of `FitResult`, one per successful model. |
| `model_spread` | Max minus min of `value` across models (a systematic-error indicator). `None` with one model. |
| `failed_models` | Models that could not be fitted, with the reason. |
| `warnings` | Guard warnings (see section 7). |

### `FitResult` (one model)
| Field | Description |
|---|---|
| `model`, `quantity`, `target` | What was fitted and where it was evaluated. |
| `value`, `ci_low`, `ci_high`, `boot_std` | Extrapolated value, interval, bootstrap standard deviation. |
| `p_L_equivalent` | The value as a logical error rate (differs from `value` only for `quantity="expectation"`). |
| `params`, `param_cov` | Fitted parameters and their covariance matrix. |
| `chi2`, `dof`, `reduced_chi2` | Goodness of fit. |
| `n_points_used`, `n_boot_valid` | Points used in the fit; successful bootstrap fits. |
| `warnings` | Warnings specific to this fit. |

## 7. The extrapolation (ZNE)

### Models
| Model | Form | Best for | `params` keys |
|---|---|---|---|
| `powerlaw` | `y = A·λ^k` (weighted fit in log-log) | Logical error rate below threshold. **Default.** | `A`, `log_A`, `exponent` |
| `exponential` | `y = A·exp(b·λ)` (weighted `scipy.optimize.curve_fit`) | Expectation values that decay with noise. | `A`, `b` |
| `polynomial` | degree `poly_order` polynomial (weighted least squares) | Sanity check against the other models. | `c0`, `c1`, … |

`powerlaw` applies only to the logical error rate and needs `target > 0`
(`p_L` is trivially zero at zero noise). `exponential` and `polynomial` work with
either quantity and allow `target = 0`.

### Uncertainty
- Each point is weighted by its binomial standard error.
- The confidence interval comes from a bootstrap: failures at each noise scale
  are resampled from a binomial, the model is refit, and percentiles of the
  extrapolated values are taken.
- List several models in `zne.models`; `model_spread` shows how much the choice of
  model changes the answer.

### Warnings
| Warning | Meaning and what to do |
|---|---|
| dropped lambdas | A noise scale had zero (or all) failures, so it has no variance estimate and was excluded. Use more shots or a larger lambda. |
| threshold_guard | A simulated rate is above `threshold_guard`. The low-noise scaling law may not hold; use smaller lambdas. |
| long extrapolation | The target is more than twice the sampled lambda range below the lowest lambda. Add lower lambdas. |
| target above range | The target is above all sampled lambdas, so this is not extrapolation to lower noise. |
| poor fit | Reduced chi² above 3. Try another model or different lambdas. |
| bootstrap shortfall | Too few bootstrap fits succeeded, so no interval is reported. |
| model skipped | A model could not be fitted (reason given). |

### Choosing lambdas
- Keep every scaled rate `lambda × p` below roughly 0.5–1% (circuit-level
  threshold of the surface code). The default `threshold_guard` is 0.007.
- Use at least one more usable point than the model has parameters
  (3+ for `powerlaw` and `exponential`).
- Choose lambdas and shots so that each point has enough failures (tens to
  hundreds) to give a usable error bar.
- Staying close to the target gives a more reliable extrapolation than a long jump.

## 8. Recipes

### Compare fit models
```python
cfg.zne.models = ("powerlaw", "exponential", "polynomial")
result = run(cfg)
for f in result.zne.fits:
    print(f.model, f.value, f.ci_low, f.ci_high, f.reduced_chi2)
print(result.zne.model_spread)
```

### Use a larger code
```python
cfg.circuit.distance = 5      # rounds defaults to the distance
```

### Reduce memory
```python
cfg.sampler.bit_packed = True
cfg.decoder.batch_size = 50_000
```

### Keep the raw data
```python
cfg.store_raw = True
result = run(cfg)
raw = result.points[0].raw     # det_events, obs_flips, predictions
```

### Scale only some noise channels
`noise_scale` receives the `CircuitArgs` and `lambda`, and returns the four rates.
```python
from qec_qem import Config, default_scale

def measurement_only(args, lam):
    rates = default_scale(args, 1.0)               # base rates, unscaled
    rates["before_measure_flip_probability"] *= lam
    return rates

cfg = Config(noise_scale=measurement_only)
```

### Use your own circuit
Pass a callable that builds the circuit for a given noise scale. For custom
circuits `PointResult.noise` and `max_noise_rate` are `None`, so the threshold
guard is inactive.
```python
import stim
from qec_qem import Config

def factory(lam):
    p = 1e-3 * lam
    return stim.Circuit.generated(
        "surface_code:rotated_memory_x", distance=3, rounds=3,
        after_clifford_depolarization=p,
        before_round_data_depolarization=p,
        before_measure_flip_probability=p,
        after_reset_flip_probability=p)

cfg = Config(custom_circuit=factory, lambdas=(2.0, 3.0, 4.0, 5.0))
```

### Use your own decoder
`decoder_factory` receives the detector error model and returns an object whose
`decode_batch(shots, **kwargs)` returns an array of predicted observable flips with
shape `(shots, num_observables)`. The keyword arguments are `return_weights`,
`bit_packed_shots`, `bit_packed_predictions`, plus anything in `decoder.extra`.
```python
class MyDecoder:
    def __init__(self, dem): ...
    def decode_batch(self, shots, **kwargs): ...

cfg.decoder.decoder_factory = lambda dem: MyDecoder(dem)
```

### Extrapolate an expectation value to zero noise
```python
cfg.zne.quantity = "expectation"        # y = 1 - 2*p_L
cfg.zne.models = ("exponential",)
cfg.zne.target = 0.0
```
With the generated memory circuits the zero-noise expectation is trivially 1,
so this mode is mainly useful with a custom circuit whose observable is not
trivially preserved.

### Read a saved result
```python
import json
data = json.load(open("result.json"))
data["zne"]["value"], data["points"][0]["stats"]["num_qubits"]
```

## 9. Reproducibility
- Set `sampler.seed` to fix the sampling. Noise scale number `i` uses `seed + i`,
  so scales get independent samples. The seeds used are stored in `result.seed`
  and `PointResult.seed`.
- Set `zne.bootstrap_seed` to fix the confidence interval.
- The JSON export stores the config, the circuit and DEM text for every noise
  scale, counts, library versions, and all fit results.

## 10. Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
| `ValueError: ... separate_observables ...` | Decoding needs `separate_observables=True` and no prepend/append of observables. |
| `ValueError: ... bit_packed ...` | Decoder bit-packing flags must match `sampler.bit_packed`, or be left as `None`. |
| `ValueError: a fixed stim.Circuit cannot be noise-scaled` | Pass `custom_circuit` as a callable `lam -> circuit` when using several lambdas. |
| `FitError: no model could be fitted` | Too few usable points (need more than the model's parameters), or all points had zero failures. Add shots or lambdas. |
| `FitError: power law cannot be evaluated at target <= 0` | Use `target > 0`, or switch to the exponential model with `quantity="expectation"`. |
| "dropped lambdas" warning | Zero failures at that noise scale. Increase `shots` or use larger lambdas. |
| No confidence interval | Too few bootstrap fits succeeded. Add points or shots. |
| Very large extrapolated error bars | Few failures or a long extrapolation. Add shots and lower lambdas. |
| Out of memory | Set `decoder.batch_size`, `sampler.bit_packed=True`, and leave `store_raw=False`. |
| A Stim argument is rejected | Your Stim version differs. Check `help(stim.Circuit.generated)` and the argument names in section 5. |

`FitError` can be imported with `from qec_qem.zne import FitError`.

## 11. Limitations
- Extrapolation gives a **model-based estimate**, not a guarantee. It is reliable
  only when all simulated noise levels are below threshold and the fit model
  matches the real scaling.
- It costs extra simulations at the amplified noise levels.
- The generated circuits are single-logical-qubit memory experiments with four
  uniform noise rates. They have no idle noise, crosstalk, biased noise, or
  routing between patches. Use `custom_circuit` for richer circuits.
- Surface-code qubit counts in section 1 are for one rotated patch. The exact
  number for your circuit is in `PointResult.stats["num_qubits"]`.

## 12. Development
```
qec_qem/
  config.py     configuration dataclasses
  simulate.py   Stim circuit, DEM, sampling, decoding
  zne.py        fit models, bootstrap, warnings
  results.py    result dataclasses and JSON export
  run.py        run(config)
  manifest.py   Stim argument names handled by the package
tests/          unit tests and a pipeline test (source distribution only)
examples/       runnable example
```
Run the tests from the source distribution with `pip install -e .[test]` and
`pytest`. `tests/test_stim_pipeline.py` includes a check that fails if the
installed Stim or PyMatching adds arguments the package does not know about.
