Skip to content

Commit 91c916f

Browse files
Fix app UI integration and cleanup
1 parent 5332c97 commit 91c916f

File tree

1 file changed

+95
-63
lines changed

1 file changed

+95
-63
lines changed

app.py

Lines changed: 95 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
Gradio interface for QPyth - Quantum-inspired Python experimentation.
3-
This provides a comprehensive web UI for the QPyth quantum computing library on Hugging Face Spaces.
3+
This provides a comprehensive web UI for the QPyth quantum computing
4+
library on Hugging Face Spaces.
45
"""
56

67
import json
@@ -42,7 +43,8 @@ def run_quantum_teleport():
4243
circuit = build_teleport_circuit()
4344
result = engine.run(circuit)
4445
return (
45-
f"Teleportation circuit executed successfully!\n\nCounts: {result.counts}"
46+
"Teleportation circuit executed successfully!\n\n"
47+
f"Counts: {result.counts}"
4648
)
4749
except Exception as e:
4850
return f"Error: {str(e)}"
@@ -61,7 +63,6 @@ def run_qec_demo(code_type="Shor"):
6163
return run_steane_qec_demo()
6264
else: # Surface
6365
from quantumpytho.modules.qec_surface import run_surface_code_demo
64-
6566
return run_surface_code_demo()
6667
except Exception as e:
6768
return f"Error: {str(e)}"
@@ -88,26 +89,23 @@ def generate_qrng(count, phi_scale=False):
8889
def run_vqe_h2(bond_length=0.74, shots=1024):
8990
"""Run VQE for H2 molecule."""
9091
try:
91-
from quantumpytho.modules.vqe_core import VQEEngine
92-
from quantumpytho.modules.vqe_h2_exact import compute_exact_energy
93-
94-
# Compute exact energy
95-
exact_energy = compute_exact_energy(bond_length)
92+
from quantumpytho.modules.vqe_core import run_vqe_h2 as run_vqe_h2_core
9693

97-
# Run VQE
98-
vqe_engine = VQEEngine()
99-
result = vqe_engine.run_h2(bond_length=bond_length, shots=shots)
94+
geometry = f"H 0 0 0; H 0 0 {bond_length}"
95+
result = run_vqe_h2_core(geometry=geometry, max_iters=int(shots))
96+
energies = result.energy_history
97+
initial_energy = energies[0][1] if energies else result.ground_energy
98+
error = abs(result.ground_energy - initial_energy) if energies else 0.0
10099

101100
output = f"""VQE Results for H₂ Molecule:
102101
Bond Length: {bond_length} Å
103-
Shots: {shots}
102+
Iterations: {result.iterations}
104103
105-
Exact Energy: {exact_energy:.6f} Hartree
106-
VQE Energy: {result.get("energy", "N/A")} Hartree
107-
Error: {result.get("error", "N/A")} Hartree
104+
Ground Energy: {result.ground_energy:.6f} Hartree
105+
Estimated Improvement: {error:.6f} Hartree
108106
109-
Circuit Depth: {result.get("depth", "N/A")}
110-
Iterations: {result.get("iterations", "N/A")}
107+
Optimizer: {result.metadata.optimizer}
108+
Backend: {result.metadata.backend}
111109
"""
112110
return output
113111
except Exception as e:
@@ -117,39 +115,35 @@ def run_vqe_h2(bond_length=0.74, shots=1024):
117115
def run_noisy_simulation(backend_profile="IBM", noise_level=0.01):
118116
"""Run noisy simulation with backend profiles."""
119117
try:
120-
from quantumpytho.modules.backend_profiles import get_backend_profile
121-
from quantumpytho.modules.noise_builder import NoiseModelBuilder
118+
from quantumpytho.modules.hardware_ibm import NoisySimulatorEngine
119+
from quantumpytho.modules.noise_builder import get_backend_info
122120

123-
# Get backend profile
124-
profile = get_backend_profile(backend_profile)
121+
available_profiles = NoisySimulatorEngine.get_available_profiles()
122+
profile_name = (
123+
backend_profile if backend_profile in available_profiles else None
124+
)
125125

126-
# Create circuit
127126
circuit = QuantumCircuit(2, 2)
128127
circuit.h(0)
129128
circuit.cx(0, 1)
130129
circuit.measure([0, 1], [0, 1])
131130

132-
# Build noise model
133-
noise_builder = NoiseModelBuilder()
134-
noise_model = noise_builder.build_from_profile(profile, noise_level)
135-
136-
# Run with noise
137-
from qiskit_aer import AerSimulator
138-
139-
backend = AerSimulator(noise_model=noise_model)
140-
job = backend.run(circuit, shots=1024)
141-
result = job.result()
142-
counts = result.get_counts()
131+
simulator = NoisySimulatorEngine(
132+
noise_profile=profile_name,
133+
shots=1024,
134+
)
135+
result = simulator.run(circuit)
136+
profile_info = get_backend_info(profile_name) if profile_name else None
143137

144138
output = f"""Noisy Simulation Results:
145-
Backend Profile: {backend_profile}
139+
Backend Profile: {profile_name or 'simulator'}
146140
Noise Level: {noise_level}
147141
148142
Measurement Counts:
149-
{json.dumps(counts, indent=2)}
143+
{json.dumps(result.counts, indent=2)}
150144
151145
Profile Info:
152-
{json.dumps(profile, indent=2)}
146+
{json.dumps(profile_info or {'noise_model': 'none'}, indent=2)}
153147
"""
154148
return output
155149
except Exception as e:
@@ -177,7 +171,7 @@ def explore_dna_circuits(sequence_name="ATCG"):
177171
output = f"""DNA Circuit Exploration:
178172
Sequence: {sequence_name}
179173
180-
Available Sequences: {", ".join(available[:10])}...
174+
Available Sequences: {', '.join(available[:10])}...
181175
182176
Sequence Data:
183177
{json.dumps(sequence_data, indent=2)}
@@ -193,21 +187,23 @@ def explore_dna_circuits(sequence_name="ATCG"):
193187
def run_tmt_sierpinski():
194188
"""Run TMT Sierpinski 21-qubit sacred geometry circuit."""
195189
try:
196-
from quantumpytho.modules.tmt_sierpinski import build_tmt_circuit
190+
from quantumpytho.modules.tmt_sierpinski import (
191+
run_tmt_sierpinski as run_tmt_demo,
192+
)
197193

