Tatopenn commited on
Commit
d8eca12
·
verified ·
1 Parent(s): f3bc3b7

Sync ui_pages/ from v8.1.33

Browse files
ui_pages/ai_middleware.py CHANGED
@@ -12,6 +12,7 @@ statevector's flat probability array (2**n_qubits) does not.
12
  import pandas as pd
13
 
14
  from ia_utils.vector_healing import enhanced_dense_healing_hybrid
 
15
 
16
 
17
  def heal_telemetry(df: pd.DataFrame):
@@ -19,11 +20,7 @@ def heal_telemetry(df: pd.DataFrame):
19
  (healed_df, metadata). Empty/None input passes through with a neutral
20
  metadata dict (no NaN-safety claim to make about zero rows)."""
21
  if df is None or df.empty:
22
- return (df if df is not None else pd.DataFrame()), {
23
- 'fallback_triggered': False,
24
- 'adaptive_radius_used': 0,
25
- 'reconstruction_error': 0.0,
26
- }
27
 
28
  healed_values, metadata = enhanced_dense_healing_hybrid(df.to_numpy(dtype=float))
29
  healed_df = pd.DataFrame(healed_values, columns=df.columns, index=df.index)
 
12
  import pandas as pd
13
 
14
  from ia_utils.vector_healing import enhanced_dense_healing_hybrid
15
+ from ui_pages.components import AI_SHIELD_NEUTRAL_META
16
 
17
 
18
  def heal_telemetry(df: pd.DataFrame):
 
20
  (healed_df, metadata). Empty/None input passes through with a neutral
21
  metadata dict (no NaN-safety claim to make about zero rows)."""
22
  if df is None or df.empty:
23
+ return (df if df is not None else pd.DataFrame()), dict(AI_SHIELD_NEUTRAL_META)
 
 
 
 
24
 
25
  healed_values, metadata = enhanced_dense_healing_hybrid(df.to_numpy(dtype=float))
26
  healed_df = pd.DataFrame(healed_values, columns=df.columns, index=df.index)
ui_pages/components.py CHANGED
@@ -1,11 +1,15 @@
1
  """
2
  Shared, reusable rendering pieces used by more than one page — keeps the
3
- same visual language (bordered "card" grids) consistent across Vector
4
- Healing and Quantum Simulator instead of each page hand-rolling its own.
 
5
  """
6
 
 
7
  import streamlit as st
8
 
 
 
9
 
10
  def render_metric_grid(metrics: list, columns: int = 4):
11
  """Renders a list of {'label', 'value', 'help'} dicts as a grid of
@@ -28,3 +32,72 @@ def render_ai_shield_card(title: str, metadata: dict):
28
  c1.metric("Fallback scattato", "Sì" if metadata["fallback_triggered"] else "No")
29
  c2.metric("Raggio adattivo", metadata["adaptive_radius_used"])
30
  c3.metric("Errore di ricostruzione", f"{metadata['reconstruction_error']:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  """
2
  Shared, reusable rendering pieces used by more than one page — keeps the
3
+ same visual language (bordered "card" grids, gradient banners, the
4
+ run-then-render guard) consistent across all dashboard pages instead of
5
+ each one hand-rolling its own copy.
6
  """
7
 
8
+ import matplotlib.pyplot as plt
9
  import streamlit as st
10
 
11
+ import dense_evolution
12
+
13
 
14
  def render_metric_grid(metrics: list, columns: int = 4):
15
  """Renders a list of {'label', 'value', 'help'} dicts as a grid of
 
32
  c1.metric("Fallback scattato", "Sì" if metadata["fallback_triggered"] else "No")
33
  c2.metric("Raggio adattivo", metadata["adaptive_radius_used"])
34
  c3.metric("Errore di ricostruzione", f"{metadata['reconstruction_error']:.4f}")
