-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
333 lines (265 loc) · 9.96 KB
/
app.py
File metadata and controls
333 lines (265 loc) · 9.96 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
"""
Gradio interface for QPyth - Quantum-inspired Python experimentation.
This provides a comprehensive web UI for the QPyth quantum computing
library on Hugging Face Spaces.
"""
import json
import gradio as gr
from qiskit import QuantumCircuit
from quantumpytho.engine import QuantumEngine
from quantumpytho.modules.bloch_ascii import one_qubit_from_angles
from quantumpytho.modules.circuit_explorer import bell_pair
# Initialize quantum engine
engine = QuantumEngine()
def bloch_sphere_demo(theta, phi):
"""Generate Bloch sphere ASCII visualization."""
try:
result = one_qubit_from_angles(theta, phi)
return result
except Exception as e:
return f"Error: {str(e)}"
def create_bell_pair():
"""Create a Bell pair and return circuit diagram."""
try:
result = bell_pair(engine)
return result.circuit.draw(output="text")
except Exception as e:
return f"Error: {str(e)}"
def run_quantum_teleport():
"""Run quantum teleportation demo."""
try:
from quantumpytho.modules.teleport_bridge import build_teleport_circuit
circuit = build_teleport_circuit()
result = engine.run(circuit)
return (
f"Teleportation circuit executed successfully!\n\nCounts: {result.counts}"
)
except Exception as e:
return f"Error: {str(e)}"
def run_qec_demo(code_type="Shor"):
"""Run Quantum Error Correction demo."""
try:
if code_type == "Shor":
from quantumpytho.modules.qec_shor import run_shor_qec_demo
return run_shor_qec_demo()
elif code_type == "Steane":
from quantumpytho.modules.qec_steane import run_steane_qec_demo
return run_steane_qec_demo()
else: # Surface
from quantumpytho.modules.qec_surface import run_surface_code_demo
return run_surface_code_demo()
except Exception as e:
return f"Error: {str(e)}"
def generate_qrng(count, phi_scale=False):
"""Generate quantum random numbers."""
try:
from quantumpytho.modules.qrng_sacred import qrng_phi_sequence
if phi_scale:
result = qrng_phi_sequence(count)
return f"QRNG with phi-scaling:\n{result}"
else:
circuit = QuantumCircuit(8, 8)
circuit.h(range(8))
circuit.measure(range(8), range(8))
job_result = engine.run(circuit)
return f"Standard QRNG results:\n{job_result.counts}"
except Exception as e:
return f"Error: {str(e)}"
def run_vqe_h2(bond_length=0.74, shots=1024):
"""Run VQE for H2 molecule."""
try:
from quantumpytho.modules.vqe_core import run_vqe_h2 as run_vqe_h2_core
geometry = f"H 0 0 0; H 0 0 {bond_length}"
result = run_vqe_h2_core(geometry=geometry, max_iters=int(shots))
energies = result.energy_history
initial_energy = energies[0][1] if energies else result.ground_energy
error = abs(result.ground_energy - initial_energy) if energies else 0.0
output = f"""VQE Results for H₂ Molecule:
Bond Length: {bond_length} Å
Iterations: {result.iterations}
Ground Energy: {result.ground_energy:.6f} Hartree
Estimated Improvement: {error:.6f} Hartree
Optimizer: {result.metadata.optimizer}
Backend: {result.metadata.backend}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
def run_noisy_simulation(backend_profile="IBM", noise_level=0.01):
"""Run noisy simulation with backend profiles."""
try:
from quantumpytho.modules.hardware_ibm import NoisySimulatorEngine
from quantumpytho.modules.noise_builder import get_backend_info
available_profiles = NoisySimulatorEngine.get_available_profiles()
profile_name = (
backend_profile if backend_profile in available_profiles else None
)
circuit = QuantumCircuit(2, 2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure([0, 1], [0, 1])
simulator = NoisySimulatorEngine(
noise_profile=profile_name,
shots=1024,
)
result = simulator.run(circuit)
profile_info = get_backend_info(profile_name) if profile_name else None
output = f"""Noisy Simulation Results:
Backend Profile: {profile_name or "simulator"}
Noise Level: {noise_level}
Measurement Counts:
{json.dumps(result.counts, indent=2)}
Profile Info:
{json.dumps(profile_info or {"noise_model": "none"}, indent=2)}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
def explore_dna_circuits(sequence_name="ATCG"):
"""Explore DNA-inspired circuits."""
try:
from quantumpytho.modules.dna_circuits import (
get_available_dna_sequences,
get_dna_sequence,
summarize_dna_circuit,
)
# Get available sequences
available = get_available_dna_sequences()
# Get specific sequence
sequence_data = get_dna_sequence(sequence_name)
# Summarize
summary = summarize_dna_circuit(sequence_name)
output = f"""DNA Circuit Exploration:
Sequence: {sequence_name}
Available Sequences: {", ".join(available[:10])}...
Sequence Data:
{json.dumps(sequence_data, indent=2)}
Circuit Summary:
{summary}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
def run_tmt_sierpinski():
"""Run TMT Sierpinski 21-qubit sacred geometry circuit."""
try:
from quantumpytho.modules.tmt_sierpinski import (
run_tmt_sierpinski as run_tmt_demo,
)
result = run_tmt_demo(engine)
output = f"""TMT Sierpinski Circuit (Sacred Geometry):
Qubits: {result["qubits"]}
Circuit Type: {result["circuit"]}
Measurement Counts:
{json.dumps(result["counts"], indent=2)}
Circuit Metadata:
Depth: {result["depth"]}
Shots: {result["shots"]}
Most Common: {result["most_common"]}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
def run_benchmark():
"""Run benchmark dashboard."""
try:
from quantumpytho.validation import (
ValidationRunConfig,
build_noisy_simulation_executor,
reference_benchmarks,
run_benchmark_suite,
)
benchmarks = reference_benchmarks()
config = ValidationRunConfig(backend_name="simulator", shots=1024)
executor = build_noisy_simulation_executor(
noise_profile=None,
default_shots=1024,
)
results = run_benchmark_suite(benchmarks, executor, executor, config)
mean_match_score = sum(record.mean_metric for record in results) / len(results)
output = f"""QPyth Benchmark Results:
{json.dumps([record.to_dict() for record in results], indent=2)}
Summary:
- Total Tests: {len(results)}
- Mean Match Score: {mean_match_score:.4f}
- Backend: {config.backend_name}
"""
return output
except Exception as e:
return f"Error: {str(e)}"
# Create Gradio interface
def create_interface():
with gr.Blocks(
title="QPyth - Quantum Computing",
theme=gr.themes.Soft(),
) as app_interface:
gr.Markdown("""
# ⚛️ QPyth - Quantum Computing Environment
A professionally engineered quantum computing library built on Qiskit.
Featuring VQE, IBM Quantum integration, QEC, noisy simulation,
and more.
""")
with gr.Tab("Bloch Sphere"):
gr.Markdown("Visualize quantum states on the Bloch sphere")
with gr.Row():
theta = gr.Slider(0, 180, value=45, label="Theta (degrees)")
phi = gr.Slider(0, 360, value=45, label="Phi (degrees)")
bloch_output = gr.Textbox(
label="Bloch Sphere Visualization",
lines=20,
)
bloch_btn = gr.Button("Generate")
bloch_btn.click(
bloch_sphere_demo,
inputs=[theta, phi],
outputs=bloch_output,
)
with gr.Tab("Bell Pair"):
gr.Markdown("Create an entangled Bell pair")
bell_output = gr.Textbox(label="Bell Pair Results", lines=15)
bell_btn = gr.Button("Create Bell Pair")
bell_btn.click(create_bell_pair, outputs=bell_output)
with gr.Tab("Quantum Teleportation"):
gr.Markdown("Run the quantum teleportation protocol")
teleport_output = gr.Textbox(
label="Teleportation Results",
lines=15,
)
teleport_btn = gr.Button("Run Teleportation")
teleport_btn.click(run_quantum_teleport, outputs=teleport_output)
with gr.Tab("Quantum Error Correction"):
gr.Markdown("Demonstrate quantum error correction codes")
code_type = gr.Radio(
["Shor", "Steane"],
label="Code Type",
value="Shor",
)
qec_output = gr.Textbox(label="Result", lines=15)
qec_btn = gr.Button("Run QEC Demo")
qec_btn.click(run_qec_demo, inputs=code_type, outputs=qec_output)
with gr.Tab("Quantum RNG"):
gr.Markdown("Generate quantum random numbers")
with gr.Row():
count = gr.Slider(
1,
100,
value=10,
step=1,
label="Number of values",
)
phi_scale = gr.Checkbox(label="Use phi-scaling")
qrng_output = gr.Textbox(label="Random Numbers", lines=15)
qrng_btn = gr.Button("Generate")
qrng_btn.click(
generate_qrng, inputs=[count, phi_scale], outputs=qrng_output
)
gr.Markdown("""
---
**QPyth v0.4.0** | Built with Qiskit | Apache 2.0 License
For CLI access and advanced features, install with: `pip install QPyth`
""")
return app_interface
# Launch the app
if __name__ == "__main__":
launched_interface = create_interface()
launched_interface.launch()