198-
circuit = build_tmt_circuit()
199-
result = engine.run(circuit)
194+
result = run_tmt_demo(engine)
200195

201196
output = f"""TMT Sierpinski Circuit (Sacred Geometry):
202-
Qubits: 21
203-
Circuit Type: Sierpinski Triangle Pattern
197+
Qubits: {result['qubits']}
198+
Circuit Type: {result['circuit']}
204199
205200
Measurement Counts:
206-
{result.counts}
201+
{json.dumps(result['counts'], indent=2)}
207202
208203
Circuit Metadata:
209-
Depth: {result.circuit.depth()}
210-
Gates: {len(result.circuit.data)}
204+
Depth: {result['depth']}
205+
Shots: {result['shots']}
206+
Most Common: {result['most_common']}
211207
"""
212208
return output
213209
except Exception as e:
@@ -217,18 +213,32 @@ def run_tmt_sierpinski():
217213
def run_benchmark():
218214
"""Run benchmark dashboard."""
219215
try:
220-
from quantumpytho.modules.benchmark_dashboard import run_benchmark_suite
216+
from quantumpytho.validation import (
217+
ValidationRunConfig,
218+
build_noisy_simulation_executor,
219+
reference_benchmarks,
220+
run_benchmark_suite,
221+
)
221222

222-
results = run_benchmark_suite()
223+
benchmarks = reference_benchmarks()
224+
config = ValidationRunConfig(backend_name="simulator", shots=1024)
225+
executor = build_noisy_simulation_executor(
226+
noise_profile=None,
227+
default_shots=1024,
228+
)
229+
results = run_benchmark_suite(benchmarks, executor, executor, config)
230+
mean_match_score = sum(
231+
record.mean_metric for record in results
232+
) / len(results)
223233

224234
output = f"""QPyth Benchmark Results:
225235
226-
{json.dumps(results, indent=2)}
236+
{json.dumps([record.to_dict() for record in results], indent=2)}
227237
228238
Summary:
229239
- Total Tests: {len(results)}
230-
- Passed: {sum(1 for r in results.values() if r.get("status") == "pass")}
231-
- Failed: {sum(1 for r in results.values() if r.get("status") == "fail")}
240+
- Mean Match Score: {mean_match_score:.4f}
241+
- Backend: {config.backend_name}
232242
"""
233243
return output
234244
except Exception as e:
@@ -237,23 +247,32 @@ def run_benchmark():
237247