35
+
36
+
37
+ # Neutral AI-shield metadata for the "no healing ran" case (empty/None
38
+ # input to ui_pages.ai_middleware.heal_telemetry, or a page that hasn't
39
+ # run yet) -- was hand-duplicated as an identical dict literal in
40
+ # ai_middleware.py and twice in quantum_simulator.py.
41
+ AI_SHIELD_NEUTRAL_META = {
42
+ 'fallback_triggered': False,
43
+ 'adaptive_radius_used': 0,
44
+ 'reconstruction_error': 0.0,
45
+ }
46
+
47
+
48
+ def render_page_banner(page_title: str, subtitle_html: str, accent: str = "#a78bfa",
49
+ bg_from: str = "#0a0014", bg_to: str = "#1a0226") -> None:
50
+ """Gradient header banner at the top of every dashboard page.
51
+
52
+ `page_title` is appended after "Dense Evolution v{dense_evolution.__version__} — "
53
+ so the version shown always reflects what's actually installed instead
54
+ of a hand-typed number that silently drifts out of sync per page
55
+ (found: v8.1.9 / v8.1.7 / v8.1.22, three different stale values
56
+ hardcoded across three pages before this).
57
+
58
+ `subtitle_html` is rendered as-is inside a <p> — callers already build
59
+ their own <code>/<a> markup for the subtitle text, this doesn't
60
+ re-escape it."""
61
+ st.markdown(
62
+ f"""
63
+ <div style="padding: 1.25rem 1.5rem; border-radius: 0.75rem;
64
+ background: linear-gradient(90deg, {bg_from}, {bg_to});
65
+ border: 1px solid {accent}44; margin-bottom: 1rem;">
66
+ <h1 style="margin: 0; color: {accent};">Dense Evolution v{dense_evolution.__version__} — {page_title}</h1>
67
+ <p style="margin: 0.5rem 0 0 0; color: #cccccc;">
68
+ {subtitle_html}
69
+ </p>
70
+ </div>
71
+ """,
72
+ unsafe_allow_html=True,
73
+ )
74
+
75
+
76
+ def render_run_guard(*keys: str, message: str):
77
+ """Retrieves each of `keys` from st.session_state. If any is missing
78
+ (None), shows `message` via st.info and returns None — the caller
79
+ should `return` immediately in that case, nothing left to render yet.
80
+ Otherwise returns the retrieved values: a single value when one key
81
+ was given, a tuple when several were.
82
+
83
+ Encapsulates the "run → session_state → guard → render" flow repeated
84
+ across quantum_simulator.py (2 keys: result + panels),
85
+ vector_healing.py and quantum_scars.py (1 key each)."""
86
+ values = [st.session_state.get(k) for k in keys]
87
+ if any(v is None for v in values):
88
+ st.info(message)
89
+ return None
90
+ return values[0] if len(values) == 1 else tuple(values)
91
+
92
+
93
+ def render_matplotlib_figure(fig, *, close: bool = True) -> None:
94
+ """st.pyplot(fig), then plt.close(fig) unless close=False.
95
+
96
+ For the "build a figure, show it immediately" call sites
97
+ (vector_healing.py, quantum_scars.py) — NOT quantum_simulator.py,
98
+ which builds every panel once in _execute_run and renders
99
+ already-closed figures later in _render_tabs, a different and
100
+ intentional pattern left as-is."""
101
+ st.pyplot(fig)
102
+ if close:
103
+ plt.close(fig)
ui_pages/quantum_scars.py CHANGED
@@ -1,241 +1,234 @@
1
- """
2
- Quantum Scars page — interactive live demo of the PXP model (Rydberg
3
- blockade), the system studied in the "quantum_scar_investigation" report:
4
- github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation
5
-
6
- That investigation found no genuine many-body scar in Dense Evolution's
7
- frustrated Ising grids (wrong observable + gauge equivalence), then
8
- validated the same verification pipeline against the PXP model, where
9
- scars are real and well documented. This page lets you reproduce the core
10
- PXP result interactively: start from the Néel state, inject real
11
- depolarizing noise via NoiseModel.apply_to_sv, and compare the fidelity
12
- revival with/without protection.
13
- """
14
-
15
- import numpy as np
16
- import scipy.sparse as sp
17
- from scipy.linalg import eigh
18
- import matplotlib.pyplot as plt
19
- import streamlit as st
20
-
21
- from dense_evolution.registry import NoiseModel
22
- from ui_pages.components import render_metric_grid
23
-
24
- DT_CHUNK = 0.2
25
- N_CHUNK = 100
26
-
27
-
28
- def _is_valid_state(state_int, n):
29
- prev_bit = 0
30
- for _ in range(n):
31
- bit = state_int & 1
32
- if bit == 1 and prev_bit == 1:
33
- return False
34
- prev_bit = bit
35
- state_int >>= 1
36
- return True
37
-
38
-
39
- # st.cache_resource (first use in this codebase): exact diagonalization here
40
- # is scipy.linalg.eigh on a dense 2**n_qubits matrix -- genuinely expensive
41
- # and depends only on n_qubits, so it's cached in memory across reruns and
42
- # widget interactions instead of recomputed on every slider tweak.
43
- @st.cache_resource(show_spinner="Costruzione H_PXP e diagonalizzazione esatta...")
44
- def _build_pxp(n_qubits: int):
45
- dim = 2 ** n_qubits
46
- identity_1q = sp.identity(2, format="csr", dtype=np.complex128)
47
- x_1q = sp.csr_matrix([[0, 1], [1, 0]], dtype=np.complex128)
48
- z_1q = sp.csr_matrix([[1, 0], [0, -1]], dtype=np.complex128)
49
-
50
- def op(o, q):
51
- mats = [identity_1q] * n_qubits
52
- mats[q] = o
53
- out = mats[0]
54
- for m in mats[1:]:
55
- out = sp.kron(out, m, format="csr")
56
- return out
57
-
58
- z_cache = {q: op(z_1q, q) for q in range(n_qubits)}
59
- x_cache = {q: op(x_1q, q) for q in range(n_qubits)}
60
- identity = sp.identity(dim, format="csr", dtype=np.complex128)
61
- p_cache = {q: 0.5 * (identity + z_cache[q]) for q in range(n_qubits)}
62
-
63
- h_pxp = sp.csr_matrix((dim, dim), dtype=np.complex128)
64
- for i in range(n_qubits):
65
- term = x_cache[i]
66
- if i > 0:
67
- term = p_cache[i - 1] @ term
68
- if i < n_qubits - 1:
69
- term = term @ p_cache[i + 1]
70
- h_pxp = h_pxp + term
71
- h_pxp = h_pxp.toarray()
72
-
73
- eigenvalues, eigenvectors = eigh(h_pxp)
74
-
75
- neel_bits = [0 if i % 2 == 0 else 1 for i in range(n_qubits)]
76
- neel_idx = int("".join(map(str, neel_bits)), 2)
77
-
78
- neel_overlap = np.abs(eigenvectors[neel_idx, :]) ** 2
79
- k = n_qubits + 1
80
- tower_indices = np.argsort(neel_overlap)[::-1][:k]
81
- tower_vectors = eigenvectors[:, tower_indices]
82
- tower_ceiling = float(neel_overlap[tower_indices].sum())
83
-
84
- valid_mask = np.array([_is_valid_state(i, n_qubits) for i in range(dim)], dtype=bool)
85
-
86
- return {
87
- "n_qubits": n_qubits,
88
- "dim": dim,
89
- "h_pxp": h_pxp,
90
- "eigenvalues": eigenvalues,
91
- "eigenvectors": eigenvectors,
92
- "eigenvectors_h": eigenvectors.conj().T,
93
- "neel_idx": neel_idx,
94
- "tower_vectors": tower_vectors,
95
- "tower_ceiling": tower_ceiling,
96
- "valid_mask": valid_mask,
97
- "valid_dim": int(valid_mask.sum()),
98
- }
99
-
100
-
101
- def _propagate(pxp, sv, dt):
102
- c = pxp["eigenvectors_h"] @ sv
103
- c = c * np.exp(-1j * pxp["eigenvalues"] * dt)
104
- return pxp["eigenvectors"] @ c
105
-
106
-
107
- def _project_tower(pxp, sv):
108
- v = pxp["tower_vectors"]
109
- sv_proj = v @ (v.conj().T @ sv)
110
- norm = np.linalg.norm(sv_proj)
111
- return sv_proj if norm < 1e-12 else sv_proj / norm
112
-
113
-
114
- def _project_constraint(pxp, sv):
115
- mask = pxp["valid_mask"]
116
- sv_proj = np.where(mask, sv, 0.0)
117
- norm = np.linalg.norm(sv_proj)
118
- return sv_proj if norm < 1e-12 else sv_proj / norm
119
-
120
-
121
- def _invalid_weight(pxp, sv):
122
- return float(np.sum(np.abs(sv[~pxp["valid_mask"]]) ** 2))
123
-
124
-
125
- def _run_experiment(pxp, n_trajectories, noise_p, protection, weight_threshold, base_seed):
126
- dim = pxp["dim"]
127
- n_qubits = pxp["n_qubits"]
128
- neel = np.zeros(dim, dtype=np.complex128)
129
- neel[pxp["neel_idx"]] = 1.0
130
-
131
- fidelity_acc = np.zeros(N_CHUNK)
132
- for trajectory in range(n_trajectories):
133
- rng = np.random.default_rng(base_seed + trajectory)
134
- sv = neel.copy()
135
- for step in range(N_CHUNK):
136
- sv = _propagate(pxp, sv, DT_CHUNK)
137
- if noise_p > 0:
138
- sv = NoiseModel.apply_to_sv(sv, n=n_qubits, model="depolarizing", p=noise_p, rng=rng)
139
- if protection == "Proiezione vincolo (economica)" and _invalid_weight(pxp, sv) > weight_threshold:
140
- sv = _project_constraint(pxp, sv)
141
- elif protection == "Proiezione torre (ideale)":
142
- sv = _project_tower(pxp, sv)
143
- fidelity_acc[step] += np.abs(np.vdot(neel, sv)) ** 2
144
-
145
- return fidelity_acc / n_trajectories
146
-
147
-
148
- def render():
149
- st.markdown(
150
- """
151
- <div style="padding: 1.25rem 1.5rem; border-radius: 0.75rem;
152
- background: linear-gradient(90deg, #001014, #012026);
153
- border: 1px solid #00e5ff44; margin-bottom: 1rem;">
154
- <h1 style="margin: 0; color: #00e5ff;">Dense Evolution v8.1.22 — Quantum Many-Body Scars: PXP Live Demo</h1>
155
- <p style="margin: 0.5rem 0 0 0; color: #cccccc;">
156
- Dinamica esatta del modello PXP (blocco di Rydberg), lo stesso sistema usato per
157
- validare la pipeline di verifica nell'indagine
158
- <a href="https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation"
159
- style="color:#00e5ff;" target="_blank">quantum_scar_investigation</a>.
160
- Parte dallo stato di Néel, inietta rumore reale
161
- (<code>dense_evolution.registry.NoiseModel.apply_to_sv</code>, media su più
162
- traiettorie quantistiche) e confronta i revival di fedeltà con/senza protezione.
163
- </p>
164
- </div>
165
- """,
166
- unsafe_allow_html=True,
167
- )
168
-
169
- with st.sidebar:
170
- st.header("⚙️ Configurazione")
171
- n_qubits = st.slider(
172
- "Numero di qubit (catena PXP)", min_value=6, max_value=12, value=10,
173
- help="Oltre 10 la diagonalizzazione esatta (e la simulazione) rallenta sensibilmente.",
174
- )
175
- noise_p = st.slider("Rumore depolarizzante per sito (p)", 0.0, 0.05, 0.01, step=0.005)
176
- n_trajectories = st.slider("Traiettorie quantistiche (media)", 5, 30, 10)
177
- protection = st.selectbox(
178
- "Protezione",
179
- ["Nessuna", "Proiezione vincolo (economica)", "Proiezione torre (ideale)"],
180
- help=(
181
- "Vincolo: nessuna diagonalizzazione aggiuntiva, economica ma parziale. "
182
- "Torre: limite teorico, richiede lo spettro esatto — non realizzabile su "
183
- "hardware reale così com'è."
184
- ),
185
- )
186
- run_clicked = st.button("🚀 Esegui esperimento", type="primary")
187
-
188
- if run_clicked:
189
- pxp = _build_pxp(n_qubits)
190
- with st.spinner("Simulazione delle traiettorie quantistiche in corso..."):
191
- fidelity_protected = _run_experiment(
192
- pxp, n_trajectories=n_trajectories, noise_p=noise_p,
193
- protection=protection, weight_threshold=0.02, base_seed=1000,
194
- )
195
- fidelity_clean = _run_experiment(
196
- pxp, n_trajectories=1, noise_p=0.0,
197
- protection="Nessuna", weight_threshold=0.02, base_seed=0,
198
- )
199
- st.session_state["scar_result"] = {
200
- "n_qubits": n_qubits, "noise_p": noise_p, "protection": protection,
201
- "fidelity_protected": fidelity_protected, "fidelity_clean": fidelity_clean,
202
- "valid_dim": pxp["valid_dim"], "dim": pxp["dim"], "tower_ceiling": pxp["tower_ceiling"],
203
- }
204
-
205
- result = st.session_state.get("scar_result")
206
- if result is None:
207
- st.info("Configura i parametri nella sidebar e premi **Esegui esperimento** per iniziare.")
208
- return
209
-
210
- render_metric_grid([
211
- {"label": "Qubit", "value": result["n_qubits"]},
212
- {"label": "Dimensione Hilbert", "value": result["dim"]},
213
- {"label": "Sottospazio valido (vincolo)", "value": result["valid_dim"]},
214
- {"label": "Soffitto torre (peso Néel)", "value": f"{result['tower_ceiling']*100:.1f}%",
215
- "help": "Peso massimo che lo stato di Néel puro ha sulla torre di N+1 autostati — "
216
- "il limite teorico che nessuna correzione può superare."},
217
- ])
218
-
219
- with st.container(border=True):
220
- st.subheader("📈 Fedeltà di revival")
221
- times = np.arange(1, N_CHUNK + 1) * DT_CHUNK
222
- fig, ax = plt.subplots(figsize=(11, 5))
223
- ax.plot(times, result["fidelity_clean"], label="Nessun rumore (riferimento)",
224
- color="gold", linewidth=1.5, linestyle="--")
225
- ax.plot(times, result["fidelity_protected"],
226
- label=f"p={result['noise_p']} — {result['protection']}",
227
- color="#00e5ff", linewidth=2.2)
228
- ax.set_xlabel("Tempo t")
229
- ax.set_ylabel("Fedeltà |⟨Néel|ψ(t)⟩|²")
230
- ax.set_title("Revival della scar PXP")
231
- ax.legend(loc="upper right")
232
- ax.grid(alpha=0.2)
233
- st.pyplot(fig)
234
- plt.close(fig)
235
-
236
- st.caption(
237
- "Report completo dell'indagine (inclusa la scar smentita nell'Ising frustrato, "
238
- "lo scan sistematico e i tentativi di protezione economica): "
239
- "[quantum_scar_investigation su GitHub]"
240
- "(https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation)."
241
- )
 
