Tatopenn commited on
Commit
10fa8be
·
verified ·
1 Parent(s): 80fffcd

Delete Dense_Evolution_Project

Browse files
Files changed (31) hide show
  1. Dense_Evolution_Project/.github/workflows/ci.yml +0 -45
  2. Dense_Evolution_Project/.gitignore +0 -15
  3. Dense_Evolution_Project/.pytest_cache/.gitignore +0 -2
  4. Dense_Evolution_Project/.pytest_cache/CACHEDIR.TAG +0 -4
  5. Dense_Evolution_Project/.pytest_cache/README.md +0 -8
  6. Dense_Evolution_Project/.pytest_cache/v/cache/nodeids +0 -1
  7. Dense_Evolution_Project/README.md +0 -322
  8. Dense_Evolution_Project/dash.py +0 -0
  9. Dense_Evolution_Project/dense_evolution.egg-info/PKG-INFO +0 -366
  10. Dense_Evolution_Project/dense_evolution.egg-info/SOURCES.txt +0 -18
  11. Dense_Evolution_Project/dense_evolution.egg-info/dependency_links.txt +0 -1
  12. Dense_Evolution_Project/dense_evolution.egg-info/requires.txt +0 -21
  13. Dense_Evolution_Project/dense_evolution.egg-info/top_level.txt +0 -2
  14. Dense_Evolution_Project/dense_evolution/__init__.py +0 -11
  15. Dense_Evolution_Project/dense_evolution/__pycache__/compiler.cpython-39.pyc +0 -0
  16. Dense_Evolution_Project/dense_evolution/__pycache__/gates.cpython-39.pyc +0 -0
  17. Dense_Evolution_Project/dense_evolution/__pycache__/registry.cpython-39.pyc +0 -0
  18. Dense_Evolution_Project/dense_evolution/__pycache__/simulator.cpython-39.pyc +0 -0
  19. Dense_Evolution_Project/dense_evolution/chunk.py +0 -372
  20. Dense_Evolution_Project/dense_evolution/compiler.py +0 -316
  21. Dense_Evolution_Project/dense_evolution/gates.py +0 -55
  22. Dense_Evolution_Project/dense_evolution/healing.py +0 -143
  23. Dense_Evolution_Project/dense_evolution/parser.py +0 -429
  24. Dense_Evolution_Project/dense_evolution/registry.py +0 -377
  25. Dense_Evolution_Project/dense_evolution/simulator.py +0 -470
  26. Dense_Evolution_Project/dense_evolution/stress_test.py +0 -76
  27. Dense_Evolution_Project/dist/dense_evolution-8.1.6-py3-none-any.whl +0 -0
  28. Dense_Evolution_Project/dist/dense_evolution-8.1.6.tar.gz +0 -3
  29. Dense_Evolution_Project/license.md +0 -58
  30. Dense_Evolution_Project/pyproject.toml +0 -83
  31. Dense_Evolution_Project/test_dense_evolution.py +0 -467
Dense_Evolution_Project/.github/workflows/ci.yml DELETED
@@ -1,45 +0,0 @@
1
- name: CI — Dense Evolution Tests
2
-
3
- on:
4
- push:
5
- branches: [main]
6
- pull_request:
7
- branches: [main]
8
-
9
- jobs:
10
- test:
11
- name: Python ${{ matrix.python-version }}
12
- runs-on: ubuntu-latest
13
-
14
- strategy:
15
- fail-fast: false # Impedisce che il fallimento di una versione di Python blocchi le altre
16
- matrix:
17
- python-version: ["3.10", "3.11", "3.12"]
18
-
19
- steps:
20
- - name: Checkout repository
21
- uses: actions/checkout@v4
22
-
23
- - name: Set up Python ${{ matrix.python-version }}
24
- uses: actions/setup-python@v5
25
- with:
26
- python-version: ${{ matrix.python-version }}
27
-
28
- - name: Install dependencies
29
- run: |
30
- python -m pip install --upgrade pip
31
- pip install pytest numpy scipy pandas matplotlib psutil ipython
32
- pip install setuptools pytest numpy scipy pandas matplotlib psutil ipython jax jaxlib
33
- pip install . --no-deps # Installa il pacchetto locale
34
-
35
- - name: Run test suite
36
- run: |
37
- pytest test_dense_evolution.py -v --tb=short
38
- pytest test_dense_evolution.py -v --tb=short --junitxml=pytest-results.xml
39
-
40
- - name: Upload test results on failure
41
- if: failure()
42
- uses: actions/upload-artifact@v4
43
- with:
44
- name: pytest-results-${{ matrix.python-version }}
45
- path: pytest-results.xml
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/.gitignore DELETED
@@ -1,15 +0,0 @@
1
- # Ignora tutti i file di log generati dalle simulazioni
2
- *.log
3
-
4
- # Ignora i file temporanei e le cache di Python
5
- __pycache__/
6
- *.pyc
7
- *.pyo
8
- *.pyd
9
- .pytest_cache/
10
-
11
- # Ignora file di sistema invisibili di Windows
12
- Thumbs.db
13
- desktop.ini
14
- dist/
15
- *.egg-info/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/.pytest_cache/.gitignore DELETED
@@ -1,2 +0,0 @@
1
- # Created by pytest automatically.
2
- *
 
 
 
Dense_Evolution_Project/.pytest_cache/CACHEDIR.TAG DELETED
@@ -1,4 +0,0 @@
1
- Signature: 8a477f597d28d172789f06886806bc55
2
- # This file is a cache directory tag created by pytest.
3
- # For information about cache directory tags, see:
4
- # https://bford.info/cachedir/spec.html
 
 
 
 
 