238248
# Create Gradio interface
239249
def create_interface():
240-
with gr.Blocks(title="QPyth - Quantum Computing", theme=gr.themes.Soft()) as demo:
250+
with gr.Blocks(
251+
title="QPyth - Quantum Computing",
252+
theme=gr.themes.Soft(),
253+
) as app_interface:
241254
gr.Markdown("""
242255
# ⚛️ QPyth - Quantum Computing Environment
243-
256+
244257
A professionally engineered quantum computing library built on Qiskit.
245-
Featuring VQE, IBM Quantum integration, QEC, noisy simulation, and more.
258+
Featuring VQE, IBM Quantum integration, QEC, noisy simulation,
259+
and more.
246260
""")
247261

248262
with gr.Tab("Bloch Sphere"):
249263
gr.Markdown("Visualize quantum states on the Bloch sphere")
250264
with gr.Row():
251265
theta = gr.Slider(0, 180, value=45, label="Theta (degrees)")
252266
phi = gr.Slider(0, 360, value=45, label="Phi (degrees)")
253-
bloch_output = gr.Textbox(label="Bloch Sphere Visualization", lines=20)
267+
bloch_output = gr.Textbox(
268+
label="Bloch Sphere Visualization",
269+
lines=20,
270+
)
254271
bloch_btn = gr.Button("Generate")
255272
bloch_btn.click(
256-
bloch_sphere_demo, inputs=[theta, phi], outputs=bloch_output
273+
bloch_sphere_demo,
274+
inputs=[theta, phi],
275+
outputs=bloch_output,
257276
)
258277

259278
with gr.Tab("Bell Pair"):
@@ -264,21 +283,34 @@ def create_interface():
264283

265284
with gr.Tab("Quantum Teleportation"):
266285
gr.Markdown("Run the quantum teleportation protocol")
267-
teleport_output = gr.Textbox(label="Teleportation Results", lines=15)
286+
teleport_output = gr.Textbox(
287+
label="Teleportation Results",
288+
lines=15,
289+
)
268290
teleport_btn = gr.Button("Run Teleportation")
269291
teleport_btn.click(run_quantum_teleport, outputs=teleport_output)
270292

271293
with gr.Tab("Quantum Error Correction"):
272294
gr.Markdown("Demonstrate quantum error correction codes")
273-
code_type = gr.Radio(["Shor", "Steane"], label="Code Type", value="Shor")
295+
code_type = gr.Radio(
296+
["Shor", "Steane"],
297+
label="Code Type",
298+
value="Shor",
299+
)
274300
qec_output = gr.Textbox(label="Result", lines=15)
275301
qec_btn = gr.Button("Run QEC Demo")
276302
qec_btn.click(run_qec_demo, inputs=code_type, outputs=qec_output)
277303

278304
with gr.Tab("Quantum RNG"):
279305
gr.Markdown("Generate quantum random numbers")
280306
with gr.Row():
281-
count = gr.Slider(1, 100, value=10, step=1, label="Number of values")
307+
count = gr.Slider(
308+
1,
309+
100,
310+
value=10,
311+
step=1,
312+
label="Number of values",
313+
)
282314
phi_scale = gr.Checkbox(label="Use phi-scaling")
283315
qrng_output = gr.Textbox(label="Random Numbers", lines=15)
284316
qrng_btn = gr.Button("Generate")
@@ -288,16 +320,16 @@ def create_interface():
288320

289321
gr.Markdown("""
290322
---
291-
323+
292324
**QPyth v0.4.0** | Built with Qiskit | Apache 2.0 License
293-
325+
294326
For CLI access and advanced features, install with: `pip install QPyth`
295327
""")
296328

297-
return demo
329+
return app_interface
298330

299331

300332
# Launch the app
301333
if __name__ == "__main__":
302-
demo = create_interface()
303-
demo.launch()
334+
launched_interface = create_interface()
335+
launched_interface.launch()

0 commit comments

Comments
 (0)