1
+ """
2
+ Quantum Scars page — interactive live demo of the PXP model (Rydberg
3
+ blockade), the system studied in the "quantum_scar_investigation" report:
4
+ github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation
5
+
6
+ That investigation found no genuine many-body scar in Dense Evolution's
7
+ frustrated Ising grids (wrong observable + gauge equivalence), then
8
+ validated the same verification pipeline against the PXP model, where
9
+ scars are real and well documented. This page lets you reproduce the core
10
+ PXP result interactively: start from the Néel state, inject real
11
+ depolarizing noise via NoiseModel.apply_to_sv, and compare the fidelity
12
+ revival with/without protection.
13
+ """
14
+
15
+ import numpy as np
16
+ import scipy.sparse as sp
17
+ from scipy.linalg import eigh
18
+ import matplotlib.pyplot as plt
19
+ import streamlit as st
20
+
21
+ from dense_evolution.registry import NoiseModel
22
+ from ui_pages.components import render_metric_grid, render_page_banner, render_run_guard, render_matplotlib_figure
23
+
24
+ DT_CHUNK = 0.2
25
+ N_CHUNK = 100
26
+
27
+
28
+ def _is_valid_state(state_int, n):
29
+ prev_bit = 0
30
+ for _ in range(n):
31
+ bit = state_int & 1
32
+ if bit == 1 and prev_bit == 1:
33
+ return False
34
+ prev_bit = bit
35
+ state_int >>= 1
36
+ return True
37
+
38
+
39
+ # st.cache_resource (first use in this codebase): exact diagonalization here
40
+ # is scipy.linalg.eigh on a dense 2**n_qubits matrix -- genuinely expensive
41
+ # and depends only on n_qubits, so it's cached in memory across reruns and
42
+ # widget interactions instead of recomputed on every slider tweak.
43
+ @st.cache_resource(show_spinner="Costruzione H_PXP e diagonalizzazione esatta...")
44
+ def _build_pxp(n_qubits: int):
45
+ dim = 2 ** n_qubits
46
+ identity_1q = sp.identity(2, format="csr", dtype=np.complex128)
47
+ x_1q = sp.csr_matrix([[0, 1], [1, 0]], dtype=np.complex128)
48
+ z_1q = sp.csr_matrix([[1, 0], [0, -1]], dtype=np.complex128)
49
+
50
+ def op(o, q):
51
+ mats = [identity_1q] * n_qubits
52
+ mats[q] = o
53
+ out = mats[0]
54
+ for m in mats[1:]:
55
+ out = sp.kron(out, m, format="csr")
56
+ return out
57
+
58
+ z_cache = {q: op(z_1q, q) for q in range(n_qubits)}
59
+ x_cache = {q: op(x_1q, q) for q in range(n_qubits)}
60
+ identity = sp.identity(dim, format="csr", dtype=np.complex128)
61
+ p_cache = {q: 0.5 * (identity + z_cache[q]) for q in range(n_qubits)}
62
+
63
+ h_pxp = sp.csr_matrix((dim, dim), dtype=np.complex128)
64
+ for i in range(n_qubits):
65
+ term = x_cache[i]
66
+ if i > 0:
67
+ term = p_cache[i - 1] @ term
68
+ if i < n_qubits - 1:
69
+ term = term @ p_cache[i + 1]
70
+ h_pxp = h_pxp + term
71
+ h_pxp = h_pxp.toarray()
72
+
73
+ eigenvalues, eigenvectors = eigh(h_pxp)
74
+
75
+ neel_bits = [0 if i % 2 == 0 else 1 for i in range(n_qubits)]
76
+ neel_idx = int("".join(map(str, neel_bits)), 2)
77
+
78
+ neel_overlap = np.abs(eigenvectors[neel_idx, :]) ** 2
79
+ k = n_qubits + 1
80
+ tower_indices = np.argsort(neel_overlap)[::-1][:k]
81
+ tower_vectors = eigenvectors[:, tower_indices]
82
+ tower_ceiling = float(neel_overlap[tower_indices].sum())
83
+
84
+ valid_mask = np.array([_is_valid_state(i, n_qubits) for i in range(dim)], dtype=bool)
85
+
86
+ return {
87
+ "n_qubits": n_qubits,
88
+ "dim": dim,
89
+ "h_pxp": h_pxp,
90
+ "eigenvalues": eigenvalues,
91
+ "eigenvectors": eigenvectors,
92
+ "eigenvectors_h": eigenvectors.conj().T,
93
+ "neel_idx": neel_idx,
94
+ "tower_vectors": tower_vectors,
95
+ "tower_ceiling": tower_ceiling,
96
+ "valid_mask": valid_mask,
97
+ "valid_dim": int(valid_mask.sum()),
98
+ }
99
+
100
+
101
+ def _propagate(pxp, sv, dt):
102
+ c = pxp["eigenvectors_h"] @ sv
103
+ c = c * np.exp(-1j * pxp["eigenvalues"] * dt)
104
+ return pxp["eigenvectors"] @ c
105
+
106
+
107
+ def _project_tower(pxp, sv):
108
+ v = pxp["tower_vectors"]
109
+ sv_proj = v @ (v.conj().T @ sv)
110
+ norm = np.linalg.norm(sv_proj)
111
+ return sv_proj if norm < 1e-12 else sv_proj / norm
112
+
113
+
114
+ def _project_constraint(pxp, sv):
115
+ mask = pxp["valid_mask"]
116
+ sv_proj = np.where(mask, sv, 0.0)
117
+ norm = np.linalg.norm(sv_proj)
118
+ return sv_proj if norm < 1e-12 else sv_proj / norm
119
+
120
+
121
+ def _invalid_weight(pxp, sv):
122
+ return float(np.sum(np.abs(sv[~pxp["valid_mask"]]) ** 2))
123
+
124
+
125
+ def _run_experiment(pxp, n_trajectories, noise_p, protection, weight_threshold, base_seed):
126
+ dim = pxp["dim"]
127
+ n_qubits = pxp["n_qubits"]
128
+ neel = np.zeros(dim, dtype=np.complex128)
129
+ neel[pxp["neel_idx"]] = 1.0
130
+
131
+ fidelity_acc = np.zeros(N_CHUNK)
132
+ for trajectory in range(n_trajectories):
133
+ rng = np.random.default_rng(base_seed + trajectory)
134
+ sv = neel.copy()
135
+ for step in range(N_CHUNK):
136
+ sv = _propagate(pxp, sv, DT_CHUNK)
137
+ if noise_p > 0:
138
+ sv = NoiseModel.apply_to_sv(sv, n=n_qubits, model="depolarizing", p=noise_p, rng=rng)
139
+ if protection == "Proiezione vincolo (economica)" and _invalid_weight(pxp, sv) > weight_threshold:
140
+ sv = _project_constraint(pxp, sv)
141
+ elif protection == "Proiezione torre (ideale)":
142
+ sv = _project_tower(pxp, sv)
143
+ fidelity_acc[step] += np.abs(np.vdot(neel, sv)) ** 2
144
+
145
+ return fidelity_acc / n_trajectories
146
+
147
+
148
+ def render():
149
+ render_page_banner(
150
+ "Quantum Many-Body Scars: PXP Live Demo",
151
+ """Dinamica esatta del modello PXP (blocco di Rydberg), lo stesso sistema usato per
152
+ validare la pipeline di verifica nell'indagine
153
+ <a href="https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation"
154
+ style="color:#00e5ff;" target="_blank">quantum_scar_investigation</a>.
155
+ Parte dallo stato di Néel, inietta rumore reale
156
+ (<code>dense_evolution.registry.NoiseModel.apply_to_sv</code>, media su più
157
+ traiettorie quantistiche) e confronta i revival di fedeltà con/senza protezione.""",
158
+ accent="#00e5ff", bg_from="#001014", bg_to="#012026",
159
+ )
160
+
161
+ with st.sidebar:
162
+ st.header("⚙️ Configurazione")
163
+ n_qubits = st.slider(
164
+ "Numero di qubit (catena PXP)", min_value=6, max_value=12, value=10,
165
+ help="Oltre 10 la diagonalizzazione esatta (e la simulazione) rallenta sensibilmente.",
166
+ )
167
+ noise_p = st.slider("Rumore depolarizzante per sito (p)", 0.0, 0.05, 0.01, step=0.005)
168
+ n_trajectories = st.slider("Traiettorie quantistiche (media)", 5, 30, 10)
169
+ protection = st.selectbox(
170
+ "Protezione",
171
+ ["Nessuna", "Proiezione vincolo (economica)", "Proiezione torre (ideale)"],
172
+ help=(
173
+ "Vincolo: nessuna diagonalizzazione aggiuntiva, economica ma parziale. "
174
+ "Torre: limite teorico, richiede lo spettro esatto — non realizzabile su "
175
+ "hardware reale così com'è."
176
+ ),
177
+ )
178
+ run_clicked = st.button("🚀 Esegui esperimento", type="primary")
179
+
180
+ if run_clicked:
181
+ pxp = _build_pxp(n_qubits)
182
+ with st.spinner("Simulazione delle traiettorie quantistiche in corso..."):
183
+ fidelity_protected = _run_experiment(
184
+ pxp, n_trajectories=n_trajectories, noise_p=noise_p,
185
+ protection=protection, weight_threshold=0.02, base_seed=1000,
186
+ )
187
+ fidelity_clean = _run_experiment(
188
+ pxp, n_trajectories=1, noise_p=0.0,
189
+ protection="Nessuna", weight_threshold=0.02, base_seed=0,
190
+ )
191
+ st.session_state["scar_result"] = {
192
+ "n_qubits": n_qubits, "noise_p": noise_p, "protection": protection,
193
+ "fidelity_protected": fidelity_protected, "fidelity_clean": fidelity_clean,
194
+ "valid_dim": pxp["valid_dim"], "dim": pxp["dim"], "tower_ceiling": pxp["tower_ceiling"],
195
+ }
196
+
197
+ result = render_run_guard(
198
+ "scar_result",
199
+ message="Configura i parametri nella sidebar e premi **Esegui esperimento** per iniziare.",
200
+ )
201
+ if result is None:
202
+ return
203
+
204
+ render_metric_grid([
205
+ {"label": "Qubit", "value": result["n_qubits"]},
206
+ {"label": "Dimensione Hilbert", "value": result["dim"]},
207
+ {"label": "Sottospazio valido (vincolo)", "value": result["valid_dim"]},
208
+ {"label": "Soffitto torre (peso Néel)", "value": f"{result['tower_ceiling']*100:.1f}%",
209
+ "help": "Peso massimo che lo stato di Néel puro ha sulla torre di N+1 autostati — "
210
+ "il limite teorico che nessuna correzione può superare."},
211
+ ])
212
+
213
+ with st.container(border=True):
214
+ st.subheader("📈 Fedeltà di revival")
215
+ times = np.arange(1, N_CHUNK + 1) * DT_CHUNK
216
+ fig, ax = plt.subplots(figsize=(11, 5))
217
+ ax.plot(times, result["fidelity_clean"], label="Nessun rumore (riferimento)",
218
+ color="gold", linewidth=1.5, linestyle="--")
219
+ ax.plot(times, result["fidelity_protected"],
220
+ label=f"p={result['noise_p']} — {result['protection']}",
221
+ color="#00e5ff", linewidth=2.2)
222
+ ax.set_xlabel("Tempo t")
223
+ ax.set_ylabel("Fedeltà |⟨Néel|ψ(t)⟩|²")
224
+ ax.set_title("Revival della scar PXP")
225
+ ax.legend(loc="upper right")
226
+ ax.grid(alpha=0.2)
227
+ render_matplotlib_figure(fig)
228
+
229
+ st.caption(
230
+ "Report completo dell'indagine (inclusa la scar smentita nell'Ising frustrato, "
231
+ "lo scan sistematico e i tentativi di protezione economica): "
232
+ "[quantum_scar_investigation su GitHub]"
233
+ "(https://github.com/tatopenn-cell/Dense-Evolution-Ising-Tests/tree/main/scripts/quantum_scar_investigation)."
234
+ )
 
 
 
 
 
 
 
