Author: grisun0 · ORCID: 0009-0002-7622-3916 DOI: 10.5281/zenodo.18795538 License: AGPL v3
A functional quasi-quantum computing simulator on classical hardware using physics models as a backend, now extended with Matrix Product State (MPS) tensor networks for scalable simulation.
Q²C simulates quantum systems on classical hardware through two complementary modes selectable at runtime:
| Mode | Backend | Precision | Max Qubits | When to use |
|---|---|---|---|---|
| Direct (exact) | Full statevector | Machine ε (~1e-15) | ~14 | Need exact amplitudes |
| MPS (scalable) | Tensor network | Tunable (chi) | 33+ | Need more qubits |
Both modes share the same gate library, algorithms, and physics backends. The user chooses via precision_mode in quantum_framework_config.toml or at the interactive menu prompt.
quantum_framework_main.py ← CLI entry point
quantum_lab.py ← Educational TUI (bilingual EN/ES)
quantum_framework_menu.py ← Interactive menu (11 sections)
│
├── quantum_framework_core.py ← MPS tensor network engine
│ ├── MPSState / MPSCore ← O(n·χ²) memory representation
│ ├── QuantumCircuit ← Gate builder (H, X, Y, Z, CNOT, CZ, SWAP, Rx/Ry/Rz, ...)
│ └── MPSQuantumComputer ← Bell, GHZ, W-state, Grover, QFT
│
├── quantum_framework_physics.py ← Neural physics backends
│ ├── HamiltonianBackboneNet ← Spectral FFT Hamiltonian network
│ ├── SchrodingerSpectralNet ← Wavefunction evolution network
│ └── DiracSpectralNet ← Relativistic 8-channel spinor network
│
├── quantum_framework_molecular*.py ← VQE molecular simulations
│ ├── UCCSD ansatz (Jordan-Wigner)
│ └── Molecules: H2, LiH, H2O
│
├── quantum_computer.py ← Legacy statevector simulator (exact)
│ └── Backends: Hamiltonian, Schrodinger, Dirac (float32)
│
├── higgs_four_lepton_analysis.py ← Higgs → ZZ* → 4l on CMS Open Data
├── quantum_visualizer.py ← Probability / Bloch / phase visualizer
├── quantum_dash.py ← Brutalist matplotlib + Plotly visualizer
├── quantum_3dview.py ← 3D holographic Plotly dashboard + audio
├── app.py ← H2 polarizability VQE (Stark effect)
│
├── relativistic_hydrogen.py ← Dirac equation, fine structure, Zitterbewegung
├── entangled_hydrogen.py ← Entangled hydrogen orbital simulations
├── topological_hilbert_compression2.py ← Topological Hilbert space analysis
├── advanced_experiments.py ← Grover, QFT, phase estimation, Simon
│
├── **qc_integration.py** ← **SDD: OpenQASM 2.0 / Qiskit / PennyLane bridge**
│ ├── OpenQasmAdapter ← Export / Import OpenQASM 2.0 circuits
│ ├── QiskitAdapter ← Convert to/from Qiskit QuantumCircuit
│ ├── PennyLaneAdapter ← Convert to/from PennyLane tapes / QNode
│ ├── StandardCircuitFactory ← Bell, GHZ, W-state, QFT, Grover generators
│ ├── IntegrationBridge ← One-shot export → run → diagram
│ └── IntegrationConfig ← Centralized gate map, names, version
│
├── **qc_dashboard.py** ← **SDD: Streamlit real-time playground**
│ ├── DashboardConfig ← Centralized theme, gates, session defaults
│ ├── H2VQESolver ← Self-contained H2 VQE (numpy, no PySCF)
│ ├── VisualisationEngine ← Matplotlib: probabilities, Bloch, phase, entropy
│ ├── Plotly3DEngine ← 3D Bloch spheres, probability bars, state scatter
│ ├── RealOrbitalEngine ← Hydrogen orbital sampling bridge
│ ├── BrutalVizEngine ← Legacy brutalist matplotlib visualizer
│ ├── BackendComparator ← Side-by-side backend comparison
│ ├── SimulatorBackend ← MPS / statevector / synthetic backend adapter
│ └── DashboardApp ← Streamlit orchestrator (7 tabs)
│
├── **test_qc_integration.py** ← **69 BDD tests (100% pass rate)** for both modules
└── test_quantum_framework.py ← 34 pytest tests (100% pass rate)
| Algorithm | Result |
|---|---|
| Bell state entropy | 1.000000 bits (exact) |
| GHZ state (n=3) | 50/50 distribution |
| Grover 3-qubit search | 94.53% marked-state probability |
| QFT norm preservation | sum(P) = 1 to machine precision |
| Phase coherence (HZH=X, XX=I, etc.) | 22/22 tests pass |
| Molecule | HF Energy (Ha) | VQE Energy (Ha) | FCI Ref (Ha) | Corr. recovered |
|---|---|---|---|---|
| H2 | −1.1168 | −1.1373060358 | −1.1373060358 | 100% |
| LiH | −7.87 | — | −7.88 | — |
| H2O | −74.963 | — | −75.012 | — |
- α = 2.750 a₀³ — exact match with STO-3G diagonalization
- |E(+F) − E(−F)| at machine precision (10⁻¹⁵) across all field values
- Anomalous magnetic moment (g−2)/2 to 5th order: 0.3% error vs experiment
- Lamb shift: 57.31 MHz (perturbative; experimental: 1057.84 MHz)
| Qubits | MPS Memory | Full statevector | Compression |
|---|---|---|---|
| 10 | 21 KB | 16 KB | — (chi=32 saturated) |
| 20 | 182 KB | 16 MB | ~90× |
| 33 | ~350 KB | 128 GB | ~370,000× |
python3 quantum_framework_main.py --learn # or: python3 quantum_lab.py
python3 quantum_lab.py --lang es # interfaz en español
python3 quantum_lab.py --lesson 3 # jump to lesson 3A bilingual (English/Spanish) interactive terminal experience built on the real simulation engine — nothing is pre-recorded:
| Section | What you do |
|---|---|
| Lessons | 6-lesson guided course: qubits & superposition, measurement, entanglement & Bell states, Grover search, quantum chemistry, and a live VQE of H2 — animated gradient descent on the real energy landscape, with ASCII electron-cloud renderings of the bonding/antibonding molecular orbitals. Live simulations + quizzes. |
| Playground | Build circuits gate by gate (h 0, cnot 0 1, ry 0 pi/3, ...) and watch probability bars, amplitudes/phases and entanglement entropy update live. |
| Chemistry lab | Molecule cards (H2, LiH, H2O) with HF/FCI/correlation energies, and a colored ASCII hydrogen-orbital viewer (1s → 3d) showing lobes, signs and nodes. |
| Glossary | Quick reference for all the vocabulary used in the lessons. |
Requires only rich on top of the core dependencies.
python3 quantum_framework_main.pypython3 quantum_framework_main.py --run-allpytest test_quantum_framework.py -v
pytest test_qc_integration.py -v # 69 integration & dashboard tests
pytest test_quantum_framework.py test_qc_integration.py -v # all 103python3 quantum_framework_main.py --help
python3 quantum_framework_main.py --learn --lang es
python3 quantum_framework_main.py --benchmark --max-qubits 20
python3 quantum_framework_main.py --infoA native OpenGL window: GLSL raymarching on your GPU (70-170 fps on an RTX 2060), HDR bloom, filmic grading.
English by default; the EN button (or F2) switches to Spanish.
python3 -m venv --system-site-packages .venv && .venv/bin/pip install pyscf # once, for the Matter scene
.venv/bin/python qc_launcher.py # Textual front door
.venv/bin/python qc_immersive.py --tour # ~2 min cinematic tour
.venv/bin/python qc_immersive.py --scene rydberg # open a scene directly
.venv/bin/python qc_immersive.py --scene atom --do preset:3,born # Born-rule detections on 2p
.venv/bin/python qc_immersive.py --scene spin --do preset:3 --screenshot out.png # offscreen render
.venv/bin/python qc_immersive.py --lang es # start in SpanishOptions: --scene {atom,spin,matter,rydberg,tune,bloch,entangle}, --tour, --size WxH, --lang {en,es},
--do cmd1,cmd2 (scene commands such as preset:5, cut, born, sys:H2O), --screenshot FILE --frames N.
| Scene | What it shows | Where the numbers come from |
|---|---|---|
| Atom | Hydrogenic clouds up to 4f, slicing with probability contours, phase as colour, beating superpositions. B switches to Born-rule detections: glowing dots drawn from |
psi |
| Spin | Pauli-spinor states | n l j m_j>: spin arrows inside the cloud, Larmor precession in a magnetic field, spin-orbit beating. |
| Matter | H to Ne and 10 molecules: density, molecular orbitals, spin density, FCI density (H2), ball-and-stick geometry. | PySCF (UHF/RHF 6-31G). Integrals are checked against the electron count. Panel for H2 runs the project's own VQE. |
| Rydberg | A wave packet of circular states | n, l=n-1, m=n-1> around n0 (8/10/12/14) that orbits like a classical planet at the Kepler frequency 1/n0^3, then spreads and revives. The quantum packet angle and the classical angle are printed side by side. |
| Fine-tune | Fine-tunes copies of the backend's real networks (Hamiltonian, Schrodinger, Dirac) against the exact results of the backend's own analytical path, live. Four 3D plates: the field update (net solid, exact wire), the operator rate versus wavevector (net surface against the exact one), and the spectral kernels of both layers (height = magnitude, colour = phase, wire = the original weights). Metrics on seen (training set) and unseen (held-out, per data family) data, plus delta, alpha, kappa, T_eff, Berry phase and winding. | Targets: ifft(fft*0.5k^2) (Hamiltonian), the exact spectral propagator at propagator_dt (Schrodinger), DiracBackend._analytical_dirac on spinors from DiracBackend._pack (Dirac). A pushes the tuned weights into the running backend (Qubit/Entanglement use them), R restores the originals, E exports a project-format checkpoint to h/tuned/. |
| Qubit / Entanglement | Bloch spheres, animated gates, Bell pairs, entropy, measurement. | Every state is a JointHilbertState from quantum_computer.QuantumComputer; the NN checkpoints are loaded and the spatial fields they evolve are shown (K switches backend, V evolves). An ideal-unitary reference runs in lockstep and its gap is displayed. The panel also carries a Hamiltonian-network audit (Hermiticity defect, distance from -laplacian/2, fidelity after 200 steps versus the exact propagator and versus doing nothing). Caveat added later: these are measured against a free-particle reference with hbar=1, while the checkpoint was trained with another objective (hbar=1e-6, Poynting/entropy terms); I have not yet verified them against the training code. |
Controls: drag = orbit, wheel = zoom, Tab = next scene, T/F5 = tour, F2 = language, F11 = fullscreen, F12 = screenshot.
Fine-tune: Space tune/pause, 1 2 3 network, up/down learning rate, left/right sample, L loss (relative or MSE), D data family, N new data, R reset, A apply to backend, E export. Atom: 1-9,0 presets, N L M quantum numbers, B Born detections. Rydberg: left/right = time speed, P pause, R restart, up/down = shell, O classical orbit.
Every volume scene: X slice, Z slice axis, S sweep, C colour, -/= density.
Requires OpenGL 3.3+, pygame, PyOpenGL, torch; textual for the launcher, pyscf for Matter.
Keep running the terminal lab (quantum_lab.py) with the system Python: with PySCF installed MoleculeBuilder.h2_sto3g switches to the 4-qubit branch that H2VQEEngine does not expect.
JointHilbertState.bloch_vectorhad the y axis mirrored; Rx(pi/2)|0> now gives -y as in the standard convention.DiracBackend.evolve_amplitudecrashed when theEvolvegate passed float64 data to the float32 network.LambShiftCalculatornow uses the leading-order formula with tabulated Bethe logarithms: 1S 8127 MHz (literature 8172), 2S-2P1/2 1052 MHz (1057.8), and the Uehling term has the right sign.
Known limits, not fixed: the learned Hamiltonian network is not Hermitian (about 11 % defect) and acts almost as the identity (the audit panel shows it; see the caveat above, this is relative to a free-particle reference), and the 4-qubit VQESolver returns the Hartree-Fock energy when PySCF is installed.
python3 -m pytest tests -q # deploy gate: ~4 s, no GPU needed
Q2C_GL_TESTS=1 python3 -m pytest tests -q # also renders every scene (needs a display + OpenGL 3.3)
.venv/bin/python -m pytest test_immersive.py -q # extended suite incl. PySCF conservation and the project VQE
python3 -m pytest test_quantum_framework.py test_qc_integration.py -q # original suitestests/ is the release gate used by deploynator: deploynator.toml declares
python3 -m pytest tests -q as the [tests] command, so a failing physics or backend check aborts the release.
deploynator status # project and git state
deploynator release --dry-run --project . --type feat --subject "immersive viewer" --scope viewer
deploynator release --project . --no-docs --type feat --subject "immersive viewer" --scope viewerA proof of concept that retrains the Hamiltonian network with the same architecture and checkpoint layout as the project's
HamiltonianBackboneNet, so it loads as hamiltonian.pth. It fixes the training objective (relative error instead of an MSE
the zero map already satisfies, adaptive lambda pressure) and adds the Maxwell protocol: GOE/GUE ratio scan, batch-size
prospecting, seed mining, long training. Details and the reasoning are in h/README.md.
python3 -m h.train --out h/runs/run1 # phases 0-3, long run
python3 -m h.train --out h/runs/quick --quick # minutes
python3 -m h.validate h/weights/hamiltonian_h.pth # through the project's HamiltonianBackend
python3 -m h.research list # research-suite experiments
python3 -m h.research run maxwell # audit of the Maxwell checkpoint
Q2C_HAMILTONIAN=$PWD/h/weights/hamiltonian_h.pth .venv/bin/python qc_immersive.py --scene entangle| # | Section | Contents |
|---|---|---|
| 1 | Quantum Circuits | Custom circuits, Bell, GHZ, W-state, gate demos |
| 2 | Entanglement | Entropy scaling, cut-position analysis, heatmaps |
| 3 | Molecular Simulations | VQE H2/LiH/H2O, energy landscape, polarizability |
| 4 | Orbital Visualization | Hydrogen orbitals, 3D scatter, probability distributions |
| 5 | Relativistic Physics | Dirac equation, fine structure, Zitterbewegung |
| 6 | QED Effects | Lamb shift, anomalous magnetic moment, vacuum polarization |
| 7 | Advanced Algorithms | Grover, QFT, phase estimation, Simon, teleportation |
| 8 | Benchmarks | MPS scaling, memory efficiency, timing |
| 9 | Configuration | Atoms, molecules, parameters |
| 10 | Particle Physics | Higgs → 4 lepton on CMS Open Data + quantum backends |
| 11 | Quantum Visualization | Brutalist matplotlib/Plotly, 3D holographic dashboard |
Edit quantum_framework_config.toml:
[simulation]
precision_mode = false # true = exact statevector, false = MPS
max_qubits = 33 # max qubits for MPS mode
max_qubits_direct = 14 # max qubits for direct mode
[mps]
bond_dimension = 16 # χ — higher = more precise, more memory
max_bond_dimension = 64 # maximum χ
svd_threshold = 1.0e-10 # truncation threshold
adaptive_bond = trueThree pre-trained physics networks are included:
| File | Network | Size | Purpose |
|---|---|---|---|
weights/latest.pth |
HamiltonianBackboneNet | 18.9 MB | Spectral Hamiltonian operator |
weights/schrodinger_crystal_final.pth |
SchrodingerSpectralNet | 18.9 MB | Wavefunction time evolution |
weights/dirac_phase5_latest.pth |
DiracSpectralNet | 18.9 MB | Relativistic spinor dynamics |
All networks use FFT-based spectral convolution layers (SpectralLayer) operating in Fourier space.
pip install -r requirements.txt| Package | Required | Purpose |
|---|---|---|
| torch | Yes | MPS tensors, neural backends |
| numpy | Yes | Numerical computation |
| scipy | Yes | VQE optimizer (L-BFGS-B) |
| matplotlib | Yes | Visualization |
| tomllib/tomli | Required | TOML config (Python 3.11+ built-in) |
| plotly | Optional | 3D holographic visualization |
| openfermion | Optional | Molecular Hamiltonians |
| pyscf | Optional | Ab initio molecular integrals |
| pytest | Dev | Test suite |
| pyqasm | Optional | OpenQASM 2.0 parsing (qc_integration.py) |
| qiskit | Optional | Qiskit adapter (qc_integration.py) |
| pennylane | Optional | PennyLane adapter (qc_integration.py) |
| streamlit | Optional | Web dashboard (qc_dashboard.py) |
qc_integration.py provides a single-file, self-contained bridge between the Q²C framework and three external standards:
from qc_integration import IntegrationBridge, StandardCircuitFactory
bridge = IntegrationBridge()
# Build → export → run → diagram (one shot)
result = bridge.run_export_diagram("ghz", 4, backend="mps")
print(result["qasm"]) # OpenQASM 2.0 string
print(result["probabilities"]) # measurement outcomes
print(result["diagram"]) # ASCII circuit diagram
# Qiskit interop (if qiskit installed)
qc = StandardCircuitFactory.bell_state()
qiskit_qc = QiskitAdapter.to_qiskit(qc)
bell = QiskitAdapter.from_qiskit(qiskit_qc)| Feature | Description |
|---|---|
IntegrationBridge |
One-shot run_export_diagram() |
OpenQasmAdapter |
.export() / .import_qasm() |
QiskitAdapter |
.to_qiskit() / .from_qiskit() |
PennyLaneAdapter |
.to_pennylane() / .from_pennylane() |
StandardCircuitFactory |
Bell, GHZ, W-state, QFT, Grover |
qc_dashboard.py provides a Streamlit web playground with 7 interactive tabs:
streamlit run qc_dashboard.py| Tab | Features |
|---|---|
| Playground | Interactive circuit builder (gate palette, qubit slider), real-time state visualisation (probabilities, Bloch spheres, phase-space), step metrics |
| OpenQASM Editor | QASM 2.0 code editor with export/import, file download, playground integration |
| Entropy | Entropy evolution chart, step-by-step snapshot data table |
| Entanglement | Entropy vs cut-position profile, entropy scaling with system size, Schmidt decomposition |
| Molecules | Self-contained H2 VQE solver (numpy, no PySCF), energy convergence, landscape sweep, orbital visualisation |
| 3D Viz | 3D Bloch spheres, probability bars, state scatter (Plotly), snapshot slider navigation |
| Orbitals | Hydrogen orbital sampling (1s to 4f), single and entangled modes |
Circuit Builder sidebar:
- Gates: H, X, Y, Z, S, T, CNOT, CZ, SWAP, Rx, Ry, Rz
- Qubit count slider (1-8), parameter control for rotation gates
- Standard circuit presets: Bell, GHZ, W-state
- Clear and Run controls
The higgs_four_lepton_analysis.py module downloads real CMS Open Data from CERN and processes H → ZZ* → 4ℓ events through the quantum neural backends:
python3 higgs_four_lepton_analysis.pyThis will:
- Download 6 CSV files from the CERN Open Data Portal (~100 MB)
- Reconstruct 4-lepton invariant mass spectra
- Identify Higgs candidates in the 120–130 GeV window
- Evolve each lepton's wavefunction through DiracBackend, HamiltonianBackend, SchrodingerBackend
- Generate a Plotly 3D detector visualization with quantum-modulated tracks
| Feature | v1 | v2 (this) |
|---|---|---|
| State representation | Full statevector (2^n, 2, G, G) | MPS O(n·χ²) + exact mode |
| Numerical precision | float32 | float64 |
| Max qubits | 8 | 33+ (MPS) / 14 (exact) |
| Architecture | Monolithic files | Modular (7+ framework modules + 3 new) |
| Tests | None | 103 pytest tests (100% pass) |
| OpenQASM / Qiskit / PennyLane | No | Bridge module (qc_integration.py) |
| Web dashboard | No | Streamlit (qc_dashboard.py) |
| Particle physics | No | Higgs 4-lepton + CMS data |
| 3D visualization | No | Plotly holographic dashboard + 3D visualizer |
| Polarizability VQE | Separate script | Integrated in menu |
| Grover (framework) | via advanced_experiments | run_grover_search() in core |
| Configuration | Basic TOML | Extended TOML (9 sections) |
- MPS oracle for multi-controlled gates is circuit-approximate;
run_grover_search()uses statevector for correctness - GPU execution untested (CPU only)
- Higgs analysis requires internet connection for CMS data download
- PySCF/OpenFermion required for full molecular VQE (graceful fallback otherwise)
- Polarizability (app.py) tested only for H2 STO-3G
- Integration bridge (
qc_integration.py): Qiskit/PennyLane adapters require optional packages (qiskit, pennylane) - Dashboard (
qc_dashboard.py): requiresstreamlit; MPS visualisation truncates to first 5 qubits; Plotly 3D requires the plotly package
@software{grisuno_qc2026,
author = {grisun0},
title = {Q²C: Quasi Quantum Computing Simulator v2},
year = {2026},
doi = {10.5281/zenodo.18795538},
url = {https://github.com/grisuno/QC},
orcid = {0009-0002-7622-3916}
}This project has been analyzed by ReadMenator,
a zero-token polyglot static analysis tool. Regenerate with
pip install readmenator && readmenator . --rebuild. Analysis outputs:
- KNOWLEDGE_BASE.md -- Full architecture reference with all classes, functions, imports, dependency graphs, UML class diagrams, security audit findings, community analysis, taint paths, hotspots, cycles, and more.
- readmenator-agent/ -- Agent-friendly, grep-optimized index.
INDEX.md-- Quick reference: what each file doesSYMBOLS.md-- Every symbol with file:lineARCHITECTURE.md-- Internal dependency pairs + external importsAPI.md-- Public function contractsGOTCHAS.md-- Change warnings (blast radius, cycles, hotspots)SECURITY.md-- Findings by severity with fix hintsMEMORY.md-- Rules, workflow, style, deliverables, session logMANIFEST.json-- Freshness (git_commit + source_fingerprint) + read orderKB_<subsystem>.md-- Per-subsystem contextrecipes/*.md-- Grounded task guides (add-function, fix-cycle, ...)
- readmenator-wiki/ -- Navigable wiki (start here for the big picture).
index.md-- Entry point: overview, reading order, god nodes, connectionscommunity_*.md-- One synthesis page per code communityconnections.json-- Typed bridges between communitiesqueries.md-- Suggested questions + answer logREPORT.md-- Honest audit: coverage, confidence, limits
- readmenator-graphrag/ -- Zero-token GraphRAG index.
index.json+REPORTS.md-- Query withreadmenator . ask "<question>"
- readmenator-apidocs/ -- API reference (Sphinx/Doxygen style).
index.md+modules/*.md-- Signatures, parameters, returns, raises, examples, call graphsarchitecture.md-- Tiered architecture + execution flows (control flow, call tree, sequence)classes.md,genindex.md,COVERAGE.md-- Hierarchy, A-Z index, doc coverage + warningsindex.html+api/-- Offline searchable browser and machine-readable model (api/index.json,api/modules/*.jsonlone entity per line)
- readmenator-maps/ -- Interactive gallery (
index.html).- 5 system maps: architecture, workflow, sequence, dataflow, lifecycle
graph-force.html-- Force-graph explorer (2D/3D, reach, paths, lenses)graph-bundle.html-- Edge bundle explorer (circle + sphere)components.html-- Component diagrams
- docs/ -- Static site (GitHub Pages ready).
- Gallery copy +
llms.txt(agent entry point) +md/docs + video
- Gallery copy +
- readmenator-diagrams/ -- Component diagrams.
analysis.json+graph LRmarkdown + per-component pages +index.html
- readmenator-rules/ -- Suggested Semgrep rules (
*.yml),yara_rules.yar(YARA-lite) +exclusions.yaml(false-positive blocklist) - readmenator.mp4 -- Cinematic synthwave overview video
- .cursorrules -- Generated AI assistant rules
- readmenator_audit.sarif -- SARIF v2.1.0 audit (when security scan is on)
Cache (.readmenator_cache/), packaged agent skills (.claude/skills/), and the
GitHub wiki mirror are also produced on run/--rebuild.
AI agents: Read readmenator-wiki/index.md first for the big picture, then readmenator-agent/INDEX.md for grep-friendly lookup.
Developers: Read KNOWLEDGE_BASE.md for full architecture reference, open readmenator-maps/index.html for the visual gallery.
Deployed with deploynator