Skip to content
PyhroffPublic

About

Rotated surface code quantum error correction simulator: Stim + PyMatching threshold curve, D3 lattice animation, RSA-2048 qubit estimator

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Quantum OS

Python 3.11+ FastAPI D3.js v7 Stim PyMatching v2

This is an educational simulator, not a validated forecast of quantum hardware capabilities or a cryptographic break-time prediction. Resource estimates are assumption-sensitive; cite the source papers and report model assumptions when interpreting them.

This is the second half of a two-project arc. The first half - Quantum Collapse - simulates what happens when a cryptographically relevant quantum computer breaks RSA: cascading infrastructure failure across banks, CAs, cloud providers, and government systems. It's the "what breaks" story.

Quantum OS is the "how and when" story. It simulates the fault-tolerant quantum computer that would actually do that: a surface code engine running real MWPM decoding, lattice surgery primitives, and a physical resource estimator grounded in current literature. The gap between "cryptographically relevant QC" and today's hardware is mostly an error correction problem, and this is what that problem looks like under the hood.


What's in the simulator

Surface code lattice - rotated memory-Z code at d = 3, 5, 7, 9. Data qubits, X/Z stabilizer faces, weight-2 boundary checks. Click any distance and watch the geometry update.

Shot animation - inject depolarizing errors, run syndrome extraction, decode with MWPM, see corrections applied qubit-by-qubit, check whether a logical error survived. All of it animated step by step in D3 so you can actually watch what the decoder is doing.

Error threshold - the classic surface code plot: logical error rate vs physical error rate across d = 3, 5, 7. Threshold comes out near p ≈ 1% using circuit-level Stim noise. Below the threshold, larger codes do better. Above it, they do worse. This is the number that determines whether fault-tolerant QC is even viable on a given hardware platform.

Lattice surgery - X-merge - two d×d patches joined at a rough boundary, measuring the joint logical X_L ⊗ X_R parity. This is the primitive operation behind logical CNOT in a surface code computer. Animated in 5 phases: merge, inject errors, extract syndromes, MWPM correct, split. Verified correct at p=0 for d=3,5.

Phenomenological noise - adds measurement errors on top of data errors (the standard multi-round model). Threshold drops from ~1% to ~0.7%. Overlaid on the circuit-level curves so you can see exactly how much measurement noise costs.

Fault-tolerant gate scheduler - maps logical gate sequences to lattice surgery primitives and draws a D3 Gantt chart showing the schedule. Four preset circuits: CNOT (3 patches, depth 4), T gate via magic state injection (2 patches), Bell pair (3 patches), Toffoli (8 patches, depth 34, T-count 7). Resource counts - physical qubits, QEC rounds, runtime in µs - are exact for each circuit at any code distance.

Logical qubit register - N×M grid of independent surface code patches (1×1 up to 4×4). Runs a full shot on each patch and shows which ones survived without a logical error. Good for seeing how error rates scale when you're trying to keep a register alive between gates.

RSA-2048 resource estimator - physical qubit count as a function of physical error rate and logical qubit count. Side-by-side comparison against three published estimates: Gidney & Ekerå 2019 (~20M qubits), Gidney 2025 (<1M), and the 2026 heterogeneous architecture paper (~100K). The 200× reduction is almost entirely algorithmic.


Running it

cd backend
pip install -r requirements.txt
uvicorn server:app --port 8001 --reload

In a second terminal from the repository root, run python -m http.server 8080, then open http://localhost:8080/frontend/. The UI connects to http://localhost:8001. The API allows these local origins by default; set QEC_LAB_ALLOWED_ORIGINS to a comma-separated origin allowlist for a different local setup. Do not expose the development server to untrusted networks.

If you just want to see some numbers without the UI:

cd backend
python demo.py

Project structure

backend/
  server.py         FastAPI app, port 8001
  qec/
    lattice.py      Rotated surface code geometry
    simulator.py    Code-capacity shots + Stim circuit-level threshold
    surgery.py      Two-patch X-merge with seam stabilizers
    scheduler.py    Gate → lattice surgery primitive mapping + Gantt data
    register.py     N×M patch grid simulation
    resource.py     Physical qubit estimator + published benchmarks
frontend/
  index.html        Everything - D3 visualiser, controls, all panels
docs/
  DESIGN.md         Lattice math, noise models, decoder internals

PQC evidence → QEC resource scenario bridge

QEC Lab can consume the versioned scenario JSON produced by Quantum Collapse's PQC Scanner bridge. It retains the input finding references and runs the existing resource estimator only for RSA findings, because the current estimator models RSA-2048 factoring. ECC, DH, and DSA observations are preserved with an explicit unsupported_crypto_model status rather than being treated as RSA equivalents.

From backend/:

python -m qec.scenario_bridge /path/to/scenario.json \
  --p-physical 0.001 --n-logical 3000 --t-gates 3000000000 \
  --p-total-failure 0.5 --output qec-resource-scenario.json

Each output labels itself conditional_analytical_resource_estimate_not_hardware_measurement. It carries the estimator's model-domain and distance-cap flags and documents that the result is assumption-sensitive, omits architecture-specific overhead, and does not prove source-code reachability, deployed use, or an attack timeline. Input scenario risk scores and dependency assumptions are not recomputed or treated as physical evidence.

