Dvirmor100 commited on
Commit
a5fcd60
Β·
1 Parent(s): 8f5c845

feat(demo): Created basic demo template for demo the project

Browse files
src/{__init__.py β†’ app/__init__.py} RENAMED
File without changes
src/app/gradio_demo.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import gradio as gr
2
+ # import pennylane as qml
3
+ # from quantum_circuits import CircuitManager, circuits
4
+ # from quantum_circuits.circuits_helpers import visualize_circuit, build_quantum_circuit
5
+ # from quantum_circuits.noisy_circuit import NoisyCircuit
6
+
7
+
8
+ # def run_selected_circuit(circuit_index, randomize=False):
9
+ # """
10
+ # Run and visualize a selected circuit from the module.
11
+ #
12
+ # Args:
13
+ # circuit_index (int): Index of the circuit to run.
14
+ #
15
+ # Returns:
16
+ # tuple: Circuit information and visualization image.
17
+ # """
18
+ # try:
19
+ # circuit_func, params, circuit_name, wires = circuits[circuit_index]
20
+ # noise_types = [
21
+ # (qml.BitFlip, {"prob": 0.05}),
22
+ # (qml.PhaseFlip, {"prob": 0.05}),
23
+ # (qml.DepolarizingChannel, {"prob": 0.05}),
24
+ # ]
25
+ # # Build the quantum circuit
26
+ # constructed_circuit, noisy_qnode = build_quantum_circuit((circuit_func, params, circuit_name, wires),
27
+ # noise_types)
28
+ #
29
+ # noisy_path = None
30
+ # if randomize:
31
+ # visualize_circuit(noisy_qnode, *params, title=circuit_name,
32
+ # save_path="noise.png")
33
+ # noisy_path = "noise.png"
34
+ #
35
+ # # Visualize the circuit
36
+ # visualize_circuit(constructed_circuit, *params, title=circuit_name,
37
+ # save_path="output.png")
38
+ # return "success", "output.png", noisy_path
39
+ #
40
+ # except IndexError:
41
+ # return "Invalid circuit selection", None, None
42
+ #
43
+ #
44
+ # # Gradio app interface
45
+ # def run_app():
46
+ # iface = gr.Interface(
47
+ # fn=lambda circuit_choice, randomize: run_selected_circuit(
48
+ # int(circuit_choice) - 1, randomize),
49
+ # inputs=[
50
+ # gr.Radio(
51
+ # choices=[str(i + 1) for i in range(len(circuits))],
52
+ # label="Choose Circuit Type"
53
+ # ),
54
+ # gr.Checkbox(label="Randomize Circuit", visible=True)
55
+ # ],
56
+ # outputs=[
57
+ # gr.Textbox(label="Circuit Info"),
58
+ # gr.Image(type="filepath", label="Circuit Image"),
59
+ # gr.Image(type="filepath", label="Noisy Circuit Image")
60
+ # ],
61
+ # title="Quantum Circuit Visualizer",
62
+ # description="Visualize circuits from the module or generate a randomized quantum circuit.",
63
+ # )
64
+ #
65
+ # # Launch interface
66
+ # iface.launch()
67
+
68
+ ############################
69
+ import gradio as gr
70
+ import logging
71
+
72
+ # from circuits.circuit_optimizer import optimize_circuit_with_llm
73
+ # from circuits.noisy_circuit_runner import simulate_noisy_circuit
74
+ from utils.qasm_utils import remove_measurements
75
+ # from utils.visualization import plot_circuit
76
+ from utils.metrics import euclidean_distance
77
+ # from database.db_handler import fetch_latest_circuits
78
+
79
+ # Setup logging
80
+ logging.basicConfig(level=logging.INFO)
81
+ logger = logging.getLogger(__name__)
82
+
83
+ def process_qasm(qasm_code):
84
+ """Handles QASM input, optimizes with LLM, and returns results."""
85
+ if not qasm_code.strip():
86
+ return "⚠️ Error: No QASM code provided.", None, None, None, None
87
+
88
+ try:
89
+ # Clean input QASM
90
+ cleaned_qasm = remove_measurements(qasm_code)
91
+
92
+ # Generate optimized QASM using LLM
93
+ logger.info("Optimizing QASM with LLM...")
94
+ optimized_qasm = optimize_circuit_with_llm(cleaned_qasm)
95
+
96
+ # Simulate both circuits
97
+ logger.info("Simulating original noisy circuit...")
98
+ original_results = simulate_noisy_circuit(cleaned_qasm)
99
+
100
+ logger.info("Simulating optimized circuit...")
101
+ optimized_results = simulate_noisy_circuit(optimized_qasm)
102
+
103
+ # Compute distance metric
104
+ circuit_distance = euclidean_distance(original_results, optimized_results)
105
+
106
+ # Generate visualizations
107
+ original_plot = plot_circuit(cleaned_qasm)
108
+ optimized_plot = plot_circuit(optimized_qasm)
109
+
110
+ return optimized_qasm, original_plot, optimized_plot, f"{circuit_distance:.4f}"
111
+
112
+ except Exception as e:
113
+ logger.error(f"Error processing QASM: {e}")
114
+ return f"❌ Error: {str(e)}", None, None, None
115
+
116
+ def fetch_recent_circuits():
117
+ """Fetches recent circuits from DuckDB and returns as dropdown options."""
118
+ # circuits = fetch_latest_circuits(limit=5)
119
+ circuits = []
120
+ return [(c["id"], c["qasm"]) for c in circuits]
121
+
122
+ def main():
123
+ """Launches the Gradio demo interface with a full-screen, beautiful design."""
124
+
125
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
126
+ gr.Markdown(
127
+ "<h1 style='text-align: center;'>✨ Quantum Circuit Error Mitigation</h1>"
128
+ "<h3 style='text-align: center; color: gray;'>Optimize noisy circuits using AI-powered correction πŸš€</h3>"
129
+ )
130
+ with gr.Row():
131
+ gr.HTML('<button class="fixed-button" onclick="myJsFunction()">Click Me</button>')
132
+
133
+ with gr.Row():
134
+ gr.Markdown("### 🎭 Original Circuit")
135
+
136
+ # INPUT AREA
137
+ with gr.Row():
138
+ with gr.Column(scale=1, min_width=500):
139
+ qasm_input = gr.Textbox(
140
+ lines=10,
141
+ label="πŸ“œ Input QASM Code",
142
+ placeholder="Paste your QASM code here...",
143
+ elem_classes="full-width-textbox"
144
+ )
145
+ circuit_selector = gr.Dropdown(
146
+ label="πŸ” Load Circuit From Duck DB",
147
+ choices=fetch_recent_circuits(),
148
+ interactive=True
149
+ )
150
+
151
+ with gr.Column(scale=1, min_width=600):
152
+ original_plot = gr.Image(label="Original Circuit Visualization")
153
+
154
+ with gr.Row():
155
+ submit_button = gr.Button("⚑ Optimize Circuit", size="lg")
156
+
157
+ # VISUALIZATION AREA
158
+ with gr.Row():
159
+ gr.Markdown("### πŸš€ Optimized Circuit")
160
+ with gr.Row():
161
+ with gr.Column(scale=1, min_width=600):
162
+ optimized_qasm_output = gr.Textbox(
163
+ lines=10,
164
+ label="✨ Optimized QASM Code",
165
+ interactive=False,
166
+ elem_classes="full-width-textbox"
167
+ )
168
+
169
+
170
+ with gr.Column(scale=1, min_width=600):
171
+ optimized_plot = gr.Image(label="Optimized Circuit Visualization")
172
+
173
+ with gr.Row():
174
+ circuit_distance = gr.Textbox(
175
+ label="πŸ“ Circuit Distance (Euclidean)",
176
+ interactive=False,
177
+ elem_classes="full-width-textbox"
178
+ )
179
+
180
+ # Button Actions
181
+ submit_button.click(
182
+ process_qasm,
183
+ inputs=[qasm_input],
184
+ outputs=[optimized_qasm_output, original_plot, optimized_plot, circuit_distance]
185
+ )
186
+
187
+ circuit_selector.change(
188
+ lambda cid: next(q for i, q in fetch_recent_circuits() if i == cid),
189
+ inputs=[circuit_selector],
190
+ outputs=[qasm_input]
191
+ )
192
+
193
+ demo.launch(share=False)
194
+
195
+ launch_demo = main
196
+
197
+ if __name__ == "__main__":
198
+ main()
src/main.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ from scripts.generate_random_circuits import main as generate_circuits
4
+ from scripts.run_error_mitigation import main as run_error_mitigation
5
+ from app.gradio_demo import launch_demo
6
+
7
+ # Setup logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def main():
13
+ """Main CLI interface for running different parts of the quantum pipeline."""
14
+
15
+ parser = argparse.ArgumentParser(description="Quantum Circuit Error Mitigation Pipeline")
16
+
17
+ parser.add_argument("--generate", "-g", type=int,
18
+ help="Generate random quantum circuits (provide number of circuits)")
19
+
20
+ parser.add_argument("--mitigate", "-m", action="store_true",
21
+ help="Run LLM-based error mitigation on stored circuits")
22
+
23
+ parser.add_argument("--visualize", "-v", action="store_true",
24
+ help="Launch the Gradio visualization demo")
25
+
26
+ args = parser.parse_args()
27
+
28
+ if args.generate:
29
+ logger.info(f"Generating {args.generate} random quantum circuits...")
30
+ generate_circuits(num_circuits=args.generate)
31
+
32
+ if args.mitigate:
33
+ logger.info("Running LLM-based error mitigation on circuits...")
34
+ run_error_mitigation()
35
+
36
+ if args.visualize:
37
+ logger.info("Launching Gradio visualization app...")
38
+ launch_demo()
39
+
40
+ if not any(vars(args).values()):
41
+ parser.print_help()
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()