ui_pages/quantum_simulator.py CHANGED
@@ -1,350 +1,411 @@
1
- """
2
- Quantum Simulator page — circuit execution, VQE (real JAX-autodiff or
3
- hash-seeded mock), MD telemetry, Hamiltonian library, and the
4
- Overview/Fisica Stato/Mosaico/VQE Results/MD Results/Performance/3D
5
- Helix/Hamiltonian panels (dashboard_core.py, ported from dash.py).
6
-
7
- VQE and MD telemetry are routed through the same AI vector-healing shield
8
- used standalone on the Vector Healing page (ui_pages/ai_middleware.py)
9
- before any panel is built from them — this is real infrastructure, not a
10
- cosmetic touch: if a run produces NaN/Inf/spike artifacts, the shield
11
- cleans them up here exactly like it does on the Vector Healing page, and
12
- its telemetry (fallback/radius/reconstruction-error) is shown alongside
13
- the physics metrics it protects.
14
- """
15
-
16
- import io
17
- import json
18
-
19
- import matplotlib.pyplot as plt
20
- import pandas as pd
21
- import streamlit as st
22
-
23
- import dashboard_core as dc
24
- from ui_pages.ai_middleware import heal_telemetry
25
- from ui_pages.components import render_ai_shield_card, render_metric_grid
26
-
27
-
28
- def _render_sidebar() -> dict:
29
- with st.sidebar:
30
- st.header("⚙️ Circuito")
31
- source_mode = st.radio("Sorgente", ["Libreria Built-in", "Custom QASM Textarea"], key="qs_source")
32
- if source_mode == "Libreria Built-in":
33
- circuit_name = st.selectbox("Circuito", options=list(dc.QASM_LIBRARY.keys()), key="qs_circuit")
34
- qasm_text = ""
35
- else:
36
- circuit_name = "Custom Workspace"
37
- qasm_text = st.text_area(
38
- "OpenQASM 2.0", height=140,
39
- value='OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; cx q[0],q[1]; measure q -> c;',
40
- key="qs_qasm_text",
41
- )
42
-
43
- st.header("🧮 Motore")
44
- engine = st.selectbox(
45
- "Motore di simulazione", options=["dense", "mps"],
46
- format_func=lambda e: "Denso (DenseSVSimulator/Chunk)" if e == "dense" else "MPS (bond-troncato, ≤24 qubit)",
47
- key="qs_engine",
48
- help=(
49
- "Denso: sempre esatto, adatta memoria automaticamente (Chunk) fino al "
50
- "limite RAM della macchina. MPS: esatto per circuiti a bassa entanglement "
51
- "(vedi dense_evolution/mps.py), limitato a 24 qubit in questa dashboard "
52
- "-- oltre serve il campionamento sequenziale, non ancora collegato ai pannelli."
53
- ),
54
- )
55
-
56
- st.header("🌪️ Rumore")
57
- noise_model = st.selectbox("Modello", options=['ideal', 'depolarizing', 'bitflip', 'phaseflip', 'amplitude_damping', 'combined'], key="qs_noise")
58
- noise_p = st.slider("Probabilità p", 0.0, 0.5, 0.0, 0.01, key="qs_noise_p")
59
- shots = st.slider("Shots", 50, 5000, 512, 50, key="qs_shots")
60
- seed = st.number_input("Seed", min_value=0, max_value=10_000, value=42, key="qs_seed")
61
- double_precision = st.checkbox("Doppia precisione (float64)", value=False, key="qs_precision")
62
-
63
- st.header("🧪 VQE")
64
- vqe_enabled = st.checkbox("Abilita telemetria VQE", value=True, key="qs_vqe_enabled")
65
- if vqe_enabled:
66
- vqe_epochs = st.slider("Epochs", 5, 100, 20, key="qs_vqe_epochs")
67
- vqe_lr = st.slider("Learning rate", 0.001, 0.5, 0.05, key="qs_vqe_lr")
68
- vqe_beta1 = st.slider("Adam β1", 0.5, 0.999, 0.9, key="qs_vqe_beta1")
69
- vqe_beta2 = st.slider("Adam β2", 0.9, 0.9999, 0.999, key="qs_vqe_beta2")
70
- confirm_heavy_vqe = st.checkbox(
71
- f"Confermo VQE reale anche su circuiti pesanti (>{dc.QM_MM_HEAVY_QUBIT_THRESHOLD} qubit — costo O(4ⁿ), può essere lento)",
72
- value=False, key="qs_confirm_heavy",
73
- )
74
- else:
75
- vqe_epochs, vqe_lr, vqe_beta1, vqe_beta2, confirm_heavy_vqe = 20, 0.05, 0.9, 0.999, False
76
-
77
- hamiltonian_values, hamiltonian_name = None, None
78
- if vqe_enabled:
79
- st.header("🧬 Hamiltoniana personalizzata")
80
- hamiltonian_enabled = st.checkbox("Abilita Hamiltoniana personalizzata", value=False, key="qs_ham_enabled")
81
- if hamiltonian_enabled:
82
- ham_library = st.session_state.setdefault("hamiltonian_library", dict(dc.LIBRERIA_HAMILTONIANE))
83
- current_qasm = dc.QASM_LIBRARY[circuit_name] if source_mode == "Libreria Built-in" else qasm_text
84
- inferred_n_qubits = dc.infer_qubit_count_from_qasm(current_qasm)
85
- compatible = dc.get_compatible_hamiltonians(inferred_n_qubits, ham_library)
86
-
87
- ham_mode = st.radio("Modalità", ["Libreria Built-in", "Custom JSON Textarea"], key="qs_ham_mode")
88
- if ham_mode == "Libreria Built-in":
89
- if compatible:
90
- hamiltonian_name = st.selectbox(
91
- f"Hamiltoniana ({inferred_n_qubits} qubit, dim={2**inferred_n_qubits if inferred_n_qubits else '?'})",
92
- options=list(compatible.keys()), key="qs_ham_sel",
93
- )
94
- hamiltonian_values = compatible[hamiltonian_name]
95
- else:
96
- st.caption(
97
- f"Nessuna Hamiltoniana in libreria è compatibile con {inferred_n_qubits or '?'} qubit "
98
- f"(serve un array di lunghezza 2^n = {2**inferred_n_qubits if inferred_n_qubits else '?'}). "
99
- "Usa la modalità Custom JSON qui sotto."
100
- )
101
- else:
102
- ham_json_text = st.text_area(
103
- "Array JSON (lunghezza = 2^n_qubits)", value="[-1.13, -0.45, 0.12, 0.64]",
104
- height=80, key="qs_ham_json",
105
- )
106
- ham_save_name = st.text_input("Nome per salvare in libreria (opzionale)", key="qs_ham_save_name")
107
- if st.button("💾 Salva in libreria", key="qs_ham_save_btn"):
108
- ok, msg = dc.save_custom_hamiltonian(ham_library, ham_save_name, ham_json_text)
109
- (st.success if ok else st.error)(msg)
110
- try:
111
- hamiltonian_values = json.loads(ham_json_text)
112
- hamiltonian_name = ham_save_name or "Custom JSON"
113
- except json.JSONDecodeError:
114
- st.error("JSON non valido — verrà usata un'Hamiltoniana casuale per questa run.")
115
- hamiltonian_values = None
116
-
117
- st.header("🌡️ Molecular Dynamics")
118
- md_enabled = st.checkbox("Abilita telemetria MD", value=True, key="qs_md_enabled")
119
- if md_enabled:
120
- md_steps = st.slider("MD steps", 10, 500, 80, key="qs_md_steps")
121
- md_temp = st.slider("Temperatura (K)", 10, 800, 300, key="qs_md_temp")
122
- else:
123
- md_steps, md_temp = 80, 300
124
-
125
- run_clicked = st.button("▶️ Esegui Simulazione", type="primary")
126
-
127
- return dict(
128
- source_mode=source_mode, circuit_name=circuit_name, qasm_text=qasm_text,
129
- engine=engine,
130
- noise_model=noise_model, noise_p=noise_p, shots=shots, seed=seed,
131
- double_precision=double_precision,
132
- vqe_enabled=vqe_enabled, vqe_epochs=vqe_epochs, vqe_lr=vqe_lr,
133
- vqe_beta1=vqe_beta1, vqe_beta2=vqe_beta2, confirm_heavy_vqe=confirm_heavy_vqe,
134
- hamiltonian_values=hamiltonian_values, hamiltonian_name=hamiltonian_name,
135
- md_enabled=md_enabled, md_steps=md_steps, md_temp=md_temp,
136
- run_clicked=run_clicked,
137
- )
138
-
139
-
140
- def _execute_run(p: dict) -> None:
141
- with st.spinner("Esecuzione circuito..."):
142
- try:
143
- res = dc.run_simulation(
144
- p["source_mode"], p["circuit_name"], p["qasm_text"],
145
- p["noise_model"], p["noise_p"], p["shots"], int(p["seed"]),
146
- use_float32=not p["double_precision"], engine=p["engine"],
147
- )
148
- except Exception as e:
149
- st.error(f"Errore durante l'esecuzione del circuito: {e}")
150
- return
151
-
152
- df_vqe = pd.DataFrame()
153
- vqe_ai_meta = {'fallback_triggered': False, 'adaptive_radius_used': 0, 'reconstruction_error': 0.0}
154
- if p["vqe_enabled"]:
155
- if res['n_qubits'] > dc.QM_MM_HEAVY_QUBIT_THRESHOLD and not p["confirm_heavy_vqe"]:
156
- st.warning(
157
- f"Circuito a {res['n_qubits']} qubit: il VQE reale (se il circuito ha gate parametrici) "
158
- f"userebbe QMMMForceEngine con costo O(4ⁿ) ≈ dim²={2**res['n_qubits']:,}² — telemetria VQE "
159
- "saltata per questa run. Spunta la conferma nella sidebar per eseguirla comunque."
160
- )
161
- else:
162
- progress_bar = st.progress(0.0, text="VQE: avvio ottimizzazione...")
163
- log_lines = []
164
- log_container = st.empty()
165
-
166
- def _on_epoch(epoch, total, row):
167
- progress_bar.progress((epoch + 1) / total, text=f"VQE epoch {epoch + 1}/{total}")
168
- log_lines.append(
169
- f"[epoch {epoch + 1:03d}/{total}] "
170
- f"E={row['VQE_Energy']:.5f} S={row['Entropy']:.4f} "
171
- f"purity={row['Purity']:.4f} grad={row['Gradient']:.5f}"
172
- )
173
- log_container.code("\n".join(log_lines[-12:]), language="text")
174
-
175
- try:
176
- df_vqe = dc.run_vqe_telemetry(
177
- res['sim'], res['parser'],
178
- dc.QASM_LIBRARY[p["circuit_name"]] if p["source_mode"] == "Libreria Built-in" else p["qasm_text"],
179
- p["circuit_name"], res['n_qubits'], not p["double_precision"],
180
- p["vqe_epochs"], p["vqe_lr"], p["vqe_beta1"], p["vqe_beta2"], int(p["seed"]),
181
- hamiltonian_values=p["hamiltonian_values"], on_epoch=_on_epoch,
182
- )
183
- except Exception as e:
184
- st.error(f"Errore durante la telemetria VQE: {e}")
185
- finally:
186
- progress_bar.empty()
187
-
188
- if not df_vqe.empty:
189
- df_vqe, vqe_ai_meta = heal_telemetry(df_vqe)
190
- if vqe_ai_meta["fallback_triggered"]:
191
- log_lines.append(
192
- f"⚠️ AI Shield: fallback mediano attivato (raggio adattivo="
193
- f"{vqe_ai_meta['adaptive_radius_used']}, errore ricostruzione="
194
- f"{vqe_ai_meta['reconstruction_error']:.4f})"
195
- )
196
- log_container.code("\n".join(log_lines[-12:]), language="text")
197
-
198
- df_md, corr_matrix = pd.DataFrame(), pd.DataFrame()
199
- md_ai_meta = {'fallback_triggered': False, 'adaptive_radius_used': 0, 'reconstruction_error': 0.0}
200
- if p["md_enabled"]:
201
- with st.spinner("Telemetria MD..."):
202
- df_md, _raw_corr = dc.run_md_telemetry(p["md_steps"], p["md_temp"])
203
- df_md, md_ai_meta = heal_telemetry(df_md)
204
- corr_matrix = df_md.corr(method="pearson") # recomputed from the healed data, not the raw one
205
-
206
- history = st.session_state.setdefault("qs_run_history", [])
207
- history.append({
208
- 'nome': res['nome'],
209
- 'n_qubits': res['n_qubits'],
210
- 'tempo': res['tempo'],
211
- 'ram': res['ram'],
212
- 'porte_count': res['porte_count'],
213
- 'entropy': float(res['entropy']),
214
- 'fidelity': res['fidelity'],
215
- 'stato_dominante': res['stato_dominante'],
216
- 'noise_model': p["noise_model"],
217
- 'noise_p': p["noise_p"],
218
- })
219
-
220
- # Build every panel once, here, right after the data that feeds it
221
- # changes — not on every sidebar rerun. Figures are closed immediately
222
- # (plt.close) and the objects kept in session_state; st.pyplot() can
223
- # render an already-closed Figure object just fine, this only stops
224
- # them accumulating in pyplot's registry.
225
- with st.spinner("Rendering pannelli..."):
226
- metrics = dc.compute_overview_metrics(res, p["noise_model"], p["noise_p"])
227
- overview_fig = dc.build_panel_overview(res, df_vqe, corr_matrix, p["noise_model"], p["noise_p"])
228
- fisica_fig = dc.build_panel_fisica(res, seed=int(p["seed"]))
229
- mosaico_fig = dc.build_panel_mosaico(res)
230
- vqe_fig = dc.build_panel_vqe_results(df_vqe)
231
- md_fig = dc.build_panel_md_results(df_md, corr_matrix)
232
- perf_fig = dc.build_panel_performance(res, history)
233
- helix_fig = dc.build_3d_helix_patch(res['n_qubits'], res['prob'])
234
- ham_fig = dc.build_panel_hamiltonian(p["hamiltonian_values"], p["hamiltonian_name"] or 'nessuna')
235
-
236
- overview_png = io.BytesIO()
237
- overview_fig.savefig(overview_png, format="png", dpi=300, facecolor='#010409', bbox_inches='tight')
238
-
239
- for fig in (overview_fig, fisica_fig, mosaico_fig, vqe_fig, md_fig, perf_fig, ham_fig):
240
- plt.close(fig)
241
-
242
- st.session_state["qs_res"] = res
243
- st.session_state["qs_panels"] = {
244
- "metrics": metrics,
245
- "vqe_ai_meta": vqe_ai_meta,
246
- "md_ai_meta": md_ai_meta,
247
- "overview": overview_fig,
248
- "overview_png": overview_png.getvalue(),
249
- "fisica": fisica_fig,
250
- "mosaico": mosaico_fig,
251
- "vqe": vqe_fig,
252
- "md": md_fig,
253
- "hamiltonian": ham_fig,
254
- "performance": perf_fig,
255
- "helix": helix_fig,
256
- }
257
-
258
-
259
- def _render_tabs() -> None:
260
- res = st.session_state.get("qs_res")
261
- panels = st.session_state.get("qs_panels")
262
-
263
- if res is None or panels is None:
264
- st.info("Configura il circuito nella sidebar e premi **Esegui Simulazione** per iniziare.")
265
- return
266
-
267
- run_history = st.session_state.get("qs_run_history", [])
268
-
269
- tabs = st.tabs(["Overview", "Fisica Stato", "Mosaico", "VQE Results", "MD Results", "Performance", "3D Helix", "Hamiltonian"])
270
-
271
- with tabs[0]:
272
- render_ai_shield_card("AI Vector-Healing Shield — Telemetria VQE", panels["vqe_ai_meta"])
273
- with st.container(border=True):
274
- st.subheader("📊 Simulation Metrics")
275
- render_metric_grid(panels["metrics"])
276
- st.pyplot(panels["overview"])
277
- st.download_button(
278
- "🖼️ Esporta Overview come PNG (300 DPI)",
279
- data=panels["overview_png"],
280
- file_name="quantum_dashboard_overview.png",
281
- mime="image/png",
282
- )
283
-
284
- with tabs[1]:
285
- st.pyplot(panels["fisica"])
286
-
287
- with tabs[2]:
288
- st.pyplot(panels["mosaico"])
289
-
290
- with tabs[3]:
291
- st.pyplot(panels["vqe"])
292
-
293
- with tabs[4]:
294
- render_ai_shield_card("AI Vector-Healing Shield — Telemetria MD", panels["md_ai_meta"])
295
- st.pyplot(panels["md"])
296
-
297
- with tabs[5]:
298
- st.pyplot(panels["performance"])
299
-
300
- if run_history:
301
- st.dataframe(pd.DataFrame(run_history), use_container_width=True)
302
- st.download_button(
303
- "💾 Esporta provenance JSON",
304
- data=dc.build_provenance_json(run_history),
305
- file_name="quantum_provenance_archive.json",
306
- mime="application/json",
307
- )
308
-
309
- st.divider()
310
- st.caption(
311
- "Benchmark scan: alloca simulatori da 2 a 14 qubit e misura tempo/RAM. "
312
- "Genuinamente lento (allocazione densa fino a 2¹⁴) — esegui solo se necessario."
313
- )
314
- if st.button("🧪 Esegui Benchmark Scan (2→14 qubit)"):
315
- with st.spinner("Benchmark in corso..."):
316
- bench_df = dc.run_benchmark_scan()
317
- st.dataframe(bench_df, use_container_width=True)
318
-
319
- with tabs[6]:
320
- st.plotly_chart(panels["helix"], use_container_width=True)
321
-
322
- with tabs[7]:
323
- st.pyplot(panels["hamiltonian"])
324
- st.caption(
325
- "Se nessuna Hamiltoniana personalizzata è abilitata nella sidebar, il VQE usa uno spettro "
326
- "casuale ordinato (comportamento di default, invariato)."
327
- )
328
-
329
-
330
- def render():
331
- st.markdown(
332
- """
333
- <div style="padding: 1.25rem 1.5rem; border-radius: 0.75rem;
334
- background: linear-gradient(90deg, #0a0014, #1a0226);
335
- border: 1px solid #a78bfa44; margin-bottom: 1rem;">
336
- <h1 style="margin: 0; color: #a78bfa;">Dense Evolution v8.1.7 — Quantum Simulator Dashboard</h1>
337
- <p style="margin: 0.5rem 0 0 0; color: #cccccc;">
338
- Esegui un circuito OpenQASM su <code>DenseSVSimulator</code>, opzionalmente con rumore,
339
- telemetria VQE (JAX autodiff + forze QM/MM Hellmann-Feynman) e dinamica molecolare —
340
- entrambe protette dallo stesso scudo AI Vector-Healing della pagina Vector Healing.
341
- </p>
342
- </div>
343
- """,
344
- unsafe_allow_html=True,
345
- )
346
-
347
- params = _render_sidebar()
348
- if params["run_clicked"]:
349
- _execute_run(params)
350
- _render_tabs()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Quantum Simulator page — circuit execution, VQE (real JAX-autodiff or
3
+ hash-seeded mock), MD telemetry, Hamiltonian library, and the
4
+ Overview/Fisica Stato/Mosaico/VQE Results/MD Results/Performance/3D
5
+ Helix/Hamiltonian panels (dashboard_core.py, ported from dash.py).
6
+
7
+ VQE and MD telemetry are routed through the same AI vector-healing shield
8
+ used standalone on the Vector Healing page (ui_pages/ai_middleware.py)
9
+ before any panel is built from them — this is real infrastructure, not a
10
+ cosmetic touch: if a run produces NaN/Inf/spike artifacts, the shield
11
+ cleans them up here exactly like it does on the Vector Healing page, and
12
+ its telemetry (fallback/radius/reconstruction-error) is shown alongside
13
+ the physics metrics it protects.
14
+ """
15
+
16
+ import io
17
+ import json
18
+
19
+ import matplotlib.pyplot as plt
20
+ import pandas as pd
21
+ import streamlit as st
22
+
23
+ import dashboard_core as dc
24
+ from ui_pages.ai_middleware import heal_telemetry
25
+ from ui_pages.components import (
26
+ render_ai_shield_card, render_metric_grid, render_page_banner, render_run_guard,
27
+ AI_SHIELD_NEUTRAL_META,
28
+ )
29
+
30
+
31
+ def _render_sidebar() -> dict:
32
+ with st.sidebar:
33
+ st.header("⚙️ Circuito")
34
+ source_mode = st.radio("Sorgente", ["Libreria Built-in", "Custom QASM Textarea"], key="qs_source")
35
+ if source_mode == "Libreria Built-in":
36
+ circuit_name = st.selectbox("Circuito", options=list(dc.QASM_LIBRARY.keys()), key="qs_circuit")
37
+ qasm_text = ""
38
+ else:
39
+ circuit_name = "Custom Workspace"
40
+ qasm_text = st.text_area(
41
+ "OpenQASM 2.0", height=140,
42
+ value='OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; creg c[2]; h q[0]; cx q[0],q[1]; measure q -> c;',
43
+ key="qs_qasm_text",
44
+ )
45
+
46
+ st.header("🧮 Motore")
47
+ engine = st.selectbox(
48
+ "Motore di simulazione", options=["dense", "mps"],
49
+ format_func=lambda e: "Denso (DenseSVSimulator/Chunk)" if e == "dense" else "MPS (bond-troncato, ≤24 qubit)",
50
+ key="qs_engine",
51
+ help=(
52
+ "Denso: sempre esatto, adatta memoria automaticamente (Chunk) fino al "
53
+ "limite RAM della macchina. MPS: esatto per circuiti a bassa entanglement "
54
+ "(vedi dense_evolution/mps.py), limitato a 24 qubit in questa dashboard "
55
+ "-- oltre serve il campionamento sequenziale, non ancora collegato ai pannelli."
56
+ ),
57
+ )
58
+
59
+ st.header("🌪️ Rumore")
60
+ noise_model = st.selectbox("Modello", options=['ideal', 'depolarizing', 'bitflip', 'phaseflip', 'amplitude_damping', 'combined'], key="qs_noise")
61
+ noise_p = st.slider("Probabilità p", 0.0, 0.5, 0.0, 0.01, key="qs_noise_p")
62
+ shots = st.slider("Shots", 50, 5000, 512, 50, key="qs_shots")
63
+ seed = st.number_input("Seed", min_value=0, max_value=10_000, value=42, key="qs_seed")
64
+ double_precision = st.checkbox("Doppia precisione (float64)", value=False, key="qs_precision")
65
+
66
+ st.header("🩹 Error Mitigation (ZNE)")
67
+ zne_enabled = st.checkbox(
68
+ "Abilita Zero-Noise Extrapolation", value=False, key="qs_zne_enabled",
69
+ disabled=(noise_model == 'ideal'),
70
+ help="Richiede un modello di rumore attivo -- non applicabile a 'ideal'.",
71
+ )
72
+ if noise_model == 'ideal' and zne_enabled:
73
+ st.caption("⚠️ ZNE disabilitato: nessun rumore da estrapolare con 'ideal'.")
74
+ zne_enabled = False
75
+ if zne_enabled:
76
+ zne_healing = st.checkbox(
77
+ "Healing predittivo (Δpre_emp-adapted)", value=False, key="qs_zne_healing",
78
+ help=(
79
+ "Corregge i 3 coefficienti di Richardson in base alla deviazione di "
80
+ "coerenza osservata (σ da shot-noise binomiale alla scala base), invece "
81
+ "del ZNE standard a pesi fissi."
82
+ ),
83
+ )
84
+ zne_target_sigma = (
85
+ st.number_input("Target σ ideale", value=10.0, key="qs_zne_target_sigma")
86
+ if zne_healing else 10.0
87
+ )
88
+ else:
89
+ zne_healing, zne_target_sigma = False, 10.0
90
+
91
+ st.header("🧪 VQE")
92
+ vqe_enabled = st.checkbox("Abilita telemetria VQE", value=True, key="qs_vqe_enabled")
93
+ if vqe_enabled:
94
+ vqe_epochs = st.slider("Epochs", 5, 100, 20, key="qs_vqe_epochs")
95
+ vqe_lr = st.slider("Learning rate", 0.001, 0.5, 0.05, key="qs_vqe_lr")
96
+ vqe_beta1 = st.slider("Adam β1", 0.5, 0.999, 0.9, key="qs_vqe_beta1")
97
+ vqe_beta2 = st.slider("Adam β2", 0.9, 0.9999, 0.999, key="qs_vqe_beta2")
98
+ confirm_heavy_vqe = st.checkbox(
99
+ f"Confermo VQE reale anche su circuiti pesanti (>{dc.QM_MM_HEAVY_QUBIT_THRESHOLD} qubit — costo O(4ⁿ), può essere lento)",
100
+ value=False, key="qs_confirm_heavy",
101
+ )
102
+ else:
103
+ vqe_epochs, vqe_lr, vqe_beta1, vqe_beta2, confirm_heavy_vqe = 20, 0.05, 0.9, 0.999, False
104
+
105
+ hamiltonian_values, hamiltonian_name = None, None
106
+ if vqe_enabled:
107
+ st.header("🧬 Hamiltoniana personalizzata")
108
+ hamiltonian_enabled = st.checkbox("Abilita Hamiltoniana personalizzata", value=False, key="qs_ham_enabled")
109
+ if hamiltonian_enabled:
110
+ ham_library = st.session_state.setdefault("hamiltonian_library", dict(dc.LIBRERIA_HAMILTONIANE))
111
+ current_qasm = dc.QASM_LIBRARY[circuit_name] if source_mode == "Libreria Built-in" else qasm_text
112
+ inferred_n_qubits = dc.infer_qubit_count_from_qasm(current_qasm)
113
+ compatible = dc.get_compatible_hamiltonians(inferred_n_qubits, ham_library)
114
+
115
+ ham_mode = st.radio("Modalità", ["Libreria Built-in", "Custom JSON Textarea"], key="qs_ham_mode")
116
+ if ham_mode == "Libreria Built-in":
117
+ if compatible:
118
+ hamiltonian_name = st.selectbox(
119
+ f"Hamiltoniana ({inferred_n_qubits} qubit, dim={2**inferred_n_qubits if inferred_n_qubits else '?'})",
120
+ options=list(compatible.keys()), key="qs_ham_sel",
121
+ )
122
+ hamiltonian_values = compatible[hamiltonian_name]
123
+ else:
124
+ st.caption(
125
+ f"Nessuna Hamiltoniana in libreria è compatibile con {inferred_n_qubits or '?'} qubit "
126
+ f"(serve un array di lunghezza 2^n = {2**inferred_n_qubits if inferred_n_qubits else '?'}). "
127
+ "Usa la modalità Custom JSON qui sotto."
128
+ )
129
+ else:
130
+ ham_json_text = st.text_area(
131
+ "Array JSON (lunghezza = 2^n_qubits)", value="[-1.13, -0.45, 0.12, 0.64]",
132
+ height=80, key="qs_ham_json",
133
+ )
134
+ ham_save_name = st.text_input("Nome per salvare in libreria (opzionale)", key="qs_ham_save_name")
135
+ if st.button("💾 Salva in libreria", key="qs_ham_save_btn"):
136
+ ok, msg = dc.save_custom_hamiltonian(ham_library, ham_save_name, ham_json_text)
137
+ (st.success if ok else st.error)(msg)
138
+ try:
139
+ hamiltonian_values = json.loads(ham_json_text)
140
+ hamiltonian_name = ham_save_name or "Custom JSON"
141
+ except json.JSONDecodeError:
142
+ st.error("JSON non valido — verrà usata un'Hamiltoniana casuale per questa run.")
143
+ hamiltonian_values = None
144
+
145
+ st.header("🌡️ Molecular Dynamics")
146
+ md_enabled = st.checkbox("Abilita telemetria MD", value=True, key="qs_md_enabled")
147
+ if md_enabled:
148
+ md_steps = st.slider("MD steps", 10, 500, 80, key="qs_md_steps")
149
+ md_temp = st.slider("Temperatura (K)", 10, 800, 300, key="qs_md_temp")
150
+ else:
151
+ md_steps, md_temp = 80, 300
152
+
153
+ run_clicked = st.button("▶️ Esegui Simulazione", type="primary")
154
+
155
+ return dict(
156
+ source_mode=source_mode, circuit_name=circuit_name, qasm_text=qasm_text,
157
+ engine=engine,
158
+ noise_model=noise_model, noise_p=noise_p, shots=shots, seed=seed,
159
+ double_precision=double_precision,
160
+ zne_enabled=zne_enabled, zne_healing=zne_healing, zne_target_sigma=zne_target_sigma,
161
+ vqe_enabled=vqe_enabled, vqe_epochs=vqe_epochs, vqe_lr=vqe_lr,
162
+ vqe_beta1=vqe_beta1, vqe_beta2=vqe_beta2, confirm_heavy_vqe=confirm_heavy_vqe,
163
+ hamiltonian_values=hamiltonian_values, hamiltonian_name=hamiltonian_name,
164
+ md_enabled=md_enabled, md_steps=md_steps, md_temp=md_temp,
165
+ run_clicked=run_clicked,
166
+ )
167
+
168
+
169
+ def _execute_run(p: dict) -> None:
170
+ with st.spinner("Esecuzione circuito..."):
171
+ try:
172
+ res = dc.run_simulation(
173
+ p["source_mode"], p["circuit_name"], p["qasm_text"],
174
+ p["noise_model"], p["noise_p"], p["shots"], int(p["seed"]),
175
+ use_float32=not p["double_precision"], engine=p["engine"],
176
+ )
177
+ except Exception as e:
178
+ st.error(f"Errore durante l'esecuzione del circuito: {e}")
179
+ return
180
+
181
+ mitigation_res = None
182
+ if p["zne_enabled"]:
183
+ with st.spinner("Mitigazione ZNE (3 scale di rumore)..."):
184
+ try:
185
+ mitigation_res = dc.run_mitigation_sweep(
186
+ p["source_mode"], p["circuit_name"], p["qasm_text"], p["noise_model"],
187
+ p["noise_p"], p["shots"], int(p["seed"]),
188
+ use_float32=not p["double_precision"], engine=p["engine"],
189
+ healing_enabled=p["zne_healing"], target_sigma_ideal=p["zne_target_sigma"],
190
+ )
191
+ except Exception as e:
192
+ st.error(f"Errore durante la mitigazione ZNE: {e}")
193
+
194
+ df_vqe = pd.DataFrame()
195
+ vqe_ai_meta = dict(AI_SHIELD_NEUTRAL_META)
196
+ if p["vqe_enabled"]:
197
+ if res['n_qubits'] > dc.QM_MM_HEAVY_QUBIT_THRESHOLD and not p["confirm_heavy_vqe"]:
198
+ st.warning(
199
+ f"Circuito a {res['n_qubits']} qubit: il VQE reale (se il circuito ha gate parametrici) "
200
+ f"userebbe QMMMForceEngine con costo O(4ⁿ) ≈ dim²={2**res['n_qubits']:,}² — telemetria VQE "
201
+ "saltata per questa run. Spunta la conferma nella sidebar per eseguirla comunque."
202
+ )
203
+ else:
204
+ progress_bar = st.progress(0.0, text="VQE: avvio ottimizzazione...")
205
+ log_lines = []
206
+ log_container = st.empty()
207
+
208
+ def _on_epoch(epoch, total, row):
209
+ progress_bar.progress((epoch + 1) / total, text=f"VQE epoch {epoch + 1}/{total}")
210
+ log_lines.append(
211
+ f"[epoch {epoch + 1:03d}/{total}] "
212
+ f"E={row['VQE_Energy']:.5f} S={row['Entropy']:.4f} "
213
+ f"purity={row['Purity']:.4f} grad={row['Gradient']:.5f}"
214
+ )
215
+ log_container.code("\n".join(log_lines[-12:]), language="text")
216
+
217
+ try:
218
+ df_vqe = dc.run_vqe_telemetry(
219
+ res['sim'], res['parser'],
220
+ dc.QASM_LIBRARY[p["circuit_name"]] if p["source_mode"] == "Libreria Built-in" else p["qasm_text"],
221
+ p["circuit_name"], res['n_qubits'], not p["double_precision"],
222
+ p["vqe_epochs"], p["vqe_lr"], p["vqe_beta1"], p["vqe_beta2"], int(p["seed"]),
223
+ hamiltonian_values=p["hamiltonian_values"], on_epoch=_on_epoch,
224
+ )
225
+ except Exception as e:
226
+ st.error(f"Errore durante la telemetria VQE: {e}")
227
+ finally:
228
+ progress_bar.empty()
229
+
230
+ if not df_vqe.empty:
231
+ df_vqe, vqe_ai_meta = heal_telemetry(df_vqe)
232
+ if vqe_ai_meta["fallback_triggered"]:
233
+ log_lines.append(
234
+ f"⚠️ AI Shield: fallback mediano attivato (raggio adattivo="
235
+ f"{vqe_ai_meta['adaptive_radius_used']}, errore ricostruzione="
236
+ f"{vqe_ai_meta['reconstruction_error']:.4f})"
237
+ )
238
+ log_container.code("\n".join(log_lines[-12:]), language="text")
239
+
240
+ df_md, corr_matrix = pd.DataFrame(), pd.DataFrame()
241
+ md_ai_meta = dict(AI_SHIELD_NEUTRAL_META)
242
+ md_is_real, md_note = False, ''
243
+ if p["md_enabled"]:
244
+ with st.spinner("Telemetria MD..."):
245
+ # Real dynamics under p["hamiltonian_values"] when it's compatible
246
+ # with this circuit's statevector; otherwise run_md_telemetry
247
+ # falls back to the labeled mock itself (see md_telemetry.py).
248
+ df_md, _raw_corr = dc.run_md_telemetry(
249
+ p["md_steps"], p["md_temp"],
250
+ hamiltonian_values=p["hamiltonian_values"], sv=res['sim'].sv,
251
+ n_qubits=res['n_qubits'], seed=int(p["seed"]),
252
+ )
253
+ md_is_real = df_md.attrs.get('is_real', False)
254
+ md_note = df_md.attrs.get('note', '')
255
+ df_md, md_ai_meta = heal_telemetry(df_md)
256
+ corr_matrix = df_md.corr(method="pearson") # recomputed from the healed data, not the raw one
257
+
258
+ history = st.session_state.setdefault("qs_run_history", [])
259
+ history.append({
260
+ 'nome': res['nome'],
261
+ 'n_qubits': res['n_qubits'],
262
+ 'tempo': res['tempo'],
263
+ 'ram': res['ram'],
264
+ 'porte_count': res['porte_count'],
265
+ 'entropy': float(res['entropy']),
266
+ 'fidelity': res['fidelity'],
267
+ 'stato_dominante': res['stato_dominante'],
268
+ 'noise_model': p["noise_model"],
269
+ 'noise_p': p["noise_p"],
270
+ })
271
+
272
+ # Build every panel once, here, right after the data that feeds it
273
+ # changes — not on every sidebar rerun. Figures are closed immediately
274
+ # (plt.close) and the objects kept in session_state; st.pyplot() can
275
+ # render an already-closed Figure object just fine, this only stops
276
+ # them accumulating in pyplot's registry.
277
+ with st.spinner("Rendering pannelli..."):
278
+ metrics = dc.compute_overview_metrics(res, p["noise_model"], p["noise_p"])
279
+ overview_fig = dc.build_panel_overview(res, df_vqe, corr_matrix, p["noise_model"], p["noise_p"])
280
+ fisica_fig = dc.build_panel_fisica(res, seed=int(p["seed"]))
281
+ mosaico_fig = dc.build_panel_mosaico(res)
282
+ vqe_fig = dc.build_panel_vqe_results(df_vqe)
283
+ md_fig = dc.build_panel_md_results(df_md, corr_matrix)
284
+ perf_fig = dc.build_panel_performance(res, history)
285
+ helix_fig = dc.build_3d_helix_patch(res['n_qubits'], res['prob'])
286
+ ham_fig = dc.build_panel_hamiltonian(p["hamiltonian_values"], p["hamiltonian_name"] or 'nessuna')
287
+ mitigation_fig = dc.build_panel_mitigation(mitigation_res, res) if mitigation_res else None
288
+
289
+ overview_png = io.BytesIO()
290
+ overview_fig.savefig(overview_png, format="png", dpi=300, facecolor='#010409', bbox_inches='tight')
291
+
292
+ figs_to_close = [overview_fig, fisica_fig, mosaico_fig, vqe_fig, md_fig, perf_fig, ham_fig]
293
+ if mitigation_fig is not None:
294
+ figs_to_close.append(mitigation_fig)
295
+ for fig in figs_to_close:
296
+ plt.close(fig)
297
+
298
+ st.session_state["qs_res"] = res
299
+ st.session_state["qs_panels"] = {
300
+ "metrics": metrics,
301
+ "vqe_ai_meta": vqe_ai_meta,
302
+ "md_ai_meta": md_ai_meta,
303
+ "md_is_real": md_is_real,
304
+ "md_note": md_note,
305
+ "overview": overview_fig,
306
+ "overview_png": overview_png.getvalue(),
307
+ "fisica": fisica_fig,
308
+ "mosaico": mosaico_fig,
309
+ "vqe": vqe_fig,
310
+ "md": md_fig,
311
+ "hamiltonian": ham_fig,
312
+ "performance": perf_fig,
313
+ "helix": helix_fig,
314
+ "mitigation": mitigation_fig,
315
+ }
316
+
317
+
318
+ def _render_tabs() -> None:
319
+ guard = render_run_guard(
320
+ "qs_res", "qs_panels",
321
+ message="Configura il circuito nella sidebar e premi **Esegui Simulazione** per iniziare.",
322
+ )
323
+ if guard is None:
324
+ return
325
+ res, panels = guard
326
+
327
+ run_history = st.session_state.get("qs_run_history", [])
328
+
329
+ tabs = st.tabs(["Overview", "Fisica Stato", "Mosaico", "VQE Results", "MD Results", "Performance", "3D Helix", "Hamiltonian", "Mitigation (ZNE)"])
330
+
331
+ with tabs[0]:
332
+ render_ai_shield_card("AI Vector-Healing Shield — Telemetria VQE", panels["vqe_ai_meta"])
333
+ with st.container(border=True):
334
+ st.subheader("📊 Simulation Metrics")
335
+ render_metric_grid(panels["metrics"])
336
+ st.pyplot(panels["overview"])
337
+ st.download_button(
338
+ "🖼️ Esporta Overview come PNG (300 DPI)",
339
+ data=panels["overview_png"],
340
+ file_name="quantum_dashboard_overview.png",
341
+ mime="image/png",
342
+ )
343
+
344
+ with tabs[1]:
345
+ st.pyplot(panels["fisica"])
346
+
347
+ with tabs[2]:
348
+ st.pyplot(panels["mosaico"])
349
+
350
+ with tabs[3]:
351
+ st.pyplot(panels["vqe"])
352
+
353
+ with tabs[4]:
354
+ if panels.get("md_is_real"):
355
+ st.success(f"● DATI REALI — {panels.get('md_note', '')}")
356
+ else:
357
+ st.warning(f"● MOCK — {panels.get('md_note', '')}")
358
+ render_ai_shield_card("AI Vector-Healing Shield — Telemetria MD", panels["md_ai_meta"])
359
+ st.pyplot(panels["md"])
360
+
361
+ with tabs[5]:
362
+ st.pyplot(panels["performance"])
363
+
364
+ if run_history:
365
+ st.dataframe(pd.DataFrame(run_history), use_container_width=True)
366
+ st.download_button(
367
+ "💾 Esporta provenance JSON",
368
+ data=dc.build_provenance_json(run_history),
369
+ file_name="quantum_provenance_archive.json",
370
+ mime="application/json",
371
+ )
372
+
373
+ st.divider()
374
+ st.caption(
375
+ "Benchmark scan: alloca simulatori da 2 a 14 qubit e misura tempo/RAM. "
376
+ "Genuinamente lento (allocazione densa fino a 2¹⁴) — esegui solo se necessario."
377
+ )
378
+ if st.button("🧪 Esegui Benchmark Scan (2→14 qubit)"):
379
+ with st.spinner("Benchmark in corso..."):
380
+ bench_df = dc.run_benchmark_scan()
381
+ st.dataframe(bench_df, use_container_width=True)
382
+
383
+ with tabs[6]:
384
+ st.plotly_chart(panels["helix"], use_container_width=True)
385
+
386
+ with tabs[7]:
387
+ st.pyplot(panels["hamiltonian"])
388
+ st.caption(
389
+ "Se nessuna Hamiltoniana personalizzata è abilitata nella sidebar, il VQE usa uno spettro "
390
+ "casuale ordinato (comportamento di default, invariato)."
391
+ )
392
+
393
+ with tabs[8]:
394
+ if panels.get("mitigation") is None:
395
+ st.info("Abilita ZNE nella sidebar e riesegui per vedere questo pannello.")
396
+ else:
397
+ st.pyplot(panels["mitigation"])
398
+
399
+
400
+ def render():
401
+ render_page_banner(
402
+ "Quantum Simulator Dashboard",
403
+ """Esegui un circuito OpenQASM su <code>DenseSVSimulator</code>, opzionalmente con rumore,
404
+ telemetria VQE (JAX autodiff + forze QM/MM Hellmann-Feynman) e dinamica molecolare —
405
+ entrambe protette dallo stesso scudo AI Vector-Healing della pagina Vector Healing.""",
406
+ )
407
+
408
+ params = _render_sidebar()
409
+ if params["run_clicked"]:
410
+ _execute_run(params)
411
+ _render_tabs()
ui_pages/vector_healing.py CHANGED
@@ -11,7 +11,7 @@ import matplotlib.pyplot as plt
11
  import streamlit as st
12
 
13
  from ia_utils.vector_healing import enhanced_dense_healing_hybrid
14
- from ui_pages.components import render_ai_shield_card
15
 
16
  HIDDEN_DIM = 6
17
 
@@ -40,24 +40,16 @@ def _generate_corrupted_sequence(n_steps, hidden_dim, anomaly_pct, rng):
40
 
41
 
42
  def render():
43
- st.markdown(
44
- """
45
- <div style="padding: 1.25rem 1.5rem; border-radius: 0.75rem;
46
- background: linear-gradient(90deg, #001014, #012026);
47
- border: 1px solid #00e5ff44; margin-bottom: 1rem;">
48
- <h1 style="margin: 0; color: #00e5ff;">Dense Evolution v8.1.9 — AI Vector Healing Dashboard</h1>
49
- <p style="margin: 0.5rem 0 0 0; color: #cccccc;">
50
- <code>ia_utils.vector_healing.enhanced_dense_healing_hybrid</code> è uno scudo anti-crash
51
- per sequenze di vettori (es. hidden states): ripulisce <code>NaN</code>/<code>Inf</code>,
52
- poi decide passo per passo — tramite la logica Φ-trigger di
53
- <code>dense_evolution.healing</code> — se il valore fa parte di un cambio di tendenza
54
- genuino (lasciato passare) o di uno spike isolato/rumore (sostituito con la mediana
55
- locale). Lo stesso scudo protegge in produzione anche la telemetria VQE/MD del Quantum
56
- Simulator.
57
- </p>
58
- </div>
59
- """,
60
- unsafe_allow_html=True,
61
  )
62
 
63
  with st.sidebar:
@@ -80,10 +72,11 @@ def render():
80
  "n_steps": n_steps,
81
  }
82
 
83
- result = st.session_state.get("healing_result")
84
-
 
 
85
  if result is None:
86
- st.info("Configura i parametri nella sidebar e premi **Genera ed Esegui Healing** per iniziare.")
87
  return
88
 
89
  ideal, corrupted, healed, metadata = (
@@ -116,5 +109,4 @@ def render():
116
  ax.legend(loc="upper right")
117
  ax.grid(alpha=0.2)
118
 
119
- st.pyplot(fig)
120
- plt.close(fig)
 
11
  import streamlit as st
12
 
13
  from ia_utils.vector_healing import enhanced_dense_healing_hybrid
14
+ from ui_pages.components import render_ai_shield_card, render_page_banner, render_run_guard, render_matplotlib_figure
15
 
16
  HIDDEN_DIM = 6
17
 
 
40
 
41
 
42
  def render():
43
+ render_page_banner(
44
+ "AI Vector Healing Dashboard",
45
+ """<code>ia_utils.vector_healing.enhanced_dense_healing_hybrid</code> è uno scudo anti-crash
46
+ per sequenze di vettori (es. hidden states): ripulisce <code>NaN</code>/<code>Inf</code>,
47
+ poi decide passo per passo — tramite la logica Φ-trigger di
48
+ <code>dense_evolution.healing</code> — se il valore fa parte di un cambio di tendenza
49
+ genuino (lasciato passare) o di uno spike isolato/rumore (sostituito con la mediana
50
+ locale). Lo stesso scudo protegge in produzione anche la telemetria VQE/MD del Quantum
51
+ Simulator.""",
52
+ accent="#00e5ff", bg_from="#001014", bg_to="#012026",
 
 
 
 
 
 
 
 
53
  )
54
 
55
  with st.sidebar:
 
72
  "n_steps": n_steps,
73
  }
74
 
75
+ result = render_run_guard(
76
+ "healing_result",
77
+ message="Configura i parametri nella sidebar e premi **Genera ed Esegui Healing** per iniziare.",
78
+ )
79
  if result is None:
 
80
  return
81
 
82
  ideal, corrupted, healed, metadata = (
 
109
  ax.legend(loc="upper right")
110
  ax.grid(alpha=0.2)
111
 
112
+ render_matplotlib_figure(fig)