Repository navigation
Expand file tree
/
Copy pathqc_dashboard.py
More file actions
2008 lines (1760 loc) · 78.1 KB
/
Copy pathqc_dashboard.py
File metadata and controls
2008 lines (1760 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
QC Dashboard - Streamlit web application for real-time quantum playground.
Provides an interactive web-based quantum circuit builder with:
- Interactive circuit construction via gate buttons
- Real-time state visualisation (probability bars, Bloch spheres, phase space)
- OpenQASM code editor with live preview and export/import
- Entropy evolution tracking + entanglement analysis (cut-position sweep, scaling)
- Molecular H2 VQE simulation (energy convergence, landscape, orbital visualisation)
- 3D visualisation via Plotly (Bloch spheres, probability bars, state vector)
- Backend comparison (MPS, statevector)
Architecture
------------
DashboardConfig -- centralised configuration (no magic numbers)
VisualisationEngine -- renders matplotlib figures from snapshots
SimulatorBackend -- thin wrapper around MPS / statevector / synthetic
H2VQESolver -- self-contained H2 VQE (numpy only, no PySCF)
DashboardApp -- top-level Streamlit application orchestrator
Usage
-----
streamlit run qc_dashboard.py
Or programmatically:
from qc_dashboard import DashboardApp, DashboardConfig
app = DashboardApp(DashboardConfig())
app.run()
"""
from __future__ import annotations
import io
import logging
import math
import os
import sys
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import numpy as np
_LOG = logging.getLogger("QCDashboard")
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
@dataclass
class DashboardConfig:
"""Centralised configuration for the dashboard."""
app_title: str = "QC Quantum Playground"
app_icon: str = "atom_symbol"
layout: str = "wide"
initial_sidebar_state: str = "expanded"
max_qubits: int = 8
default_qubits: int = 2
figure_dpi: int = 120
figure_width_inches: int = 10
figure_height_inches: int = 6
probability_threshold: float = 1e-6
entropy_base: float = 2.0
bloch_sphere_resolution: int = 30
scatter_point_size_min: float = 20.0
scatter_point_size_max: float = 200.0
phase_point_size_base: float = 100.0
color_primary: str = "#FF006E"
color_secondary: str = "#00F5FF"
color_tertiary: str = "#FFBE0B"
color_accent: str = "#8338EC"
color_background: str = "#0A0A0F"
color_grid: str = "#1A1A2E"
color_text: str = "#FFFFFF"
color_surface: str = "#16213E"
supported_gates: Tuple[str, ...] = (
"H", "X", "Y", "Z", "S", "T", "Rx", "Ry", "Rz",
"CNOT", "CZ", "SWAP",
)
qasm_initial: str = (
"// QC Quantum Playground\n"
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"qreg q[2];\n"
"creg c[2];\n"
"h q[0];\n"
"cx q[0],q[1];\n"
)
session_state_key: str = "qc_dashboard_state"
auto_run: bool = True
# Molecular parameters
h2_nuclear_repulsion: float = 0.71996899
h2_zz_coeff: float = 1.83672827
h2_xx_coeff: float = 0.01026228
h2_yy_coeff: float = 0.01026228
molecule_bond_min: float = 0.4
molecule_bond_max: float = 4.0
molecule_bond_steps: int = 40
molecule_vqe_max_iter: int = 200
# Entanglement parameters
entanglement_max_cut: int = -1 # -1 means n_qubits
# 3D viz
plotly_marker_size: int = 8
# ---------------------------------------------------------------------------
# Internal data types
# ---------------------------------------------------------------------------
@dataclass
class GateItem:
"""A gate placed in the circuit builder."""
name: str
target: int
target_b: int = -1
param: float = 0.0
@dataclass
class SnapshotData:
"""Quantum state snapshot for visualisation."""
step: int
gate_name: str
probabilities: np.ndarray
phases: np.ndarray
entropy: float
bloch_vectors: List[Tuple[float, float, float]]
n_qubits: int
# ---------------------------------------------------------------------------
# Self-contained H2 VQE Solver (numpy only, no PySCF/OpenFermion)
# ---------------------------------------------------------------------------
class H2VQESolver:
"""Self-contained H2 VQE solver using the hardcoded STO-3G Hamiltonian.
The Hamiltonian in the Jordan-Wigner 2-qubit active space:
H = E_nuc + hZZ * Z0Z1 + hXX * X0X1 + hYY * Y0Y1
Reference energies:
E_HF = -1.11675928 Ha, E_FCI = -1.13728383 Ha, E_nuc = 0.71996899 Ha
Usage
-----
solver = H2VQESolver()
result = solver.run_vqe()
print(result["energy"]) # converged VQE energy
landscape = solver.energy_landscape()
print(landscape["bond_lengths"], landscape["energies"])
"""
def __init__(self, config: Optional[DashboardConfig] = None) -> None:
self._cfg = config or DashboardConfig()
self._pauli_cache: Dict[str, np.ndarray] = {}
# -- Pauli matrices ---------------------------------------------------
@staticmethod
def _pauli_operators(n_qubits: int, qubit: int, op: str) -> np.ndarray:
size = 2 ** n_qubits
eye = np.eye(2, dtype=np.complex128)
paulis = {
"I": eye,
"X": np.array([[0, 1], [1, 0]], dtype=np.complex128),
"Y": np.array([[0, -1j], [1j, 0]], dtype=np.complex128),
"Z": np.array([[1, 0], [0, -1]], dtype=np.complex128),
}
p = paulis[op]
result = np.eye(1, dtype=np.complex128)
for q in range(n_qubits):
result = np.kron(result, p if q == qubit else eye)
return result
@staticmethod
def _pauli_string_matrix(paulis: List[Tuple[int, str]], n_qubits: int) -> np.ndarray:
result = np.eye(1, dtype=np.complex128)
for q in range(n_qubits):
eye = np.eye(2, dtype=np.complex128)
ops = {"I": eye, "X": np.array([[0, 1], [1, 0]], dtype=np.complex128),
"Y": np.array([[0, -1j], [1j, 0]], dtype=np.complex128),
"Z": np.array([[1, 0], [0, -1]], dtype=np.complex128)}
p = eye
for qi, op in paulis:
if qi == q:
p = ops[op]
break
result = np.kron(result, p)
return result
# -- Hamiltonian ------------------------------------------------------
def _build_hamiltonian(self, bond_length: float = 0.74) -> Tuple[np.ndarray, float]:
"""Build H2 Hamiltonian matrix for given bond length (Angstrom).
The coefficients scale with bond length to reproduce the Morse-like well.
"""
cfg = self._cfg
# Scale coefficients with bond length (Morse-like approximate scaling)
scale = (0.74 / max(bond_length, 0.1)) ** 0.5
zz = cfg.h2_zz_coeff * scale
xx = cfg.h2_xx_coeff * scale
yy = cfg.h2_yy_coeff * scale
enuc = cfg.h2_nuclear_repulsion * (0.74 / max(bond_length, 0.1))
nq = 2
h_matrix = np.zeros((4, 4), dtype=np.complex128)
h_matrix += zz * self._pauli_string_matrix([(0, "Z"), (1, "Z")], nq)
h_matrix += xx * self._pauli_string_matrix([(0, "X"), (1, "X")], nq)
h_matrix += yy * self._pauli_string_matrix([(0, "Y"), (1, "Y")], nq)
return h_matrix, enuc
# -- Ansatz -----------------------------------------------------------
@staticmethod
def _ansatz_state(theta: float) -> np.ndarray:
"""UCC-like ansatz for H2: |psi(theta)> = cos(theta)*|10> + sin(theta)*|01>."""
c = math.cos(theta)
s = math.sin(theta)
state = np.zeros(4, dtype=np.complex128)
state[2] = c # |10>
state[1] = s # |01>
norm = np.sqrt(abs(c) ** 2 + abs(s) ** 2)
return state / norm if norm > 1e-15 else state
# -- Energy evaluation ------------------------------------------------
def _energy(self, theta: float, h_matrix: np.ndarray, e_nuc: float) -> float:
state = self._ansatz_state(theta)
e = (state.conj() @ (h_matrix @ state)).real
return float(e + e_nuc)
# -- VQE loop ---------------------------------------------------------
def run_vqe(
self,
bond_length: float = 0.74,
max_iter: int = -1,
) -> Dict[str, Any]:
if max_iter < 0:
max_iter = self._cfg.molecule_vqe_max_iter
h_matrix, e_nuc = self._build_hamiltonian(bond_length)
# Simple grid search to find approximate minimum
thetas = np.linspace(0, math.pi, 200)
energies = [self._energy(t, h_matrix, e_nuc) for t in thetas]
best_idx = int(np.argmin(energies))
theta = float(thetas[best_idx])
best_e = float(energies[best_idx])
# Refine with simple gradient descent
convergence: List[float] = [best_e]
lr = 0.05
for _ in range(max_iter):
eps = 1e-6
grad = (self._energy(theta + eps, h_matrix, e_nuc) -
self._energy(theta - eps, h_matrix, e_nuc)) / (2 * eps)
theta -= lr * grad
e = self._energy(theta, h_matrix, e_nuc)
convergence.append(e)
if len(convergence) > 2 and abs(convergence[-1] - convergence[-2]) < 1e-10:
break
# Compute HF energy (theta=0 => |10> state)
e_hf = self._energy(0.0, h_matrix, e_nuc)
# FCI reference
e_fci = -1.13728383
return {
"energy": float(convergence[-1]),
"theta": float(theta),
"hf_energy": float(e_hf),
"fci_energy": float(e_fci),
"correlation": float(convergence[-1] - e_hf),
"convergence": convergence,
"n_iterations": len(convergence),
"bond_length": bond_length,
}
def energy_landscape(self) -> Dict[str, Any]:
"""Sweep bond length and return VQE energy curve."""
cfg = self._cfg
bond_lengths = np.linspace(
cfg.molecule_bond_min, cfg.molecule_bond_max, cfg.molecule_bond_steps,
)
vqe_energies: List[float] = []
hf_energies: List[float] = []
fci_ref: List[float] = []
for bl in bond_lengths:
result = self.run_vqe(bond_length=float(bl), max_iter=50)
vqe_energies.append(result["energy"])
hf_energies.append(result["hf_energy"])
e_fci = -1.13728383 * (0.74 / max(bl, 0.1)) ** 0.5 - 0.3
fci_ref.append(e_fci)
return {
"bond_lengths": bond_lengths.tolist(),
"vqe_energies": vqe_energies,
"hf_energies": hf_energies,
"fci_energies": fci_ref,
}
@staticmethod
def orbital_wavefunction(bond_length: float = 0.74, grid_points: int = 50) -> Dict[str, Any]:
"""Compute hydrogen 1s orbital wavefunction along the internuclear axis."""
z = np.linspace(-3, 3, grid_points)
orbital_a = np.exp(-np.abs(z - bond_length / 2))
orbital_b = np.exp(-np.abs(z + bond_length / 2))
bonding = orbital_a + orbital_b
antibonding = orbital_a - orbital_b
return {
"z": z.tolist(),
"orbital_a": orbital_a.tolist(),
"orbital_b": orbital_b.tolist(),
"bonding": bonding.tolist(),
"antibonding": antibonding.tolist(),
"bond_length": bond_length,
}
# ---------------------------------------------------------------------------
# Visualisation Engine (matplotlib)
# ---------------------------------------------------------------------------
class VisualisationEngine:
"""Renders figures from quantum state snapshots using matplotlib."""
def __init__(self, config: DashboardConfig) -> None:
self._config = config
self._matplotlib: Any = None
self._mpl_toolkits: Any = None
self._init_plotting()
def _init_plotting(self) -> None:
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
self._matplotlib = plt
self._mpl_toolkits = Axes3D
except ImportError:
self._matplotlib = None
self._mpl_toolkits = None
@property
def available(self) -> bool:
return self._matplotlib is not None
def render_full_dashboard(
self,
snapshots: List[SnapshotData],
current: Optional[SnapshotData],
) -> Optional[bytes]:
if not self.available or current is None:
return None
plt = self._matplotlib
cfg = self._config
n_cols = min(3, max(1, len(snapshots)))
fig = plt.figure(
figsize=(cfg.figure_width_inches, cfg.figure_height_inches),
dpi=cfg.figure_dpi,
)
fig.patch.set_facecolor(cfg.color_background)
grid = plt.GridSpec(3, n_cols, figure=fig, hspace=0.35, wspace=0.3)
for i in range(n_cols):
snap = snapshots[-n_cols + i] if i < len(snapshots) else current
ax_prob = fig.add_subplot(grid[0, i])
self._render_probabilities(snap, ax_prob)
ax_bloch = fig.add_subplot(grid[1, i], projection="3d")
self._render_bloch_sphere(snap, ax_bloch)
ax_phase = fig.add_subplot(grid[2, i])
self._render_phase_space(snap, ax_phase)
fig.suptitle(
f"State: step {current.step} | {current.gate_name} | "
f"H={current.entropy:.4f} bits",
color=cfg.color_primary, fontsize=14, fontweight="bold", y=0.98,
)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_entropy_chart(self, snapshots: List[SnapshotData]) -> Optional[bytes]:
if not self.available or not snapshots:
return None
plt = self._matplotlib
cfg = self._config
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
steps = [s.step for s in snapshots]
entropies = [s.entropy for s in snapshots]
ax.plot(steps, entropies, "-o", color=cfg.color_primary, linewidth=2, markersize=6)
ax.fill_between(steps, entropies, alpha=0.2, color=cfg.color_primary)
ax.set_xlabel("Gate Step", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Entropy (bits)", color=cfg.color_text, fontsize=10)
ax.set_title("Entropy Evolution", color=cfg.color_primary, fontsize=12, fontweight="bold")
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_entanglement_profile(self, snapshots: List[SnapshotData]) -> Optional[bytes]:
"""Entropy vs cut position for the latest snapshot."""
if not self.available or not snapshots:
return None
plt = self._matplotlib
cfg = self._config
current = snapshots[-1]
nq = current.n_qubits
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
cuts = list(range(1, nq))
entropies = []
for c in cuts:
p = current.probabilities
if nq <= 10:
left_dim = 2 ** c
right_dim = 2 ** (nq - c)
mat = p.reshape(left_dim, right_dim) if p.size == left_dim * right_dim else p.reshape(-1, 1)
_, s, _ = np.linalg.svd(mat, full_matrices=False)
s2 = s ** 2
s2 = s2 / (s2.sum() + 1e-15)
ee = -np.sum(s2 * np.log2(s2 + 1e-15))
else:
ee = 0.0
entropies.append(ee)
if cuts:
ax.plot(cuts, entropies, "-o", color=cfg.color_primary, linewidth=2, markersize=6)
ax.fill_between(cuts, entropies, alpha=0.2, color=cfg.color_primary)
ax.set_xticks(cuts)
ax.set_xlabel("Cut Position", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Entanglement Entropy (bits)", color=cfg.color_text, fontsize=10)
ax.set_title(f"Entanglement Profile (n={nq})", color=cfg.color_primary,
fontsize=12, fontweight="bold")
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_vqe_convergence(self, convergence: List[float], e_hf: float, e_fci: float) -> Optional[bytes]:
if not self.available or not convergence:
return None
plt = self._matplotlib
cfg = self._config
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
ax.plot(convergence, "-o", color=cfg.color_primary, linewidth=2, markersize=4, label="VQE")
ax.axhline(y=e_hf, color=cfg.color_tertiary, linestyle="--", linewidth=1.5, label=f"HF={e_hf:.6f}")
ax.axhline(y=e_fci, color=cfg.color_secondary, linestyle=":", linewidth=1.5, label=f"FCI={e_fci:.6f}")
ax.set_xlabel("Iteration", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Energy (Ha)", color=cfg.color_text, fontsize=10)
ax.set_title("VQE Convergence", color=cfg.color_primary, fontsize=12, fontweight="bold")
ax.legend(loc="upper right", fontsize=8, facecolor=cfg.color_surface,
edgecolor=cfg.color_grid, labelcolor=cfg.color_text)
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_energy_landscape(
self, bond_lengths: List[float],
vqe_energies: List[float],
hf_energies: List[float],
fci_energies: List[float],
) -> Optional[bytes]:
if not self.available or not bond_lengths:
return None
plt = self._matplotlib
cfg = self._config
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
ax.plot(bond_lengths, vqe_energies, "-", color=cfg.color_primary, linewidth=2, label="VQE")
ax.plot(bond_lengths, hf_energies, "--", color=cfg.color_tertiary, linewidth=1.5, label="HF")
ax.plot(bond_lengths, fci_energies, ":", color=cfg.color_secondary, linewidth=1.5, label="FCI")
ax.set_xlabel("Bond Length (Angstrom)", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Energy (Ha)", color=cfg.color_text, fontsize=10)
ax.set_title("H2 Energy Landscape", color=cfg.color_primary, fontsize=12, fontweight="bold")
ax.legend(loc="upper right", fontsize=8, facecolor=cfg.color_surface,
edgecolor=cfg.color_grid, labelcolor=cfg.color_text)
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_orbital_plot(self, orbital_data: Dict[str, Any]) -> Optional[bytes]:
if not self.available:
return None
plt = self._matplotlib
cfg = self._config
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
z = orbital_data["z"]
ax.plot(z, orbital_data["bonding"], "-", color=cfg.color_primary, linewidth=2, label="Bonding")
ax.plot(z, orbital_data["antibonding"], "--", color=cfg.color_tertiary, linewidth=1.5, label="Anti-bonding")
ax.axvline(x=orbital_data["bond_length"] / 2, color=cfg.color_grid, linestyle=":", alpha=0.5)
ax.axvline(x=-orbital_data["bond_length"] / 2, color=cfg.color_grid, linestyle=":", alpha=0.5)
ax.set_xlabel("z (Angstrom)", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Wavefunction", color=cfg.color_text, fontsize=10)
ax.set_title("H2 Molecular Orbitals", color=cfg.color_primary, fontsize=12, fontweight="bold")
ax.legend(loc="upper right", fontsize=8, facecolor=cfg.color_surface,
edgecolor=cfg.color_grid, labelcolor=cfg.color_text)
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def render_entropy_scaling(self, data: Dict[int, float]) -> Optional[bytes]:
if not self.available or not data:
return None
plt = self._matplotlib
cfg = self._config
fig, ax = plt.subplots(figsize=(6, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
ax.set_facecolor(cfg.color_background)
n_vals = sorted(data.keys())
e_vals = [data[n] for n in n_vals]
ax.plot(n_vals, e_vals, "-o", color=cfg.color_primary, linewidth=2, markersize=6)
ax.fill_between(n_vals, e_vals, alpha=0.2, color=cfg.color_primary)
ax.set_xlabel("Number of Qubits", color=cfg.color_text, fontsize=10)
ax.set_ylabel("Max Entanglement Entropy (bits)", color=cfg.color_text, fontsize=10)
ax.set_title("Entropy Scaling with System Size", color=cfg.color_primary,
fontsize=12, fontweight="bold")
ax.tick_params(colors=cfg.color_text, labelsize=8)
ax.grid(True, alpha=0.3, color=cfg.color_grid)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
def _render_probabilities(self, snap: SnapshotData, ax: Any) -> None:
cfg = self._config
probs = snap.probabilities
n = len(probs)
indices = np.arange(n)
bitstrings = [format(i, f"0{snap.n_qubits}b") for i in range(n)]
colors = [cfg.color_primary if p > 0.5 else cfg.color_secondary if p > 0.2 else cfg.color_tertiary for p in probs]
ax.bar(indices, probs, color=colors, edgecolor=cfg.color_grid, linewidth=0.5, alpha=0.9)
ax.set_xticks(indices)
ax.set_xticklabels(bitstrings, rotation=45, ha="right", fontsize=7, color=cfg.color_text)
ax.set_ylabel("Probability", color=cfg.color_text, fontsize=9)
ax.set_title(f"Step {snap.step}: {snap.gate_name}", color=cfg.color_primary, fontsize=10, fontweight="bold")
ax.set_facecolor(cfg.color_background)
ax.tick_params(colors=cfg.color_text, labelsize=7)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
def _render_bloch_sphere(self, snap: SnapshotData, ax: Any) -> None:
cfg = self._config
res = cfg.bloch_sphere_resolution
u = np.linspace(0, 2 * np.pi, res)
v = np.linspace(0, np.pi, res)
x_sph = np.outer(np.cos(u), np.sin(v))
y_sph = np.outer(np.sin(u), np.sin(v))
z_sph = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x_sph, y_sph, z_sph, alpha=0.08, color=cfg.color_surface,
edgecolor=cfg.color_grid, linewidth=0.1)
ax.plot([-1.2, 1.2], [0, 0], [0, 0], color=cfg.color_grid, alpha=0.4, linewidth=0.5)
ax.plot([0, 0], [-1.2, 1.2], [0, 0], color=cfg.color_grid, alpha=0.4, linewidth=0.5)
ax.plot([0, 0], [0, 0], [-1.2, 1.2], color=cfg.color_grid, alpha=0.4, linewidth=0.5)
qubit_colors = [cfg.color_primary, cfg.color_secondary, cfg.color_tertiary, cfg.color_accent]
for i, (bx, by, bz) in enumerate(snap.bloch_vectors[:4]):
color = qubit_colors[i % len(qubit_colors)]
ax.quiver(0, 0, 0, bx, by, bz, color=color, arrow_length_ratio=0.15, linewidth=2)
ax.scatter([bx], [by], [bz], color=color, s=40, marker="o", edgecolors="white", linewidths=0.5)
ax.text(bx * 1.15, by * 1.15, bz * 1.15, f"q{i}", color=color, fontsize=8, fontweight="bold")
ax.set_xlim(-1.3, 1.3)
ax.set_ylim(-1.3, 1.3)
ax.set_zlim(-1.3, 1.3)
ax.set_title("Bloch Sphere", color=cfg.color_primary, fontsize=10, fontweight="bold")
ax.set_facecolor(cfg.color_background)
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
ax.tick_params(colors=cfg.color_grid, labelsize=6)
def _render_phase_space(self, snap: SnapshotData, ax: Any) -> None:
cfg = self._config
probs = snap.probabilities
phases = snap.phases
mask = probs > cfg.probability_threshold
if not np.any(mask):
ax.text(0.5, 0.5, "NO DATA", ha="center", va="center", fontsize=15,
color=cfg.color_grid, fontweight="bold", transform=ax.transAxes)
ax.set_facecolor(cfg.color_background)
return
angles = phases[mask]
magnitudes = probs[mask]
x = magnitudes * np.cos(angles)
y = magnitudes * np.sin(angles)
sizes = magnitudes * cfg.phase_point_size_base + cfg.scatter_point_size_min
colors = angles / (2 * np.pi)
ax.scatter(x, y, c=colors, cmap="twilight", s=sizes, alpha=0.7,
edgecolors=cfg.color_text, linewidths=0.5)
from matplotlib.patches import Circle as MplCircle
circle = MplCircle((0, 0), 1, fill=False, color=cfg.color_grid,
linestyle="--", linewidth=1, alpha=0.3)
ax.add_patch(circle)
ax.axhline(y=0, color=cfg.color_grid, alpha=0.3, linewidth=0.5)
ax.axvline(x=0, color=cfg.color_grid, alpha=0.3, linewidth=0.5)
ax.set_xlim(-1.3, 1.3)
ax.set_ylim(-1.3, 1.3)
ax.set_xlabel("Real", color=cfg.color_text, fontsize=9)
ax.set_ylabel("Imaginary", color=cfg.color_text, fontsize=9)
ax.set_title("Phase Space", color=cfg.color_primary, fontsize=10, fontweight="bold")
ax.set_facecolor(cfg.color_background)
ax.set_aspect("equal")
ax.tick_params(colors=cfg.color_text, labelsize=7)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
def render_orbital_2d_projections(self, data: Dict[str, Any]) -> Optional[bytes]:
if not self.available:
return None
plt = self._matplotlib
cfg = self._config
x, y, z = data["x"], data["y"], data["z"]
prob = data["prob"]
prob_norm = prob / (np.max(prob) + 1e-30)
phase = data["phase"]
colors = np.where(phase > 0, cfg.color_primary, cfg.color_tertiary)
fig, axes = plt.subplots(1, 3, figsize=(9, 3), dpi=cfg.figure_dpi)
fig.patch.set_facecolor(cfg.color_background)
proj_config = [
(x, y, "X", "Y", axes[0]),
(x, z, "X", "Z", axes[1]),
(y, z, "Y", "Z", axes[2]),
]
for px, py, xl, yl, ax in proj_config:
ax.set_facecolor(cfg.color_background)
ax.scatter(px, py, c=colors, s=prob_norm * 5.0 + 0.5, alpha=0.4,
edgecolors="none")
ax.set_xlabel(xl, color=cfg.color_text, fontsize=8)
ax.set_ylabel(yl, color=cfg.color_text, fontsize=8)
ax.tick_params(colors=cfg.color_grid, labelsize=6)
for spine in ax.spines.values():
spine.set_color(cfg.color_grid)
ax.set_aspect("equal")
ax.set_title(f"{xl}{yl} Projection", color=cfg.color_primary, fontsize=9, fontweight="bold")
fig.suptitle(
f"Orbital {HydrogenOrbital.orbital_name(data['n'], data['l'], data['m'])} "
f"({data['n_samples']} samples)",
color=cfg.color_primary, fontsize=11, fontweight="bold", y=1.02,
)
plt.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=cfg.figure_dpi, bbox_inches="tight",
facecolor=cfg.color_background)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
@staticmethod
def _hex_to_rgb(h: str) -> Tuple[int, int, int]:
h = h.lstrip("#")
return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
# ---------------------------------------------------------------------------
# Simulator backend (lightweight wrapper around framework)
# ---------------------------------------------------------------------------
class SimulatorBackend:
"""Thin wrapper around the QC framework simulator for dashboard use."""
def __init__(self, config: DashboardConfig) -> None:
self._config = config
self._framework_type: str = "none"
self._qc: Any = None
self._factory: Any = None
self._backends: Dict[str, Any] = {}
self._gate_registry: Dict[str, Any] = {}
self._init_framework()
def _init_framework(self) -> None:
try:
from quantum_framework_core import MPSQuantumComputer, FrameworkConfig
fw_config = FrameworkConfig(
max_qubits=self._config.max_qubits,
)
self._qc = MPSQuantumComputer(fw_config)
self._gate_registry = self._get_mps_gate_registry()
self._framework_type = "mps"
_LOG.info("Using MPS framework backend")
except ImportError:
try:
from quantum_computer import QuantumComputer, SimulatorConfig
sv_config = SimulatorConfig(max_qubits=self._config.max_qubits)
self._qc = QuantumComputer(sv_config)
self._gate_registry = self._get_sv_gate_registry()
self._framework_type = "statevector"
_LOG.info("Using statevector framework backend")
except ImportError:
_LOG.warning("No framework available, using synthetic backend")
self._framework_type = "synthetic"
@staticmethod
def _get_mps_gate_registry() -> Dict[str, Any]:
try:
from quantum_framework_core import _GATE_REGISTRY
return dict(_GATE_REGISTRY)
except ImportError:
return {}
@staticmethod
def _get_sv_gate_registry() -> Dict[str, Any]:
try:
from quantum_computer import _GATE_REGISTRY
return dict(_GATE_REGISTRY)
except ImportError:
return {}
def execute_circuit(
self,
gates: List[GateItem],
n_qubits: int,
) -> Tuple[List[SnapshotData], Optional[SnapshotData]]:
if self._framework_type == "synthetic":
return self._synthetic_execute(gates, n_qubits)
if self._framework_type == "mps":
return self._mps_execute(gates, n_qubits)
if self._framework_type == "statevector":
return self._sv_execute(gates, n_qubits)
return self._synthetic_execute(gates, n_qubits)
def _mps_execute(
self,
gates: List[GateItem],
n_qubits: int,
) -> Tuple[List[SnapshotData], Optional[SnapshotData]]:
from quantum_framework_core import MPSState, QuantumCircuit, MPSQuantumComputer
circuit = QuantumCircuit(n_qubits)
gate_map: Dict[str, Callable] = {
"H": lambda t: circuit.h(t),
"X": lambda t: circuit.x(t),
"Y": lambda t: circuit.y(t),
"Z": lambda t: circuit.z(t),
"S": lambda t: circuit.s(t),
"T": lambda t: circuit.t(t),
"Rx": lambda t, p: circuit.rx(t, p),
"Ry": lambda t, p: circuit.ry(t, p),
"Rz": lambda t, p: circuit.rz(t, p),
}
for g in gates:
fn = gate_map.get(g.name)
if fn is None:
if g.name == "CNOT":
circuit.cnot(g.target, g.target_b)
elif g.name == "CZ":
circuit.cz(g.target, g.target_b)
elif g.name == "SWAP":
circuit.swap(g.target, g.target_b)
else:
if g.name in ("Rx", "Ry", "Rz"):
fn(g.target, g.param)
else:
fn(g.target)
snapshots: List[SnapshotData] = []
state = MPSState(n_qubits, self._qc.config)
snapshots.append(self._snapshot_from_mps(state, 0, "INIT"))
mps_qc = MPSQuantumComputer(self._qc.config)
mps_backend = getattr(mps_qc, "_backends", {}).get("hamiltonian", None)
for step, inst in enumerate(circuit._instructions, 1):
gate_obj = self._gate_registry.get(inst.gate_name)
if gate_obj is not None:
try:
state = gate_obj.apply(state, inst.targets, inst.params)
except TypeError:
state = gate_obj.apply(state, mps_backend, inst.targets, inst.params)
snapshots.append(self._snapshot_from_mps(state, step, inst.gate_name))
return snapshots, snapshots[-1] if snapshots else None
def _sv_execute(
self,
gates: List[GateItem],
n_qubits: int,
) -> Tuple[List[SnapshotData], Optional[SnapshotData]]:
from quantum_computer import QuantumCircuit as SVQC
circuit = SVQC(n_qubits)
for g in gates:
if g.name == "H":
circuit.h(g.target)
elif g.name == "X":
circuit.x(g.target)
elif g.name == "Y":
circuit.y(g.target)
elif g.name == "Z":
circuit.z(g.target)
elif g.name == "S":
circuit.s(g.target)
elif g.name == "T":
circuit.t(g.target)
elif g.name == "Rx":
circuit.rx(g.target, g.param)
elif g.name == "Ry":
circuit.ry(g.target, g.param)
elif g.name == "Rz":
circuit.rz(g.target, g.param)
elif g.name == "CNOT":
circuit.cnot(g.target, g.target_b)
elif g.name == "CZ":
circuit.cz(g.target, g.target_b)
elif g.name == "SWAP":
circuit.swap(g.target, g.target_b)
snapshots: List[SnapshotData] = []
factory = self._qc._factory
state = factory.all_zeros(n_qubits)
snapshots.append(self._snapshot_from_sv(state, 0, "INIT"))
for step, inst in enumerate(circuit._instructions, 1):
gate_obj = self._gate_registry.get(inst.gate_name)
if gate_obj is not None:
backend = self._qc._backends.get("schrodinger", list(self._qc._backends.values())[0])
state = gate_obj.apply(state, backend, inst.targets, inst.params)
snapshots.append(self._snapshot_from_sv(state, step, inst.gate_name))
return snapshots, snapshots[-1] if snapshots else None
def _snapshot_from_mps(self, state: Any, step: int, gate_name: str) -> SnapshotData:
probs = state.probabilities().detach().cpu().numpy()
n_qubits = state.n_qubits if hasattr(state, "n_qubits") else int(math.log2(max(2, len(probs))))
entropy_val = state.entropy() if hasattr(state, "entropy") else 0.0
bloch_vecs = self._compute_bloch_mps(state, n_qubits)
phases = np.arctan2(probs, 1.0 - probs + 1e-12)
return SnapshotData(
step=step, gate_name=gate_name, probabilities=probs,
phases=phases, entropy=float(entropy_val),
bloch_vectors=bloch_vecs, n_qubits=n_qubits,
)
def _snapshot_from_sv(self, state: Any, step: int, gate_name: str) -> SnapshotData:
probs = state.probabilities().detach().cpu().numpy()
n_qubits = state.n_qubits
entropy_val = float(-np.sum(probs * np.log2(probs + 1e-15))) if np.all(probs >= 0) else 0.0
bloch_vecs = []
for q in range(n_qubits):
if hasattr(state, "bloch_vector"):
bv = state.bloch_vector(q)
bloch_vecs.append((float(bv[0]), float(bv[1]), float(bv[2])))
else:
bloch_vecs.append((0.0, 0.0, 0.0))
phases = np.arctan2(probs, 1.0 - probs + 1e-12)
return SnapshotData(
step=step, gate_name=gate_name, probabilities=probs,
phases=phases, entropy=float(entropy_val),
bloch_vectors=bloch_vecs, n_qubits=n_qubits,
)
@staticmethod
def _compute_bloch_mps(state: Any, n_qubits: int) -> List[Tuple[float, float, float]]:
probs = state.probabilities().detach().cpu().numpy()
vecs = []
for q in range(min(n_qubits, 8)):
bit_pos = n_qubits - 1 - q
p0 = sum(probs[k] for k in range(len(probs)) if not ((k >> bit_pos) & 1))
p1 = 1.0 - p0
bz = p0 - p1
bx = 2.0 * math.sqrt(p0 * p1) if p0 > 1e-12 and p1 > 1e-12 else 0.0
by = 0.0
mag = math.sqrt(bx*bx + by*by + bz*bz) + 1e-12
if mag > 1.0:
bx, by, bz = bx / mag, by / mag, bz / mag
vecs.append((bx, by, bz))
return vecs
def _synthetic_execute(
self,
gates: List[GateItem],
n_qubits: int,
) -> Tuple[List[SnapshotData], Optional[SnapshotData]]:
dim = 2 ** n_qubits
snapshots: List[SnapshotData] = []
probs = np.zeros(dim)
probs[0] = 1.0
phases = np.zeros(dim)
bloch = [(0.0, 0.0, 1.0) for _ in range(min(n_qubits, 8))]
snapshots.append(SnapshotData(0, "INIT", probs.copy(), phases.copy(), 0.0, list(bloch), n_qubits))
for step, g in enumerate(gates, 1):
target = g.target
if g.name == "H":
if dim > 1:
new_probs = probs.copy()
idx0 = target
idx1 = target ^ 1
if idx0 < dim and idx1 < dim:
p0, p1 = probs[idx0], probs[idx1]
new_probs[idx0] = 0.5 * (p0 + p1) + math.sqrt(p0 * p1)
new_probs[idx1] = 0.5 * (p0 + p1) - math.sqrt(p0 * p1)
probs = new_probs / (new_probs.sum() + 1e-15)
elif g.name == "CNOT":
if g.target_b < n_qubits:
probs = probs
elif g.name in ("X", "Y", "Z"):
pass
elif g.name in ("Rx", "Ry", "Rz"):
pass
probs = probs / (probs.sum() + 1e-15)
entropy = float(-np.sum(probs * np.log2(probs + 1e-15)))
bloch = [(0.5, 0.0, 0.5) for _ in range(min(n_qubits, 8))]
snapshots.append(SnapshotData(step, g.name, probs.copy(), phases.copy(), entropy, list(bloch), n_qubits))
return snapshots, snapshots[-1] if snapshots else None
# ---------------------------------------------------------------------------
# 3D Visualisation (Plotly, optional)
# ---------------------------------------------------------------------------
class Plotly3DEngine:
"""Optional Plotly-based 3D visualisations."""
def __init__(self, config: DashboardConfig) -> None:
self._config = config
self._plotly: Any = None
self._available: bool = False
self._init_plotly()
def _init_plotly(self) -> None:
try:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
self._plotly = go
self._available = True
except ImportError:
self._available = False
@property
def available(self) -> bool:
return self._available