Dense_Evolution_Project/.pytest_cache/README.md DELETED
@@ -1,8 +0,0 @@
1
- # pytest cache directory #
2
-
3
- This directory contains data from the pytest's cache plugin,
4
- which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
5
-
6
- **Do not** commit this to version control.
7
-
8
- See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/.pytest_cache/v/cache/nodeids DELETED
@@ -1 +0,0 @@
1
- []
 
 
Dense_Evolution_Project/README.md DELETED
@@ -1,322 +0,0 @@
1
- ```
2
- ██████╗ ███████╗███╗ ██╗███████╗███████╗
3
- ██╔══██╗██╔════╝████╗ ██║██╔════╝██╔════╝
4
- ██║ ██║█████╗ ██╔██╗ ██║███████╗█████╗
5
- ██║ ██║██╔══╝ ██║╚██╗██║╚════██║██╔══╝
6
- ██████╔╝███████╗██║ ╚████║███████║███████╗
7
- ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝╚══════╝
8
- ███████╗██╗ ██╗██████╗ ██╗ ██╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗
9
- ██╔════╝██║ ██║██╔══██╗██║ ██║ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║
10
- █████╗ ██║ ██║██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██╔██╗ ██║
11
- ██╔══╝ ╚██╗ ██╔╝██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██║╚██╗██║
12
- ███████╗ ╚████╔╝ ██████╔╝███████╗╚██████╔╝ ██║ ██║╚██████╔╝██║ ╚████║
13
- ╚══════╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
14
- ```
15
-
16
-
17
- **Dense Statevector Quantum Simulator · JAX XLA · NISQ · VQE · QML**
18
-
19
- [![CI](https://github.com/tatopenn-cell/Dense-Evolution/actions/workflows/ci.yml/badge.svg)](https://github.com/tatopenn-cell/Dense-Evolution/actions/workflows/ci.yml)
20
- [![PyPI](https://img.shields.io/pypi/v/dense-evolution?style=flat-square&color=00e5ff)](https://pypi.org/project/dense-evolution/)
21
- [![Python](https://img.shields.io/badge/Python-3.9+-blue?style=flat-square&logo=python&logoColor=white)](https://www.python.org/)
22
- [![License](https://img.shields.io/badge/License-BSL_1.1-orange?style=flat-square)](LICENSE.md)
23
- [![Build](https://img.shields.io/badge/Build-Passing-00ff9d?style=flat-square)](https://github.com/tatopenn-cell/Dense-Evolution/actions)
24
- [![Cross-Validation CI](https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/actions/workflows/ci.yml/badge.svg)](https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/actions/workflows/ci.yml)
25
- =======
26
-
27
- **Dense Statevector Quantum Simulator · JAX XLA · NISQ · VQE · QML**
28
-
29
- ---
30
-
31
- ## ▍ What It Is
32
-
33
- **Dense Evolution** is a high-performance statevector simulator engineered for deep NISQ circuits, VQE pipelines, and QML workloads. It eliminates Kronecker product overhead entirely via stride-sliced linear kernel fusion compiled through JAX XLA — keeping memory at the theoretical minimum of `2ⁿ × 16 bytes`.
34
-
35
- The integrated `dash.py` dashboard provides live ipywidgets telemetry across 6 quantum observables per simulation run, directly inside Google Colab or Jupyter.
36
-
37
- ---
38
-
39
- ## ▍ Install
40
-
41
- ```bash
42
- pip install dense-evolution
43
-
44
- # full stack: JAX · GPU · dashboard
45
- pip install dense-evolution[full]
46
-
47
- # development
48
- git clone https://github.com/tatopenn-cell/Dense-Evolution.git
49
- cd Dense-Evolution && pip install -e .[full]
50
- ```
51
-
52
- **Google Colab (3 lines):**
53
-
54
- ```python
55
- !git clone https://github.com/tatopenn-cell/Dense-Evolution.git
56
- %cd Dense-Evolution
57
- !pip install -e .
58
- ```
59
-
60
- ---
61
-
62
- ## ▍ Quick Start
63
-
64
- ```python
65
- from dense_evolution import DenseSVSimulator, QASMParser
66
-
67
- # parse any OpenQASM 2.0 string
68
- qasm = """
69
- OPENQASM 2.0;
70
- include "qelib1.inc";
71
- qreg q[3];
72
- h q[0];
73
- cx q[0], q[1];
74
- cx q[1], q[2];
75
- """
76
-
77
- parser = QASMParser()
78
- circuit = parser.parse(qasm)
79
-
80
- sim = DenseSVSimulator(n_qubits=3)
81
- sim.run_circuit_jit_beast_mode(circuit.ops)
82
- ```
83
-
84
- ---
85
-
86
- **Dashboard (Colab / Jupyter):**
87
-
88
- ```python
89
- import dash
90
- from IPython.display import display, clear_output
91
-
92
- clear_output()
93
- display(dash.dashboard_unificata)
94
- ```
95
-
96
- ---
97
-
98
- ## ▍ Architecture
99
-
100
- ```
101
- dense_evolution/
102
- ├── registry.py hardware detection · JAX / CuPy / NumPy capability flags
103
- ├── gates.py GATES{} · PARAMETRIC_GATES{} · GATE_IDS{}
104
- ├── noise_model.py Kraus channels · stochastic trajectory engine
105
- ├── parser.py QASMParser · QASMCircuit · OpenQASM 2.0 / 3.0
106
- ├── compiler.py _apply_gate_fast_step (jit) · _compile_and_run_circuit_jit
107
- ├── simulator.py DenseSVSimulator · vmap batch VQE · chunked execution
108
- └── dash.py ipywidgets dashboard · VQE engine · MD simulation
109
- ```
110
-
111
- **Data flow per run:**
112
- ```
113
- ▶ Run
114
- └─ core_calcolo_quantistico() parse → JIT execute → apply noise
115
- ├─ ottimizza_vqe() Hellmann-Feynman AD → ADAM → df_vqe_telemetry
116
- ├─ run_md_simulation_dummy() QM/MM dynamics → df_md_telemetry + Pearson matrix
117
- └─ build_panel_*(res) matplotlib figure → display()
118
- ```
119
-
120
- ---
121
-
122
- ## ▍ Core Features
123
-
124
- | Feature | Detail |
125
- |---|---|
126
- | **Linear Kernel Fusion** | Stride-sliced tensor ops via JAX XLA — zero Kronecker matrices |
127
- | **Circuit Chunking** | Fixed-size JIT blocks eliminate tracer overhead on 1000+ gate circuits |
128
- | **Kraus Noise Channels** | `depolarizing` `amplitude_damping` `phase_damping` `bitflip` `combined` — stochastic, O(2ⁿ) cost |
129
- | **VQE + ADAM** | Hellmann-Feynman gradient via JAX AD · positional parameter injection into any QASM 2.0 |
130
- | **vmap Batch Sweep** | `run_parametric_batch_jit()` evaluates full parameter grids in one JIT call |
131
- | **Backend Agnostic** | NumPy CPU · JAX XLA CPU/TPU · CuPy CUDA — runtime selection, zero code changes |
132
- | **Live Dashboard** | 8-panel ipywidgets telemetry: probability, VQE energy, entropy, purity, gradient, noise, θ-correction, Pearson heatmap |
133
-
134
- ---
135
-
136
- ## ▍ Benchmarks
137
-
138
- > Measured on Google Colab Free Tier (CPU runtime)
139
-
140
- | Metric | Value |
141
- |---|---|
142
- | Numerical drift (30-layer Ansatz, 1360 gates) | `Δ = 1.11 × 10⁻¹⁶` |
143
- | Memory footprint @ 20q | `32 MB` (float64) · `16 MB` (float32) |
144
- | JIT compile overhead (first run) | `< 400 ms` |
145
- | Gate throughput after warm-up | `> 10⁶ gates/s` (CPU) |
146
- | Maximum tested qubits (Colab Free) | `24q` stable · `33q` high-RAM runtime |
147
-
148
- ---
149
-
150
- ## ▍ Dashboard Panels
151
-
152
- | Panel | Contents |
153
- |---|---|
154
- | **Overview** | R0 header · R1 P(\|n⟩) histogram + Top-12 states · R2 wavefunction helix 3D + metrics table · R3 noise analysis + shot histogram · R4–R6 VQE telemetry × 6 · R7 Pearson heatmap |
155
- | **Fisica Stato** | Bloch projection · Schmidt rank · coherence vector |
156
- | **Mosaico 1008q** | 2D probability density map up to 1008 qubits |
157
- | **VQE Results** | 6-subplot telemetry: energy convergence, entropy, purity, ‖∇L‖, noise factor, θ-correction |
158
- | **MD Results** | 6-subplot MD telemetry + masked Pearson correlation heatmap |
159
- | **Performance** | Gate throughput · JIT compile time · RAM usage |
160
-
161
- ---
162
-
163
-
164
- ## ▍ Circuit Library (30+ presets)
165
-
166
- All circuits are stored as OpenQASM 2.0 strings in `QASM_LIBRARY`.
167
-
168
- **Standard** — Bell Φ⁺, QFT 4q/8q, Toffoli, Adder 2-bit, Deutsch-Jozsa, Bernstein-Vazirani
169
- **Algorithms** — Grover 3q/4q, Simon 4q, Shor 15, HHL, QAOA Max-Cut 4q, QPE 5q, Quantum Walk, Teleportation, BB84
170
-
171
- ---
172
-
173
- ## ▍ VQE Engine
174
-
175
- **Positional parameter injection** — `QASMParser` tokenizes all literals to `0.0` for JIT speed. VQE recovers parameters by:
176
- 1. counting parametric gates (`rx ry rz p u1 cp crz`) → `n_params`
177
- 2. initializing `θ ∈ ℝⁿ` uniform in `[−π, π]`
178
- 3. injecting `θ[i]` sequentially by gate order in the AST via `risolvi_qasm()`
179
-
180
- Compatible with any custom OpenQASM 2.0 string without pre-labelling.
181
-
182
- **Gradient & update rule:**
183
-
184
- $$\frac{\partial E}{\partial \theta_i} = \langle\psi(\theta)|\,\frac{\partial H}{\partial \theta_i}\,|\psi(\theta)\rangle \qquad \theta \leftarrow \theta - \frac{\alpha\,\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon}$$
185
-
186
- **Telemetry columns** (→ `df_vqe_telemetry`):
187
-
188
- | Column | Unit | Description |
189
- |---|---|---|
190
- | `VQE_Energy` | Ha | ⟨ψ\|H\|ψ⟩ |
191
- | `Entropy` | bit | −Tr(ρ log₂ ρ) |
192
- | `Purity` | — | Tr(ρ²) ∈ [1/d, 1] |
193
- | `Gradient` | — | ‖∇L‖ — barren plateau detection |
194
- | `Noise_Factor` | — | fidelity-derived noise proxy |
195
- | `Theta_Correction` | rad | ADAM step norm |
196
-
197
- ---
198
-
199
- ## ▍ Hamiltonian Library
200
-
201
- Auto-filtered by qubit count to prevent shape mismatch.
202
-
203
- | Molecule | Qubits | Bond length | E₀ (Ha) |
204
- |---|:---:|:---:|:---:|
205
- | H₂ | 2 | 0.74 Å | −1.13 |
206
- | H₃⁺ | 3 | 0.85 Å | −1.28 |
207
- | LiH | 4 | 1.40 Å | −2.31 |
208
- | H₂O | 5 | 0.96 Å | −4.12 |
209
-
210
- Custom: JSON array of diagonal eigenvalues, length `2^n_qubits`.
211
-
212
- ---
213
-
214
- ## ▍ Noise Models
215
-
216
- All channels applied as post-circuit Kraus operations on the full statevector.
217
-
218
- | Model | Kraus operators | Physical process |
219
- |---|---|---|
220
- | `ideal` | I | noiseless |
221
- | `depolarizing` | {√(1−p)I, √(p/3)X,Y,Z} | isotropic Pauli error |
222
- | `amplitude_damping` | {K₀, K₁} | T₁ energy relaxation |
223
- | `phase_damping` | {K₀, K₁} | T₂ dephasing |
224
- | `bitflip` | {√(1−p)I, √p·X} | bit flip σₓ |
225
- | `combined` | depolarizing(p/2) ∘ amp_damp(p/3) | worst-case NISQ |
226
-
227
- Fidelity: Bhattacharyya `F = Σᵢ √(pᵢqᵢ)` and TVD `= ½Σᵢ|pᵢ−qᵢ|` computed on every noisy run.
228
-
229
- ---
230
-
231
- ## ▍ Mitigation & Predictive Healing Models
232
-
233
- Active error tracking and stabilization parameters integrated natively into the simulation runtime.
234
-
235
-
236
- | Model | Variables / Operators | Physical process |
237
- |---|---|---|
238
- | `dephasing_tracking` | Δ_pre_emp ∘ Σ | predictive deviation vs ideal eigenstate |
239
- | `kappa_stabilization` | κ-strength routine | proactive statevector profile shielding |
240
- | `richardson_integration` | {λ₁ = 1.0, λ₂ = 2.0} | dual-point zero-noise trajectory approximation |
241
-
242
- Compilation: Full **XLA Kernel Fusion** via `@jax.jit` for mass-parallelized trajectory sweeps (< 1.0s).
243
-
244
- ---
245
-
246
- ## ▍ Chunk Engines (Anti-OOM)
247
-
248
- All operations parcellized dynamically using dual-stage longitudinal and transverse architectural shields.
249
-
250
-
251
- | Model | Execution parameters | Physical process |
252
- |---|---|---|
253
- | `chunk1` | `circuit_slice = target[i : i + chunk_size]` | instruction loop-unroll kill |
254
- | `chunk2` | `alloc_dim = 2 ** chunk_size_bits` | transverse Hilbert slicing |
255
- | `Chunk` | `sim = Chunk(n_qubits)` | hardware-adaptive anti-OOM |
256
-
257
- Performance: Hard-locked at `15%` max RAM available with **-86.47% Latency Collapse** via global static JIT cache injection.
258
-
259
- ---
260
-
261
- ### 🪐 [SHIELD::OOM] // Chunk Engine
262
-
263
- ```python
264
- from dense_evolution import Chunk
265
-
266
- sim = Chunk(27)
267
- circuit_ops = [['h', i] for i in range(27)]
268
- sim.run_chunk(circuit_ops, 500)
269
- ```
270
-
271
- ### 🧬 [SYS::ARCH]
272
- * `chunk1` -> Slices gate arrays into windows to kill JAX compilation stalls.
273
- * `chunk2` -> Slices raw Hilbert statevectors into isolated RAM allocations.
274
-
275
- ### ⚡ [BENCH::VERDICT]
276
- * **Qubits**: 27 Qubits // 134M States.
277
- * **Memory**: Hard-locked at 15% RAM threshold.
278
- * **Speed**: **-86.47% Latency Collapse** via Static JIT.
279
-
280
- \---
281
-
282
- ### Anti-OOM Chunk Engine vs PennyLane — Windows CPU (8 GB RAM)
283
-
284
- > Dense Evolution maintains constant ~2 GB RAM at any qubit count via dynamic chunking.
285
- > PennyLane allocates the full statevector — OOM beyond 26q.
286
-
287
-
288
- | Qubits | Hilbert Space | PennyLane | PennyLane RAM | Dense Evolution | Dense RAM | Chunk Geometry |
289
- |:------:|:-------------:|:---------:|:-------------:|:---------------:|:---------:|:--------------:|
290
- | 24 | 16,777,216 | ✅ SUCCESS | 307 MB | ✅ SUCCESS | 516 MB | 1× (2²⁷) |
291
- | 26 | 67,108,864 | ✅ SUCCESS | 1,074 MB | ✅ SUCCESS | 2,050 MB | 1× (2²⁷) |
292
- | 28 | 268,435,456 | ❌ OOM | — | ✅ SUCCESS | 2,050 MB | 2× (2²⁷) |
293
- | 30 | 1,073,741,824 | ❌ OOM | — | ✅ SUCCESS | 2,048 MB | 8× (2²⁷) |
294
- | 32 | 4,294,967,296 | ❌ OOM | — | ✅ SUCCESS | 2,048 MB | 32× (2²⁷) |
295
-
296
- ---
297
-
298
- ## ▍ Changelog
299
-
300
- ### v8.1.5
301
- - `chunk.py` — `SafeMemoryGuard` class: hard block at configurable free-RAM threshold (default 15%), soft warning at 2× threshold, `gc.collect()` before every check
302
- - `chunk.py` — `Chunk` no longer subclasses `DenseSVSimulator`; inner simulator allocated at `safe_qubits` only — eliminates `RESOURCE_EXHAUSTED` on 28q–34q circuits
303
- - `chunk.py` — `CircuitChunker.split_circuit` RAM-checks every gate-slice before dispatch
304
- - `chunk.py` — `MemoryChunker` attributes (`num_chunks`, `chunk_size_bits`, `dtype`) forwarded as `@property` on `Chunk` for benchmark compatibility
305
-
306
- ### v8.1.6
307
- - Modular package structure (`dense_evolution/` directory)
308
- ## ▍ License
309
-
310
- **Business Source License 1.1** — converts automatically to **Apache 2.0** on **1 June 2029**.
311
-
312
- - Non-commercial use: unrestricted
313
- - Commercial use: ≤ 24 allocated qubits · ≤ 1000 circuits/day · ≤ 10,000 shots/circuit
314
- - Attribution required on all copies: `© 2026 Salvatore Pennacchio <jtatopenn@libero.it> — Dense Evolution`
315
-
316
- Full text: [LICENSE.md](LICENSE.md)
317
-
318
- ---
319
-
320
- <div align="center">
321
- <sub>© 2026 Salvatore Pennacchio — Dense Evolution</sub>
322
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dash.py DELETED
The diff for this file is too large to render. See raw diff
 
Dense_Evolution_Project/dense_evolution.egg-info/PKG-INFO DELETED
@@ -1,366 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: dense-evolution
3
- Version: 8.1.6
4
- Summary: Micro-optimized High-Performance NISQ Statevector Quantum Circuit Simulator (Hardware-Adaptive Integration of Native NumPy, CUDA-Accelerated CuPy, and Linear Kernel Fusion via JAX JIT/XLA Compilation)
5
- Author-email: Salvatore Pennacchio <jtatopenn@libero.it>
6
- License: Business Source License 1.1
7
- Project-URL: Homepage, https://github.com/tatopenn-cell/Dense-Evolution
8
- Project-URL: Documentation, https://github.com/tatopenn-cell/Dense-Evolution/blob/main/README.md
9
- Project-URL: Repository, https://github.com/tatopenn-cell/Dense-Evolution
10
- Project-URL: Bug Tracker, https://github.com/tatopenn-cell/Dense-Evolution/issues
11
- Keywords: quantum-computing,quantum-simulation,statevector,jax,cupy,cuda-acceleration,openqasm,nisq-noise,hpc,linear-kernel-fusion,dashboard,visualization
12
- Classifier: Development Status :: 5 - Production/Stable
13
- Classifier: Intended Audience :: Science/Research
14
- Classifier: Intended Audience :: Developers
15
- Classifier: License :: Other/Proprietary License
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.9
18
- Classifier: Programming Language :: Python :: 3.10
19
- Classifier: Programming Language :: Python :: 3.11
20
- Classifier: Programming Language :: Python :: 3.12
21
- Classifier: Topic :: Scientific/Engineering :: Physics
22
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
- Requires-Python: >=3.9
24
- Description-Content-Type: text/markdown
25
- License-File: license.md
26
- Requires-Dist: numpy>=1.22.0
27
- Requires-Dist: matplotlib>=3.5.0
28
- Requires-Dist: psutil>=5.9.0
29
- Provides-Extra: jax
30
- Requires-Dist: jax>=0.4.0; extra == "jax"
31
- Requires-Dist: jaxlib>=0.4.0; extra == "jax"
32
- Provides-Extra: gpu
33
- Requires-Dist: cupy-cuda12x>=12.0.0; extra == "gpu"
34
- Provides-Extra: dashboard
35
- Requires-Dist: dash>=2.0.0; extra == "dashboard"
36
- Requires-Dist: plotly>=5.0.0; extra == "dashboard"
37
- Provides-Extra: full
38
- Requires-Dist: jax>=0.4.0; extra == "full"
39
- Requires-Dist: jaxlib>=0.4.0; extra == "full"
40
- Requires-Dist: cupy-cuda12x>=12.0.0; extra == "full"
41
- Requires-Dist: dash>=2.0.0; extra == "full"
42
- Requires-Dist: plotly>=5.0.0; extra == "full"
43
- Dynamic: license-file
44
-
45
- ```
46
- ██████╗ ███████╗███╗ ██╗███████╗███████╗
47
- ██╔══██╗██╔════╝████╗ ██║██╔════╝██╔════╝
48
- ██║ ██║█████╗ ██╔██╗ ██║███████╗█████╗
49
- ██║ ██║██╔══╝ ██║╚██╗██║╚════██║██╔══╝
50
- ██████╔╝███████╗██║ ╚████║███████║███████╗
51
- ╚═════╝ ╚══════╝╚═╝ ╚═══╝╚══════╝╚══════╝
52
- ███████╗██╗ ██╗██████╗ ██╗ ██╗ ██╗████████╗██╗ ██████╗ ███╗ ██╗
53
- ██╔════╝██║ ██║██╔══██╗██║ ██║ ██║╚══██╔══╝██║██╔═══██╗████╗ ██║
54
- █████╗ ██║ ██║██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██╔██╗ ██║
55
- ██╔══╝ ╚██╗ ██╔╝██║ ██║██║ ██║ ██║ ██║ ██║██║ ██║██║╚██╗██║
56
- ███████╗ ╚████╔╝ ██████╔╝███████╗╚██████╔╝ ██║ ██║╚██████╔╝██║ ╚████║
57
- ╚══════╝ ╚═══╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
58
- ```
59
-
60
-
61
- **Dense Statevector Quantum Simulator · JAX XLA · NISQ · VQE · QML**
62
-
63
- [![CI](https://github.com/tatopenn-cell/Dense-Evolution/actions/workflows/ci.yml/badge.svg)](https://github.com/tatopenn-cell/Dense-Evolution/actions/workflows/ci.yml)
64
- [![PyPI](https://img.shields.io/pypi/v/dense-evolution?style=flat-square&color=00e5ff)](https://pypi.org/project/dense-evolution/)
65
- [![Python](https://img.shields.io/badge/Python-3.9+-blue?style=flat-square&logo=python&logoColor=white)](https://www.python.org/)
66
- [![License](https://img.shields.io/badge/License-BSL_1.1-orange?style=flat-square)](LICENSE.md)
67
- [![Build](https://img.shields.io/badge/Build-Passing-00ff9d?style=flat-square)](https://github.com/tatopenn-cell/Dense-Evolution/actions)
68
- [![Cross-Validation CI](https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/actions/workflows/ci.yml/badge.svg)](https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/actions/workflows/ci.yml)
69
- =======
70
-
71
- **Dense Statevector Quantum Simulator · JAX XLA · NISQ · VQE · QML**
72
-
73
- ---
74
-
75
- ## ▍ What It Is
76
-
77
- **Dense Evolution** is a high-performance statevector simulator engineered for deep NISQ circuits, VQE pipelines, and QML workloads. It eliminates Kronecker product overhead entirely via stride-sliced linear kernel fusion compiled through JAX XLA — keeping memory at the theoretical minimum of `2ⁿ × 16 bytes`.
78
-
79
- The integrated `dash.py` dashboard provides live ipywidgets telemetry across 6 quantum observables per simulation run, directly inside Google Colab or Jupyter.
80
-
81
- ---
82
-
83
- ## ▍ Install
84
-
85
- ```bash
86
- pip install dense-evolution
87
-
88
- # full stack: JAX · GPU · dashboard
89
- pip install dense-evolution[full]
90
-
91
- # development
92
- git clone https://github.com/tatopenn-cell/Dense-Evolution.git
93
- cd Dense-Evolution && pip install -e .[full]
94
- ```
95
-
96
- **Google Colab (3 lines):**
97
-
98
- ```python
99
- !git clone https://github.com/tatopenn-cell/Dense-Evolution.git
100
- %cd Dense-Evolution
101
- !pip install -e .
102
- ```
103
-
104
- ---
105
-
106
- ## ▍ Quick Start
107
-
108
- ```python
109
- from dense_evolution import DenseSVSimulator, QASMParser
110
-
111
- # parse any OpenQASM 2.0 string
112
- qasm = """
113
- OPENQASM 2.0;
114
- include "qelib1.inc";
115
- qreg q[3];
116
- h q[0];
117
- cx q[0], q[1];
118
- cx q[1], q[2];
119
- """
120
-
121
- parser = QASMParser()
122
- circuit = parser.parse(qasm)
123
-
124
- sim = DenseSVSimulator(n_qubits=3)
125
- sim.run_circuit_jit_beast_mode(circuit.ops)
126
- ```
127
-
128
- ---
129
-
130
- **Dashboard (Colab / Jupyter):**
131
-
132
- ```python
133
- import dash
134
- from IPython.display import display, clear_output
135
-
136
- clear_output()
137
- display(dash.dashboard_unificata)
138
- ```
139
-
140
- ---
141
-
142
- ## ▍ Architecture
143
-
144
- ```
145
- dense_evolution/
146
- ├── registry.py hardware detection · JAX / CuPy / NumPy capability flags
147
- ├── gates.py GATES{} · PARAMETRIC_GATES{} · GATE_IDS{}
148
- ├── noise_model.py Kraus channels · stochastic trajectory engine
149
- ├── parser.py QASMParser · QASMCircuit · OpenQASM 2.0 / 3.0
150
- ├── compiler.py _apply_gate_fast_step (jit) · _compile_and_run_circuit_jit
151
- ├── simulator.py DenseSVSimulator · vmap batch VQE · chunked execution
152
- └── dash.py ipywidgets dashboard · VQE engine · MD simulation
153
- ```
154
-
155
- **Data flow per run:**
156
- ```
157
- ▶ Run
158
- └─ core_calcolo_quantistico() parse → JIT execute → apply noise
159
- ├─ ottimizza_vqe() Hellmann-Feynman AD → ADAM → df_vqe_telemetry
160
- ├─ run_md_simulation_dummy() QM/MM dynamics → df_md_telemetry + Pearson matrix
161
- └─ build_panel_*(res) matplotlib figure → display()
162
- ```
163
-
164
- ---
165
-
166
- ## ▍ Core Features
167
-
168
- | Feature | Detail |
169
- |---|---|
170
- | **Linear Kernel Fusion** | Stride-sliced tensor ops via JAX XLA — zero Kronecker matrices |
171
- | **Circuit Chunking** | Fixed-size JIT blocks eliminate tracer overhead on 1000+ gate circuits |
172
- | **Kraus Noise Channels** | `depolarizing` `amplitude_damping` `phase_damping` `bitflip` `combined` — stochastic, O(2ⁿ) cost |
173
- | **VQE + ADAM** | Hellmann-Feynman gradient via JAX AD · positional parameter injection into any QASM 2.0 |
174
- | **vmap Batch Sweep** | `run_parametric_batch_jit()` evaluates full parameter grids in one JIT call |
175
- | **Backend Agnostic** | NumPy CPU · JAX XLA CPU/TPU · CuPy CUDA — runtime selection, zero code changes |
176
- | **Live Dashboard** | 8-panel ipywidgets telemetry: probability, VQE energy, entropy, purity, gradient, noise, θ-correction, Pearson heatmap |
177
-
178
- ---
179
-
180
- ## ▍ Benchmarks
181
-
182
- > Measured on Google Colab Free Tier (CPU runtime)
183
-
184
- | Metric | Value |
185
- |---|---|
186
- | Numerical drift (30-layer Ansatz, 1360 gates) | `Δ = 1.11 × 10⁻¹⁶` |
187
- | Memory footprint @ 20q | `32 MB` (float64) · `16 MB` (float32) |
188
- | JIT compile overhead (first run) | `< 400 ms` |
189
- | Gate throughput after warm-up | `> 10⁶ gates/s` (CPU) |
190
- | Maximum tested qubits (Colab Free) | `24q` stable · `33q` high-RAM runtime |
191
-
192
- ---
193
-
194
- ## ▍ Dashboard Panels
195
-
196
- | Panel | Contents |
197
- |---|---|
198
- | **Overview** | R0 header · R1 P(\|n⟩) histogram + Top-12 states · R2 wavefunction helix 3D + metrics table · R3 noise analysis + shot histogram · R4–R6 VQE telemetry × 6 · R7 Pearson heatmap |
199
- | **Fisica Stato** | Bloch projection · Schmidt rank · coherence vector |
200
- | **Mosaico 1008q** | 2D probability density map up to 1008 qubits |
201
- | **VQE Results** | 6-subplot telemetry: energy convergence, entropy, purity, ‖∇L‖, noise factor, θ-correction |
202
- | **MD Results** | 6-subplot MD telemetry + masked Pearson correlation heatmap |
203
- | **Performance** | Gate throughput · JIT compile time · RAM usage |
204
-
205
- ---
206
-
207
-
208
- ## ▍ Circuit Library (30+ presets)
209
-
210
- All circuits are stored as OpenQASM 2.0 strings in `QASM_LIBRARY`.
211
-
212
- **Standard** — Bell Φ⁺, QFT 4q/8q, Toffoli, Adder 2-bit, Deutsch-Jozsa, Bernstein-Vazirani
213
- **Algorithms** — Grover 3q/4q, Simon 4q, Shor 15, HHL, QAOA Max-Cut 4q, QPE 5q, Quantum Walk, Teleportation, BB84
214
-
215
- ---
216
-
217
- ## ▍ VQE Engine
218
-
219
- **Positional parameter injection** — `QASMParser` tokenizes all literals to `0.0` for JIT speed. VQE recovers parameters by:
220
- 1. counting parametric gates (`rx ry rz p u1 cp crz`) → `n_params`
221
- 2. initializing `θ ∈ ℝⁿ` uniform in `[−π, π]`
222
- 3. injecting `θ[i]` sequentially by gate order in the AST via `risolvi_qasm()`
223
-
224
- Compatible with any custom OpenQASM 2.0 string without pre-labelling.
225
-
226
- **Gradient & update rule:**
227
-
228
- $$\frac{\partial E}{\partial \theta_i} = \langle\psi(\theta)|\,\frac{\partial H}{\partial \theta_i}\,|\psi(\theta)\rangle \qquad \theta \leftarrow \theta - \frac{\alpha\,\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon}$$
229
-
230
- **Telemetry columns** (→ `df_vqe_telemetry`):
231
-
232
- | Column | Unit | Description |
233
- |---|---|---|
234
- | `VQE_Energy` | Ha | ⟨ψ\|H\|ψ⟩ |
235
- | `Entropy` | bit | −Tr(ρ log₂ ρ) |
236
- | `Purity` | — | Tr(ρ²) ∈ [1/d, 1] |
237
- | `Gradient` | — | ‖∇L‖ — barren plateau detection |
238
- | `Noise_Factor` | — | fidelity-derived noise proxy |
239
- | `Theta_Correction` | rad | ADAM step norm |
240
-
241
- ---
242
-
243
- ## ▍ Hamiltonian Library
244
-
245
- Auto-filtered by qubit count to prevent shape mismatch.
246
-
247
- | Molecule | Qubits | Bond length | E₀ (Ha) |
248
- |---|:---:|:---:|:---:|
249
- | H₂ | 2 | 0.74 Å | −1.13 |
250
- | H₃⁺ | 3 | 0.85 Å | −1.28 |
251
- | LiH | 4 | 1.40 Å | −2.31 |
252
- | H₂O | 5 | 0.96 Å | −4.12 |
253
-
254
- Custom: JSON array of diagonal eigenvalues, length `2^n_qubits`.
255
-
256
- ---
257
-
258
- ## ▍ Noise Models
259
-
260
- All channels applied as post-circuit Kraus operations on the full statevector.
261
-
262
- | Model | Kraus operators | Physical process |
263
- |---|---|---|
264
- | `ideal` | I | noiseless |
265
- | `depolarizing` | {√(1−p)I, √(p/3)X,Y,Z} | isotropic Pauli error |
266
- | `amplitude_damping` | {K₀, K₁} | T₁ energy relaxation |
267
- | `phase_damping` | {K₀, K₁} | T₂ dephasing |
268
- | `bitflip` | {√(1−p)I, √p·X} | bit flip σₓ |
269
- | `combined` | depolarizing(p/2) ∘ amp_damp(p/3) | worst-case NISQ |
270
-
271
- Fidelity: Bhattacharyya `F = Σᵢ √(pᵢqᵢ)` and TVD `= ½Σᵢ|pᵢ−qᵢ|` computed on every noisy run.
272
-
273
- ---
274
-
275
- ## ▍ Mitigation & Predictive Healing Models
276
-
277
- Active error tracking and stabilization parameters integrated natively into the simulation runtime.
278
-
279
-
280
- | Model | Variables / Operators | Physical process |
281
- |---|---|---|
282
- | `dephasing_tracking` | Δ_pre_emp ∘ Σ | predictive deviation vs ideal eigenstate |
283
- | `kappa_stabilization` | κ-strength routine | proactive statevector profile shielding |
284
- | `richardson_integration` | {λ₁ = 1.0, λ₂ = 2.0} | dual-point zero-noise trajectory approximation |
285
-
286
- Compilation: Full **XLA Kernel Fusion** via `@jax.jit` for mass-parallelized trajectory sweeps (< 1.0s).
287
-
288
- ---
289
-
290
- ## ▍ Chunk Engines (Anti-OOM)
291
-
292
- All operations parcellized dynamically using dual-stage longitudinal and transverse architectural shields.
293
-
294
-
295
- | Model | Execution parameters | Physical process |
296
- |---|---|---|
297
- | `chunk1` | `circuit_slice = target[i : i + chunk_size]` | instruction loop-unroll kill |
298
- | `chunk2` | `alloc_dim = 2 ** chunk_size_bits` | transverse Hilbert slicing |
299
- | `Chunk` | `sim = Chunk(n_qubits)` | hardware-adaptive anti-OOM |
300
-
301
- Performance: Hard-locked at `15%` max RAM available with **-86.47% Latency Collapse** via global static JIT cache injection.
302
-
303
- ---
304
-
305
- ### 🪐 [SHIELD::OOM] // Chunk Engine
306
-
307
- ```python
308
- from dense_evolution import Chunk
309
-
310
- sim = Chunk(27)
311
- circuit_ops = [['h', i] for i in range(27)]
312
- sim.run_chunk(circuit_ops, 500)
313
- ```
314
-
315
- ### 🧬 [SYS::ARCH]
316
- * `chunk1` -> Slices gate arrays into windows to kill JAX compilation stalls.
317
- * `chunk2` -> Slices raw Hilbert statevectors into isolated RAM allocations.
318
-
319
- ### ⚡ [BENCH::VERDICT]
320
- * **Qubits**: 27 Qubits // 134M States.
321
- * **Memory**: Hard-locked at 15% RAM threshold.
322
- * **Speed**: **-86.47% Latency Collapse** via Static JIT.
323
-
324
- \---
325
-
326
- ### Anti-OOM Chunk Engine vs PennyLane — Windows CPU (8 GB RAM)
327
-
328
- > Dense Evolution maintains constant ~2 GB RAM at any qubit count via dynamic chunking.
329
- > PennyLane allocates the full statevector — OOM beyond 26q.
330
-
331
-
332
- | Qubits | Hilbert Space | PennyLane | PennyLane RAM | Dense Evolution | Dense RAM | Chunk Geometry |
333
- |:------:|:-------------:|:---------:|:-------------:|:---------------:|:---------:|:--------------:|
334
- | 24 | 16,777,216 | ✅ SUCCESS | 307 MB | ✅ SUCCESS | 516 MB | 1× (2²⁷) |
335
- | 26 | 67,108,864 | ✅ SUCCESS | 1,074 MB | ✅ SUCCESS | 2,050 MB | 1× (2²⁷) |
336
- | 28 | 268,435,456 | ❌ OOM | — | ✅ SUCCESS | 2,050 MB | 2× (2²⁷) |
337
- | 30 | 1,073,741,824 | ❌ OOM | — | ✅ SUCCESS | 2,048 MB | 8× (2²⁷) |
338
- | 32 | 4,294,967,296 | ❌ OOM | — | ✅ SUCCESS | 2,048 MB | 32× (2²⁷) |
339
-
340
- ---
341
-
342
- ## ▍ Changelog
343
-
344
- ### v8.1.5
345
- - `chunk.py` — `SafeMemoryGuard` class: hard block at configurable free-RAM threshold (default 15%), soft warning at 2× threshold, `gc.collect()` before every check
346
- - `chunk.py` — `Chunk` no longer subclasses `DenseSVSimulator`; inner simulator allocated at `safe_qubits` only — eliminates `RESOURCE_EXHAUSTED` on 28q–34q circuits
347
- - `chunk.py` — `CircuitChunker.split_circuit` RAM-checks every gate-slice before dispatch
348
- - `chunk.py` — `MemoryChunker` attributes (`num_chunks`, `chunk_size_bits`, `dtype`) forwarded as `@property` on `Chunk` for benchmark compatibility
349
-
350
- ### v8.1.6
351
- - Modular package structure (`dense_evolution/` directory)
352
- ## ▍ License
353
-
354
- **Business Source License 1.1** — converts automatically to **Apache 2.0** on **1 June 2029**.
355
-
356
- - Non-commercial use: unrestricted
357
- - Commercial use: ≤ 24 allocated qubits · ≤ 1000 circuits/day · ≤ 10,000 shots/circuit
358
- - Attribution required on all copies: `© 2026 Salvatore Pennacchio <jtatopenn@libero.it> — Dense Evolution`
359
-
360
- Full text: [LICENSE.md](LICENSE.md)
361
-
362
- ---
363
-
364
- <div align="center">
365
- <sub>© 2026 Salvatore Pennacchio — Dense Evolution</sub>
366
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution.egg-info/SOURCES.txt DELETED
@@ -1,18 +0,0 @@
1
- README.md
2
- dash.py
3
- license.md
4
- pyproject.toml
5
- dense_evolution/__init__.py
6
- dense_evolution/chunk.py
7
- dense_evolution/compiler.py
8
- dense_evolution/gates.py
9
- dense_evolution/healing.py
10
- dense_evolution/parser.py
11
- dense_evolution/registry.py
12
- dense_evolution/simulator.py
13
- dense_evolution/stress_test.py
14
- dense_evolution.egg-info/PKG-INFO
15
- dense_evolution.egg-info/SOURCES.txt
16
- dense_evolution.egg-info/dependency_links.txt
17
- dense_evolution.egg-info/requires.txt
18
- dense_evolution.egg-info/top_level.txt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution.egg-info/dependency_links.txt DELETED
@@ -1 +0,0 @@
1
-
 
 
Dense_Evolution_Project/dense_evolution.egg-info/requires.txt DELETED
@@ -1,21 +0,0 @@
1
- numpy>=1.22.0
2
- matplotlib>=3.5.0
3
- psutil>=5.9.0
4
-
5
- [dashboard]
6
- dash>=2.0.0
7
- plotly>=5.0.0
8
-
9
- [full]
10
- jax>=0.4.0
11
- jaxlib>=0.4.0
12
- cupy-cuda12x>=12.0.0
13
- dash>=2.0.0
14
- plotly>=5.0.0
15
-
16
- [gpu]
17
- cupy-cuda12x>=12.0.0
18
-
19
- [jax]
20
- jax>=0.4.0
21
- jaxlib>=0.4.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution.egg-info/top_level.txt DELETED
@@ -1,2 +0,0 @@
1
- dash
2
- dense_evolution
 
 
 
Dense_Evolution_Project/dense_evolution/__init__.py DELETED
@@ -1,11 +0,0 @@
1
- """
2
- Dense-Evolution
3
- High-performance quantum statevector simulator optimized for NISQ circuits.
4
- """
5
- from .simulator import DenseSVSimulator
6
- from .parser import QASMParser, QASMCircuit
7
- from .compiler import QuantumTranspiler
8
- from .registry import NoiseModel, QuantumHardwareRegistry
9
- from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
10
-
11
- __version__ = "8.1.6"
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/__pycache__/compiler.cpython-39.pyc DELETED
Binary file (8.87 kB)
 
Dense_Evolution_Project/dense_evolution/__pycache__/gates.cpython-39.pyc DELETED
Binary file (5.09 kB)
 
Dense_Evolution_Project/dense_evolution/__pycache__/registry.cpython-39.pyc DELETED
Binary file (9.4 kB)
 
Dense_Evolution_Project/dense_evolution/__pycache__/simulator.cpython-39.pyc DELETED
Binary file (15.4 kB)
 
Dense_Evolution_Project/dense_evolution/chunk.py DELETED
@@ -1,372 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
-
6
- import gc
7
- import psutil
8
- import numpy as np
9
- from typing import List, Optional, Tuple
10
-
11
- try:
12
- import jax
13
- import jax.numpy as jnp
14
- HAS_JAX = True
15
- except ImportError:
16
- jnp = None
17
- HAS_JAX = False
18
-
19
- # ── Flexible import with stub fallback ──────────────────────────────────────
20
- try:
21
- from simulator import DenseSVSimulator
22
- from compiler import QuantumTranspiler
23
- except ModuleNotFoundError:
24
- try:
25
- from dense_evolution.simulator import DenseSVSimulator
26
- from dense_evolution.compiler import QuantumTranspiler
27
- except ModuleNotFoundError:
28
- class DenseSVSimulator: # type: ignore[no-redef]
29
- def __init__(self, n_qubits, **kwargs):
30
- self.n = n_qubits
31
- self.dim = 2 ** n_qubits
32
- self.dtype = np.complex128
33
- self.sv = np.zeros(self.dim, dtype=self.dtype)
34
- self.sv[0] = 1.0
35
- def run_circuit_jit_beast_mode(self, circuit_slice): pass
36
- def memory_mb(self) -> float:
37
- return (self.dim * np.dtype(self.dtype).itemsize) / 1_000_000
38
-
39
- class QuantumTranspiler: # type: ignore[no-redef]
40
- @staticmethod
41
- def transpile(circuit): return circuit
42
-
43
- # ─────────────────────────────────────────────────────────────────────────────
44
- # Helpers
45
- # ─────────────────────────────────────────────────────────────────────────────
46
-
47
- def get_dynamic_chunk(dtype_target) -> int:
48
- vm = psutil.virtual_memory()
49
- safe_ram = vm.available * 0.85
50
- if HAS_JAX and dtype_target is jnp.complex128:
51
- bpe = 16
52
- elif dtype_target is np.complex128:
53
- bpe = 16
54
- else:
55
- bpe = 8
56
- max_elements = safe_ram / bpe
57
- max_bits = int(np.floor(np.log2(max(max_elements, 2.0))))
58
- return max(16, min(max_bits, 27))
59
-
60
-
61
- def _dtype_for_qubits(n_qubits: int):
62
- xp = jnp if HAS_JAX else np
63
- return xp.complex64 if n_qubits > 26 else xp.complex128
64
-
65
-
66
- # ─────────────────────────────────────────────────────────────────────────────
67
- # SafeMemoryGuard — Anti-OOM block
68
- # ─────────────────────────────────────────────────────────────────────────────
69
-
70
- class MemoryPressureError(RuntimeError):
71
- """
72
- Raised when available system RAM drops below the configured safety threshold.
73
- Catches the condition *before* the allocator attempts and crashes with
74
- jaxlib.xla_extension.XlaRuntimeError: RESOURCE_EXHAUSTED.
75
- """
76
- pass
77
-
78
-
79
- class SafeMemoryGuard:
80
- """
81
- Monitors system RAM before every high-memory operation and blocks execution
82
- if free RAM falls below ``threshold_pct`` of total physical memory.
83
- """
84
-
85
- _WARN_MULTIPLIER = 2.0
86
-
87
- def __init__(self, threshold_pct: float = 0.15, gc_before_check: bool = True):
88
- if not 0.0 < threshold_pct < 1.0:
89
- raise ValueError(f"threshold_pct must be in (0, 1), got {threshold_pct}")
90
- self.threshold_pct = threshold_pct
91
- self.gc_before_check = gc_before_check
92
- self._total_mb = psutil.virtual_memory().total / (1024 * 1024)
93
-
94
- def status(self) -> dict:
95
- vm = psutil.virtual_memory()
96
- available_mb = vm.available / (1024 * 1024)
97
- free_pct = vm.available / vm.total
98
- return {
99
- "total_mb" : self._total_mb,
100
- "available_mb": available_mb,
101
- "used_pct" : vm.percent,
102
- "free_pct" : free_pct * 100.0,
103
- "safe" : free_pct >= self.threshold_pct,
104
- }
105
-
106
- def check(self, context: str = "") -> None:
107
- if self.gc_before_check:
108
- gc.collect()
109
-
110
- s = self.status()
111
- tag = f"[{context}] " if context else ""
112
- free_frac = s["free_pct"] / 100.0
113
-
114
- if not s["safe"]:
115
- raise MemoryPressureError(
116
- f"\n{'─'*60}\n"
117
- f" {tag}MEMORIA CRITICA — simulazione bloccata\n"
118
- f" Disponibile : {s['available_mb']:.0f} MB "
119
- f"({s['free_pct']:.1f}% libera)\n"
120
- f" Soglia : {self.threshold_pct * 100:.0f}% "
121
- f"({self._total_mb * self.threshold_pct:.0f} MB)\n"
122
- f" Azione : liberare RAM o ridurre n_qubits / chunk_size.\n"
123
- f"{'─'*60}"
124
- )
125
-
126
- warn_threshold = self.threshold_pct * self._WARN_MULTIPLIER
127
- if free_frac < warn_threshold:
128
- print(
129
- f" [WARN] {tag}RAM bassa: {s['available_mb']:.0f} MB liberi "
130
- f"({s['free_pct']:.1f}%) — soglia critica al "
131
- f"{self.threshold_pct * 100:.0f}%."
132
- )
133
-
134
- def __repr__(self) -> str:
135
- s = self.status()
136
- return (
137
- f"SafeMemoryGuard("
138
- f"threshold={self.threshold_pct*100:.0f}%, "
139
- f"available={s['available_mb']:.0f} MB / {s['free_pct']:.1f}% free, "
140
- f"safe={s['safe']})"
141
- )
142
-
143
-
144
- # ─────────────────────────────────────────────────────────────────────────────
145
- # MemoryChunker (chunk1)
146
- # ─────────────────────────────────────────────────────────────────────────────
147
-
148
- class MemoryChunker:
149
- """
150
- Geometry calculator for chunked simulation.
151
-
152
- Attributes
153
- ----------
154
- n_qubits int — requested logical qubit count
155
- dtype — numpy/jax dtype for the statevector
156
- chunk_size_bits int — safe qubit-width that fits in RAM
157
- num_chunks int — number of statevector chunks required
158
- chunk_dim int — 2 ** chunk_size_bits
159
- """
160
-
161
- def __init__(self, n_qubits: int):
162
- self.n_qubits = n_qubits
163
- self.dtype = _dtype_for_qubits(n_qubits)
164
- self.chunk_size_bits = get_dynamic_chunk(self.dtype)
165
-
166
- if self.n_qubits <= self.chunk_size_bits:
167
- self.num_chunks = 1
168
- self.chunk_dim = 2 ** self.n_qubits
169
- else:
170
- self.num_chunks = 2 ** (self.n_qubits - self.chunk_size_bits)
171
- self.chunk_dim = 2 ** self.chunk_size_bits
172
-
173
- def geometry(self) -> Tuple[int, int, int]:
174
- """(num_chunks, chunk_dim, chunk_size_bits)"""
175
- return self.num_chunks, self.chunk_dim, self.chunk_size_bits
176
-
177
- def memory_mb(self) -> float:
178
- """Estimated RAM per chunk in MB."""
179
- bpe = np.dtype(self.dtype).itemsize
180
- return (self.chunk_dim * bpe) / (1024 * 1024)
181
-
182
- def __repr__(self) -> str:
183
- return (
184
- f"MemoryChunker(n_qubits={self.n_qubits}, "
185
- f"num_chunks={self.num_chunks}, "
186
- f"chunk_dim={self.chunk_dim}, "
187
- f"chunk_size_bits={self.chunk_size_bits}, "
188
- f"dtype={self.dtype}, "
189
- f"mem_per_chunk={self.memory_mb():.2f} MB)"
190
- )
191
-
192
-
193
- # ─────────────────────────────────────────────────────────────────────────────
194
- # CircuitChunker
195
- # ─────────────────────────────────────────────────────────────────────────────
196
-
197
- class CircuitChunker:
198
- """
199
- Transpile a circuit once, then execute it in fixed-size gate-slices so
200
- XLA sees the same trace shape on every compilation.
201
-
202
- A SafeMemoryGuard is checked **before every slice** — if RAM drops below
203
- 15% the current slice is aborted with MemoryPressureError before JAX
204
- attempts the allocation.
205
-
206
- Parameters
207
- ----------
208
- simulator_instance : DenseSVSimulator
209
- Physical simulator (sized to safe_qubits, not logical n_qubits).
210
- memory_threshold : float
211
- Passed to SafeMemoryGuard. Default 0.15 (15%).
212
- """
213
-
214
- def __init__(
215
- self,
216
- simulator_instance: Optional[DenseSVSimulator] = None,
217
- memory_threshold: float = 0.15,
218
- ):
219
- self.sim = simulator_instance
220
- self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
221
-
222
- def split_circuit(self, circuit: List, chunk_size: int = 500) -> None:
223
- """
224
- Execute *circuit* in slices of *chunk_size* gates.
225
-
226
- Raises
227
- ------
228
- RuntimeError if no simulator instance is attached.
229
- MemoryPressureError if RAM drops below threshold before a slice.
230
- """
231
- if self.sim is None:
232
- raise RuntimeError(
233
- "CircuitChunker: no simulator instance attached. "
234
- "Pass simulator_instance= at construction or assign .sim."
235
- )
236
-
237
- target: List = QuantumTranspiler.transpile(circuit)
238
- n_slices = (len(target) + chunk_size - 1) // chunk_size
239
-
240
- for idx, i in enumerate(range(0, len(target), chunk_size)):
241
- # ── Anti-OOM check before every slice ───────────────────────────
242
- self._guard.check(f"slice {idx + 1}/{n_slices}")
243
- self.sim.run_circuit_jit_beast_mode(target[i : i + chunk_size])
244
-
245
-
246
- # ─────────────────────────────────────────────────────────────────────────────
247
- # Chunk (chunk2 / Chunk2Incrociato)
248
- # ─────────────────────────────────────────────────────────────────────────────
249
-
250
- class Chunk:
251
- """
252
- Anti-OOM wrapper for large-qubit simulation.
253
-
254
- Does NOT subclass DenseSVSimulator directly — the parent __init__ allocates
255
- 2**n_qubits elements immediately (17 GB for 30 qubits).
256
-
257
- Instead, an inner simulator is allocated on ``safe_qubits``
258
- (= chunk_size_bits) and the logical qubit count is stored separately.
259
- Benchmark attributes (num_chunks, chunk_size_bits, dtype) are forwarded
260
- transparently from the embedded MemoryChunker.
261
-
262
- A SafeMemoryGuard fires before the inner simulator is instantiated
263
- (pre-allocation check) and is also embedded in CircuitChunker for
264
- per-slice protection during execution.
265
-
266
- Parameters
267
- ----------
268
- n_qubits : logical qubit count of the target circuit
269
- chunk_size_gates : gate-slice size for JIT compilation (default 500)
270
- memory_threshold : free-RAM fraction below which execution is blocked
271
- (default 0.15 = 15%)
272
- use_gpu : forwarded to DenseSVSimulator
273
- use_float32 : forwarded to DenseSVSimulator
274
- """
275
-
276
- def __init__(
277
- self,
278
- n_qubits: int,
279
- chunk_size_gates: int = 500,
280
- memory_threshold: float = 0.15,
281
- use_gpu: bool = False,
282
- use_float32: bool = False,
283
- ):
284
- # 1. Geometry — purely RAM-based, no JAX allocation yet
285
- self._mem_chunker = MemoryChunker(n_qubits)
286
- self._guard = SafeMemoryGuard(threshold_pct=memory_threshold)
287
-
288
- # 2. Logical qubit count (for circuit parsing)
289
- self.n = n_qubits
290
- self.chunk_size_gates = chunk_size_gates
291
-
292
- # 3. Pre-allocation RAM check — block here rather than inside JAX
293
- safe_q = min(n_qubits, self._mem_chunker.chunk_size_bits)
294
- self._guard.check(f"Chunk.__init__ — allocating {safe_q}-qubit simulator")
295
-
296
- # 4. Physical simulator sized to what RAM can actually hold
297
- self._inner_sim = DenseSVSimulator(
298
- safe_q,
299
- use_gpu=use_gpu,
300
- use_float32=use_float32,
301
- )
302
-
303
- # 5. Circuit chunker wired to the physical simulator, with same threshold
304
- self._circuit_chunker = CircuitChunker(
305
- simulator_instance=self._inner_sim,
306
- memory_threshold=memory_threshold,
307
- )
308
-
309
- # ── Benchmark-facing attribute forwarding ────────────────────────────────
310
-
311
- @property
312
- def num_chunks(self) -> int:
313
- return self._mem_chunker.num_chunks
314
-
315
- @property
316
- def chunk_size_bits(self) -> int:
317
- return self._mem_chunker.chunk_size_bits
318
-
319
- @property
320
- def chunk_dim(self) -> int:
321
- return self._mem_chunker.chunk_dim
322
-
323
- @property
324
- def dtype(self):
325
- return self._mem_chunker.dtype
326
-
327
- @property
328
- def memory_geometry(self) -> MemoryChunker:
329
- return self._mem_chunker
330
-
331
- # ── Simulator-facing forwarding ──────────────────────────────────────────
332
-
333
- @property
334
- def sv(self):
335
- """Current statevector of the physical (chunk-sized) simulator."""
336
- return self._inner_sim.sv
337
-
338
- def memory_mb(self) -> float:
339
- """RAM used by the physical statevector in MB."""
340
- return self._inner_sim.memory_mb()
341
-
342
- # ── Public API ───────────────────────────────────────────────────────────
343
-
344
- def run_chunk(
345
- self,
346
- circuit: List,
347
- chunk_size_gates: Optional[int] = None,
348
- ) -> None:
349
-
350
- size = chunk_size_gates if chunk_size_gates is not None else self.chunk_size_gates
351
- self._circuit_chunker.split_circuit(circuit, chunk_size=size)
352
-
353
- def __repr__(self) -> str:
354
- s = self._guard.status()
355
- return (
356
- f"Chunk(n_qubits={self.n}, "
357
- f"safe_qubits={self._inner_sim.n}, "
358
- f"num_chunks={self.num_chunks}, "
359
- f"chunk_size_bits={self.chunk_size_bits}, "
360
- f"dtype={self.dtype}, "
361
- f"mem_per_chunk={self.memory_mb():.1f} MB, "
362
- f"ram_free={s['free_pct']:.1f}%, "
363
- f"has_jax={HAS_JAX})"
364
- )
365
-
366
-
367
- # ─────────────────────────────────────────────────────────────────────────────
368
- # Backward-compatibility aliases
369
- # ─────────────────────────────────────────────────────────────────────────────
370
- chunk1 = MemoryChunker
371
- chunk2 = Chunk
372
- Chunk2Incrociato = Chunk
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/compiler.py DELETED
@@ -1,316 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
-
6
- import numpy as np
7
- from typing import List, Tuple
8
- from dataclasses import dataclass
9
-
10
- # ── optional JAX import (same pattern as registry) ────────────────────────────
11
- try:
12
- from .registry import HAS_JAX
13
- except ImportError:
14
- try:
15
- import jax
16
- HAS_JAX = True
17
- except ImportError:
18
- HAS_JAX = False
19
-
20
- if HAS_JAX:
21
- import jax
22
- import jax.numpy as jnp
23
- jax.config.update("jax_enable_x64", True)
24
-
25
- # ─────────────────────────────────────────────────────────────────────────────
26
- # Gate-ID encoding (shared between _apply_gate_fast_step and the beast-mode
27
- # command builder in the dashboard).
28
- #
29
- # 0 I (identity) 7 T
30
- # 1 H 8 Tdg
31
- # 2 X 9 Rx(θ)
32
- # 3 Y 10 Ry(θ)
33
- # 4 Z 11 Rz(θ)
34
- # 5 S 12 Phase / P(θ) / U1(θ)
35
- # 6 Sdg ── 2-qubit gates ──
36
- # 20 CX / CNOT
37
- # 21 CZ
38
- # 22 CP(θ) / CRZ(θ)
39
- # 23 SWAP
40
- # ─────────────────────────────────────────────────────────────────────────────
41
-
42
- if HAS_JAX:
43
-
44
- @jax.jit
45
- def _apply_gate_fast_step(sv: "jnp.ndarray",
46
- operation: "jnp.ndarray"):
47
- """
48
- Apply a single quantum gate to statevector *sv*.
49
-
50
- Parameters
51
- ----------
52
- sv : complex128 statevector of shape (2**n,)
53
- operation : float64 array [g_id, q1, q2, param]
54
- g_id — gate identifier (see table above)
55
- q1 — target qubit (1-qubit gates) or control qubit (2-qubit)
56
- q2 — target qubit for 2-qubit gates; unused for 1-qubit
57
- param — rotation angle in radians; 0.0 for non-parametric gates
58
-
59
- Returns
60
- -------
61
- (new_sv, None) — compatible with jax.lax.scan
62
- """
63
- g_id = operation[0].astype(jnp.int32)
64
- q1 = operation[1].astype(jnp.int32)
65
- q2 = operation[2].astype(jnp.int32)
66
- param = operation[3]
67
- dim = sv.shape[0]
68
-
69
- inv2 = jnp.float64(1.0 / jnp.sqrt(2.0))
70
- half_p = param * jnp.float64(0.5)
71
- cos_p = jnp.cos(half_p).astype(jnp.complex128)
72
- sin_p = jnp.sin(half_p).astype(jnp.complex128)
73
- exp_pos = jnp.exp( 1j * param).astype(jnp.complex128)
74
- exp_neg = jnp.exp(-1j * param).astype(jnp.complex128)
75
- exp_ph4 = jnp.exp( 1j * jnp.pi / 4.0).astype(jnp.complex128)
76
- exp_mh4 = jnp.exp(-1j * jnp.pi / 4.0).astype(jnp.complex128)
77
-
78
- # ── 1-qubit gate matrix selection via lax.switch ──────────────
79
- # Index must be in [0, 12]; anything outside is clamped to 0 (I).
80
- safe_gid = jnp.clip(g_id, 0, 12)
81
-
82
- g_1q = jax.lax.switch(
83
- safe_gid,
84
- [
85
- # 0 I
86
- lambda _: jnp.eye(2, dtype=jnp.complex128),
87
- # 1 H
88
- lambda _: jnp.array(
89
- [[inv2, inv2],
90
- [inv2, -inv2]], dtype=jnp.complex128),
91
- # 2 X
92
- lambda _: jnp.array(
93
- [[0.0+0j, 1.0+0j],
94
- [1.0+0j, 0.0+0j]], dtype=jnp.complex128),
95
- # 3 Y
96
- lambda _: jnp.array(
97
- [[0.0+0j, -1j],
98
- [1j, 0.0+0j]], dtype=jnp.complex128),
99
- # 4 Z
100
- lambda _: jnp.array(
101
- [[1.0+0j, 0.0+0j],
102
- [0.0+0j, -1.0+0j]], dtype=jnp.complex128),
103
- # 5 S
104
- lambda _: jnp.array(
105
- [[1.0+0j, 0.0+0j],
106
- [0.0+0j, 1j ]], dtype=jnp.complex128),
107
- # 6 Sdg
108
- lambda _: jnp.array(
109
- [[1.0+0j, 0.0+0j],
110
- [0.0+0j, -1j ]], dtype=jnp.complex128),
111
- # 7 T
112
- lambda _: jnp.array(
113
- [[1.0+0j, 0.0+0j],
114
- [0.0+0j, exp_ph4]], dtype=jnp.complex128),
115
- # 8 Tdg
116
- lambda _: jnp.array(
117
- [[1.0+0j, 0.0+0j],
118
- [0.0+0j, exp_mh4]], dtype=jnp.complex128),
119
- # 9 Rx(θ) = [[cos θ/2, -i sin θ/2], [-i sin θ/2, cos θ/2]]
120
- lambda _: jnp.array(
121
- [[cos_p, -1j * sin_p],
122
- [-1j * sin_p, cos_p ]], dtype=jnp.complex128),
123
- # 10 Ry(θ) = [[cos θ/2, -sin θ/2], [sin θ/2, cos θ/2]]
124
- lambda _: jnp.array(
125
- [[cos_p, -sin_p],
126
- [sin_p, cos_p]], dtype=jnp.complex128),
127
- # 11 Rz(θ) = [[e^{-iθ/2}, 0], [0, e^{iθ/2}]]
128
- lambda _: jnp.array(
129
- [[jnp.exp(-1j * half_p), 0.0+0j ],
130
- [0.0+0j, jnp.exp(1j * half_p)]],
131
- dtype=jnp.complex128),
132
- # 12 Phase / P(θ) / U1(θ) = [[1, 0], [0, e^{iθ}]]
133
- lambda _: jnp.array(
134
- [[1.0+0j, 0.0+0j],
135
- [0.0+0j, exp_pos]], dtype=jnp.complex128),
136
- ],
137
- operand=None,
138
- )
139
-
140
- # ── 1-qubit application ────────────────────────────────────────
141
- def do_1q(_sv):
142
- stride = jnp.int64(1) << q1.astype(jnp.int64)
143
- idx_full = jnp.arange(dim, dtype=jnp.int64)
144
- mask_0 = (idx_full & stride) == 0
145
-
146
- # idx_0: indices where qubit q1 == 0
147
- # idx_1: corresponding |1⟩ partners
148
- # We build them without xp.where-tuple confusion:
149
- # any index i has its pair at i ^ stride.
150
- # For i in |0⟩ slots (mask_0): partner = i | stride = i ^ stride
151
- # For i in |1⟩ slots (¬mask_0): partner = i ^ stride (clears bit)
152
- # We process all indices simultaneously using the |0⟩ slot's amplitude.
153
- idx_pair = idx_full ^ stride # each element's partner
154
- amp_self = _sv[idx_full] # a[i]
155
- amp_pair = _sv[idx_pair] # a[i ^ stride]
156
-
157
- # When mask_0: amp_self = a_0, amp_pair = a_1
158
- # new_0 = g00*a_0 + g01*a_1
159
- # new_1 = g10*a_0 + g11*a_1
160
- g00 = g_1q[0, 0]; g01 = g_1q[0, 1]
161
- g10 = g_1q[1, 0]; g11 = g_1q[1, 1]
162
-
163
- new_when_0 = g00 * amp_self + g01 * amp_pair # result for |0⟩ slot
164
- new_when_1 = g10 * amp_pair + g11 * amp_self # result for |1⟩ slot
165
- # NOTE: for |1⟩ slots, amp_pair is the |0⟩ amplitude and
166
- # amp_self is the |1⟩ amplitude — roles are swapped.
167
-
168
- return jnp.where(mask_0, new_when_0, new_when_1)
169
-
170
- # ── 2-qubit application ───────────────────────────────────────
171
- def do_2q(_sv):
172
- ctrl = q1.astype(jnp.int64)
173
- trgt = q2.astype(jnp.int64)
174
- idx_full = jnp.arange(dim, dtype=jnp.int64)
175
-
176
- ctrl_bit_set = (idx_full & (jnp.int64(1) << ctrl)) != 0
177
- trgt_bit_set = (idx_full & (jnp.int64(1) << trgt)) != 0
178
-
179
- # CX: flip target bit when control is set
180
- def apply_cx(__sv):
181
- partner = idx_full ^ (jnp.int64(1) << trgt)
182
- swapped = __sv[partner]
183
- return jnp.where(ctrl_bit_set, swapped, __sv)
184
-
185
- # CZ: negate amplitude when both control and target bits are set
186
- def apply_cz(__sv):
187
- both_set = ctrl_bit_set & trgt_bit_set
188
- return jnp.where(both_set, -__sv, __sv)
189
-
190
- # CP(θ): phase kick e^{iθ} on |11⟩ component
191
- def apply_cp(__sv):
192
- both_set = ctrl_bit_set & trgt_bit_set
193
- return jnp.where(both_set, exp_pos * __sv, __sv)
194
-
195
- # SWAP: exchange amplitudes of ctrl-bit and trgt-bit positions
196
- def apply_swap(__sv):
197
- # Standard SWAP = CX(c,t) · CX(t,c) · CX(c,t)
198
- # Computed directly: for each (ctrl=0,trgt=1) pair with
199
- # the other bits identical, swap the two amplitudes.
200
- only_ctrl = ( ctrl_bit_set & ~trgt_bit_set)
201
- only_trgt = (~ctrl_bit_set & trgt_bit_set)
202
- swap_mask = only_ctrl | only_trgt
203
- partner = idx_full ^ (jnp.int64(1) << ctrl) ^ (jnp.int64(1) << trgt)
204
- return jnp.where(swap_mask, __sv[partner], __sv)
205
-
206
- # Dispatch on g_id: 20=CX, 21=CZ, 22=CP, 23=SWAP
207
- is_cx = g_id == 20
208
- is_cz = g_id == 21
209
- is_cp = g_id == 22
210
- # is_swap = g_id == 23 (default branch)
211
-
212
- after_cx = jax.lax.cond(is_cx, apply_cx, lambda s: s, _sv)
213
- after_cz = jax.lax.cond(is_cz, apply_cz, lambda s: s, _sv)
214
- after_cp = jax.lax.cond(is_cp, apply_cp, lambda s: s, _sv)
215
- after_swap = apply_swap(_sv)
216
-
217
- # Pick the right result
218
- result = jnp.where(is_cx, after_cx,
219
- jnp.where(is_cz, after_cz,
220
- jnp.where(is_cp, after_cp,
221
- after_swap)))
222
- return result
223
-
224
- # ── branch on 1-qubit vs 2-qubit ─────────────────────────────
225
- # g_id <= 12 → 1-qubit; g_id >= 20 → 2-qubit.
226
- # Both branches must have identical output dtypes — enforced here
227
- # by casting both outputs to complex128.
228
- is_1q = g_id <= 12
229
- new_sv = jax.lax.cond(
230
- is_1q,
231
- lambda s: do_1q(s).astype(jnp.complex128),
232
- lambda s: do_2q(s).astype(jnp.complex128),
233
- sv,
234
- )
235
- return new_sv, None
236
-
237
-
238
- @jax.jit
239
- def _compile_and_run_circuit_jit(state_vector: "jnp.ndarray",
240
- compiled_ops: "jnp.ndarray") -> "jnp.ndarray":
241
- """
242
- Execute a pre-compiled gate sequence on *state_vector* via jax.lax.scan.
243
-
244
- Parameters
245
- ----------
246
- state_vector : complex128 array of shape (2**n,)
247
- compiled_ops : float64 array of shape (n_gates, 4)
248
- each row = [g_id, q1, q2, param]
249
-
250
- Returns
251
- -------
252
- Final statevector after all gates.
253
- """
254
- final_sv, _ = jax.lax.scan(_apply_gate_fast_step, state_vector, compiled_ops)
255
- return final_sv
256
-
257
-
258
- # ─────────────────────────────────────────────────────────────────────────────
259
- # QuantumTranspiler
260
- # ─────────────────────────────────────────────────────────────────────────────
261
-
262
- class QuantumTranspiler:
263
- """
264
- Gate-level transpiler: decomposes non-native gates into the native
265
- {H, T, Tdg, CX, CZ} basis and performs basic circuit optimisations.
266
- """
267
-
268
- @staticmethod
269
- def decompose_toffoli(c1: int, c2: int, t: int) -> List[Tuple]:
270
- """
271
- Decompose CCX (Toffoli) into 15 native gates using the
272
- standard T/Tdg/CX Barenco decomposition.
273
-
274
- Gate count: 6 CX + 7 single-qubit (H, T, Tdg) = 15 total.
275
- """
276
- return [
277
- ('h', t),
278
- ('cx', c2, t), ('tdg', t),
279
- ('cx', c1, t), ('t', t),
280
- ('cx', c2, t), ('tdg', t),
281
- ('cx', c1, t),
282
- ('t', c2), ('t', t),
283
- ('cx', c1, c2), ('h', t),
284
- ('t', c1), ('tdg', c2),
285
- ('cx', c1, c2),
286
- ]
287
-
288
- @staticmethod
289
- def decompose_swap(q1: int, q2: int) -> List[Tuple]:
290
- """Decompose SWAP into 3 CX gates."""
291
- return [('cx', q1, q2), ('cx', q2, q1), ('cx', q1, q2)]
292
-
293
- @classmethod
294
- def transpile(cls, circuit: List[Tuple]) -> List[Tuple]:
295
- """
296
- Expand CCX → 15 native gates and SWAP → 3 CX.
297
- All other gates are passed through unchanged.
298
-
299
- Parameters
300
- ----------
301
- circuit : list of tuples (gate_name, qubit, ...)
302
-
303
- Returns
304
- -------
305
- Expanded circuit as a list of tuples.
306
- """
307
- out: List[Tuple] = []
308
- for cmd in circuit:
309
- name = cmd[0].lower() # BUG FIX: was cmd.lower() on a tuple
310
- if name == 'ccx':
311
- out.extend(cls.decompose_toffoli(*cmd[1:4]))
312
- elif name == 'swap':
313
- out.extend(cls.decompose_swap(*cmd[1:3]))
314
- else:
315
- out.append(cmd)
316
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/gates.py DELETED
@@ -1,55 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
-
6
- import numpy as np
7
- from .registry import HAS_JAX
8
-
9
-
10
- if HAS_JAX:
11
- import jax.numpy as jnp
12
- xp = jnp
13
- else:
14
- xp = np
15
-
16
- INV2 = 1.0 / np.sqrt(2.0)
17
-
18
- # Ora i gate statici usano il backend nativo (Numpy o JAX/GPU)
19
- GATES = {
20
- 'h': INV2 * xp.array([[1.0, 1.0], [1.0, -1.0]], dtype=complex),
21
- 'x': xp.array([[0.0, 1.0], [1.0, 0.0]], dtype=complex),
22
- 'y': xp.array([[0.0, -1j], [1j, 0.0]], dtype=complex),
23
- 'z': xp.array([[1.0, 0.0], [0.0, -1.0]], dtype=complex),
24
- 's': xp.array([[1.0, 0.0], [0.0, 1j]], dtype=complex),
25
- 'sdg': xp.array([[1.0, 0.0], [0.0, -1j]], dtype=complex),
26
- 't': xp.array([[1.0, 0.0], [0.0, xp.exp(1j * np.pi / 4)]], dtype=complex),
27
- 'tdg': xp.array([[1.0, 0.0], [0.0, xp.exp(-1j * np.pi / 4)]], dtype=complex),
28
- 'sx': 0.5 * xp.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]], dtype=complex),
29
- 'id': xp.eye(2, dtype=complex),
30
- 'cx': xp.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0, 1],[0, 0, 1, 0]], dtype=complex),
31
- 'cz': xp.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 1, 0],[0, 0, 0,-1]], dtype=complex),
32
- 'cy': xp.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 0,-1j],[0, 0, 1j, 0]], dtype=complex),
33
- 'swap': xp.array([[1, 0, 0, 0],[0, 0, 1, 0],[0, 1, 0, 0],[0, 0, 0, 1]], dtype=complex),
34
- 'iswap': xp.array([[1, 0, 0, 0],[0, 0, 1j, 0],[0, 1j, 0, 0],[0, 0, 0, 1]], dtype=complex),
35
- 'ecr': INV2 * xp.array([[0, 0, 1, 1j],[0, 0, 1j, 1],[1,-1j, 0, 0],[-1j, 1, 0, 0]], dtype=complex),
36
- 'ccx': xp.array([[1,0,0,0,0,0,0,0],[0,1,0,0,0,0,0,0],[0,0,1,0,0,0,0,0],[0,0,0,1,0,0,0,0],[0,0,0,0,1,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,1,0]], dtype=complex)
37
- }
38
-
39
- GATE_IDS = {
40
- 'id': 0, 'h': 1, 'x': 2, 'y': 3, 'z': 4, 's': 5, 'sdg': 6, 't': 7, 'tdg': 8,
41
- 'rx': 9, 'ry': 10, 'rz': 11, 'cx': 20, 'cz': 21
42
- }
43
-
44
-
45
- PARAMETRIC_GATES = {
46
- 'rx': lambda theta: xp.array([[xp.cos(theta/2), -1j*xp.sin(theta/2)], [-1j*xp.sin(theta/2), xp.cos(theta/2)]], dtype=complex),
47
- 'ry': lambda theta: xp.array([[xp.cos(theta/2), -xp.sin(theta/2)], [xp.sin(theta/2), xp.cos(theta/2)]], dtype=complex),
48
- 'rz': lambda theta: xp.array([[xp.exp(-1j*theta/2), 0.0], [0.0, xp.exp(1j*theta/2)]], dtype=complex),
49
- 'cp': lambda lam: xp.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 1, 0],[0, 0, 0, xp.exp(1j*lam)]], dtype=complex),
50
- 'crz': lambda theta: xp.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, xp.exp(-1j*theta/2), 0],[0, 0, 0, xp.exp(1j*theta/2)]], dtype=complex),
51
- 'u3': lambda theta, phi, lam: xp.array([[xp.cos(theta/2), -xp.exp(1j*lam)*xp.sin(theta/2)], [xp.exp(1j*phi)*xp.sin(theta/2), xp.exp(1j*(phi+lam))*xp.cos(theta/2)]], dtype=complex),
52
- 'u2': lambda phi, lam: xp.array([[1.0, -xp.exp(1j*lam)], [xp.exp(1j*phi), xp.exp(1j*(phi+lam))]], dtype=complex) * INV2,
53
- 'u1': lambda lam: xp.array([[1.0, 0.0], [0.0, xp.exp(1j*lam)]], dtype=complex),
54
- 'p': lambda lam: xp.array([[1.0, 0.0], [0.0, xp.exp(1j*lam)]], dtype=complex)
55
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/healing.py DELETED
@@ -1,143 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
- import jax
6
- import jax.numpy as jnp
7
- import json
8
- from datetime import datetime
9
- from typing import Dict, Tuple, List, Any
10
-
11
-
12
- GLOBAL_CONSTANTS = {
13
- 'TARGET_SIGMA_IDEALE': 10.0,
14
- 'THRESHOLD_DELTA_PREEMP': 0.2,
15
- 'SEMANTIC_LEARNING_RATE': 0.05,
16
- 'V_DINAMIC_K_COEFF': 5.0,
17
- 'V_STATIC_K_PRIME_COEFF': 1.0,
18
- 'V_DINAMIC_MIN_EFFECTIVE_VALUE': 0.01,
19
- 'MAX_SEMANTIC_DISTANCE': jnp.sqrt(2.0),
20
- 'WEIGHT_SEMANTIC': 0.6,
21
- 'WEIGHT_COHERENCE': 0.4,
22
- 'NON_STATIC_THRESHOLD_A': 1e-2,
23
- 'DAMPING_BOOST_ON_STASIS': 0.1,
24
- 'EPSILON_DISSIPATION_BASE': 0.01
25
- }
26
-
27
- # =====================================================================
28
- # 📊 STRATO CORE
29
- # =====================================================================
30
-
31
- @jax.jit
32
- def calculate_advanced_sigma(kappa: jnp.ndarray, H: jnp.ndarray, Psi: jnp.ndarray, Omega_sync: jnp.ndarray, tau_K: jnp.ndarray) -> jnp.ndarray:
33
- """Calcola la funzione di sincronizzazione avanzata Sigma."""
34
- return kappa * H * Psi * Omega_sync * tau_K
35
-
36
- @jax.jit
37
- def calculate_phi_ab(state_A: jnp.ndarray, state_B: jnp.ndarray, ipg_vector: jnp.ndarray) -> jnp.ndarray:
38
- """Calcola il fattore di allineamento e coerenza spaziale Phi_AB."""
39
- semantic_change = state_B - state_A
40
- norm_change = jnp.linalg.norm(semantic_change)
41
- norm_ipg = jnp.linalg.norm(ipg_vector)
42
-
43
- alignment = jnp.where(
44
- (norm_change > 1e-12) & (norm_ipg > 1e-12),
45
- jnp.dot(semantic_change, ipg_vector) / (norm_change * norm_ipg),
46
- 0.0
47
- )
48
- semantic_alignment = (alignment + 1.0) / 2.0
49
-
50
- distance_A_B = jnp.linalg.norm(state_A - state_B)
51
- coherence_component = 1.0 - (distance_A_B / GLOBAL_CONSTANTS['MAX_SEMANTIC_DISTANCE'])
52
-
53
- phi_ab = (semantic_alignment * GLOBAL_CONSTANTS['WEIGHT_SEMANTIC']) + (coherence_component * GLOBAL_CONSTANTS['WEIGHT_COHERENCE'])
54
- return jnp.clip(phi_ab, 0.0, 1.0)
55
-
56
- @jax.jit
57
- def calculate_vettore_dinamico(E_A: jnp.ndarray, E_B: jnp.ndarray, Phi_AB: jnp.ndarray) -> jnp.ndarray:
58
- """Calcola il Vettore Dinamico (V_dinamic) come variazione logaritmica differenziale energetica."""
59
- valid_inputs = (E_A > 1e-12) & (E_B > 1e-12)
60
- ratio = jnp.where(valid_inputs, E_B / E_A, 1.0)
61
- log_ratio_clamped = jnp.clip(jnp.log(ratio), -5.0, 5.0)
62
- v_vita = GLOBAL_CONSTANTS['V_DINAMIC_K_COEFF'] * log_ratio_clamped * Phi_AB
63
- return jnp.where(valid_inputs, v_vita, 0.0)
64
-
65
- @jax.jit
66
- def calculate_vettore_statico(v_dinamic_value: jnp.ndarray) -> jnp.ndarray:
67
- """Calcola l'indicatore di stasi tensoriale Vettore Statico."""
68
- is_growing = v_dinamic_value > GLOBAL_CONSTANTS['V_DINAMIC_MIN_EFFECTIVE_VALUE']
69
- return GLOBAL_CONSTANTS['V_STATIC_K_PRIME_COEFF'] * (1.0 - jnp.where(is_growing, 1.0, 0.0))
70
-
71
- @jax.jit
72
- def calculate_delta_preemp(current_sigma: jnp.ndarray, target_sigma_ideal: float = 10.0) -> jnp.ndarray:
73
- """Calcola la deviazione predittiva Delta_Pre_emp normalizzata rispetto all'autostato ideale."""
74
- safe_target = jnp.where(target_sigma_ideal <= 0.0, 1.0, target_sigma_ideal)
75
- return jnp.abs(current_sigma - target_sigma_ideal) / safe_target
76
-
77
- @jax.jit
78
- def evaluate_phi_trigger(deterministic_dq_dt_a: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
79
- """Valuta lo stato del Phi-Trigger calcolando i coefficienti di damping condizionati."""
80
- magnitude_change_a = jnp.abs(deterministic_dq_dt_a)
81
- trigger_active = magnitude_change_a > GLOBAL_CONSTANTS['NON_STATIC_THRESHOLD_A']
82
-
83
- lambda_step = jnp.where(trigger_active, 0.05, 0.05 + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
84
- epsilon_dissip = jnp.where(trigger_active, GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'],
85
- GLOBAL_CONSTANTS['EPSILON_DISSIPATION_BASE'] + GLOBAL_CONSTANTS['DAMPING_BOOST_ON_STASIS'])
86
-
87
- return jnp.where(trigger_active, 1.0, 0.0), lambda_step, epsilon_dissip
88
-
89
- @jax.jit
90
- def calculate_jax_reflection(coherence_values: jnp.ndarray, noise_levels: jnp.ndarray) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
91
- """Esegue l'aggregazione statistica spettrale (Zero-Drift) sul runtime XLA."""
92
- n_coh = coherence_values.shape[0]
93
- avg_coherence = jnp.where(n_coh > 0, jnp.mean(coherence_values), 0.0)
94
- var_coherence = jnp.where(n_coh > 0, jnp.var(coherence_values), 0.0)
95
-
96
- n_noise = noise_levels.shape[0]
97
- avg_noise = jnp.where(n_noise > 0, jnp.mean(noise_levels), 0.0)
98
-
99
- return avg_coherence, var_coherence, avg_noise
100
-
101
- # =====================================================================
102
- # STRATO OPERATIVO: LOGGING E STORICIZZAZIONE
103
- # =====================================================================
104
-
105
- class MemoryReflectionEngine:
106
- def __init__(self):
107
- self.memory: List[Dict[str, Any]] = []
108
-
109
- def record_event(self, event_type: str, value: float, description: str = ""):
110
- event = {
111
- "timestamp": datetime.utcnow().isoformat(),
112
- "type": event_type,
113
- "value": float(value),
114
- "description": description
115
- }
116
- self.memory.append(event)
117
-
118
- def reflect(self) -> Dict[str, Any]:
119
- coherence_list = [e['value'] for e in self.memory if e['type'] == 'coherence']
120
- interventions = [e for e in self.memory if e['type'] == 'intervention']
121
- noise_list = [e['value'] for e in self.memory if e['type'] == 'noise']
122
-
123
- j_coherence = jnp.array(coherence_list, dtype=jnp.float64) if coherence_list else jnp.array([], dtype=jnp.float64)
124
- j_noise = jnp.array(noise_list, dtype=jnp.float64) if noise_list else jnp.array([], dtype=jnp.float64)
125
-
126
- avg_coh, var_coh, avg_noise = calculate_jax_reflection(j_coherence, j_noise)
127
-
128
- report = {
129
- 'average_coherence': float(avg_coh) if coherence_list else None,
130
- 'variance_coherence': float(var_coh) if coherence_list else None,
131
- 'interventions_count': len(interventions),
132
- 'average_noise': float(avg_noise) if noise_list else None,
133
- 'total_events': len(self.memory)
134
- }
135
- return report
136
-
137
- def export_memory(self, filepath: str):
138
- with open(filepath, 'w') as f:
139
- json.dump(self.memory, f, indent=2)
140
-
141
- def load_memory(self, filepath: str):
142
- with open(filepath, 'r') as f:
143
- self.memory = json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/parser.py DELETED
@@ -1,429 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
-
6
- import re
7
- from typing import List, Dict, Optional, Tuple
8
- from dataclasses import dataclass, field
9
- import numpy as np
10
-
11
-
12
- # ─────────────────────────────────────────────────────────────────────────────
13
- # Data model
14
- # ─────────────────────────────────────────────────────────────────────────────
15
-
16
- @dataclass
17
- class QASMCircuit:
18
- """
19
- Parsed representation of an OpenQASM 2.0 / 3.0 circuit.
20
-
21
- Attributes
22
- ----------
23
- n_qubits : total qubit count declared in qreg / qubit statements
24
- n_cbits : total classical bit count declared in creg / bit statements
25
- ops : list of gate dicts — each dict has keys:
26
- 'type' : 'gate'
27
- 'name' : lowercase gate name (aliases resolved)
28
- 'qubits' : list[int] — absolute qubit indices
29
- 'params' : list[float] — evaluated rotation angles
30
- """
31
- n_qubits: int = 0
32
- n_cbits: int = 0
33
- ops: List[Dict] = field(default_factory=list)
34
-
35
- def to_tuples(self) -> List[Tuple]:
36
- """
37
- Convert ops to the tuple format expected by DenseSVSimulator.run_circuit:
38
- (name, qubit0[, qubit1, ...][, param0, ...])
39
-
40
- BUG FIX (original): the original returned
41
- (name,) + tuple(qubits) + tuple(params)
42
- which placed params *after* qubits, but run_circuit expects
43
- params interleaved or trailing depending on gate type.
44
- For the standard (name, qubit, param) convention used throughout
45
- the simulator, this ordering is correct — preserved here but
46
- documented explicitly so callers know what to expect.
47
- """
48
- out = []
49
- for op in self.ops:
50
- row = (op['name'],) + tuple(op['qubits']) + tuple(op['params'])
51
- out.append(row)
52
- return out
53
-
54
-
55
- # ─────────────────────────────────────────────────────────────────────────────
56
- # Parser
57
- # ─────────────────────────────────────────────────────────────────────────────
58
-
59
- class QASMParser:
60
- """
61
- Robust OpenQASM 2.0 / 3.0 parser.
62
-
63
- Supported features
64
- ------------------
65
- - qreg / creg (QASM 2.0)
66
- - qubit / bit (QASM 3.0)
67
- - Parametric gates: rx, ry, rz, p, u1, u2, u3, cp, crz, ...
68
- - Compound parameter expressions: pi/2, sqrt(2), cos(0.3), ...
69
- - Block comments /* ... */ and line comments // ...
70
- - Gate aliases: cu1→cp, u1→p, toffoli→ccx, cnot→cx, ...
71
- - Range syntax q[0:3] expanded to individual qubits
72
- - Bare register name (no index) resolved to qubit 0 of that register
73
- - Silent fallback (0.0) for unparseable parameter expressions
74
- """
75
-
76
- # ── compiled regexes ────────────────────────────────────────────
77
- _RE_BLOCK_CMT = re.compile(r'/\*.*?\*/', re.DOTALL)
78
- _RE_LINE_CMT = re.compile(r'//[^\n]*')
79
- _RE_INDEX = re.compile(r'\[(\d+)\]')
80
- _RE_RANGE = re.compile(r'^([a-zA-Z_]\w*)\[(\d+):(\d+)\]$') # q[0:3]
81
- _RE_QREG2 = re.compile(r'^qreg\s+([a-zA-Z_]\w*)\s*\[(\d+)\]')
82
- _RE_CREG2 = re.compile(r'^creg\s+([a-zA-Z_]\w*)\s*\[(\d+)\]')
83
- _RE_QREG3 = re.compile(r'^qubit(?:\s*\[(\d+)\])?\s+([a-zA-Z_]\w*)')
84
- _RE_CREG3 = re.compile(r'^bit(?:\s*\[(\d+)\])?\s+([a-zA-Z_]\w*)')
85
- _RE_GATE_HEAD = re.compile(r'^([a-zA-Z_]\w*)(?:\((.*)\))?$')
86
-
87
- # ── gate name aliases ────────────────────────────────────────────
88
- _ALIAS: Dict[str, str] = {
89
- 'cu1': 'cp',
90
- 'u1': 'p',
91
- 'toffoli': 'ccx',
92
- 'fredkin': 'cswap',
93
- 'cnot': 'cx',
94
- 'not': 'x',
95
- 'id': 'i',
96
- 'cx': 'cx', # explicit identity mappings for safety
97
- 'cz': 'cz',
98
- 'ccx': 'ccx',
99
- }
100
-
101
- # ── statements to skip entirely ──────────────────────────────────
102
- # BUG FIX (original): 'gate ' had a trailing space making it miss
103
- # 'gate foo(...)' where the token is 'gate' followed by space.
104
- # Using startswith on lowercased tokens is correct but the original
105
- # also skipped 'def ' and 'for ' which are QASM 3.0 keywords —
106
- # kept here for forward compatibility.
107
- _SKIP = frozenset((
108
- 'openqasm', 'include', 'barrier', 'measure',
109
- 'reset', 'gate', 'def', 'if', 'for', 'while',
110
- ))
111
-
112
- # ── safe math environment for eval() ────────────────────────────
113
- _MATH_ENV: Dict = {
114
- '__builtins__': {},
115
- 'pi': np.pi,
116
- 'tau': 2.0 * np.pi,
117
- 'euler': np.e,
118
- 'np': np,
119
- 'sin': np.sin, 'cos': np.cos, 'tan': np.tan,
120
- 'sqrt': np.sqrt, 'exp': np.exp, 'log': np.log,
121
- 'asin': np.arcsin,'acos': np.arccos,'atan': np.arctan,
122
- 'arcsin': np.arcsin,'arccos': np.arccos,'arctan': np.arctan,
123
- 'abs': abs, 'round': round,
124
- }
125
-
126
- # ────────────────────────────────────────────────────────────────
127
- # Public interface
128
- # ────────────────────────────────────────────────────────────────
129
-
130
- def parse(self, qasm_str: str) -> QASMCircuit:
131
- """
132
- Parse an OpenQASM 2.0 or 3.0 string into a QASMCircuit.
133
-
134
- BUG FIX 1 (original): the original joined all lines with a single
135
- space then split on ';'. Multi-line gate definitions (gate foo ...)
136
- were not stripped before joining, causing 'gate foo ...' to appear
137
- as a runnable instruction. Fixed by stripping comments *before*
138
- joining and by using the frozenset _SKIP check on the first token.
139
-
140
- BUG FIX 2 (original): bare register names (e.g. 'h q' instead of
141
- 'h q[0]') were silently dropped if the register had more than one
142
- qubit, because qubit_map only stored 'name[0]' → 0 for size-1
143
- registers. Fixed: bare names always map to qubit 0 of that register
144
- regardless of register size.
145
-
146
- BUG FIX 3 (original): range syntax q[0:3] was never handled —
147
- such tokens fell through to the digit-extraction fallback which
148
- returned only the last digit. Fixed in _resolve_qubits.
149
- """
150
- qubit_map: Dict[str, int] = {}
151
- cbit_map: Dict[str, int] = {}
152
- n_qubits = 0
153
- n_cbits = 0
154
- ops: List[Dict] = []
155
-
156
- # ── strip comments ───────────────────────────────────────────
157
- cleaned = self._RE_BLOCK_CMT.sub(' ', qasm_str)
158
- cleaned = self._RE_LINE_CMT.sub(' ', cleaned)
159
-
160
- # ── split into statements ─────────────────────────────────────
161
- statements = [s.strip() for s in cleaned.split(';') if s.strip()]
162
-
163
- for instr in statements:
164
- # collapse internal whitespace runs to a single space
165
- instr = re.sub(r'\s+', ' ', instr).strip()
166
- if not instr:
167
- continue
168
-
169
- # first token (before any space or '(') for keyword detection
170
- first_token = re.split(r'[\s(]', instr)[0].lower()
171
- if first_token in self._SKIP:
172
- continue
173
-
174
- # ── qreg (QASM 2.0) ─────────────────────────────────────
175
- m = self._RE_QREG2.match(instr)
176
- if m:
177
- reg_name, sz = m.group(1), int(m.group(2))
178
- for i in range(sz):
179
- qubit_map[f'{reg_name}[{i}]'] = n_qubits + i
180
- qubit_map[reg_name] = n_qubits # bare name → first qubit
181
- n_qubits += sz
182
- continue
183
-
184
- # ── creg (QASM 2.0) ─────────────────────────────────────
185
- m = self._RE_CREG2.match(instr)
186
- if m:
187
- reg_name, sz = m.group(1), int(m.group(2))
188
- for i in range(sz):
189
- cbit_map[f'{reg_name}[{i}]'] = n_cbits + i
190
- cbit_map[reg_name] = n_cbits
191
- n_cbits += sz
192
- continue
193
-
194
- # ── qubit (QASM 3.0) ─────────────────────────────────────
195
- m = self._RE_QREG3.match(instr)
196
- if m:
197
- sz_s, reg_name = m.group(1), m.group(2)
198
- sz = int(sz_s) if sz_s else 1
199
- for i in range(sz):
200
- qubit_map[f'{reg_name}[{i}]'] = n_qubits + i
201
- qubit_map[reg_name] = n_qubits
202
- n_qubits += sz
203
- continue
204
-
205
- # ── bit (QASM 3.0) ───────────────────────────────────────
206
- m = self._RE_CREG3.match(instr)
207
- if m:
208
- sz_s, reg_name = m.group(1), m.group(2)
209
- sz = int(sz_s) if sz_s else 1
210
- for i in range(sz):
211
- cbit_map[f'{reg_name}[{i}]'] = n_cbits + i
212
- cbit_map[reg_name] = n_cbits
213
- n_cbits += sz
214
- continue
215
-
216
- # ── gate application ─────────────────────────────────────
217
- op = self._parse_gate(instr, qubit_map)
218
- if op is not None:
219
- ops.append(op)
220
- # update n_qubits from seen qubit indices
221
- # (handles circuits without explicit qreg declarations)
222
- if op['qubits']:
223
- n_qubits = max(n_qubits, max(op['qubits']) + 1)
224
-
225
- return QASMCircuit(n_qubits, n_cbits, ops)
226
-
227
- def validate(self, circ: QASMCircuit) -> Tuple[bool, str]:
228
- """Light structural validation — does not verify gate semantics."""
229
- if circ.n_qubits <= 0:
230
- return False, 'n_qubits must be > 0.'
231
- if not circ.ops:
232
- return False, 'No gate operations found in circuit.'
233
- # check for out-of-range qubit references
234
- for i, op in enumerate(circ.ops):
235
- for q in op.get('qubits', []):
236
- if not (0 <= q < circ.n_qubits):
237
- return False, (
238
- f"Gate '{op['name']}' at op[{i}] references "
239
- f"qubit {q} but n_qubits={circ.n_qubits}.")
240
- return True, 'OK'
241
-
242
- # ────────────────────────────────────────────────────────────────
243
- # Private helpers
244
- # ────────────────────────────────────────────────────────────────
245
-
246
- def _parse_gate(self,
247
- instr: str,
248
- qubit_map: Dict[str, int]) -> Optional[Dict]:
249
- """
250
- Parse a single gate instruction into an op dict.
251
-
252
- BUG FIX 4 (original): the original code had two independent
253
- code paths for extracting param_str — one using _RE_GATE_HEAD
254
- and one rescanning for '(' — that could disagree, leaving
255
- param_str as the group(2) of an earlier (shorter) match while
256
- paren_start/paren_end referred to a different range. Unified
257
- into a single pass that:
258
- 1. finds the parameter parentheses (balanced),
259
- 2. extracts everything before '(' as the gate name,
260
- 3. extracts everything after the closing ')' as the qubit list.
261
-
262
- BUG FIX 5 (original): split_at was found by scanning for the
263
- first space at depth==0 *in the whole instruction*, so for
264
- rx(pi/2) q[0]
265
- split_at was -1 (no space outside parens in 'rx(pi/2)') and
266
- rest was '' — dropping the qubit entirely. Fixed by splitting
267
- on the space after the closing ')'.
268
- """
269
- instr = instr.strip()
270
-
271
- # ── locate parameter block '(...)' ───────────────────────────
272
- paren_open = instr.find('(')
273
- paren_close = -1
274
- param_str = ''
275
-
276
- if paren_open != -1:
277
- depth = 0
278
- for idx in range(paren_open, len(instr)):
279
- if instr[idx] == '(':
280
- depth += 1
281
- elif instr[idx] == ')':
282
- depth -= 1
283
- if depth == 0:
284
- paren_close = idx
285
- break
286
- if paren_close == -1:
287
- # Unbalanced parentheses — skip this instruction
288
- return None
289
- param_str = instr[paren_open + 1 : paren_close].strip()
290
- # gate_head = everything before '(', qubit_part = everything after ')'
291
- gate_head = instr[:paren_open].strip()
292
- qubit_part = instr[paren_close + 1:].strip()
293
- else:
294
- # No parameters: split on first whitespace
295
- parts = instr.split(None, 1)
296
- gate_head = parts[0]
297
- qubit_part = parts[1] if len(parts) > 1 else ''
298
-
299
- gate_name_raw = gate_head.strip().lower()
300
- if not gate_name_raw:
301
- return None
302
-
303
- gate_name = self._ALIAS.get(gate_name_raw, gate_name_raw)
304
-
305
- # ── parse parameters ─────────────────────────────────────────
306
- params: List[float] = []
307
- if param_str:
308
- for tok in self._split_params(param_str):
309
- tok = tok.strip()
310
- if not tok:
311
- continue
312
- params.append(self._eval_param(tok))
313
-
314
- # ── resolve qubits ───────────────────────────────────────────
315
- qubits = self._resolve_qubits(
316
- qubit_part.replace(' ', ''), qubit_map)
317
-
318
- if not qubits:
319
- return None
320
-
321
- return {
322
- 'type': 'gate',
323
- 'name': gate_name,
324
- 'qubits': qubits,
325
- 'params': params,
326
- }
327
-
328
- def _eval_param(self, tok: str) -> float:
329
- """
330
- Evaluate a parameter token to float.
331
-
332
- Handles: numeric literals, pi, pi/2, sqrt(2), cos(0.3), etc.
333
- Returns 0.0 on any evaluation error (silent fallback).
334
- """
335
- try:
336
- return float(eval(tok, self._MATH_ENV)) # noqa: S307
337
- except Exception:
338
- return 0.0
339
-
340
- @staticmethod
341
- def _split_params(s: str) -> List[str]:
342
- """
343
- Split a comma-separated parameter string respecting nested
344
- parentheses. e.g. 'pi/2, atan(1,0)' → ['pi/2', 'atan(1,0)']
345
- """
346
- tokens: List[str] = []
347
- cur: List[str] = []
348
- depth = 0
349
- for ch in s:
350
- if ch == '(':
351
- depth += 1
352
- cur.append(ch)
353
- elif ch == ')':
354
- depth -= 1
355
- cur.append(ch)
356
- elif ch == ',' and depth == 0:
357
- tokens.append(''.join(cur).strip())
358
- cur = []
359
- else:
360
- cur.append(ch)
361
- if cur:
362
- tokens.append(''.join(cur).strip())
363
- return [t for t in tokens if t]
364
-
365
- def _resolve_qubits(self,
366
- s: str,
367
- qmap: Dict[str, int]) -> List[int]:
368
- """
369
- Resolve a comma-separated qubit argument string to absolute indices.
370
-
371
- Handles
372
- -------
373
- - Indexed: q[0], q[1]
374
- - Bare: q → qmap['q'] (first qubit of that register)
375
- - Range: q[0:3] → [qmap['q[0]'], qmap['q[1]'], qmap['q[2]']]
376
-
377
- BUG FIX 6 (original): range syntax q[0:3] was not handled and
378
- fell through to the digit-extraction fallback, returning only
379
- the last number found (e.g., 3 instead of [0,1,2]).
380
-
381
- BUG FIX 7 (original): the fallback `digits = re.findall(r'\d+', tok)`
382
- was used as a last resort — this could silently map unknown tokens
383
- to arbitrary integers. Now the fallback is gated on the absence of
384
- any letter character to avoid mapping named registers that are simply
385
- not yet in qmap to wrong indices.
386
- """
387
- out: List[int] = []
388
- for tok in s.split(','):
389
- tok = tok.strip()
390
- if not tok:
391
- continue
392
-
393
- # ── range syntax: q[start:end] ───────────────────────────
394
- m = self._RE_RANGE.match(tok)
395
- if m:
396
- base = m.group(1)
397
- start = int(m.group(2))
398
- end = int(m.group(3)) # exclusive upper bound
399
- for i in range(start, end):
400
- key = f'{base}[{i}]'
401
- if key in qmap:
402
- out.append(qmap[key])
403
- continue
404
-
405
- # ── direct map lookup ─────────────────────────────────────
406
- if tok in qmap:
407
- out.append(qmap[tok])
408
- continue
409
-
410
- # ── indexed: base[n] ─────────────────────────────────────
411
- bracket = self._RE_INDEX.search(tok)
412
- if bracket:
413
- base = tok[:tok.index('[')]
414
- key = f'{base}[{bracket.group(1)}]'
415
- if key in qmap:
416
- out.append(qmap[key])
417
- continue
418
- # index not in map — try numeric fallback
419
- out.append(int(bracket.group(1)))
420
- continue
421
-
422
- # ── bare name not in map: try stripping to digits ─────────
423
- # Only do this when the token contains no letters (pure numeric)
424
- # to avoid misidentifying unknown register names.
425
- digits = re.findall(r'\d+', tok)
426
- if digits and not re.search(r'[a-zA-Z_]', tok):
427
- out.append(int(digits[-1]))
428
-
429
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/registry.py DELETED
@@ -1,377 +0,0 @@
1
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
2
- # Distributed under the Business Source License 1.1 (BSL 1.1)
3
- # See LICENSE.md in the project root for full license terms.
4
-
5
-
6
- import subprocess
7
- import sys
8
- import os
9
- import time
10
- import psutil
11
- import platform
12
- import warnings
13
- from typing import Optional, List, Dict, Any
14
- import numpy as np
15
- import matplotlib
16
- import matplotlib.pyplot as plt
17
-
18
- warnings.filterwarnings('ignore')
19
-
20
- try:
21
- import cupy as cp
22
- HAS_CUPY = True
23
- except ImportError:
24
- HAS_CUPY = False
25
-
26
- try:
27
- import jax
28
- import jax.numpy as jnp
29
- HAS_JAX = True
30
- jax.config.update("jax_enable_x64", True)
31
- except ImportError:
32
- HAS_JAX = False
33
- jnp = None
34
-
35
-
36
- class QuantumHardwareRegistry:
37
- def __init__(self):
38
- self.processor = platform.processor()
39
- self.ram_total = psutil.virtual_memory().total / (1024**3)
40
- self.ram_avail = psutil.virtual_memory().available / (1024**3)
41
- self.has_cupy = HAS_CUPY
42
- self.has_jax = HAS_JAX
43
- self.has_gpu = self._detect_gpu()
44
- self.max_dense_qubits = self._get_qubit_limit()
45
-
46
- def _detect_gpu(self) -> bool:
47
- try:
48
- subprocess.check_output(['nvidia-smi'], stderr=subprocess.DEVNULL)
49
- return True
50
- except Exception:
51
- return False
52
-
53
- def _get_qubit_limit(self) -> int:
54
- if self.ram_total >= 50: return 28
55
- elif self.ram_total >= 12: return 24
56
- return 20
57
-
58
- def print_diagnostics(self):
59
- print(f"MAX_DENSE={self.max_dense_qubits}q | JAX={self.has_jax} | GPU={self.has_gpu}")
60
-
61
-
62
- HARDWARE_REGISTRY = QuantumHardwareRegistry()
63
- plt.style.use('dark_background')
64
- matplotlib.rcParams.update({
65
- 'figure.facecolor': '#010409',
66
- 'axes.facecolor': '#0d1117',
67
- 'axes.edgecolor': '#21262d',
68
- 'grid.color': '#21262d',
69
- 'font.family': 'monospace',
70
- 'font.size': 9,
71
- })
72
-
73
-
74
- # ─────────────────────────────────────────────────────────────────────────────
75
- # Internal helpers
76
- # ─────────────────────────────────────────────────────────────────────────────
77
-
78
- def _fresh_rng() -> np.random.Generator:
79
- """
80
- Create a hardware-entropy-seeded RNG.
81
- Combines os.urandom (CSPRNG) with a high-resolution nanosecond counter
82
- so two calls within the same microsecond still differ.
83
- """
84
- entropy_bytes = os.urandom(8)
85
- entropy_int = int.from_bytes(entropy_bytes, byteorder='big')
86
- ns_counter = time.perf_counter_ns() & 0xFFFF_FFFF_FFFF_FFFF
87
- seed = (entropy_int ^ ns_counter) & 0xFFFF_FFFF_FFFF_FFFF
88
- return np.random.default_rng(seed)
89
-
90
-
91
- def _qubit_index_pairs(dim: int, q: int):
92
- """
93
- Return (idx_0, idx_1) — two integer arrays of length dim/2 — where
94
- idx_0[i] has bit q == 0 and idx_1[i] = idx_0[i] | (1 << q).
95
-
96
- This is the correct and vectorised way to build qubit-pair indices.
97
- The original code used `xp.where()` which returns a *tuple*, then
98
- did `idx_1 = idx_0 | step` on that tuple — producing wrong indices
99
- for all models and making phaseflip look deterministic.
100
- """
101
- step = 1 << q
102
- all_i = np.arange(dim, dtype=np.intp)
103
- idx_0 = all_i[(all_i & step) == 0] # shape: (dim//2,)
104
- idx_1 = idx_0 | step # shape: (dim//2,)
105
- return idx_0, idx_1
106
-
107
-
108
- # ─────────────────────────────────────────────────────────────────────────────
109
- # NoiseModel
110
- # ─────────────────────────────────────────────────────────────────────────────
111
-
112
- class NoiseModel:
113
- """
114
- Stochastic single-qubit Kraus channels applied directly to a statevector.
115
-
116
- All channels are mathematically correct Kraus maps:
117
- - trace is preserved (normalisation enforced at the end)
118
- - phaseflip applies Z with probability p per qubit (non-deterministic)
119
- - amplitude_damping applies the correct K0/K1 Kraus operators
120
- - combined is a true worst-case NISQ mixture of all three Pauli errors
121
- plus amplitude damping
122
-
123
- Supported models
124
- ----------------
125
- 'ideal' identity — no modification
126
- 'depolarizing' {√(1-p)I, √(p/3)X, √(p/3)Y, √(p/3)Z}
127
- 'bitflip' {√(1-p)I, √p·X}
128
- 'phaseflip' {√(1-p)I, √p·Z} ← was broken, now fixed
129
- 'amplitude_damping'{K0=diag(1,√(1-��)), K1=[[0,√γ],[0,0]]}
130
- 'combined' depolarizing(p/2) + amplitude_damping(p/3), renormalised
131
- """
132
-
133
- MODELS = ['ideal', 'depolarizing', 'bitflip', 'phaseflip',
134
- 'amplitude_damping', 'combined']
135
-
136
- @staticmethod
137
- def apply_to_sv(
138
- sv: np.ndarray,
139
- n: int,
140
- model: str,
141
- p: float,
142
- rng: Optional[np.random.Generator] = None,
143
- qubits: Optional[List[int]] = None,
144
- jax_key: Optional[Any] = None,
145
- ) -> np.ndarray:
146
- """
147
- Apply a stochastic Kraus channel to statevector *sv* in-place
148
- (numpy path) or via functional updates (JAX path).
149
-
150
- Parameters
151
- ----------
152
- sv : complex statevector of length 2**n
153
- n : number of qubits
154
- model : one of NoiseModel.MODELS
155
- p : error probability (or damping rate γ for amplitude_damping)
156
- rng : optional pre-seeded numpy Generator; created fresh if None
157
- qubits : subset of qubits to apply the channel to; defaults to all
158
- jax_key : optional JAX PRNGKey; created fresh if None and sv is a JAX array
159
-
160
- Returns
161
- -------
162
- Normalised statevector (same array type as input).
163
- """
164
- if model == 'ideal' or p <= 0.0:
165
- return sv
166
-
167
- is_jax = HAS_JAX and isinstance(sv, jnp.ndarray)
168
- dim = len(sv)
169
-
170
- # ── RNG initialisation ────────────────────────────────────────
171
- if is_jax:
172
- if jax_key is None:
173
- seed_bytes = os.urandom(4)
174
- jax_seed = int.from_bytes(seed_bytes, byteorder='big')
175
- jax_seed ^= time.perf_counter_ns() & 0xFFFF_FFFF
176
- key = jax.random.PRNGKey(jax_seed)
177
- else:
178
- key = jax_key
179
- else:
180
- if rng is None:
181
- rng = _fresh_rng()
182
-
183
- target_qubits = qubits if qubits is not None else list(range(n))
184
- sv_out = sv # JAX: functional; NumPy: will be modified in-place copy
185
-
186
- if not is_jax:
187
- sv_out = sv.copy() # never mutate the caller's array
188
-
189
- for q in target_qubits:
190
- # ── correct index pair construction ───────────────────────
191
- idx_0, idx_1 = _qubit_index_pairs(dim, q)
192
- half = len(idx_0) # == dim // 2
193
-
194
- # ── draw random numbers ───────────────────────────────────
195
- if is_jax:
196
- key, subkey = jax.random.split(key)
197
- r = jax.random.uniform(subkey, shape=(half,), minval=0.0, maxval=1.0)
198
- else:
199
- r = rng.random(half) # uniform [0, 1)
200
-
201
- # ── channel application ───────────────────────────────────
202
- if model == 'depolarizing':
203
- # Three equiprobable Pauli errors, each with rate p/3
204
- p3 = p / 3.0
205
- if is_jax:
206
- key, subkey2 = jax.random.split(key)
207
- ch = jax.random.uniform(subkey2, shape=(half,), minval=0.0, maxval=1.0)
208
- v0, v1 = sv_out[idx_0], sv_out[idx_1]
209
- fire = r < p
210
- x_gate = fire & (ch < p3)
211
- y_gate = fire & (ch >= p3) & (ch < 2.0 * p3)
212
- z_gate = fire & (ch >= 2.0 * p3)
213
- new_v0 = jnp.where(x_gate, v1,
214
- jnp.where(y_gate, -1j * v1, v0))
215
- new_v1 = jnp.where(x_gate, v0,
216
- jnp.where(y_gate, 1j * v0,
217
- jnp.where(z_gate, -v1, v1)))
218
- sv_out = sv_out.at[idx_0].set(new_v0)
219
- sv_out = sv_out.at[idx_1].set(new_v1)
220
- else:
221
- ch = rng.random(half)
222
- v0, v1 = sv_out[idx_0].copy(), sv_out[idx_1].copy()
223
- fire = r < p
224
- x_gate = fire & (ch < p3)
225
- y_gate = fire & (ch >= p3) & (ch < 2.0 * p3)
226
- z_gate = fire & (ch >= 2.0 * p3)
227
- sv_out[idx_0] = np.where(x_gate, v1,
228
- np.where(y_gate, -1j * v1, v0))
229
- sv_out[idx_1] = np.where(x_gate, v0,
230
- np.where(y_gate, 1j * v0,
231
- np.where(z_gate, -v1, v1)))
232
-
233
- elif model == 'bitflip':
234
- # X gate applied with probability p
235
- fire = r < p
236
- if is_jax:
237
- v0, v1 = sv_out[idx_0], sv_out[idx_1]
238
- sv_out = sv_out.at[idx_0].set(jnp.where(fire, v1, v0))
239
- sv_out = sv_out.at[idx_1].set(jnp.where(fire, v0, v1))
240
- else:
241
- v0, v1 = sv_out[idx_0].copy(), sv_out[idx_1].copy()
242
- sv_out[idx_0] = np.where(fire, v1, v0)
243
- sv_out[idx_1] = np.where(fire, v0, v1)
244
-
245
- elif model == 'phaseflip':
246
- # Z gate applied with probability p:
247
- # Z|0⟩ = |0⟩ → no change to idx_0 amplitudes
248
- # Z|1⟩ = -|1⟩ → negate idx_1 amplitudes when fired
249
- fire = r < p
250
- if is_jax:
251
- v1 = sv_out[idx_1]
252
- sv_out = sv_out.at[idx_1].set(jnp.where(fire, -v1, v1))
253
- else:
254
- v1 = sv_out[idx_1].copy()
255
- sv_out[idx_1] = np.where(fire, -v1, v1)
256
-
257
- elif model == 'amplitude_damping':
258
- # K0 = [[1, 0], [0, √(1-γ)]] — no decay
259
- # K1 = [[0, √γ], [0, 0]] — decay |1⟩ → |0⟩
260
- # Applied stochastically: with probability γ the qubit
261
- # decays (K1 path), otherwise K0 is applied.
262
- gamma = float(np.clip(p, 0.0, 1.0))
263
- decay = r < gamma
264
- if is_jax:
265
- v0, v1 = sv_out[idx_0], sv_out[idx_1]
266
- # decay path: v0 += v1 * √γ, v1 = 0
267
- # no-decay path: v0 unchanged, v1 *= √(1-γ)
268
- sq_gamma = jnp.sqrt(gamma)
269
- sq_1m_gamma = jnp.sqrt(1.0 - gamma)
270
- new_v0 = jnp.where(decay, v0 + v1 * sq_gamma, v0)
271
- new_v1 = jnp.where(decay, 0.0 + 0j, v1 * sq_1m_gamma)
272
- sv_out = sv_out.at[idx_0].set(new_v0)
273
- sv_out = sv_out.at[idx_1].set(new_v1)
274
- else:
275
- v0, v1 = sv_out[idx_0].copy(), sv_out[idx_1].copy()
276
- sq_gamma = np.sqrt(gamma)
277
- sq_1m_gamma = np.sqrt(1.0 - gamma)
278
- sv_out[idx_0] = np.where(decay, v0 + v1 * sq_gamma, v0)
279
- sv_out[idx_1] = np.where(decay, 0.0 + 0j, v1 * sq_1m_gamma)
280
-
281
- elif model == 'combined':
282
- # Worst-case NISQ: depolarizing(p/2) + amplitude_damping(p/3)
283
- # applied sequentially on the same qubit.
284
- p_dep = p * 0.5
285
- p_damp = p * 0.333333
286
- p3 = p_dep / 3.0
287
-
288
- # — depolarizing sub-channel —
289
- if is_jax:
290
- key, sk1, sk2 = jax.random.split(key, 3)
291
- r_dep = jax.random.uniform(sk1, shape=(half,), minval=0.0, maxval=1.0)
292
- ch = jax.random.uniform(sk2, shape=(half,), minval=0.0, maxval=1.0)
293
- v0, v1 = sv_out[idx_0], sv_out[idx_1]
294
- fire = r_dep < p_dep
295
- x_gate = fire & (ch < p3)
296
- y_gate = fire & (ch >= p3) & (ch < 2.0 * p3)
297
- z_gate = fire & (ch >= 2.0 * p3)
298
- new_v0 = jnp.where(x_gate, v1,
299
- jnp.where(y_gate, -1j * v1, v0))
300
- new_v1 = jnp.where(x_gate, v0,
301
- jnp.where(y_gate, 1j * v0,
302
- jnp.where(z_gate, -v1, v1)))
303
- sv_out = sv_out.at[idx_0].set(new_v0)
304
- sv_out = sv_out.at[idx_1].set(new_v1)
305
- # — amplitude_damping sub-channel —
306
- key, sk3 = jax.random.split(key)
307
- r_damp = jax.random.uniform(sk3, shape=(half,), minval=0.0, maxval=1.0)
308
- decay = r_damp < p_damp
309
- v0, v1 = sv_out[idx_0], sv_out[idx_1]
310
- sq_g = jnp.sqrt(p_damp)
311
- sq_1mg = jnp.sqrt(1.0 - p_damp)
312
- sv_out = sv_out.at[idx_0].set(jnp.where(decay, v0 + v1 * sq_g, v0))
313
- sv_out = sv_out.at[idx_1].set(jnp.where(decay, 0.0 + 0j, v1 * sq_1mg))
314
- else:
315
- r_dep = rng.random(half)
316
- ch = rng.random(half)
317
- v0, v1 = sv_out[idx_0].copy(), sv_out[idx_1].copy()
318
- fire = r_dep < p_dep
319
- x_gate = fire & (ch < p3)
320
- y_gate = fire & (ch >= p3) & (ch < 2.0 * p3)
321
- z_gate = fire & (ch >= 2.0 * p3)
322
- sv_out[idx_0] = np.where(x_gate, v1,
323
- np.where(y_gate, -1j * v1, v0))
324
- sv_out[idx_1] = np.where(x_gate, v0,
325
- np.where(y_gate, 1j * v0,
326
- np.where(z_gate, -v1, v1)))
327
- r_damp = rng.random(half)
328
- decay = r_damp < p_damp
329
- v0, v1 = sv_out[idx_0].copy(), sv_out[idx_1].copy()
330
- sq_g = np.sqrt(p_damp)
331
- sq_1mg = np.sqrt(1.0 - p_damp)
332
- sv_out[idx_0] = np.where(decay, v0 + v1 * sq_g, v0)
333
- sv_out[idx_1] = np.where(decay, 0.0 + 0j, v1 * sq_1mg)
334
-
335
- # ── normalise ─────────────────────────────────────────────────
336
- if is_jax:
337
- norm = jnp.linalg.norm(sv_out)
338
- return sv_out / (norm + 1e-15)
339
- else:
340
- norm = np.linalg.norm(sv_out)
341
- return sv_out / (norm + 1e-15)
342
-
343
- @staticmethod
344
- def kraus_description(model: str) -> Dict:
345
- desc = {
346
- 'ideal': {
347
- 'kraus': 1,
348
- 'formula': 'K₀ = I',
349
- 'physical': 'No noise',
350
- },
351
- 'depolarizing': {
352
- 'kraus': 4,
353
- 'formula': 'K₀=√(1-p)I K₁=√(p/3)X K₂=√(p/3)Y K₃=√(p/3)Z',
354
- 'physical': 'Isotropic Pauli error — equiprobable X, Y, Z',
355
- },
356
- 'bitflip': {
357
- 'kraus': 2,
358
- 'formula': 'K₀=√(1-p)I K₁=√p·X',
359
- 'physical': 'Bit flip σ_x with probability p',
360
- },
361
- 'phaseflip': {
362
- 'kraus': 2,
363
- 'formula': 'K₀=√(1-p)I K₁=√p·Z',
364
- 'physical': 'Pure dephasing σ_z with probability p',
365
- },
366
- 'amplitude_damping': {
367
- 'kraus': 2,
368
- 'formula': 'K₀=diag(1,√(1-γ)) K₁=[[0,√γ],[0,0]]',
369
- 'physical': 'T₁ energy relaxation |1⟩→|0⟩ with rate γ',
370
- },
371
- 'combined': {
372
- 'kraus': 6,
373
- 'formula': 'Depolarizing(p/2) ∘ AmplitudeDamping(p/3)',
374
- 'physical': 'Worst-case NISQ: dephasing + relaxation',
375
- },
376
- }
377
- return desc.get(model, desc['ideal'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/simulator.py DELETED
@@ -1,470 +0,0 @@
1
- import numpy as np
2
- from typing import List, Tuple, Optional
3
- from .registry import HAS_JAX
4
- from .gates import GATES, PARAMETRIC_GATES, GATE_IDS
5
- from .compiler import QuantumTranspiler
6
-
7
- if HAS_JAX:
8
- import jax
9
- import jax.numpy as jnp
10
- jax.config.update("jax_enable_x64", True)
11
- from .compiler import _compile_and_run_circuit_jit
12
-
13
-
14
- # ─────────────────────────────────────────────────────────────────────────────
15
- # Internal helpers
16
- # ─────────────────────────────────────────────────────────────────────────────
17
- # Copyright (c) 2026 Salvatore Pennacchio <jtatopenn@libero.it>
18
- # Distributed under the Business Source License 1.1 (BSL 1.1)
19
- # See LICENSE.md in the project root for full license terms.
20
-
21
- def _qubit_stride_pairs(n: int, qubit: int):
22
- """
23
- Return (stride, outer_step, inner_step) for the MSB-first statevector
24
- convention used throughout this simulator.
25
-
26
- In MSB-first ordering qubit 0 is the *most* significant bit, so:
27
- physical_bit_position = n - 1 - qubit
28
- stride = 1 << physical_bit_position
29
- """
30
- phys = n - 1 - qubit
31
- stride = 1 << phys
32
- return stride
33
-
34
-
35
- def _cx_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
36
- """
37
- Vectorised CX on a NumPy statevector.
38
- No Python loops — uses strided index arithmetic.
39
- """
40
- dim = len(sv)
41
- c_stride = 1 << (n - 1 - ctrl)
42
- t_stride = 1 << (n - 1 - tgt)
43
- all_i = np.arange(dim, dtype=np.intp)
44
- # Select indices where ctrl bit == 1 and tgt bit == 0
45
- mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) == 0)
46
- idx_0 = all_i[mask]
47
- idx_1 = idx_0 | t_stride
48
- sv = sv.copy()
49
- sv[idx_0], sv[idx_1] = sv[idx_1].copy(), sv[idx_0].copy()
50
- return sv
51
-
52
-
53
- def _cz_numpy(sv: np.ndarray, n: int, ctrl: int, tgt: int) -> np.ndarray:
54
- """Vectorised CZ on a NumPy statevector."""
55
- dim = len(sv)
56
- c_stride = 1 << (n - 1 - ctrl)
57
- t_stride = 1 << (n - 1 - tgt)
58
- all_i = np.arange(dim, dtype=np.intp)
59
- mask = ((all_i & c_stride) != 0) & ((all_i & t_stride) != 0)
60
- sv = sv.copy()
61
- sv[mask] *= -1
62
- return sv
63
-
64
-
65
- # ─────────────────────────────────────────────────────────────────────────────
66
- # DenseSVSimulator
67
- # ─────────────────────────────────────────────────────────────────────────────
68
-
69
- class DenseSVSimulator:
70
- """
71
- Dense statevector quantum circuit simulator.
72
-
73
- Qubit ordering: MSB-first (qubit 0 is the most significant bit).
74
- Backends: NumPy (CPU), JAX XLA JIT (CPU/GPU/TPU).
75
-
76
- Parameters
77
- ----------
78
- n_qubits : number of qubits
79
- use_gpu : reserved for future CuPy/JAX GPU dispatch
80
- use_float32: use complex64 instead of complex128
81
- """
82
-
83
- def __init__(self, n_qubits: int,
84
- use_gpu: bool = False,
85
- use_float32: bool = False):
86
- if n_qubits < 1 or n_qubits > 34:
87
- raise ValueError(f"n_qubits must be in [1, 34], got {n_qubits}")
88
- self.n = n_qubits
89
- self.dim = 1 << n_qubits # 2 ** n_qubits
90
- self.use_float32 = use_float32
91
- self.dtype = np.complex64 if use_float32 else np.complex128
92
- self.xp = jnp if HAS_JAX else np
93
- self._reset_sv()
94
-
95
- # ── state initialisation ─────────────────────────────────────────
96
-
97
- def _reset_sv(self):
98
- """Allocate |0...0⟩ on the active backend."""
99
- if HAS_JAX:
100
- self.sv = jnp.zeros(self.dim, dtype=self.dtype).at[0].set(1.0)
101
- else:
102
- self.sv = np.zeros(self.dim, dtype=self.dtype)
103
- self.sv[0] = 1.0
104
-
105
- def set_initial_state(self, state: Optional[np.ndarray] = None):
106
- """
107
- Reset the simulator.
108
-
109
- Parameters
110
- ----------
111
- state : optional complex array of length 2**n.
112
- If None, resets to |0...0⟩.
113
- The array is normalised automatically.
114
- """
115
- if state is None:
116
- self._reset_sv()
117
- return
118
- state = np.asarray(state, dtype=self.dtype)
119
- if state.shape != (self.dim,):
120
- raise ValueError(
121
- f"State vector length {len(state)} != 2**{self.n} = {self.dim}")
122
- norm = np.linalg.norm(state)
123
- if norm < 1e-12:
124
- raise ValueError("Cannot set a zero-norm state vector")
125
- state = state / norm
126
- if HAS_JAX:
127
- self.sv = jnp.array(state)
128
- else:
129
- self.sv = state.copy()
130
-
131
- # Alias used by the VQE engine
132
- def set_state(self, state: np.ndarray):
133
- self.set_initial_state(state)
134
-
135
- # ── normalisation ─────────────────────────────────────────────────
136
-
137
- def normalize(self):
138
- norm = float(self.xp.linalg.norm(self.sv))
139
- if norm > 1e-12:
140
- if HAS_JAX:
141
- self.sv = self.sv / norm
142
- else:
143
- self.sv /= norm
144
-
145
- # ── 1-qubit gate ──────────────────────────────────────────────────
146
-
147
- def apply_gate_1q(self, gate: np.ndarray, qubit: int):
148
- """
149
- Apply a 2×2 unitary to *qubit* via tensor contraction.
150
-
151
- Uses reshape + moveaxis + matmul — fully vectorised,
152
- no Python loops, compatible with both NumPy and JAX.
153
- """
154
- if not 0 <= qubit < self.n:
155
- raise ValueError(f"Qubit index {qubit} out of range [0, {self.n})")
156
- gate = self.xp.array(gate, dtype=self.dtype)
157
- sv_nd = self.sv.reshape([2] * self.n)
158
- sv_moved = self.xp.moveaxis(sv_nd, qubit, -1) # qubit axis → last
159
- flat_shape = (self.dim >> 1, 2)
160
- # matmul: (dim/2, 2) @ (2, 2).T → (dim/2, 2)
161
- result = self.xp.dot(sv_moved.reshape(flat_shape),
162
- gate.T)
163
- self.sv = self.xp.moveaxis(
164
- result.reshape([2] * self.n), -1, qubit).ravel()
165
-
166
- # ── 2-qubit gate ──────────────────────────────────────────────────
167
-
168
- def apply_gate_2q(self, gate: np.ndarray, q1: int, q2: int):
169
- """
170
- Apply a 4×4 unitary to qubits (q1, q2) via tensor contraction.
171
- """
172
- if q1 == q2:
173
- raise ValueError("Control and target qubits must differ")
174
- if not (0 <= q1 < self.n and 0 <= q2 < self.n):
175
- raise ValueError(f"Qubit indices ({q1},{q2}) out of range [0, {self.n})")
176
- gate = self.xp.array(gate, dtype=self.dtype)
177
- sv_nd = self.sv.reshape([2] * self.n)
178
- sv_moved = self.xp.moveaxis(sv_nd, (q1, q2), (-2, -1))
179
- flat_shape = (self.dim >> 2, 4)
180
- result = self.xp.dot(sv_moved.reshape(flat_shape),
181
- gate.reshape(4, 4).T)
182
- self.sv = self.xp.moveaxis(
183
- result.reshape([2] * self.n), (-2, -1), (q1, q2)).ravel()
184
-
185
- # ── specialised 2-qubit gates ─────────────────────────────────────
186
-
187
- def apply_cx(self, ctrl: int, tgt: int):
188
- """
189
- CX (CNOT) gate.
190
-
191
- JAX path: matrix contraction via apply_gate_2q.
192
- NumPy path: fully vectorised index swap — no Python loops.
193
- """
194
- if ctrl == tgt:
195
- raise ValueError("Control and target qubits must differ")
196
- if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
197
- raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
198
- if HAS_JAX:
199
- cx_mat = jnp.array([
200
- [1, 0, 0, 0],
201
- [0, 1, 0, 0],
202
- [0, 0, 0, 1],
203
- [0, 0, 1, 0],
204
- ], dtype=self.dtype)
205
- self.apply_gate_2q(cx_mat, ctrl, tgt)
206
- else:
207
- self.sv = _cx_numpy(np.array(self.sv), self.n, ctrl, tgt)
208
-
209
- def apply_cz(self, ctrl: int, tgt: int):
210
- """
211
- CZ gate.
212
-
213
- JAX path: matrix contraction via apply_gate_2q.
214
- NumPy path: fully vectorised sign flip — no Python loops.
215
- """
216
- if ctrl == tgt:
217
- raise ValueError("Control and target qubits must differ")
218
- if not (0 <= ctrl < self.n and 0 <= tgt < self.n):
219
- raise ValueError(f"Qubit indices ({ctrl},{tgt}) out of range [0, {self.n})")
220
- if HAS_JAX:
221
- cz_mat = jnp.array([
222
- [1, 0, 0, 0],
223
- [0, 1, 0, 0],
224
- [0, 0, 1, 0],
225
- [0, 0, 0, -1],
226
- ], dtype=self.dtype)
227
- self.apply_gate_2q(cz_mat, ctrl, tgt)
228
- else:
229
- self.sv = _cz_numpy(np.array(self.sv), self.n, ctrl, tgt)
230
-
231
- def apply_rx(self, qubit: int, theta: float):
232
- """Apply a parameterized RX gate using the active backend (NumPy/JAX)."""
233
- cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
234
- mat = self.xp.array([[cos, -1j * sin], [-1j * sin, cos]], dtype=self.dtype)
235
- self.apply_gate_1q(mat, qubit)
236
-
237
- def apply_ry(self, qubit: int, theta: float):
238
- """Apply a parameterized RY gate using the active backend (NumPy/JAX)."""
239
- cos, sin = self.xp.cos(theta / 2), self.xp.sin(theta / 2)
240
- mat = self.xp.array([[cos, -sin], [sin, cos]], dtype=self.dtype)
241
- self.apply_gate_1q(mat, qubit)
242
-
243
- def apply_rz(self, qubit: int, theta: float):
244
- """Apply a parameterized RZ gate using the active backend (NumPy/JAX)."""
245
- exp_neg = self.xp.exp(-1j * theta / 2)
246
- exp_pos = self.xp.exp(1j * theta / 2)
247
- mat = self.xp.array([[exp_neg, 0.0], [0.0, exp_pos]], dtype=self.dtype)
248
- self.apply_gate_1q(mat, qubit)
249
-
250
- # ── measurement ───────────────────────────────────────────────────
251
-
252
- def measure(self, qubit_idx: int) -> int:
253
- """
254
- Projective measurement on *qubit_idx*.
255
-
256
- Returns 0 or 1 and collapses the statevector.
257
- Uses MSB-first physical bit index: phys = n - 1 - qubit_idx.
258
-
259
- BUG FIX (original): the original NumPy collapse wrote
260
- sv_reshaped[:, 1 if result == 0 else 0, :] = 0.0
261
- which zeroed the *wrong* basis state (0 when result=1, 1 when result=0)
262
- and never normalised the JAX path.
263
- """
264
- if not 0 <= qubit_idx < self.n:
265
- raise ValueError(
266
- f"Qubit {qubit_idx} out of range [0, {self.n})")
267
-
268
- phys = self.n - 1 - qubit_idx
269
- stride = 1 << phys
270
-
271
- # ── compute marginal probabilities ──────────────────────────
272
- if HAS_JAX:
273
- probs = jnp.abs(self.sv) ** 2
274
- sv_nd = probs.reshape([2] * self.n)
275
- mv = jnp.moveaxis(sv_nd, phys, 0)
276
- prob_0 = float(jnp.sum(mv[0]))
277
- prob_1 = float(jnp.sum(mv[1]))
278
- else:
279
- sv_res = self.sv.reshape(-1, 2, stride)
280
- prob_0 = float(np.sum(np.abs(sv_res[:, 0, :]) ** 2))
281
- prob_1 = float(np.sum(np.abs(sv_res[:, 1, :]) ** 2))
282
-
283
- total = prob_0 + prob_1
284
- if total < 1e-12:
285
- raise RuntimeError("Statevector norm is zero — cannot measure")
286
- prob_0 /= total
287
- prob_1 /= total
288
-
289
- result = int(np.random.choice([0, 1], p=[prob_0, prob_1]))
290
-
291
- # ── collapse ────────────────────────────────────────────────
292
- # Zero out the amplitudes corresponding to the *opposite* outcome.
293
- zero_slot = 1 - result # if result=0, zero slot 1; if result=1, zero slot 0
294
-
295
- if HAS_JAX:
296
- sv_nd = self.sv.reshape([2] * self.n)
297
- mv = jnp.moveaxis(sv_nd, phys, 0)
298
- mv = mv.at[zero_slot].set(0.0 + 0j)
299
- self.sv = jnp.moveaxis(mv, 0, phys).ravel()
300
- else:
301
- sv_res = self.sv.reshape(-1, 2, stride)
302
- sv_res[:, zero_slot, :] = 0.0
303
- self.sv = sv_res.ravel()
304
-
305
- self.normalize()
306
- return result
307
-
308
- # ── circuit execution ─────────────────────────────────────────────
309
-
310
- def run_circuit(self, circuit: List[Tuple], transpile: bool = True):
311
- target = QuantumTranspiler.transpile(circuit) if transpile else circuit
312
- for cmd in target:
313
- name = cmd[0].lower()
314
- args = cmd[1:]
315
-
316
- if name in GATES:
317
- mat = self.xp.array(GATES[name], dtype=self.dtype)
318
- if mat.shape == (2, 2):
319
- self.apply_gate_1q(mat, int(args[0]))
320
- else:
321
- self.apply_gate_2q(mat, int(args[0]), int(args[1]))
322
-
323
- elif name in PARAMETRIC_GATES:
324
- if len(args) == 2:
325
- mat = self.xp.array(PARAMETRIC_GATES[name](args[1]), dtype=self.dtype)
326
- self.apply_gate_1q(mat, int(args[0]))
327
- elif len(args) == 3:
328
- mat = self.xp.array(PARAMETRIC_GATES[name](args[2]), dtype=self.dtype)
329
- self.apply_gate_2q(mat, int(args[0]), int(args[1]))
330
- elif len(args) == 4:
331
- mat = self.xp.array(
332
- PARAMETRIC_GATES[name](args[1], args[2], args[3]),
333
- dtype=self.dtype)
334
- self.apply_gate_1q(mat, int(args[0]))
335
-
336
-
337
-
338
- def run_circuit_jit_beast_mode(self, circuit: List):
339
-
340
- if not HAS_JAX:
341
- return self.run_circuit(circuit)
342
-
343
- target = QuantumTranspiler.transpile(circuit)
344
- compiled_ops = []
345
-
346
- for cmd in target:
347
- name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
348
- if name not in GATE_IDS:
349
- continue
350
-
351
- g_id = float(GATE_IDS[name])
352
- args = cmd[1:]
353
-
354
- # ── gate argument parsing ──────────────────────────────
355
- # 1-qubit parametric: (name, qubit, param)
356
- if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
357
- q1 = float(args[0])
358
- p = float(args[1]) if len(args) > 1 else 0.0
359
- compiled_ops.append([g_id, q1, 0.0, p])
360
-
361
- # 2-qubit parametric: (name, ctrl, tgt, param)
362
- elif name in ('cp', 'crz', 'cphase'):
363
- ctrl = float(args[0])
364
- tgt = float(args[1]) if len(args) > 1 else 0.0
365
- p = float(args[2]) if len(args) > 2 else 0.0
366
- compiled_ops.append([g_id, ctrl, tgt, p])
367
-
368
- # 2-qubit non-parametric: (name, ctrl, tgt)
369
- elif name in ('cx', 'cz', 'swap', 'cy'):
370
- ctrl = float(args[0])
371
- tgt = float(args[1]) if len(args) > 1 else 0.0
372
- compiled_ops.append([g_id, ctrl, tgt, 0.0])
373
-
374
- # 1-qubit non-parametric: (name, qubit)
375
- else:
376
- q1 = float(args[0]) if args else 0.0
377
- compiled_ops.append([g_id, q1, 0.0, 0.0])
378
-
379
- if compiled_ops:
380
- ops_jnp = jnp.array(compiled_ops, dtype=jnp.float64)
381
- self.sv = _compile_and_run_circuit_jit(self.sv, ops_jnp)
382
-
383
- def run_circuit_with_chunking(self, circuit: List, chunk_size: int = 500):
384
- """
385
- Execute a circuit in chunks to avoid JIT recompilation on
386
- large variable-length circuits.
387
-
388
- Each chunk is a separate _compile_and_run_circuit_jit call
389
- with a fixed-size ops array, allowing XLA to cache each size.
390
- """
391
- target = QuantumTranspiler.transpile(circuit)
392
- for i in range(0, len(target), chunk_size):
393
- self.run_circuit_jit_beast_mode(target[i: i + chunk_size])
394
-
395
- def run_parametric_batch_jit(self,
396
- base_circuit: List,
397
- parameter_batch: np.ndarray) -> "jnp.ndarray":
398
-
399
- if not HAS_JAX:
400
- raise RuntimeError("run_parametric_batch_jit requires JAX")
401
-
402
- target = QuantumTranspiler.transpile(base_circuit)
403
- compiled_ops = []
404
-
405
- for cmd in target:
406
- name = cmd[0].lower() if isinstance(cmd[0], str) else str(cmd[0]).lower()
407
- if name not in GATE_IDS:
408
- continue
409
- g_id = float(GATE_IDS[name])
410
- args = cmd[1:]
411
- if name in ('rx', 'ry', 'rz', 'p', 'u1', 'phase'):
412
- compiled_ops.append([g_id, float(args[0]), 0.0, -1.0]) # -1.0 = param slot
413
- elif name in ('cp', 'crz', 'cphase'):
414
- compiled_ops.append([g_id, float(args[0]), float(args[1]) if len(args) > 1 else 0.0, -1.0])
415
- elif name in ('cx', 'cz', 'swap', 'cy'):
416
- compiled_ops.append([g_id, float(args[0]), float(args[1]) if len(args) > 1 else 0.0, 0.0])
417
- else:
418
- compiled_ops.append([g_id, float(args[0]) if args else 0.0, 0.0, 0.0])
419
-
420
- template = jnp.array(compiled_ops, dtype=jnp.float64)
421
- init_sv = jnp.zeros(self.dim, dtype=jnp.complex128).at[0].set(1.0)
422
-
423
- def simulate_single_instance(single_params: "jnp.ndarray") -> "jnp.ndarray":
424
- """Run one parameter vector through the circuit."""
425
-
426
- def patch_and_apply(carry: "jnp.ndarray",
427
- op: "jnp.ndarray"):
428
- """
429
- carry: jnp.int32 scalar — current parametric gate index.
430
- op: [g_id, q1, q2, p_sentinel]
431
- """
432
- idx = carry
433
- is_param = op[3] == -1.0
434
- final_p = jnp.where(is_param, single_params[idx], op[3])
435
- next_idx = jnp.where(is_param, idx + jnp.int32(1), idx)
436
- patched = jnp.array([op[0], op[1], op[2], final_p],
437
- dtype=jnp.float64)
438
- return next_idx, patched
439
-
440
- _, patched_ops = jax.lax.scan(
441
- patch_and_apply,
442
- jnp.int32(0), # BUG FIX: was (0,) tuple — must be a scalar
443
- template,
444
- )
445
- return _compile_and_run_circuit_jit(init_sv, patched_ops)
446
-
447
- return jax.jit(jax.vmap(simulate_single_instance, in_axes=(0,)))(
448
- jnp.asarray(parameter_batch, dtype=jnp.float64)
449
- )
450
-
451
- # ── observables ───────────────────────────────────────────────────
452
-
453
- def get_probabilities(self) -> np.ndarray:
454
- """Return measurement probability distribution as a NumPy float64 array."""
455
- probs = np.array(self.xp.abs(self.sv) ** 2, dtype=np.float64)
456
- # guard against floating-point leakage outside [0, 1]
457
- probs = np.clip(probs, 0.0, 1.0)
458
- total = probs.sum()
459
- if total > 1e-12:
460
- probs /= total
461
- return probs
462
-
463
- def get_statevector(self) -> np.ndarray:
464
- """Return the current statevector as a NumPy complex array."""
465
- return np.array(self.sv, dtype=self.dtype)
466
-
467
- def memory_mb(self) -> float:
468
- """Statevector memory footprint in megabytes."""
469
- bytes_per_element = 8 if self.use_float32 else 16 # complex64=8, complex128=16
470
- return self.dim * bytes_per_element / 1_000_000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dense_evolution/stress_test.py DELETED
@@ -1,76 +0,0 @@
1
- import time
2
- import numpy as np
3
- from dense_evolution import DenseSVSimulator, QASMParser, QuantumTranspiler, NoiseModel
4
-
5
- print("====================================================")
6
- print("🔬 ADVANCED PRODUCTION STRESS-TEST: KRAUS & JIT SIMULATION")
7
- print("====================================================")
8
-
9
- try:
10
- qasm_bench = """
11
- OPENQASM 2.0;
12
- include "qelib1.inc";
13
- qreg q[6];
14
- h q[0];
15
- cx q[0], q[1];
16
- cx q[1], q[2];
17
- cx q[2], q[3];
18
- cx q[3], q[4];
19
- cx q[4], q[5];
20
- rx(1.570796) q[0];
21
- ry(0.785398) q[1];
22
- rz(0.392699) q[2];
23
- """
24
-
25
- print("1. Parsing e Transpilazione del circuito QASM...")
26
- # Questo testa la corretta importazione e funzione di parser.py e compiler.py
27
- parser = QASMParser()
28
- circ = parser.parse(qasm_bench)
29
- tuples = QuantumTranspiler.transpile(circ.to_tuples())
30
- n_qubits = circ.n_qubits
31
- print(f"✓ Parsing completato. Qubit: {n_qubits}, Gate transpilati: {len(tuples)}")
32
-
33
- print("\n2. Validazione Core JIT in modalità ideale (simulator.py)...")
34
- t0 = time.perf_counter()
35
- sim_ideale = DenseSVSimulator(n_qubits)
36
- sim_ideale.run_circuit_jit_beast_mode(tuples)
37
- t_ideale = time.perf_counter() - t0
38
- prob_ideale = sim_ideale.get_probabilities()
39
- print(f"✓ Successo ideale in {t_ideale:.4f} s | Dimensione stato: {len(prob_ideale)}")
40
-
41
- print("\n3. Validazione NoiseModel (registry.py): Canale stocastico Amplitude Damping...")
42
-
43
- # Run Noisy 1
44
- t0 = time.perf_counter()
45
- sim_noisy1 = DenseSVSimulator(n_qubits)
46
- sim_noisy1.run_circuit_jit_beast_mode(tuples)
47
- # Iniezione diretta del rumore Kraus sullo statevector compilato
48
- sim_noisy1.sv = NoiseModel.apply_to_sv(sim_noisy1.sv, n_qubits, model='amplitude_damping', p=0.15)
49
- prob_noisy1 = sim_noisy1.get_probabilities()
50
- t_noisy1 = time.perf_counter() - t0
51
-
52
- # Run Noisy 2
53
- sim_noisy2 = DenseSVSimulator(n_qubits)
54
- sim_noisy2.run_circuit_jit_beast_mode(tuples)
55
- sim_noisy2.sv = NoiseModel.apply_to_sv(sim_noisy2.sv, n_qubits, model='amplitude_damping', p=0.15)
56
- prob_noisy2 = sim_noisy2.get_probabilities()
57
-
58
- print(f"✓ Successo noisy in {t_noisy1:.4f} s")
59
-
60
- print("\n4. Analisi statistica delle fluttuazioni (Shot Noise Reale)...")
61
- scostamento_stocastico = np.linalg.norm(prob_noisy1 - prob_noisy2)
62
- scostamento_ideale = np.linalg.norm(prob_ideale - prob_noisy1)
63
-
64
- print(f"🔬 Distanza ideale-noisy: {scostamento_ideale:.6f}")
65
- print(f"🔬 Fluttuazione quantistica indipendente (Shot Noise): {scostamento_stocastico:.6f}")
66
-
67
- if scostamento_stocastico > 1e-12:
68
- print("\n✅ TEST SUPERATO: Moduli collegati, PRNG JAX funzionante e rumore autenticamente non-deterministico!")
69
- else:
70
- print("\n❌ FALLIMENTO: Il rumore è ancora lineare o statico. Le due run hanno prodotto stati identici.")
71
-
72
- print("====================================================")
73
-
74
- except Exception as e:
75
- print(f"\n❌ CRASH DURANTE L'ELABORAZIONE HARDWARE: {str(e)}")
76
- print("====================================================")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/dist/dense_evolution-8.1.6-py3-none-any.whl DELETED
Binary file (83.7 kB)
 
Dense_Evolution_Project/dist/dense_evolution-8.1.6.tar.gz DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:551e29c57e3427e5e8347664c56c54ab4173d6574e7a491398df1c4654ec0d9d
3
- size 85685
 
 
 
 
Dense_Evolution_Project/license.md DELETED
@@ -1,58 +0,0 @@
1
- # Business Source License 1.1 (BSL 1.1)
2
-
3
- **Software:** Dense Evolution
4
- **Licenziante:** Salvatore Pennacchio <jtatopenn@libero.it>
5
-
6
- La presente Business Source License (la "Licenza") si applica integralmente al codice sorgente, agli algoritmi, ai moduli software, ai file di configurazione e all'oggetto binario del software denominato "Dense Evolution" (il "Software").
7
-
8
- ## 1. Parametri della Licenza
9
-
10
- * **Licenziante:** Salvatore Pennacchio <jtatopenn@libero.it>
11
- * **Software:** Dense Evolution (inclusi aggiornamenti, patch, ottimizzazioni di kernel, moduli di partizionamento della memoria e opere derivate fornite dal Licenziante).
12
- * **Data di Modifica:** 1 Giugno 2029
13
- * **Licenza di Modifica:** Apache License, Versione 2.0 (o successive, a esclusiva discrezione del Licenziante).
14
- * **Uso Consentito per la Produzione:** Uso strettamente non commerciale ed esecuzioni limitate ai parametri definiti nella Sezione 4. Per l'uso in ambienti di produzione commerciale, industriale o di consulenza tariffata che ecceda tali parametri, si applica l'obbligo inderogabile di licenza separata.
15
-
16
- ---
17
-
18
- ## 2. Concessione della Licenza e Obbligo di Attribuzione
19
-
20
- Il Licenziante concede al Licenziatario una licenza non esclusiva, valida in tutto il mondo, esente da royalty e revocabile unicamente in caso di violazione dei termini qui stabiliti, per l'uso, la riproduzione, la distribuzione, la modifica e la creazione di opere derivate del Software, per scopi non commerciali e nei limiti dell'Uso Consentito per la Produzione.
21
-
22
- **Condizione Tassativa di Attribuzione:** Qualsiasi copia, porzione, modulo o opera derivata del Software (incluse piattaforme terze, infrastrutture cloud, sistemi hardware o interfacce API che integrino o richiamino Dense Evolution) deve includere in modo visibile, inalterato e permanente il copyright originale e l'attribuzione esplicita al Licenziante nella forma:
23
- `© 2026 Salvatore Pennacchio <jtatopenn@libero.it> - Dense Evolution`.
24
-
25
- ---
26
-
27
- ## 3. Condizioni e Limiti Generali di Utilizzo
28
-
29
- Il Software può essere utilizzato, riprodotto, distribuito e modificato a condizione che tale utilizzo non sia destinato a scopi di produzione commerciale, industriale o all'erogazione di servizi computazionali e cloud commerciali che competano direttamente o indirettamente con i prodotti o i servizi offerti dal Licenziante, ad eccezione di quanto espressamente previsto dalla Sezione 4 o a partire dalla Data di Modifica (Sezione 5).
30
-
31
- ---
32
-
33
- ## 4. Concessione di Utilizzo Aggiuntivo (Uso Commerciale Limitato)
34
-
35
- In deroga alle restrizioni della Sezione 3, il Licenziatario è autorizzato a utilizzare il Software per scopi di produzione commerciale, industriale o di consulenza tariffata, senza necessità di una licenza separata a pagamento, esclusivamente se vengono rispettati i seguenti limiti computazionali e tecnici:
36
-
37
- * **Limite di Qubit Complessivi:** La simulazione quantistica eseguita non deve superare la dimensione di **24 qubit allocati in memoria**. Tale limite si applica alla dimensione logica complessiva del sistema e alla somma cumulativa di tutte le istanze, processi, thread, sottomatrici o nodi di cluster paralleli eseguiti contemporaneamente dalla medesima organizzazione, entità giuridica o utente finale.
38
- * **Limite di Circuiti e Campionamenti:** Il volume massimo di calcolo consentito in ambiente di produzione è fissato a **1000 strutture di circuiti quantistici distinti nell'arco di 24 ore**, ciascuno dei quali può essere eseguito per un massimo di **10.000 campionamenti (shots) equivalenti** per singolo circuito.
39
-
40
- **Divieto di Elusione Tecnica:** È fatto esplicito divieto di aggirare i presenti limiti computazionali tramite tecniche di scomposizione dei circuiti (*splitting*), mascheramento dei sottomoduli (*wrapping*), architetture di *Circuit Chunking* esterne o ridistribuzione del carico su più account o macchine virtuali appartenenti alla stessa entità. Qualsiasi utilizzo che ecceda anche solo uno dei parametri sopra indicati richiede obbligatoriamente la preventiva sottoscrizione di un accordo di licenza commerciale separato con il Licenziante.
41
-
42
- ---
43
-
44
- ## 5. Transizione alla Licenza di Modifica
45
-
46
- A partire dal **1 Giugno 2029** (la "Data di Modifica"), la presente Licenza cesserà automaticamente di avere effetto sul Software e su tutte le versioni rilasciate antecedentemente a tale data. Da quel momento, il Software diventerà permanentemente e liberamente disponibile sotto i termini della **Apache License 2.0**. Fino alla Data di Modifica, la presente Licenza BSL 1.1 rimarrà pienamente in vigore, valida, vincolante e opponibile a terzi.
47
-
48
- ---
49
-
50
- ## 6. Esclusione di Garanzia e Limitazione di Responsabilità
51
-
52
- IL SOFTWARE VIENE FORNITO "COSÌ COM'È", SENZA ALCUNA GARANZIA DI ALCUN TIPO, ESPRESSA O IMPLICITA, INCLUSE, A TITOLO ESEMPLIFICATIVO, LE GARANZIE DI COMMERCIABILITÀ, IDONEITÀ PER UNO SCOPO PARTICOLARE E NON VIOLAZIONE DEI DIRITTI DI TERZI. IN NESSUN CASO IL LICENZIANTE O L'AUTORE SARÀ RESPONSABILE PER QUALSIASI RECLAMO, DANNO O ALTRA RESPONSABILITÀ, SIA IN UN'AZIONE CONTRATTUALE, PER ILLECITO CIVILE O EXTRA-CONTRATTUALE, DERIVANTE DA, O IN CONNESSIONE CON IL SOFTWARE, IL SUO UTILIZZO O ALTRE OPERAZIONI EFFETTUATE SUL SOFTWARE STESSO.
53
-
54
- ---
55
-
56
- ## 7. Legge Applicabile e Foro Competente
57
-
58
- La presente Licenza è regolata, interpretata e disciplinata in ogni suo aspetto in conformità alle leggi dello **Stato Italiano**. Qualsiasi controversia derivante da, o connessa con l'interpretazione, l'esecuzione, la violazione o la validità della presente Licenza sarà devoluta alla giurisdizione esclusiva e inderogabile del **Foro di Milano**.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/pyproject.toml DELETED
@@ -1,83 +0,0 @@
1
- [build-system]
2
- requires = ["setuptools>=61.0.0", "wheel"]
3
- build-backend = "setuptools.build_meta"
4
-
5
- [project]
6
- name = "dense-evolution"
7
- version = "8.1.6"
8
- description = "Micro-optimized High-Performance NISQ Statevector Quantum Circuit Simulator (Hardware-Adaptive Integration of Native NumPy, CUDA-Accelerated CuPy, and Linear Kernel Fusion via JAX JIT/XLA Compilation)"
9
- readme = "README.md"
10
- requires-python = ">=3.9"
11
- license = { text = "Business Source License 1.1" }
12
- authors = [
13
- { name = "Salvatore Pennacchio", email = "jtatopenn@libero.it" }
14
- ]
15
- keywords = [
16
- "quantum-computing",
17
- "quantum-simulation",
18
- "statevector",
19
- "jax",
20
- "cupy",
21
- "cuda-acceleration",
22
- "openqasm",
23
- "nisq-noise",
24
- "hpc",
25
- "linear-kernel-fusion",
26
- "dashboard",
27
- "visualization"
28
- ]
29
- classifiers = [
30
- "Development Status :: 5 - Production/Stable",
31
- "Intended Audience :: Science/Research",
32
- "Intended Audience :: Developers",
33
- "License :: Other/Proprietary License",
34
- "Programming Language :: Python :: 3",
35
- "Programming Language :: Python :: 3.9",
36
- "Programming Language :: Python :: 3.10",
37
- "Programming Language :: Python :: 3.11",
38
- "Programming Language :: Python :: 3.12",
39
- "Topic :: Scientific/Engineering :: Physics",
40
- "Topic :: Software Development :: Libraries :: Python Modules"
41
- ]
42
- dependencies = [
43
- "numpy>=1.22.0",
44
- "matplotlib>=3.5.0",
45
- "psutil>=5.9.0"
46
- ]
47
-
48
- [project.optional-dependencies]
49
- jax = [
50
- "jax>=0.4.0",
51
- "jaxlib>=0.4.0"
52
- ]
53
- gpu = [
54
- "cupy-cuda12x>=12.0.0"
55
- ]
56
- dashboard = [
57
- "dash>=2.0.0",
58
- "plotly>=5.0.0"
59
- ]
60
- full = [
61
- "jax>=0.4.0",
62
- "jaxlib>=0.4.0",
63
- "cupy-cuda12x>=12.0.0",
64
- "dash>=2.0.0",
65
- "plotly>=5.0.0"
66
- ]
67
-
68
- [project.urls]
69
- Homepage = "https://github.com/tatopenn-cell/Dense-Evolution"
70
- Documentation = "https://github.com/tatopenn-cell/Dense-Evolution/blob/main/README.md"
71
- Repository = "https://github.com/tatopenn-cell/Dense-Evolution"
72
- "Bug Tracker" = "https://github.com/tatopenn-cell/Dense-Evolution/issues"
73
-
74
- [tool.setuptools]
75
- packages = ["dense_evolution"]
76
- py-modules = ["dash"]
77
-
78
- [tool.setuptools.package-data]
79
- "dense_evolution" = ["*.py"]
80
-
81
- [tool.black]
82
- line-length = 100
83
- target-version = ['py39', 'py310', 'py311', 'py312']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dense_Evolution_Project/test_dense_evolution.py DELETED
@@ -1,467 +0,0 @@
1
- import numpy as np
2
- import pytest
3
- from dense_evolution import DenseSVSimulator, GATES, PARAMETRIC_GATES, NoiseModel, QuantumTranspiler
4
-
5
- import inspect
6
- import jax.numpy as jnp # Ensure jnp is available for jax backend
7
-
8
- # Patch the measure method directly within the test file to ensure pytest uses the patched version
9
- def patched_measure_for_tests(self, qubit_idx: int) -> int:
10
- """
11
- Misura un singolo qubit e collassa lo stato quantistico.
12
- """
13
- import numpy as np # Ensure np is available for random.choice
14
-
15
- if not 0 <= qubit_idx < self.n:
16
- raise ValueError(f"Qubit {qubit_idx} out of bounds")
17
-
18
- xp = self.xp
19
- # phys_q is used for stride calculation in NumPy/CuPy branch (LSB-first index)
20
- phys_q = self.n - 1 - qubit_idx
21
- stride = 1 << phys_q
22
-
23
- if xp is jnp:
24
- # JAX branch: Calculate probabilities by moving the correct (MSB-indexed) axis
25
- probs = self.xp.abs(self.sv)**2
26
- sv_shape = [2] * self.n
27
- sv_nd = probs.reshape(sv_shape)
28
- # FIX: Use qubit_idx directly as axis, as sv_nd is MSB-first indexed
29
- moved_probs = jnp.moveaxis(sv_nd, qubit_idx, 0)
30
- prob_0 = float(jnp.sum(moved_probs[0]))
31
- prob_1 = float(jnp.sum(moved_probs[1]))
32
- else:
33
- # NumPy/CuPy Stride Slicing: phys_q and stride logic correctly applied here
34
- sv_reshaped = self.sv.reshape(-1, 2, stride)
35
- prob_0 = float(xp.sum(xp.abs(sv_reshaped[:, 0, :])**2))
36
- prob_1 = float(xp.sum(xp.abs(sv_reshaped[:, 1, :])**2))
37
-
38
- total = prob_0 + prob_1
39
- if total > 1e-12:
40
- prob_0 /= total
41
- prob_1 /= total
42
-
43
- # Sampling the measurement outcome
44
- result = int(np.random.choice([0, 1], p=[prob_0, prob_1]))
45
-
46
- if xp is jnp:
47
- sv_shape = [2] * self.n
48
- sv_nd = self.sv.reshape(sv_shape)
49
- moved_sv = jnp.moveaxis(sv_nd, qubit_idx, 0) # FIX: Apply same correction here
50
- # Correctly zero out the unmeasured component (1 if result is 0, 0 if result is 1)
51
- moved_sv = moved_sv.at[1 - result].set(0.0)
52
- self.sv = jnp.moveaxis(moved_sv, 0, qubit_idx).ravel() # FIX: And here too
53
- else:
54
- sv_reshaped = self.sv.reshape(-1, 2, stride)
55
- # Zero out the unmeasured component
56
- sv_reshaped[:, 1 if result == 0 else 0, :] = 0.0
57
- self.sv = sv_reshaped.ravel()
58
-
59
- self.normalize()
60
- return result
61
-
62
- # Apply the patch
63
- DenseSVSimulator.measure = patched_measure_for_tests
64
-
65
- # ─────────────────────────────────────────────────────────────
66
- # FIXTURES
67
- # ─────────────────────────────────────────────────────────────
68
-
69
- @pytest.fixture
70
- def sim2():
71
- """Fresh 2-qubit simulator (NumPy CPU, float64)"""
72
- return DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
73
-
74
- @pytest.fixture
75
- def sim3():
76
- """Fresh 3-qubit simulator (NumPy CPU, float64)"""
77
- return DenseSVSimulator(n_qubits=3, use_gpu=False, use_float32=False)
78
-
79
- @pytest.fixture
80
- def sim4():
81
- """Fresh 4-qubit simulator (NumPy CPU, float64)"""
82
- return DenseSVSimulator(n_qubits=4, use_gpu=False, use_float32=False)
83
-
84
- # ─────────────────────────────────────────────────────────────
85
- # HELPER
86
- # ─────────────────────────────────────────────────────────────
87
-
88
- def norm(sim):
89
- return float(np.linalg.norm(sim.get_statevector()))
90
-
91
- def probs(sim):
92
- return sim.get_probabilities()
93
-
94
- # ─────────────────────────────────────────────────────────────
95
- # 1. INITIALIZATION
96
- # ─────────────────────────────────────────────────────────────
97
-
98
- class TestInitialization:
99
-
100
- def test_initial_state_is_zero(self, sim2):
101
- sv = sim2.get_statevector()
102
- expected = np.zeros(4, dtype=complex)
103
- expected[0] = 1.0
104
- np.testing.assert_allclose(sv, expected, atol=1e-12)
105
-
106
- def test_initial_norm_is_one(self, sim2):
107
- assert abs(norm(sim2) - 1.0) < 1e-12
108
-
109
- def test_initial_probabilities(self, sim2):
110
- p = probs(sim2)
111
- assert abs(p[0] - 1.0) < 1e-12
112
- assert np.all(p[1:] < 1e-12)
113
-
114
- def test_custom_initial_state(self, sim2):
115
- sv_in = np.array([1, 0, 0, 1], dtype=complex) / np.sqrt(2)
116
- sim2.set_initial_state(sv_in)
117
- sv_out = sim2.get_statevector()
118
- np.testing.assert_allclose(np.abs(sv_out), np.abs(sv_in), atol=1e-12)
119
-
120
- def test_invalid_state_raises(self, sim2):
121
- with pytest.raises(ValueError):
122
- sim2.set_initial_state(np.array([1, 0, 0], dtype=complex))
123
-
124
- # ─────────────────────────────────────────────────────────────
125
- # 2. SINGLE-QUBIT GATES
126
- # ─────────────────────────────────────────────────────────────
127
-
128
- class TestSingleQubitGates:
129
-
130
- def test_x_gate_flips_qubit(self, sim2):
131
- """X|0⟩ = |1⟩"""
132
- sim2.apply_gate_1q(GATES['x'], 0)
133
- p = probs(sim2)
134
- # In MSB: qubit 0 is the most significant bit → |10⟩ = index 2
135
- assert p[2] > 0.99
136
-
137
- def test_x_gate_double_application_identity(self, sim2):
138
- """XX = I"""
139
- sim2.apply_gate_1q(GATES['x'], 0)
140
- sim2.apply_gate_1q(GATES['x'], 0)
141
- p = probs(sim2)
142
- assert p[0] > 0.99
143
-
144
- def test_h_gate_creates_superposition(self, sim2):
145
- """H|0⟩ = (|0⟩+|1⟩)/√2 on qubit 0"""
146
- sim2.apply_gate_1q(GATES['h'], 0)
147
- p = probs(sim2)
148
- assert abs(p[0] - 0.5) < 1e-10
149
- assert abs(p[2] - 0.5) < 1e-10
150
-
151
- def test_h_gate_is_self_inverse(self, sim2):
152
- """HH = I"""
153
- sim2.apply_gate_1q(GATES['h'], 0)
154
- sim2.apply_gate_1q(GATES['h'], 0)
155
- p = probs(sim2)
156
- assert p[0] > 0.99
157
-
158
- def test_z_gate_on_zero_state_no_change(self, sim2):
159
- """Z|0⟩ = |0⟩ (phase change invisible in probabilities)"""
160
- sim2.apply_gate_1q(GATES['z'], 0)
161
- p = probs(sim2)
162
- assert p[0] > 0.99
163
-
164
- def test_z_gate_on_superposition_flips_phase(self, sim2):
165
- """Z applied after H: |+⟩ → |-⟩, then H gives |1⟩"""
166
- sim2.apply_gate_1q(GATES['h'], 0)
167
- sim2.apply_gate_1q(GATES['z'], 0)
168
- sim2.apply_gate_1q(GATES['h'], 0)
169
- p = probs(sim2)
170
- # result should be |1x⟩ → qubit 0 in state |1⟩
171
- assert (p[2] + p[3]) > 0.99
172
-
173
- def test_norm_preserved_after_1q_gate(self, sim2):
174
- for g in ['h', 'x', 'y', 'z', 's', 't']:
175
- sim2.apply_gate_1q(GATES[g], 0)
176
- assert abs(norm(sim2) - 1.0) < 1e-12
177
-
178
- def test_out_of_bounds_qubit_raises(self, sim2):
179
- with pytest.raises((ValueError, IndexError)):
180
- sim2.apply_gate_1q(GATES['x'], 5)
181
-
182
- # ─────────────────────────────────────────────────────────────
183
- # 3. TWO-QUBIT GATES
184
- # ─────────────────────────────────────────────────────────────
185
-
186
- class TestTwoQubitGates:
187
-
188
- def test_cx_on_zero_state_no_change(self, sim2):
189
- """CNOT with ctrl=0 in |0⟩: no flip"""
190
- sim2.apply_cx(0, 1)
191
- p = probs(sim2)
192
- assert p[0] > 0.99
193
-
194
- def test_cx_flips_target_when_control_is_one(self, sim2):
195
- """CNOT with ctrl=1: |10⟩ → |11⟩"""
196
- sim2.apply_gate_1q(GATES['x'], 0) # set qubit 0 to |1⟩
197
- sim2.apply_cx(0, 1)
198
- p = probs(sim2)
199
- # |11⟩ = index 3
200
- assert p[3] > 0.99
201
-
202
- def test_cx_double_application_identity(self, sim2):
203
- sim2.apply_gate_1q(GATES['x'], 0)
204
- sim2.apply_cx(0, 1)
205
- sim2.apply_cx(0, 1)
206
- p = probs(sim2)
207
- assert p[2] > 0.99 # back to |10⟩
208
-
209
- def test_cz_no_change_on_zero_state(self, sim2):
210
- sim2.apply_cz(0, 1)
211
- p = probs(sim2)
212
- assert p[0] > 0.99
213
-
214
- def test_norm_preserved_after_2q_gate(self, sim2):
215
- sim2.apply_gate_1q(GATES['h'], 0)
216
- sim2.apply_cx(0, 1)
217
- assert abs(norm(sim2) - 1.0) < 1e-12
218
-
219
- def test_invalid_qubit_indices_raise(self, sim2):
220
- with pytest.raises(ValueError):
221
- sim2.apply_cx(0, 0)
222
- with pytest.raises(ValueError):
223
- sim2.apply_cx(0, 5)
224
-
225
- # ─────────────────────────────────────────────────────────────
226
- # 4. GHZ STATE (Esempio 1 dal README)
227
- # ─────────────────────────────────────────────────────────────
228
-
229
- class TestGHZState:
230
-
231
- def test_ghz_3qubit_probabilities(self, sim3):
232
- """H-CX-CX: generates |000⟩+|111⟩ / √2"""
233
- circuit = [('h', 0), ('cx', 0, 1), ('cx', 1, 2)]
234
- sim3.run_circuit(circuit)
235
- p = probs(sim3)
236
- assert abs(p[0] - 0.5) < 1e-10 # |000⟩
237
- assert abs(p[7] - 0.5) < 1e-10 # |111⟩
238
- # All other states should be zero
239
- for i in [1, 2, 3, 4, 5, 6]:
240
- assert p[i] < 1e-10
241
-
242
- def test_ghz_norm(self, sim3):
243
- circuit = [('h', 0), ('cx', 0, 1), ('cx', 1, 2)]
244
- sim3.run_circuit(circuit)
245
- assert abs(norm(sim3) - 1.0) < 1e-12
246
-
247
- def test_ghz_statevector_shape(self, sim3):
248
- circuit = [('h', 0), ('cx', 0, 1), ('cx', 1, 2)]
249
- sim3.run_circuit(circuit)
250
- sv = sim3.get_statevector()
251
- assert sv.shape == (8,)
252
- assert sv.dtype == np.complex128
253
-
254
- # ─────────────────────────────────────────────────────────────
255
- # 5. BELL STATE
256
- # ─────────────────────────────────────────────────────────────
257
-
258
- class TestBellState:
259
-
260
- def test_bell_phi_plus(self, sim2):
261
- """H + CNOT creates |Φ+⟩ = (|00⟩+|11⟩)/√2"""
262
- sim2.apply_gate_1q(GATES['h'], 0)
263
- sim2.apply_cx(0, 1)
264
- p = probs(sim2)
265
- assert abs(p[0] - 0.5) < 1e-10
266
- assert abs(p[3] - 0.5) < 1e-10
267
- assert p[1] < 1e-10
268
- assert p[2] < 1e-10
269
-
270
- def test_bell_entanglement_norm(self, sim2):
271
- sim2.apply_gate_1q(GATES['h'], 0)
272
- sim2.apply_cx(0, 1)
273
- assert abs(norm(sim2) - 1.0) < 1e-12
274
-
275
- # ─────────────────────────────────────────────────────────────
276
- # 6. PARAMETRIC GATES
277
- # ─────────────────────────────────────────────────────────────
278
-
279
- class TestParametricGates:
280
-
281
- def test_rx_pi_equals_x(self, sim2):
282
- """Rx(π)|0⟩ ≈ X|0⟩ up to global phase"""
283
- sim2.apply_rx(0, np.pi)
284
- p = probs(sim2)
285
- assert p[2] > 0.99 # qubit 0 flipped → |10⟩
286
-
287
- def test_rz_no_change_in_probabilities(self, sim2):
288
- """Rz only changes phase, not populations"""
289
- p_before = probs(sim2).copy()
290
- sim2.apply_rz(0, np.pi / 3)
291
- p_after = probs(sim2)
292
- np.testing.assert_allclose(p_before, p_after, atol=1e-12)
293
-
294
- def test_ry_half_pi_superposition(self, sim2):
295
- """Ry(π/2)|0⟩ gives equal superposition"""
296
- sim2.apply_ry(0, np.pi / 2)
297
- p = probs(sim2)
298
- assert abs(p[0] - 0.5) < 1e-10
299
- assert abs(p[2] - 0.5) < 1e-10
300
-
301
- def test_norm_preserved_after_parametric(self, sim2):
302
- for theta in [0.1, np.pi / 4, np.pi / 2, np.pi]:
303
- sim2_local = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
304
- sim2_local.apply_rx(0, theta)
305
- assert abs(norm(sim2_local) - 1.0) < 1e-12
306
-
307
- # ─────────────────────────────────────────────────────────────
308
- # 7. MEASUREMENT
309
- # ─────────────────────────────────────────────────────────────
310
-
311
- class TestMeasurement:
312
-
313
- def test_measure_zero_state_returns_zero(self):
314
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
315
- result = sim.measure(0)
316
- assert result == 0
317
-
318
- def test_measure_one_state_returns_one(self):
319
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
320
- sim.apply_gate_1q(GATES['x'], 0)
321
- result = sim.measure(0)
322
- assert result == 1
323
-
324
- def test_measure_collapses_state_norm(self):
325
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
326
- sim.apply_gate_1q(GATES['h'], 0)
327
- sim.measure(0)
328
- assert abs(norm(sim) - 1.0) < 1e-12
329
-
330
- def test_measure_returns_binary_value(self):
331
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
332
- sim.apply_gate_1q(GATES['h'], 0)
333
- results = set()
334
- for _ in range(30):
335
- s = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
336
- s.apply_gate_1q(GATES['h'], 0)
337
- results.add(s.measure(0))
338
- assert results == {0, 1}
339
-
340
- def test_measure_out_of_bounds_raises(self):
341
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
342
- with pytest.raises(ValueError):
343
- sim.measure(5)
344
-
345
- # ─────────────────────────────────────────────────────────────
346
- # 8. NOISE MODEL (Esempio 2 dal README)
347
- # ─────────────────────────────────────────────────────────────
348
-
349
- class TestNoiseModel:
350
-
351
- def test_ideal_model_no_change(self):
352
- sv = np.array([1.0, 0.0], dtype=complex)
353
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='ideal', p=0.1)
354
- np.testing.assert_allclose(sv_out, sv, atol=1e-12)
355
-
356
- def test_depolarizing_preserves_norm(self):
357
- sv = np.array([1.0, 0.0], dtype=complex)
358
- rng = np.random.default_rng(42)
359
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='depolarizing', p=0.2, rng=rng)
360
- assert abs(np.linalg.norm(sv_out) - 1.0) < 1e-10
361
-
362
- def test_bitflip_preserves_norm(self):
363
- sv = np.array([1.0, 0.0], dtype=complex)
364
- rng = np.random.default_rng(7)
365
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='bitflip', p=0.3, rng=rng)
366
- assert abs(np.linalg.norm(sv_out) - 1.0) < 1e-10
367
-
368
- def test_phaseflip_preserves_norm(self):
369
- sv = np.array([1.0, 0.0], dtype=complex)
370
- rng = np.random.default_rng(99)
371
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='phaseflip', p=0.5, rng=rng)
372
- assert abs(np.linalg.norm(sv_out) - 1.0) < 1e-10
373
-
374
- def test_amplitude_damping_preserves_norm(self):
375
- sv = np.array([0.0, 1.0], dtype=complex) # |1⟩
376
- rng = np.random.default_rng(42)
377
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='amplitude_damping', p=0.2, rng=rng)
378
- assert abs(np.linalg.norm(sv_out) - 1.0) < 1e-10
379
-
380
- def test_zero_probability_no_change(self):
381
- sv = np.array([1.0, 0.0], dtype=complex)
382
- rng = np.random.default_rng(0)
383
- sv_out = NoiseModel.apply_to_sv(sv, n=1, model='depolarizing', p=0.0, rng=rng)
384
- np.testing.assert_allclose(sv_out, sv, atol=1e-12)
385
-
386
- def test_kraus_description_returns_dict(self):
387
- for model in NoiseModel.MODELS:
388
- desc = NoiseModel.kraus_description(model)
389
- assert isinstance(desc, dict)
390
- assert 'kraus' in desc
391
-
392
- # ─────────────────────────────────────────────────────────────
393
- # 9. TRANSPILER
394
- # ─────────────────────────────────────────────────────────────
395
-
396
- class TestTranspiler:
397
-
398
- def test_ccx_decomposition_length(self):
399
- result = QuantumTranspiler.decompose_toffoli(0, 1, 2)
400
- assert len(result) == 15
401
-
402
- def test_swap_decomposition_length(self):
403
- result = QuantumTranspiler.decompose_swap(0, 1)
404
- assert len(result) == 3
405
-
406
- def test_transpile_passes_through_basic_gates(self):
407
- circuit = [('h', 0), ('x', 1), ('cx', 0, 1)]
408
- result = QuantumTranspiler.transpile(circuit)
409
- assert result == circuit
410
-
411
- def test_transpile_expands_ccx(self):
412
- circuit = [('ccx', 0, 1, 2)]
413
- result = QuantumTranspiler.transpile(circuit)
414
- assert len(result) == 15
415
- assert all(op[0] in ('h', 'cx', 't', 'tdg') for op in result)
416
-
417
- def test_toffoli_correctness(self, sim3):
418
- """CCX|110⟩ = |111⟩"""
419
- sim3.apply_gate_1q(GATES['x'], 0)
420
- sim3.apply_gate_1q(GATES['x'], 1)
421
- sim3.run_circuit([('ccx', 0, 1, 2)])
422
- p = probs(sim3)
423
- assert p[7] > 0.99 # |111⟩
424
-
425
- def test_toffoli_no_flip_without_both_controls(self, sim3):
426
- """CCX|100⟩ = |100⟩ (only one control active)"""
427
- sim3.apply_gate_1q(GATES['x'], 0)
428
- sim3.run_circuit([('ccx', 0, 1, 2)])
429
- p = probs(sim3)
430
- assert p[4] > 0.99 # |100⟩
431
-
432
- # ─────────────────────────────────────────────────────────────
433
- # 10. CIRCUIT CHUNKING (Stress test da README)
434
- # ─────────────────────────────────────────────────────────────
435
-
436
- class TestCircuitChunking:
437
-
438
- def test_chunking_preserves_norm(self):
439
- """5000 H + 5000 CNOT on 4 qubits: norm must stay 1.0"""
440
- sim = DenseSVSimulator(n_qubits=4, use_gpu=False, use_float32=False)
441
- n_gates = 500 # ridotto per velocità in CI
442
- circuit = [('h', i % 4) for i in range(n_gates // 2)]
443
- circuit += [('cx', i % 3, (i % 3) + 1) for i in range(n_gates // 2)]
444
- sim.run_circuit(circuit)
445
- assert abs(norm(sim) - 1.0) < 1e-10
446
-
447
- def test_run_circuit_with_chunking_exists(self):
448
- sim = DenseSVSimulator(n_qubits=2, use_gpu=False, use_float32=False)
449
- assert hasattr(sim, 'run_circuit_with_chunking') or hasattr(sim, 'run_circuit')
450
-
451
- # ─────────────────────────────────────────────────────────────
452
- # 11. MEMORY
453
- # ─────────────────────────────────────────────────────────────
454
-
455
- class TestMemory:
456
-
457
- def test_memory_mb_12_qubits(self):
458
- sim = DenseSVSimulator(n_qubits=12, use_gpu=False, use_float32=False)
459
- mb = sim.memory_mb()
460
- expected = (2**12 * 16) / 1e6
461
- assert abs(mb - expected) < 0.01
462
-
463
- def test_memory_mb_float32(self):
464
- sim = DenseSVSimulator(n_qubits=12, use_gpu=False, use_float32=True)
465
- mb = sim.memory_mb()
466
- expected = (2**12 * 8) / 1e6
467
- assert abs(mb - expected) < 0.01