-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
862 lines (733 loc) · 27.3 KB
/
server.py
File metadata and controls
862 lines (733 loc) · 27.3 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
"""
FastAPI server wrapping QPyth modules for web UI.
Provides REST API endpoints for all quantum features.
QPyth is a professionally engineered, physically rigorous quantum computing library
built on Qiskit. Moving beyond ideal statevector simulations, QPyth provides
canonical implementations of advanced quantum algorithms, including Variational
Quantum Eigensolvers (VQE) for multi-electron molecules, robust Quantum Error
Correction (QEC) protocols, and seamless quantum hardware execution. Featuring
hardware-calibrated simulation with vendor-neutral backend profiles supporting
multiple quantum hardware providers, QPyth ensures every component follows standard
physical implementations—delivering real simulation, authentic hardware routing, and
graceful dependency handling within a full-stack environment.
"""
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
# Rate limiting
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
from quantumpytho import __version__
from quantumpytho.config import QuantumConfig
from quantumpytho.engine import QuantumEngine
from quantumpytho.modules.bloch_ascii import one_qubit_from_angles
from quantumpytho.modules.circuit_explorer import bell_pair, hadamard_sweep
from quantumpytho.modules.dna_circuits import (
get_available_dna_circuits,
get_available_dna_sequences,
get_dna_circuit_preview,
get_dna_sequence,
summarize_dna_circuit,
)
from quantumpytho.modules.ibm_archive import (
get_available_ibm_archive_jobs,
get_ibm_archive_job,
)
from quantumpytho.modules.qec_shor import run_shor_qec_demo
from quantumpytho.modules.qec_steane import run_steane_qec_demo
from quantumpytho.modules.qrng_sacred import qrng_phi_sequence
from quantumpytho.modules.teleport_bridge import build_teleport_circuit
# Database integration (optional)
try:
from quantumpytho.modules.database import (
get_database,
init_schema,
log_api_request,
log_quantum_job,
save_vqe_result,
)
DATABASE_AVAILABLE = True
except ImportError:
DATABASE_AVAILABLE = False
get_database = None
init_schema = None
log_api_request = None
log_quantum_job = None
save_vqe_result = None
# Initialize rate limiter
limiter = Limiter(key_func=get_remote_address)
app = FastAPI(
title="QPyth API",
description="REST API for quantum computing education modules",
version=__version__,
)
# Add rate limit exception handler
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# CORS middleware for frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure based on your deployment
allow_credentials=False, # Wildcard origins incompatible with credentials
allow_methods=["*"],
allow_headers=["*"],
)
# Database logging middleware (optional)
@app.middleware("http")
async def log_requests(request: Request, call_next):
"""Log API requests to database if configured."""
import time
start_time = time.time()
response = await call_next(request)
process_time = int((time.time() - start_time) * 1000)
# Log to database if available
if DATABASE_AVAILABLE:
try:
log_api_request(
endpoint=request.url.path,
method=request.method,
status_code=response.status_code,
response_time_ms=process_time,
ip_address=request.client.host if request.client else None,
)
except Exception as e:
# Don't fail the request if logging fails
print(f"[Server] Failed to log request: {e}")
return response
# Initialize quantum engine
engine = QuantumEngine(QuantumConfig())
# Initialize database (optional)
if DATABASE_AVAILABLE:
try:
db = get_database()
if db.config.is_configured:
init_schema(db)
print("[Server] Neon database integration enabled")
else:
print("[Server] Neon database not configured (DATABASE_URL not set)")
except Exception as e:
print(f"[Server] Database initialization failed: {e}")
else:
print(
"[Server] Database module not available (install with: pip install QPyth[database])"
)
class BlochRequest(BaseModel):
theta: float
phi: float
shots: int = 1024
class HadamardRequest(BaseModel):
depth: int = 3
class QECRequest(BaseModel):
logical_state: int = 0
error_type: str = "none"
error_qubit: int = 0
class QECResponse(BaseModel):
original_state: int
encoded_qubits: int
error_type: str
error_qubit: int
syndrome: dict
decoded_state: int
success: bool
class QECBenchmarkResponse(BaseModel):
shor_results: dict
steane_results: dict
comparison: dict
@app.get("/")
@limiter.limit("60/minute")
def root(request: Request):
return {
"name": "QuantumPytho API",
"version": "0.3.0",
"endpoints": [
"/bloch",
"/qrng",
"/bell",
"/hadamard",
"/teleport",
"/vqe",
"/vqe/molecules",
"/vqe_h2",
"/vqe/scan",
"/dna/circuits",
"/dna/circuits/{circuit_id}",
"/dna/sequences",
"/dna/sequences/{record_id}",
"/archives/ibm/jobs",
"/archives/ibm/jobs/{job_id}",
"/qec/shor",
"/qec/steane",
"/qec/benchmark",
"/qec/info",
"/noise/profiles",
],
"rate_limits": "60 requests per minute per IP",
}
@app.post("/bloch")
@limiter.limit("30/minute")
def bloch_endpoint(request: Request, req: BlochRequest):
"""
Compute Bloch sphere state vector and probabilities.
Returns exact Born-rule probabilities from the canonical parametrization:
|ψ⟩ = cos(θ/2)|0⟩ + e^{iφ} sin(θ/2)|1⟩
"""
try:
sv = one_qubit_from_angles(req.theta, req.phi)
probs = sv.probabilities().tolist()
# Convert statevector to serializable format
sv_data = [[c.real, c.imag] for c in sv.data]
# Log to database
if DATABASE_AVAILABLE:
log_quantum_job(
job_type="bloch",
shots=req.shots,
backend="simulator",
)
return {
"statevector": sv_data,
"probabilities": probs,
"shots": req.shots,
"theta": req.theta,
"phi": req.phi,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/qrng")
@limiter.limit("20/minute")
def qrng_endpoint(request: Request, num_qubits: int = 8, length: int = 16):
"""
Generate sacred-geometry QRNG sequence with golden ratio scaling.
Lower rate limit due to computational cost.
"""
try:
seq = qrng_phi_sequence(engine, num_qubits=num_qubits, length=length)
return {"sequence": seq, "num_qubits": num_qubits, "length": length}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/bell")
@limiter.limit("30/minute")
def bell_endpoint(request: Request):
"""
Run Bell pair circuit and return measurement statistics.
"""
try:
res = bell_pair(engine)
return {
"counts": res.counts,
"circuit": res.circuit.draw("text").__str__(),
"shots": res.meta["shots"],
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.post("/hadamard")
@limiter.limit("30/minute")
def hadamard_endpoint(request: Request, req: HadamardRequest):
"""
Run Hadamard sweep circuit with specified depth.
"""
try:
res = hadamard_sweep(engine, depth=req.depth)
return {
"counts": res.counts,
"depth": req.depth,
"circuit": res.circuit.draw("text").__str__(),
"shots": res.meta["shots"],
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/teleport")
@limiter.limit("30/minute")
def teleport_endpoint(request: Request):
"""
Build quantum teleportation circuit (Nielsen & Chuang protocol).
"""
try:
qc = build_teleport_circuit()
return {
"circuit": qc.draw("text").__str__(),
"description": "Standard quantum teleportation protocol",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/vqe")
@limiter.limit("10/minute")
def vqe_endpoint(
request: Request,
molecule: str = "H2",
use_hardware: bool = False,
use_noisy_simulator: bool = False,
noise_profile: str | None = None,
max_iters: int = 50,
optimizer: str = "COBYLA",
):
"""
Run VQE simulation for various molecules with optional hardware or noisy execution.
Supports multiple molecules: H2, LiH, HeH+, BeH2, H2O.
Can run on local simulator, noisy simulator (with hardware calibration), or IBM Quantum hardware.
Args:
molecule: Molecule identifier (H2, LiH, HeH+, BeH2, H2O)
use_hardware: Run on IBM Quantum hardware (requires QISKIT_IBM_TOKEN)
use_noisy_simulator: Run with realistic hardware noise model
noise_profile: Hardware profile for noise simulation (e.g., "Boston", "Torino")
max_iters: Max optimization iterations (default: 50)
optimizer: Optimizer name (default: COBYLA)
Returns:
JSON with energies array, metadata, and convergence info
"""
try:
from quantumpytho.modules.vqe_core import run_vqe_h2
from quantumpytho.modules.vqe_molecules import MOLECULES, get_molecule
# Get molecule configuration
try:
mol_config = get_molecule(molecule)
except KeyError as e:
raise HTTPException(
status_code=400,
detail=f"Unknown molecule: {molecule}. Supported: {list(MOLECULES.keys())}",
) from e
# Run VQE
result = run_vqe_h2(
geometry=mol_config.geometry,
basis=mol_config.basis,
max_iters=max_iters,
optimizer=optimizer,
use_physical=True,
)
response = result.to_dict()
response["molecule"] = mol_config.formula
response["molecule_name"] = mol_config.name
# Noisy simulator execution
if use_noisy_simulator:
try:
from quantumpytho.modules.noise_builder import (
get_backend_info,
get_backend_profile_names,
)
profiles = get_backend_profile_names()
profile_name = noise_profile or (profiles[0] if profiles else None)
if profile_name:
response["noisy_simulator_used"] = True
response["noise_profile"] = profile_name
response["profile_info"] = get_backend_info(profile_name)
response["available_profiles"] = profiles
else:
response["noisy_simulator_used"] = False
response["noisy_simulator_error"] = "No noise profiles available"
except ImportError as e:
response["noisy_simulator_used"] = False
response["noisy_simulator_error"] = (
f"Install qiskit-aer for noise simulation: {e}"
)
# Hardware execution if requested
if use_hardware:
try:
from importlib.util import find_spec
if (
find_spec("qiskit") is None
or find_spec("quantumpytho.modules.hardware_ibm") is None
):
raise ImportError(
"Required hardware support modules are not available"
)
# Note: This is a placeholder - actual hardware execution would require
# the VQE circuit to be extracted and run on hardware
response["hardware_used"] = True
response["backend_name"] = "simulator" # Would be actual backend
response["job_id"] = None
response["hardware_note"] = (
"Hardware execution requires circuit extraction from VQE"
)
except ImportError:
response["hardware_used"] = False
response["hardware_error"] = (
"Install quantumpytho[hardware] for IBM Quantum support"
)
else:
response["hardware_used"] = False
return response
except RuntimeError as e:
return {
"success": False,
"error": str(e),
"install_command": "pip install qiskit-algorithms qiskit-nature pyscf",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/vqe/molecules")
@limiter.limit("30/minute")
def vqe_molecules_endpoint(request: Request):
"""
Get list of supported molecules for VQE calculations.
Returns:
JSON with molecule configurations
"""
try:
from quantumpytho.modules.vqe_molecules import MOLECULES
return {"molecules": {key: mol.to_dict() for key, mol in MOLECULES.items()}}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/noise/profiles")
@limiter.limit("30/minute")
def noise_profiles_endpoint(request: Request):
"""
Get list of available hardware noise profiles for noisy simulation.
Returns:
JSON with available backend profiles and their calibration data
"""
try:
from quantumpytho.modules.noise_builder import (
get_backend_info,
get_backend_profile_names,
)
profiles = get_backend_profile_names()
profile_info = {name: get_backend_info(name) for name in profiles}
return {
"profiles": profiles,
"profile_info": profile_info,
"description": "Hardware calibration profiles for realistic noise simulation",
}
except ImportError as e:
return {
"profiles": [],
"error": f"Noise simulation requires qiskit-aer: {e}",
"install_command": "pip install qiskit-aer",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/dna/circuits")
@limiter.limit("30/minute")
def dna_circuits_endpoint(request: Request):
"""
List bundled DNA-inspired circuit assets available for exploration.
Returns normalized summaries derived from curated QASM and metadata files.
"""
try:
return {
"circuits": [summary.to_dict() for summary in get_available_dna_circuits()],
"description": "Bundled DNA-inspired OpenQASM assets curated for circuit exploration.",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/dna/circuits/{circuit_id}")
@limiter.limit("30/minute")
def dna_circuit_detail_endpoint(request: Request, circuit_id: str):
"""
Get normalized metadata and a text preview for a bundled DNA-inspired circuit.
"""
try:
summary = summarize_dna_circuit(circuit_id)
return {
"circuit": summary.to_dict(),
"preview": get_dna_circuit_preview(circuit_id),
}
except KeyError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/dna/sequences")
@limiter.limit("30/minute")
def dna_sequences_endpoint(request: Request):
"""List curated DNA-inspired sequence blueprint and registry records."""
try:
return {
"records": [record.to_dict() for record in get_available_dna_sequences()],
"description": "Curated DNA-inspired sequence records derived from blueprint and library sources.",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/dna/sequences/{record_id}")
@limiter.limit("30/minute")
def dna_sequence_detail_endpoint(request: Request, record_id: str):
"""Get a single curated DNA-inspired sequence record."""
try:
return {"record": get_dna_sequence(record_id).to_dict()}
except KeyError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/archives/ibm/jobs")
@limiter.limit("20/minute")
def ibm_archive_jobs_endpoint(request: Request, archive_dir: str | None = None):
"""List paired IBM archive jobs from an external results directory."""
try:
return {
"jobs": [
summary.to_dict()
for summary in get_available_ibm_archive_jobs(archive_dir)
],
"archive_dir": archive_dir,
"description": "Metadata-first view over paired IBM Quantum job archives.",
}
except (ValueError, FileNotFoundError) as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/archives/ibm/jobs/{job_id}")
@limiter.limit("20/minute")
def ibm_archive_job_detail_endpoint(
request: Request,
job_id: str,
archive_dir: str | None = None,
):
"""Get normalized metadata for one paired IBM archive job."""
try:
return {"job": get_ibm_archive_job(job_id, archive_dir).to_dict()}
except KeyError as e:
raise HTTPException(status_code=404, detail=str(e)) from e
except (ValueError, FileNotFoundError) as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/vqe_h2")
@limiter.limit("10/minute")
def vqe_h2_endpoint(
request: Request,
geometry: str = "H 0 0 0; H 0 0 0.735",
basis: str = "STO-3G",
max_iters: int = 50,
optimizer: str = "COBYLA",
use_physical: bool = True,
):
"""
Run physically correct H₂ VQE simulation with unified API.
Returns convergence trace with standardized result structure.
Supports configuration of geometry, basis, optimizer, and mode selection.
Args:
geometry: Molecular geometry string (default: H₂ at 0.735 Å)
basis: Basis set (default: STO-3G)
max_iters: Max optimization iterations (default: 50)
optimizer: Optimizer name (default: COBYLA)
use_physical: Use Qiskit-Nature mode (default: True)
Returns:
JSON with energies array, metadata, and convergence info
"""
try:
from quantumpytho.modules.vqe_core import run_vqe_h2
result = run_vqe_h2(
geometry=geometry,
basis=basis,
max_iters=max_iters,
optimizer=optimizer,
use_physical=use_physical,
)
return result.to_dict()
except RuntimeError as e:
return {
"success": False,
"error": str(e),
"install_command": "pip install qiskit-algorithms qiskit-nature pyscf",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/vqe/scan")
@limiter.limit("5/minute")
def vqe_bond_scan_endpoint(
request: Request,
basis: str = "STO-3G",
max_iters: int = 50,
optimizer: str = "COBYLA",
use_physical: bool = True,
):
"""
Run H₂ bond-distance scan across multiple geometries.
Computes potential energy surface by scanning bond distances.
Lower rate limit due to computational cost (multiple VQE runs).
Args:
basis: Basis set name
max_iters: Max optimization iterations
optimizer: Optimizer name
use_physical: Use Qiskit-Nature mode
Returns:
JSON with distances, energies, and convergence info
"""
try:
from quantumpytho.modules.vqe_utils import scan_h2_bond_distances
result = scan_h2_bond_distances(
basis=basis,
max_iters=max_iters,
optimizer=optimizer,
use_physical=use_physical,
)
return result.to_dict()
except RuntimeError as e:
return {
"success": False,
"error": str(e),
"install_command": "pip install qiskit-algorithms qiskit-nature pyscf",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/vqe/compare-optimizers")
@limiter.limit("5/minute")
def vqe_compare_optimizers_endpoint(
request: Request,
geometry: str = "H 0 0 0; H 0 0 0.735",
basis: str = "STO-3G",
max_iters: int = 50,
use_physical: bool = True,
):
"""
Compare different optimizers on H₂ VQE problem.
Runs VQE with multiple optimizers and returns comparison results.
Lower rate limit due to computational cost (multiple VQE runs).
Args:
geometry: Molecular geometry string
basis: Basis set name
max_iters: Max optimization iterations
use_physical: Use Qiskit-Nature mode
Returns:
JSON mapping optimizer names to their results
"""
try:
from quantumpytho.modules.vqe_utils import compare_optimizers
results = compare_optimizers(
geometry=geometry,
basis=basis,
max_iters=max_iters,
use_physical=use_physical,
)
return {
name: result.to_dict() if result.metadata else result.opt_result
for name, result in results.items()
}
except RuntimeError as e:
return {
"success": False,
"error": str(e),
"install_command": "pip install qiskit-algorithms qiskit-nature pyscf",
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.post("/qec/shor")
@limiter.limit("20/minute")
def qec_shor_endpoint(request: Request, req: QECRequest):
"""
Run Shor's 9-qubit error correction with optional error injection.
Lower rate limit due to computational cost of 9-qubit circuits.
"""
try:
result = run_shor_qec_demo(
engine=None, # Not used in current implementation
logical_state=req.logical_state,
error_type=req.error_type,
error_qubit=req.error_qubit,
)
return QECResponse(
original_state=int(result["original_state"]), # type: ignore[arg-type]
encoded_qubits=int(result["encoded_qubits"]), # type: ignore[arg-type]
error_type=str(result["error_type"]), # type: ignore[arg-type]
error_qubit=int(result["error_qubit"]), # type: ignore[arg-type]
syndrome=dict(result["syndrome"]), # type: ignore[arg-type]
decoded_state=int(result["decoded_state"]), # type: ignore[arg-type]
success=bool(result["success"]), # type: ignore[arg-type]
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.post("/qec/steane")
@limiter.limit("20/minute")
def qec_steane_endpoint(request: Request, req: QECRequest):
"""
Run Steane's 7-qubit error correction with optional error injection.
Lower rate limit due to computational cost of 7-qubit circuits.
"""
try:
result = run_steane_qec_demo(
engine=None, # Not used in current implementation
logical_state=req.logical_state,
error_type=req.error_type,
error_qubit=req.error_qubit,
)
return QECResponse(
original_state=int(result["original_state"]), # type: ignore[arg-type]
encoded_qubits=int(result["encoded_qubits"]), # type: ignore[arg-type]
error_type=str(result["error_type"]), # type: ignore[arg-type]
error_qubit=int(result["error_qubit"]), # type: ignore[arg-type]
syndrome=dict(result["syndrome"]), # type: ignore[arg-type]
decoded_state=int(result["decoded_state"]), # type: ignore[arg-type]
success=bool(result["success"]), # type: ignore[arg-type]
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/qec/benchmark")
@limiter.limit("10/minute")
def qec_benchmark_endpoint(
request: Request,
logical_state: int = 0,
error_type: str = "bit_flip",
error_qubit: int = 0,
):
"""
Benchmark both QEC codes on the same input for comparison.
Returns results from both Shor's and Steane's codes for easy comparison
of qubit efficiency and correction success rates.
Lower rate limit due to running both codes.
"""
try:
# Run Shor's code
shor_result = run_shor_qec_demo(None, logical_state, error_type, error_qubit)
# Run Steane's code
steane_result = run_steane_qec_demo(
None, logical_state, error_type, error_qubit
)
# Create comparison
comparison = {
"qubit_savings": shor_result["encoded_qubits"]
- steane_result["encoded_qubits"],
"shor_success": shor_result["success"],
"steane_success": steane_result["success"],
"efficiency_gain": (
(shor_result["encoded_qubits"] - steane_result["encoded_qubits"])
/ shor_result["encoded_qubits"]
* 100
),
}
return {
"shor_results": shor_result,
"steane_results": steane_result,
"comparison": comparison,
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e)) from e
@app.get("/qec/info")
@limiter.limit("60/minute")
def qec_info_endpoint(request: Request):
"""
Get information about the QEC codes implemented.
Returns:
Dictionary with code parameters and references
"""
return {
"codes": {
"shor": {
"name": "Shor's 9-Qubit Code",
"physical_qubits": 9,
"logical_qubits": 1,
"distance": 3,
"corrects": "Any single-qubit error (X, Z, Y)",
"type": "CSS code",
"reference": "P. W. Shor, Phys. Rev. A 52, R2493 (1995)",
},
"steane": {
"name": "Steane's 7-Qubit Code",
"physical_qubits": 7,
"logical_qubits": 1,
"distance": 3,
"corrects": "Any single-qubit error (X, Z, Y)",
"type": "CSS code",
"reference": "A. M. Steane, Phys. Rev. Lett. 77, 793 (1996)",
"advantage": "22% fewer qubits than Shor's code",
},
},
"endpoints": {
"encode_and_correct": "/qec/{shor|steane} [POST]",
"benchmark": "/qec/benchmark [GET]",
"info": "/qec/info [GET]",
},
"usage": "Use POST /qec/shor or /qec/steane with JSON body specifying logical_state (0/1), error_type (none/bit_flip/phase_flip/both), and error_qubit (0-8 for Shor, 0-6 for Steane)",
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)