CI exercises this bridge using a small fixture containing one RSA and one ECC node; the fixture is a contract/regression test, not a benchmark result.

Scenario uncertainty analysis

The API endpoint GET /api/resource/uncertainty runs a seeded Monte Carlo sweep over explicitly supplied ranges for physical error rate, logical-qubit count, T-gate count, and total failure budget. It reports p05/p50/p95, mean, sample standard deviation, and rates for cap-exceeded, model-domain-valid, and feasible scenarios.

Example:

curl 'http://localhost:8001/api/resource/uncertainty?samples=1000&seed=20261010&p_min=0.0005&p_max=0.005&n_logical_min=1000&n_logical_max=5000&t_gates_min=1000000000&t_gates_max=5000000000'

Interpretation: this is a distribution of outputs under user-chosen input ranges, not a calibrated probability distribution for future hardware and not an empirical confidence interval. The default uniform sampling policy is an exploratory sensitivity choice; the model still uses its fixed analytical surface-code approximation and omits architecture-specific overhead. Record the ranges and seed when comparing reports.

API

GET  /api/lattice?d=3
GET  /api/threshold?shots=600
GET  /api/resource?p=0.001&n_logical=3000
GET  /api/surgery/geometry?d=3
GET  /api/phenomenological?shots=300
GET  /api/scheduler/circuits
GET  /api/scheduler?circuit=toffoli&d=5
GET  /api/register?n=3&m=3&d=3&p=0.01

POST /api/shot      {"d": 3, "p": 0.01, "seed": null}
POST /api/surgery   {"d": 3, "p": 0.01, "seed": null}

The noise models

Shot simulation uses code-capacity noise: independent X and Z errors per data qubit at rate p, no measurement errors. Simple enough to visualize clearly.

The threshold curve uses circuit-level noise via Stim: after_clifford_depolarization=p throughout the full syndrome extraction circuit including ancilla prep and measurement. This is the standard model in the surface code literature and gives a threshold around 0.5–1%.

Phenomenological noise is the middle ground: data errors plus measurement flip probability both at rate p, run for multiple rounds. Threshold comes out lower (~0.7%) because measurement errors create time-domain ambiguities the decoder has to chase.


References

  • Fowler et al. (2012) - Surface codes: towards practical large-scale quantum computation. arXiv:1208.0928
  • Horsman et al. (2012) - Surface code quantum computing by lattice surgery. arXiv:1111.4022
  • Bravyi & Kitaev (2005) - Universal quantum computation with ideal Clifford gates and noisy ancillas. arXiv:quant-ph/0403025
  • Selinger (2013) - Quantum circuits of T-depth one. arXiv:1210.0974
  • Gidney & Ekerå (2019) - How to factor 2048-bit RSA integers in 8 hours using 20 million noisy qubits. arXiv:1905.09749
  • Gidney (2025) - Factor RSA-2048 using less than a million noisy qubits. arXiv:2505.15917
  • Xu et al. (2026) - Constant-overhead fault-tolerant quantum computation with reconfigurable atom arrays. arXiv:2604.06319

MIT license.

Validation and scientific limitations

CI checks deterministic invariants for surface-code geometry, seeded noisy-shot reproducibility, probability and resource-input validation, monotonic behavior of the simplified logical-error approximation below its configured threshold, and explicit local CORS policy. These tests establish implementation consistency, not empirical calibration against a hardware backend.

The resource estimator is a simplified analytical model. Its outputs depend on assumptions such as the logical-error approximation, threshold, prefactor, code distance cap, algorithmic gate counts, and accepted total failure budget. Treat the result as a reproducible scenario estimate—not a benchmark of a specific quantum processor or a guarantee that RSA-2048 factoring is feasible. When comparing runs, record all inputs and the code revision; published resource estimates can differ substantially because their architectures and arithmetic assumptions differ.

Reproducible resource sweep

From backend/, run:

python -m qec.resource_sweep --output resource-sweep.json

The JSON manifest records the code revision, Python/platform, parameter grid, threshold/prefactor assumptions, run duration, and one result per physical-error-rate × T-gate-count pair. A reported distance of 61 is a sentinel meaning the search found no solution for odd distances 3..59; the associated qubit count is a cap reference, not a validated minimum. The analytical model is only predictive below its configured 1% threshold. The resource UI slider is restricted to 0.1–0.9%; the API accepts 0.01–0.9%. The separate runtime endpoint marks out-of-domain inputs explicitly.

CI resource-sweep snapshot

The full 18-case analytical grid was executed in CI with n_logical=3000 and a total failure budget of 0.5. The rows below show the 3-billion-T-gate scenario; values are outputs of this simplified model, not hardware measurements.

Physical error rate Reported distance Physical qubits at reported distance Under 10M cutoff? Search cap exceeded?
0.05% 13 1,014,000 Yes No
0.1% 17 1,734,000 Yes No
0.2% 25 3,750,000 Yes No
0.5% 59 20,886,000 No No
0.7% 61 (sentinel) 22,326,000 (cap reference) No Yes
0.9% 61 (sentinel) 22,326,000 (cap reference) No Yes

The cap rows mean the target was not met for any tested odd distance from 3 through 59. They must not be interpreted as a proven minimum-qubit design.

About

Rotated surface code quantum error correction simulator: Stim + PyMatching threshold curve, D3 lattice animation, RSA-2048 qubit estimator

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages