Spaces:
Runtime error
Runtime error
Commit ·
e0d7f28
1
Parent(s): b925346
style: using black and ruff to format the project
Browse files- src/app/gradio_demo.py +38 -89
- src/database/db_handler.py +37 -25
- src/main.py +24 -10
- src/models/llm_interface.py +35 -12
- src/models/llm_prompt_utils.py +44 -51
- src/quantum_circuits/circuit_error_mitigator.py +22 -14
- src/quantum_circuits/circuit_manager.py +34 -19
- src/quantum_circuits/noisy_circuit_generator.py +58 -26
- src/quantum_circuits/noisy_qasm_runner.py +13 -6
- src/scripts/error_mitigation_eval.py +73 -20
- src/scripts/generate_random_circuits.py +55 -14
- src/scripts/run_error_mitigation.py +19 -7
- src/tests/test_circuits.py +48 -19
- src/tests/test_db_handler.py +4 -2
- src/tests/test_noisy_qasm_runner.py +2 -5
- src/utils/metrics.py +2 -1
- src/utils/qasm_utils.py +51 -4
- src/utils/visualization.py +11 -3
src/app/gradio_demo.py
CHANGED
|
@@ -1,86 +1,18 @@
|
|
| 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 |
-
|
| 73 |
-
|
| 74 |
from utils.qasm_utils import remove_measurements
|
| 75 |
-
|
| 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 |
-
|
|
|
|
| 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
|
|
@@ -93,12 +25,12 @@ def process_qasm(qasm_code):
|
|
| 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)
|
|
@@ -113,12 +45,13 @@ def process_qasm(qasm_code):
|
|
| 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 |
|
|
@@ -127,8 +60,6 @@ def main():
|
|
| 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")
|
|
@@ -140,12 +71,25 @@ def main():
|
|
| 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):
|
|
@@ -163,10 +107,9 @@ def main():
|
|
| 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 |
|
|
@@ -174,24 +117,30 @@ def main():
|
|
| 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=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import logging
|
| 3 |
|
| 4 |
+
from circuits.circuit_optimizer import optimize_circuit_with_llm
|
| 5 |
+
from circuits.noisy_circuit_runner import simulate_noisy_circuit
|
| 6 |
from utils.qasm_utils import remove_measurements
|
| 7 |
+
from utils.visualization import plot_circuit
|
| 8 |
from utils.metrics import euclidean_distance
|
|
|
|
| 9 |
|
| 10 |
# Setup logging
|
| 11 |
logging.basicConfig(level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
|
| 15 |
+
def process_qasm(qasm_code, noise_model):
|
| 16 |
"""Handles QASM input, optimizes with LLM, and returns results."""
|
| 17 |
if not qasm_code.strip():
|
| 18 |
return "⚠️ Error: No QASM code provided.", None, None, None, None
|
|
|
|
| 25 |
logger.info("Optimizing QASM with LLM...")
|
| 26 |
optimized_qasm = optimize_circuit_with_llm(cleaned_qasm)
|
| 27 |
|
| 28 |
+
# Simulate both circuits with selected noise model
|
| 29 |
+
logger.info(f"Simulating original noisy circuit with {noise_model}...")
|
| 30 |
+
original_results = simulate_noisy_circuit(cleaned_qasm, noise_model)
|
| 31 |
|
| 32 |
+
logger.info(f"Simulating optimized circuit with {noise_model}...")
|
| 33 |
+
optimized_results = simulate_noisy_circuit(optimized_qasm, noise_model)
|
| 34 |
|
| 35 |
# Compute distance metric
|
| 36 |
circuit_distance = euclidean_distance(original_results, optimized_results)
|
|
|
|
| 45 |
logger.error(f"Error processing QASM: {e}")
|
| 46 |
return f"❌ Error: {str(e)}", None, None, None
|
| 47 |
|
| 48 |
+
|
| 49 |
def fetch_recent_circuits():
|
| 50 |
"""Fetches recent circuits from DuckDB and returns as dropdown options."""
|
|
|
|
| 51 |
circuits = []
|
| 52 |
return [(c["id"], c["qasm"]) for c in circuits]
|
| 53 |
|
| 54 |
+
|
| 55 |
def main():
|
| 56 |
"""Launches the Gradio demo interface with a full-screen, beautiful design."""
|
| 57 |
|
|
|
|
| 60 |
"<h1 style='text-align: center;'>✨ Quantum Circuit Error Mitigation</h1>"
|
| 61 |
"<h3 style='text-align: center; color: gray;'>Optimize noisy circuits using AI-powered correction 🚀</h3>"
|
| 62 |
)
|
|
|
|
|
|
|
| 63 |
|
| 64 |
with gr.Row():
|
| 65 |
gr.Markdown("### 🎭 Original Circuit")
|
|
|
|
| 71 |
lines=10,
|
| 72 |
label="📜 Input QASM Code",
|
| 73 |
placeholder="Paste your QASM code here...",
|
| 74 |
+
elem_classes="full-width-textbox",
|
| 75 |
)
|
| 76 |
circuit_selector = gr.Dropdown(
|
| 77 |
label="🔍 Load Circuit From Duck DB",
|
| 78 |
choices=fetch_recent_circuits(),
|
| 79 |
+
interactive=True,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
noise_model_selector = gr.Dropdown(
|
| 83 |
+
label="🎲 Select Noise Model",
|
| 84 |
+
choices=[
|
| 85 |
+
"Depolarizing",
|
| 86 |
+
"Bit-Flip",
|
| 87 |
+
"Phase-Flip",
|
| 88 |
+
"Amplitude-Damping",
|
| 89 |
+
"Custom",
|
| 90 |
+
],
|
| 91 |
+
value="Depolarizing",
|
| 92 |
+
interactive=True,
|
| 93 |
)
|
| 94 |
|
| 95 |
with gr.Column(scale=1, min_width=600):
|
|
|
|
| 107 |
lines=10,
|
| 108 |
label="✨ Optimized QASM Code",
|
| 109 |
interactive=False,
|
| 110 |
+
elem_classes="full-width-textbox",
|
| 111 |
)
|
| 112 |
|
|
|
|
| 113 |
with gr.Column(scale=1, min_width=600):
|
| 114 |
optimized_plot = gr.Image(label="Optimized Circuit Visualization")
|
| 115 |
|
|
|
|
| 117 |
circuit_distance = gr.Textbox(
|
| 118 |
label="📏 Circuit Distance (Euclidean)",
|
| 119 |
interactive=False,
|
| 120 |
+
elem_classes="full-width-textbox",
|
| 121 |
)
|
| 122 |
|
| 123 |
# Button Actions
|
| 124 |
submit_button.click(
|
| 125 |
process_qasm,
|
| 126 |
+
inputs=[qasm_input, noise_model_selector],
|
| 127 |
+
outputs=[
|
| 128 |
+
optimized_qasm_output,
|
| 129 |
+
original_plot,
|
| 130 |
+
optimized_plot,
|
| 131 |
+
circuit_distance,
|
| 132 |
+
],
|
| 133 |
)
|
| 134 |
|
| 135 |
circuit_selector.change(
|
| 136 |
lambda cid: next(q for i, q in fetch_recent_circuits() if i == cid),
|
| 137 |
inputs=[circuit_selector],
|
| 138 |
+
outputs=[qasm_input],
|
| 139 |
)
|
| 140 |
|
| 141 |
demo.launch(share=False)
|
| 142 |
|
| 143 |
+
|
| 144 |
launch_demo = main
|
| 145 |
|
| 146 |
if __name__ == "__main__":
|
src/database/db_handler.py
CHANGED
|
@@ -12,6 +12,7 @@ class CircuitData(BaseModel):
|
|
| 12 |
noisy_result: list
|
| 13 |
noiseless_result: list
|
| 14 |
|
|
|
|
| 15 |
class DuckDBDAO:
|
| 16 |
"""
|
| 17 |
A DAO (Data Access Object) for storing and retrieving quantum circuit data in DuckDB.
|
|
@@ -22,7 +23,7 @@ class DuckDBDAO:
|
|
| 22 |
circuits -> (circuit_id, qasm, noise_data, noiseless_result, noisy_result, noise_qasm)
|
| 23 |
"""
|
| 24 |
|
| 25 |
-
def __init__(self, db_path=
|
| 26 |
self.db_path = db_path
|
| 27 |
self.conn = duckdb.connect(self.db_path)
|
| 28 |
self._create_sequences()
|
|
@@ -34,7 +35,8 @@ class DuckDBDAO:
|
|
| 34 |
|
| 35 |
def _create_tables(self):
|
| 36 |
"""Create the circuits table for storing circuit data."""
|
| 37 |
-
self.conn.execute(
|
|
|
|
| 38 |
CREATE TABLE IF NOT EXISTS circuits (
|
| 39 |
circuit_id INTEGER PRIMARY KEY DEFAULT nextval('circuits_seq'),
|
| 40 |
qasm TEXT NOT NULL,
|
|
@@ -43,11 +45,17 @@ class DuckDBDAO:
|
|
| 43 |
noisy_result JSON,
|
| 44 |
noise_qasm TEXT
|
| 45 |
);
|
| 46 |
-
"""
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
"""
|
| 52 |
Insert a circuit row that contains the QASM, noiseless result, noise data, noisy result,
|
| 53 |
and (optionally) the noise_qasm string.
|
|
@@ -62,7 +70,9 @@ class DuckDBDAO:
|
|
| 62 |
Returns:
|
| 63 |
int: The auto-generated circuit_id.
|
| 64 |
"""
|
| 65 |
-
noiseless_json =
|
|
|
|
|
|
|
| 66 |
noise_data_json = json.dumps(noise_data) if noise_data is not None else None
|
| 67 |
noisy_json = json.dumps(noisy_result) if noisy_result is not None else None
|
| 68 |
|
|
@@ -71,7 +81,9 @@ class DuckDBDAO:
|
|
| 71 |
VALUES (?, ?, ?, ?, ?)
|
| 72 |
RETURNING circuit_id;
|
| 73 |
"""
|
| 74 |
-
row = self.conn.execute(
|
|
|
|
|
|
|
| 75 |
return row[0]
|
| 76 |
|
| 77 |
def get_by_qasm(self, qasm: str):
|
|
@@ -88,12 +100,12 @@ class DuckDBDAO:
|
|
| 88 |
rows = self.conn.execute(query, [qasm]).fetchall()
|
| 89 |
return [
|
| 90 |
{
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
}
|
| 98 |
for row in rows
|
| 99 |
]
|
|
@@ -112,17 +124,16 @@ class DuckDBDAO:
|
|
| 112 |
row = self.conn.execute(query, [circuit_id]).fetchone()
|
| 113 |
if row:
|
| 114 |
return {
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
}
|
| 122 |
return None
|
| 123 |
|
| 124 |
|
| 125 |
-
|
| 126 |
def extract_circuit_data(df: pd.DataFrame, i: int) -> CircuitData:
|
| 127 |
"""
|
| 128 |
Extracts and processes circuit data from a DataFrame.
|
|
@@ -138,12 +149,13 @@ def extract_circuit_data(df: pd.DataFrame, i: int) -> CircuitData:
|
|
| 138 |
qasm_circuit = remove_measurements(df.qasm[i])
|
| 139 |
noise_data = json.loads(json.loads(df.noise_data[i]))
|
| 140 |
noisy_result = json.loads(json.loads(df.noisy_result[i]))["expectation_values"]
|
| 141 |
-
noiseless_result = json.loads(json.loads(df.noiseless_result[i]))[
|
|
|
|
|
|
|
| 142 |
|
| 143 |
return CircuitData(
|
| 144 |
qasm_circuit=qasm_circuit,
|
| 145 |
noise_data=noise_data,
|
| 146 |
noisy_result=noisy_result,
|
| 147 |
-
noiseless_result=noiseless_result
|
| 148 |
)
|
| 149 |
-
|
|
|
|
| 12 |
noisy_result: list
|
| 13 |
noiseless_result: list
|
| 14 |
|
| 15 |
+
|
| 16 |
class DuckDBDAO:
|
| 17 |
"""
|
| 18 |
A DAO (Data Access Object) for storing and retrieving quantum circuit data in DuckDB.
|
|
|
|
| 23 |
circuits -> (circuit_id, qasm, noise_data, noiseless_result, noisy_result, noise_qasm)
|
| 24 |
"""
|
| 25 |
|
| 26 |
+
def __init__(self, db_path=":memory:"):
|
| 27 |
self.db_path = db_path
|
| 28 |
self.conn = duckdb.connect(self.db_path)
|
| 29 |
self._create_sequences()
|
|
|
|
| 35 |
|
| 36 |
def _create_tables(self):
|
| 37 |
"""Create the circuits table for storing circuit data."""
|
| 38 |
+
self.conn.execute(
|
| 39 |
+
"""
|
| 40 |
CREATE TABLE IF NOT EXISTS circuits (
|
| 41 |
circuit_id INTEGER PRIMARY KEY DEFAULT nextval('circuits_seq'),
|
| 42 |
qasm TEXT NOT NULL,
|
|
|
|
| 45 |
noisy_result JSON,
|
| 46 |
noise_qasm TEXT
|
| 47 |
);
|
| 48 |
+
"""
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def insert_circuit_result(
|
| 52 |
+
self,
|
| 53 |
+
qasm: str,
|
| 54 |
+
noiseless_result: dict = None,
|
| 55 |
+
noise_data: dict = None,
|
| 56 |
+
noisy_result: dict = None,
|
| 57 |
+
noise_qasm: str = None,
|
| 58 |
+
):
|
| 59 |
"""
|
| 60 |
Insert a circuit row that contains the QASM, noiseless result, noise data, noisy result,
|
| 61 |
and (optionally) the noise_qasm string.
|
|
|
|
| 70 |
Returns:
|
| 71 |
int: The auto-generated circuit_id.
|
| 72 |
"""
|
| 73 |
+
noiseless_json = (
|
| 74 |
+
json.dumps(noiseless_result) if noiseless_result is not None else None
|
| 75 |
+
)
|
| 76 |
noise_data_json = json.dumps(noise_data) if noise_data is not None else None
|
| 77 |
noisy_json = json.dumps(noisy_result) if noisy_result is not None else None
|
| 78 |
|
|
|
|
| 81 |
VALUES (?, ?, ?, ?, ?)
|
| 82 |
RETURNING circuit_id;
|
| 83 |
"""
|
| 84 |
+
row = self.conn.execute(
|
| 85 |
+
query, [qasm, noise_data_json, noiseless_json, noisy_json, noise_qasm]
|
| 86 |
+
).fetchone()
|
| 87 |
return row[0]
|
| 88 |
|
| 89 |
def get_by_qasm(self, qasm: str):
|
|
|
|
| 100 |
rows = self.conn.execute(query, [qasm]).fetchall()
|
| 101 |
return [
|
| 102 |
{
|
| 103 |
+
"circuit_id": row[0],
|
| 104 |
+
"qasm": row[1],
|
| 105 |
+
"noise_data": json.loads(row[2]) if row[2] else None,
|
| 106 |
+
"noiseless_result": json.loads(row[3]) if row[3] else None,
|
| 107 |
+
"noisy_result": json.loads(row[4]) if row[4] else None,
|
| 108 |
+
"noise_qasm": row[5],
|
| 109 |
}
|
| 110 |
for row in rows
|
| 111 |
]
|
|
|
|
| 124 |
row = self.conn.execute(query, [circuit_id]).fetchone()
|
| 125 |
if row:
|
| 126 |
return {
|
| 127 |
+
"circuit_id": row[0],
|
| 128 |
+
"qasm": row[1],
|
| 129 |
+
"noise_data": json.loads(row[2]) if row[2] else None,
|
| 130 |
+
"noiseless_result": json.loads(row[3]) if row[3] else None,
|
| 131 |
+
"noisy_result": json.loads(row[4]) if row[4] else None,
|
| 132 |
+
"noise_qasm": row[5],
|
| 133 |
}
|
| 134 |
return None
|
| 135 |
|
| 136 |
|
|
|
|
| 137 |
def extract_circuit_data(df: pd.DataFrame, i: int) -> CircuitData:
|
| 138 |
"""
|
| 139 |
Extracts and processes circuit data from a DataFrame.
|
|
|
|
| 149 |
qasm_circuit = remove_measurements(df.qasm[i])
|
| 150 |
noise_data = json.loads(json.loads(df.noise_data[i]))
|
| 151 |
noisy_result = json.loads(json.loads(df.noisy_result[i]))["expectation_values"]
|
| 152 |
+
noiseless_result = json.loads(json.loads(df.noiseless_result[i]))[
|
| 153 |
+
"expectation_values"
|
| 154 |
+
]
|
| 155 |
|
| 156 |
return CircuitData(
|
| 157 |
qasm_circuit=qasm_circuit,
|
| 158 |
noise_data=noise_data,
|
| 159 |
noisy_result=noisy_result,
|
| 160 |
+
noiseless_result=noiseless_result,
|
| 161 |
)
|
|
|
src/main.py
CHANGED
|
@@ -12,16 +12,30 @@ logger = logging.getLogger(__name__)
|
|
| 12 |
def main():
|
| 13 |
"""Main CLI interface for running different parts of the quantum pipeline."""
|
| 14 |
|
| 15 |
-
parser = argparse.ArgumentParser(
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
args = parser.parse_args()
|
| 27 |
|
|
|
|
| 12 |
def main():
|
| 13 |
"""Main CLI interface for running different parts of the quantum pipeline."""
|
| 14 |
|
| 15 |
+
parser = argparse.ArgumentParser(
|
| 16 |
+
description="Quantum Circuit Error Mitigation Pipeline"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
parser.add_argument(
|
| 20 |
+
"--generate",
|
| 21 |
+
"-g",
|
| 22 |
+
type=int,
|
| 23 |
+
help="Generate random quantum circuits (provide number of circuits)",
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
parser.add_argument(
|
| 27 |
+
"--mitigate",
|
| 28 |
+
"-m",
|
| 29 |
+
action="store_true",
|
| 30 |
+
help="Run LLM-based error mitigation on stored circuits",
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
parser.add_argument(
|
| 34 |
+
"--visualize",
|
| 35 |
+
"-v",
|
| 36 |
+
action="store_true",
|
| 37 |
+
help="Launch the Gradio visualization demo",
|
| 38 |
+
)
|
| 39 |
|
| 40 |
args = parser.parse_args()
|
| 41 |
|
src/models/llm_interface.py
CHANGED
|
@@ -1,26 +1,46 @@
|
|
| 1 |
from openai import OpenAI
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
client = OpenAI(
|
| 8 |
-
base_url=
|
| 9 |
-
api_key=
|
| 10 |
)
|
| 11 |
|
| 12 |
response = client.chat.completions.create(
|
| 13 |
messages=[
|
| 14 |
{"role": "system", "content": "You are a quantum computing expert."},
|
| 15 |
{
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
}
|
| 19 |
],
|
| 20 |
temperature=temperature,
|
| 21 |
top_p=top_p,
|
| 22 |
model=model_name,
|
| 23 |
-
stream=True
|
| 24 |
)
|
| 25 |
|
| 26 |
final_answer = ""
|
|
@@ -30,6 +50,9 @@ def chat_completion(user_prompt: str,
|
|
| 30 |
|
| 31 |
return final_answer
|
| 32 |
|
| 33 |
-
|
|
|
|
| 34 |
print(chat_completion(user_prompt="Who are you in a sentence", model_name="phi4"))
|
| 35 |
-
print(
|
|
|
|
|
|
|
|
|
| 1 |
from openai import OpenAI
|
| 2 |
|
| 3 |
+
|
| 4 |
+
def chat_completion(
|
| 5 |
+
user_prompt: str,
|
| 6 |
+
model_name: str = "phi4",
|
| 7 |
+
temperature: float = 0.01,
|
| 8 |
+
top_p: float = 0.99,
|
| 9 |
+
):
|
| 10 |
+
"""
|
| 11 |
+
Generates a response from a language model specialized in quantum computing.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
user_prompt (str): The input prompt provided by the user.
|
| 15 |
+
model_name (str, optional):
|
| 16 |
+
The name of the language model to use. Defaults to "phi4".
|
| 17 |
+
temperature (float, optional):
|
| 18 |
+
The sampling temperature for response generation,
|
| 19 |
+
controlling randomness. Defaults to 0.01.
|
| 20 |
+
top_p (float, optional):
|
| 21 |
+
The nucleus sampling parameter, determining the
|
| 22 |
+
probability mass for token selection. Defaults to 0.99.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
str: The generated response from the language model.
|
| 26 |
+
"""
|
| 27 |
client = OpenAI(
|
| 28 |
+
base_url="http://localhost:11434/v1",
|
| 29 |
+
api_key="ollama", # Required but ignored
|
| 30 |
)
|
| 31 |
|
| 32 |
response = client.chat.completions.create(
|
| 33 |
messages=[
|
| 34 |
{"role": "system", "content": "You are a quantum computing expert."},
|
| 35 |
{
|
| 36 |
+
"role": "user",
|
| 37 |
+
"content": user_prompt,
|
| 38 |
+
},
|
| 39 |
],
|
| 40 |
temperature=temperature,
|
| 41 |
top_p=top_p,
|
| 42 |
model=model_name,
|
| 43 |
+
stream=True, # Stream for prevent connection timeout for long response requests
|
| 44 |
)
|
| 45 |
|
| 46 |
final_answer = ""
|
|
|
|
| 50 |
|
| 51 |
return final_answer
|
| 52 |
|
| 53 |
+
|
| 54 |
+
if __name__ == "__main__":
|
| 55 |
print(chat_completion(user_prompt="Who are you in a sentence", model_name="phi4"))
|
| 56 |
+
print(
|
| 57 |
+
chat_completion(user_prompt="Who are you in sentence", model_name="qwen2.5:14b")
|
| 58 |
+
)
|
src/models/llm_prompt_utils.py
CHANGED
|
@@ -1,77 +1,70 @@
|
|
| 1 |
from typing import List
|
| 2 |
from pathlib import Path
|
| 3 |
-
|
| 4 |
-
from quantum_circuits.noisy_qasm_runner import NoisyQASMRunner
|
| 5 |
from jinja2 import Environment, FileSystemLoader
|
| 6 |
-
from
|
|
|
|
| 7 |
from utils.qasm_utils import extract_qasm_from_llm_output
|
| 8 |
-
|
| 9 |
-
logging.basicConfig(
|
|
|
|
|
|
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
template_name = "qasm.j2"
|
| 14 |
if refine:
|
| 15 |
template_name = "refine_qasm.j2"
|
| 16 |
-
env = Environment(
|
|
|
|
|
|
|
| 17 |
template = env.get_template(template_name)
|
| 18 |
rendered_template = template.render(data_dict)
|
| 19 |
|
| 20 |
return rendered_template
|
| 21 |
|
| 22 |
-
def create_qasm_with_llm(user_prompt: str):
|
| 23 |
-
client = OpenAI(
|
| 24 |
-
base_url='http://localhost:11434/v1',
|
| 25 |
-
api_key='ollama', # Required but ignored
|
| 26 |
-
)
|
| 27 |
-
|
| 28 |
-
response = client.chat.completions.create(
|
| 29 |
-
messages=[
|
| 30 |
-
{"role": "system", "content": "You are a quantum computing expert."},
|
| 31 |
-
{
|
| 32 |
-
'role': 'user',
|
| 33 |
-
'content': user_prompt,
|
| 34 |
-
}
|
| 35 |
-
],
|
| 36 |
-
temperature=0.01,
|
| 37 |
-
top_p=0.99,
|
| 38 |
-
model='phi4',
|
| 39 |
-
stream=True
|
| 40 |
-
)
|
| 41 |
-
|
| 42 |
-
final_answer = ""
|
| 43 |
-
for chunk in response:
|
| 44 |
-
if chunk.choices and chunk.choices[0].delta:
|
| 45 |
-
final_answer += chunk.choices[0].delta.content
|
| 46 |
-
|
| 47 |
-
return extract_qasm_from_llm_output(final_answer)
|
| 48 |
-
|
| 49 |
-
def create_and_run_circuit_by_llm(qasm_circuit, noise_data, noisy_result, noiseless_result):
|
| 50 |
-
circuit_data = {
|
| 51 |
-
"original_qasm": qasm_circuit,
|
| 52 |
-
"noisy_operations": noise_data,
|
| 53 |
-
"noisy_results": noisy_result,
|
| 54 |
-
"results": noiseless_result
|
| 55 |
-
}
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
prompt = create_prompt(circuit_data, is_refine)
|
| 69 |
llm_result = chat_completion(prompt, model_name=model)
|
| 70 |
generated_qasm = extract_qasm_from_llm_output(llm_result)
|
| 71 |
return generated_qasm
|
| 72 |
|
|
|
|
| 73 |
def run_noisy_qasm(qasm_circuit, noise_data) -> List[float]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
runner = NoisyQASMRunner(qasm_circuit, noise_data)
|
| 75 |
expectation_values = runner.run()
|
| 76 |
return [float(val) for val in expectation_values]
|
| 77 |
-
|
|
|
|
| 1 |
from typing import List
|
| 2 |
from pathlib import Path
|
| 3 |
+
import logging
|
|
|
|
| 4 |
from jinja2 import Environment, FileSystemLoader
|
| 5 |
+
from quantum_circuits.noisy_qasm_runner import NoisyQASMRunner
|
| 6 |
+
from models.llm_interface import chat_completion
|
| 7 |
from utils.qasm_utils import extract_qasm_from_llm_output
|
| 8 |
+
|
| 9 |
+
logging.basicConfig(
|
| 10 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 11 |
+
)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
+
|
| 15 |
+
def create_prompt(data_dict, refine=False) -> str:
|
| 16 |
+
"""
|
| 17 |
+
Generates a QASM-related prompt using a Jinja2 template.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
data_dict (dict): A dictionary containing the data to be rendered in the template.
|
| 21 |
+
refine (bool, optional): If True, uses the "refine_qasm.j2" template
|
| 22 |
+
instead of the default "qasm.j2". Defaults to False.
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
str: The rendered template as a string.
|
| 26 |
+
"""
|
| 27 |
template_name = "qasm.j2"
|
| 28 |
if refine:
|
| 29 |
template_name = "refine_qasm.j2"
|
| 30 |
+
env = Environment(
|
| 31 |
+
loader=FileSystemLoader(Path(__file__).parent / "jinja_templates")
|
| 32 |
+
)
|
| 33 |
template = env.get_template(template_name)
|
| 34 |
rendered_template = template.render(data_dict)
|
| 35 |
|
| 36 |
return rendered_template
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
def generate_qasm_with_llm(circuit_data, is_refine=False, model="phi4") -> str:
|
| 40 |
+
"""
|
| 41 |
+
Generates a QASM circuit using a language model.
|
| 42 |
|
| 43 |
+
Args:
|
| 44 |
+
circuit_data (dict): The input data required for generating the QASM circuit.
|
| 45 |
+
is_refine (bool, optional): If True, uses a refined QASM template. Defaults to False.
|
| 46 |
+
model (str, optional): The name of the language model to use. Defaults to "phi4".
|
| 47 |
|
| 48 |
+
Returns:
|
| 49 |
+
str: The generated QASM circuit as a string.
|
| 50 |
+
"""
|
| 51 |
prompt = create_prompt(circuit_data, is_refine)
|
| 52 |
llm_result = chat_completion(prompt, model_name=model)
|
| 53 |
generated_qasm = extract_qasm_from_llm_output(llm_result)
|
| 54 |
return generated_qasm
|
| 55 |
|
| 56 |
+
|
| 57 |
def run_noisy_qasm(qasm_circuit, noise_data) -> List[float]:
|
| 58 |
+
"""
|
| 59 |
+
Simulates a noisy QASM circuit and returns expectation values.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
qasm_circuit (str): The QASM representation of the quantum circuit.
|
| 63 |
+
noise_data (dict): The noise model data for simulation.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
List[float]: A list of expectation values obtained from the noisy simulation.
|
| 67 |
+
"""
|
| 68 |
runner = NoisyQASMRunner(qasm_circuit, noise_data)
|
| 69 |
expectation_values = runner.run()
|
| 70 |
return [float(val) for val in expectation_values]
|
|
|
src/quantum_circuits/circuit_error_mitigator.py
CHANGED
|
@@ -4,10 +4,13 @@ from utils.metrics import euclidean_distance
|
|
| 4 |
from models.llm_prompt_utils import generate_qasm_with_llm, run_noisy_qasm
|
| 5 |
from pydantic import BaseModel
|
| 6 |
|
| 7 |
-
logging.basicConfig(
|
|
|
|
|
|
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
logger.setLevel(logging.WARNING)
|
| 10 |
|
|
|
|
| 11 |
class CircuitErrorMitigator(BaseModel):
|
| 12 |
original_qasm: str
|
| 13 |
optimized_qasm: str
|
|
@@ -15,25 +18,29 @@ class CircuitErrorMitigator(BaseModel):
|
|
| 15 |
original_distance: float
|
| 16 |
optimized_distance: float
|
| 17 |
|
|
|
|
| 18 |
def process_circuit(i, df, model):
|
| 19 |
logger.info("Start processing circuit #%d", i + 1)
|
| 20 |
|
| 21 |
circuit_data = extract_circuit_data(df, i)
|
| 22 |
|
|
|
|
|
|
|
| 23 |
circuit_data_for_llm = {
|
| 24 |
"original_qasm": circuit_data.qasm_circuit,
|
| 25 |
"noisy_operations": circuit_data.noise_data,
|
| 26 |
-
"noisy_results":
|
| 27 |
-
"results":
|
| 28 |
}
|
| 29 |
|
| 30 |
-
optimized_qasm = generate_qasm_with_llm(
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
# original_results = run_noisy_qasm(circuit_data.qasm_circuit, circuit_data.noise_data)
|
| 33 |
optimized_results = run_noisy_qasm(optimized_qasm, circuit_data.noise_data)
|
| 34 |
|
| 35 |
-
original_dist = euclidean_distance(
|
| 36 |
-
enhanced_dist = euclidean_distance(optimized_results,
|
| 37 |
|
| 38 |
if original_dist < enhanced_dist:
|
| 39 |
logger.info("Make a refinement")
|
|
@@ -41,13 +48,17 @@ def process_circuit(i, df, model):
|
|
| 41 |
"original_qasm": circuit_data.qasm_circuit,
|
| 42 |
"enhanced_qasm": optimized_qasm,
|
| 43 |
"noisy_operations": circuit_data.noise_data,
|
| 44 |
-
"original_noisy_results":
|
| 45 |
"enhanced_noisy_results": optimized_results,
|
| 46 |
-
"results":
|
| 47 |
}
|
| 48 |
-
optimized_qasm = generate_qasm_with_llm(
|
|
|
|
|
|
|
| 49 |
refinement_results = run_noisy_qasm(optimized_qasm, circuit_data.noise_data)
|
| 50 |
-
enhanced_dist = euclidean_distance(
|
|
|
|
|
|
|
| 51 |
|
| 52 |
return CircuitErrorMitigator(
|
| 53 |
original_qasm=circuit_data.qasm_circuit,
|
|
@@ -56,6 +67,3 @@ def process_circuit(i, df, model):
|
|
| 56 |
original_distance=original_dist,
|
| 57 |
optimized_distance=enhanced_dist,
|
| 58 |
)
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
| 4 |
from models.llm_prompt_utils import generate_qasm_with_llm, run_noisy_qasm
|
| 5 |
from pydantic import BaseModel
|
| 6 |
|
| 7 |
+
logging.basicConfig(
|
| 8 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 9 |
+
)
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
logger.setLevel(logging.WARNING)
|
| 12 |
|
| 13 |
+
|
| 14 |
class CircuitErrorMitigator(BaseModel):
|
| 15 |
original_qasm: str
|
| 16 |
optimized_qasm: str
|
|
|
|
| 18 |
original_distance: float
|
| 19 |
optimized_distance: float
|
| 20 |
|
| 21 |
+
|
| 22 |
def process_circuit(i, df, model):
|
| 23 |
logger.info("Start processing circuit #%d", i + 1)
|
| 24 |
|
| 25 |
circuit_data = extract_circuit_data(df, i)
|
| 26 |
|
| 27 |
+
noisy_result = run_noisy_qasm(circuit_data.qasm_circuit, circuit_data.noise_data)
|
| 28 |
+
noiseless_result = run_noisy_qasm(circuit_data.qasm_circuit, [])
|
| 29 |
circuit_data_for_llm = {
|
| 30 |
"original_qasm": circuit_data.qasm_circuit,
|
| 31 |
"noisy_operations": circuit_data.noise_data,
|
| 32 |
+
"noisy_results": noisy_result,
|
| 33 |
+
"results": noiseless_result,
|
| 34 |
}
|
| 35 |
|
| 36 |
+
optimized_qasm = generate_qasm_with_llm(
|
| 37 |
+
circuit_data_for_llm, is_refine=False, model=model
|
| 38 |
+
)
|
| 39 |
|
|
|
|
| 40 |
optimized_results = run_noisy_qasm(optimized_qasm, circuit_data.noise_data)
|
| 41 |
|
| 42 |
+
original_dist = euclidean_distance(noisy_result, noiseless_result)
|
| 43 |
+
enhanced_dist = euclidean_distance(optimized_results, noiseless_result)
|
| 44 |
|
| 45 |
if original_dist < enhanced_dist:
|
| 46 |
logger.info("Make a refinement")
|
|
|
|
| 48 |
"original_qasm": circuit_data.qasm_circuit,
|
| 49 |
"enhanced_qasm": optimized_qasm,
|
| 50 |
"noisy_operations": circuit_data.noise_data,
|
| 51 |
+
"original_noisy_results": noisy_result,
|
| 52 |
"enhanced_noisy_results": optimized_results,
|
| 53 |
+
"results": noiseless_result,
|
| 54 |
}
|
| 55 |
+
optimized_qasm = generate_qasm_with_llm(
|
| 56 |
+
refine_data, is_refine=True, model=model
|
| 57 |
+
)
|
| 58 |
refinement_results = run_noisy_qasm(optimized_qasm, circuit_data.noise_data)
|
| 59 |
+
enhanced_dist = euclidean_distance(
|
| 60 |
+
refinement_results, circuit_data.noiseless_result
|
| 61 |
+
)
|
| 62 |
|
| 63 |
return CircuitErrorMitigator(
|
| 64 |
original_qasm=circuit_data.qasm_circuit,
|
|
|
|
| 67 |
original_distance=original_dist,
|
| 68 |
optimized_distance=enhanced_dist,
|
| 69 |
)
|
|
|
|
|
|
|
|
|
src/quantum_circuits/circuit_manager.py
CHANGED
|
@@ -1,12 +1,13 @@
|
|
| 1 |
import json
|
| 2 |
import random
|
| 3 |
-
import pennylane as qml
|
| 4 |
from typing import Callable, List, Tuple, Optional, Any
|
|
|
|
| 5 |
from pennylane.measurements import ExpectationMP
|
| 6 |
|
| 7 |
from database.db_handler import DuckDBDAO
|
| 8 |
from quantum_circuits.noisy_circuit_generator import NoisyCircuit
|
| 9 |
|
|
|
|
| 10 |
class CircuitManager:
|
| 11 |
"""
|
| 12 |
Manages circuit execution and noise injection.
|
|
@@ -19,11 +20,11 @@ class CircuitManager:
|
|
| 19 |
"""
|
| 20 |
|
| 21 |
def __init__(
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
) -> None:
|
| 28 |
"""
|
| 29 |
Args:
|
|
@@ -38,7 +39,9 @@ class CircuitManager:
|
|
| 38 |
self.noise_types = noise_types or []
|
| 39 |
|
| 40 |
@staticmethod
|
| 41 |
-
def get_random_noise_types(
|
|
|
|
|
|
|
| 42 |
"""
|
| 43 |
Randomly selects noise operations from a predefined set and assigns
|
| 44 |
random probabilities and target wires.
|
|
@@ -50,7 +53,12 @@ class CircuitManager:
|
|
| 50 |
Returns:
|
| 51 |
A list of tuples (noise_op, probability, target_wires).
|
| 52 |
"""
|
| 53 |
-
possible_noises = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
num_noises = min(num_noises, len(possible_noises))
|
| 55 |
selected_noises = []
|
| 56 |
for noise_op in random.sample(possible_noises, num_noises):
|
|
@@ -61,12 +69,12 @@ class CircuitManager:
|
|
| 61 |
return selected_noises
|
| 62 |
|
| 63 |
def run_circuit(
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
) -> None:
|
| 71 |
"""
|
| 72 |
Runs a noiseless circuit and several noisy variations, then saves results to the database.
|
|
@@ -91,7 +99,9 @@ class CircuitManager:
|
|
| 91 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 92 |
|
| 93 |
noiseless_result = get_z_expectation_value(*params)
|
| 94 |
-
result_json = json.dumps(
|
|
|
|
|
|
|
| 95 |
noiseless_qasm = get_z_expectation_value.qtape.to_openqasm()
|
| 96 |
|
| 97 |
print(f"Circuit: {circuit_name}")
|
|
@@ -103,10 +113,14 @@ class CircuitManager:
|
|
| 103 |
random_noise = self.get_random_noise_types(wires)
|
| 104 |
noisy_circ = NoisyCircuit(dev, random_noise)
|
| 105 |
use_qasm_for_noise = self.use_qasm and len(wires) < 5
|
| 106 |
-
noisy_qnode = noisy_circ.noisy_qnode(
|
|
|
|
|
|
|
| 107 |
noisy_result = noisy_qnode(*params, n_qubits=len(wires))
|
| 108 |
noisy_types_json = self.noise_types_to_json(random_noise)
|
| 109 |
-
noisy_result_json = json.dumps(
|
|
|
|
|
|
|
| 110 |
noise_qasm = noisy_qnode.qtape.to_openqasm() if use_qasm_for_noise else None
|
| 111 |
|
| 112 |
# Save the results in the database.
|
|
@@ -124,7 +138,9 @@ class CircuitManager:
|
|
| 124 |
print("-" * 30)
|
| 125 |
|
| 126 |
@staticmethod
|
| 127 |
-
def noise_types_to_json(
|
|
|
|
|
|
|
| 128 |
"""
|
| 129 |
Converts a list of noise operation tuples into a JSON-formatted string.
|
| 130 |
|
|
@@ -139,4 +155,3 @@ class CircuitManager:
|
|
| 139 |
for noise_op, prob, wires in noise_types
|
| 140 |
]
|
| 141 |
return json.dumps(noise_list, indent=4)
|
| 142 |
-
|
|
|
|
| 1 |
import json
|
| 2 |
import random
|
|
|
|
| 3 |
from typing import Callable, List, Tuple, Optional, Any
|
| 4 |
+
import pennylane as qml
|
| 5 |
from pennylane.measurements import ExpectationMP
|
| 6 |
|
| 7 |
from database.db_handler import DuckDBDAO
|
| 8 |
from quantum_circuits.noisy_circuit_generator import NoisyCircuit
|
| 9 |
|
| 10 |
+
|
| 11 |
class CircuitManager:
|
| 12 |
"""
|
| 13 |
Manages circuit execution and noise injection.
|
|
|
|
| 20 |
"""
|
| 21 |
|
| 22 |
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
db_path: str = ":memory:",
|
| 25 |
+
device_name: str = "default.qubit",
|
| 26 |
+
noise_types: Optional[List[Any]] = None,
|
| 27 |
+
use_qasm: bool = False,
|
| 28 |
) -> None:
|
| 29 |
"""
|
| 30 |
Args:
|
|
|
|
| 39 |
self.noise_types = noise_types or []
|
| 40 |
|
| 41 |
@staticmethod
|
| 42 |
+
def get_random_noise_types(
|
| 43 |
+
wires: List[int], num_noises: int = 2
|
| 44 |
+
) -> List[Tuple[Callable, float, List[int]]]:
|
| 45 |
"""
|
| 46 |
Randomly selects noise operations from a predefined set and assigns
|
| 47 |
random probabilities and target wires.
|
|
|
|
| 53 |
Returns:
|
| 54 |
A list of tuples (noise_op, probability, target_wires).
|
| 55 |
"""
|
| 56 |
+
possible_noises = [
|
| 57 |
+
qml.BitFlip,
|
| 58 |
+
qml.PhaseFlip,
|
| 59 |
+
qml.AmplitudeDamping,
|
| 60 |
+
qml.PhaseDamping,
|
| 61 |
+
]
|
| 62 |
num_noises = min(num_noises, len(possible_noises))
|
| 63 |
selected_noises = []
|
| 64 |
for noise_op in random.sample(possible_noises, num_noises):
|
|
|
|
| 69 |
return selected_noises
|
| 70 |
|
| 71 |
def run_circuit(
|
| 72 |
+
self,
|
| 73 |
+
circuit_func: Callable,
|
| 74 |
+
params: Any,
|
| 75 |
+
circuit_name: str,
|
| 76 |
+
wires: List[int],
|
| 77 |
+
num_variations: int = 3,
|
| 78 |
) -> None:
|
| 79 |
"""
|
| 80 |
Runs a noiseless circuit and several noisy variations, then saves results to the database.
|
|
|
|
| 99 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 100 |
|
| 101 |
noiseless_result = get_z_expectation_value(*params)
|
| 102 |
+
result_json = json.dumps(
|
| 103 |
+
{"expectation_values": [float(val) for val in noiseless_result]}
|
| 104 |
+
)
|
| 105 |
noiseless_qasm = get_z_expectation_value.qtape.to_openqasm()
|
| 106 |
|
| 107 |
print(f"Circuit: {circuit_name}")
|
|
|
|
| 113 |
random_noise = self.get_random_noise_types(wires)
|
| 114 |
noisy_circ = NoisyCircuit(dev, random_noise)
|
| 115 |
use_qasm_for_noise = self.use_qasm and len(wires) < 5
|
| 116 |
+
noisy_qnode = noisy_circ.noisy_qnode(
|
| 117 |
+
circuit_func, wires, use_qasm_for_noise
|
| 118 |
+
)
|
| 119 |
noisy_result = noisy_qnode(*params, n_qubits=len(wires))
|
| 120 |
noisy_types_json = self.noise_types_to_json(random_noise)
|
| 121 |
+
noisy_result_json = json.dumps(
|
| 122 |
+
{"expectation_values": [float(val) for val in noisy_result]}
|
| 123 |
+
)
|
| 124 |
noise_qasm = noisy_qnode.qtape.to_openqasm() if use_qasm_for_noise else None
|
| 125 |
|
| 126 |
# Save the results in the database.
|
|
|
|
| 138 |
print("-" * 30)
|
| 139 |
|
| 140 |
@staticmethod
|
| 141 |
+
def noise_types_to_json(
|
| 142 |
+
noise_types: List[Tuple[Callable, float, List[int]]],
|
| 143 |
+
) -> str:
|
| 144 |
"""
|
| 145 |
Converts a list of noise operation tuples into a JSON-formatted string.
|
| 146 |
|
|
|
|
| 155 |
for noise_op, prob, wires in noise_types
|
| 156 |
]
|
| 157 |
return json.dumps(noise_list, indent=4)
|
|
|
src/quantum_circuits/noisy_circuit_generator.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import pennylane as qml
|
| 2 |
-
from
|
|
|
|
| 3 |
|
| 4 |
|
| 5 |
class NoisyCircuit:
|
|
@@ -13,7 +14,11 @@ class NoisyCircuit:
|
|
| 13 |
List of noise operations as (noise_gate, probability, target_wires).
|
| 14 |
"""
|
| 15 |
|
| 16 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
Args:
|
| 19 |
device: The PennyLane quantum device.
|
|
@@ -33,6 +38,7 @@ class NoisyCircuit:
|
|
| 33 |
Returns:
|
| 34 |
A new circuit function that runs the original circuit then applies noise.
|
| 35 |
"""
|
|
|
|
| 36 |
def noisy_circuit(*params: Any, n_qubits: Optional[int] = None) -> None:
|
| 37 |
# Run the noiseless circuit.
|
| 38 |
circuit(*params, n_qubits=n_qubits)
|
|
@@ -40,9 +46,12 @@ class NoisyCircuit:
|
|
| 40 |
for noise_op, prob, target_wires in self.noise_operations:
|
| 41 |
for w in target_wires:
|
| 42 |
noise_op(prob, wires=[w])
|
|
|
|
| 43 |
return noisy_circuit
|
| 44 |
|
| 45 |
-
def noisy_qnode(
|
|
|
|
|
|
|
| 46 |
"""
|
| 47 |
Constructs a QNode that applies a noiseless circuit and then injects noise.
|
| 48 |
|
|
@@ -62,19 +71,18 @@ class NoisyCircuit:
|
|
| 62 |
noiseless_circuit=circuit,
|
| 63 |
n_system_wires=len(wires),
|
| 64 |
noise_channels=self.noise_operations,
|
| 65 |
-
measurement_fn=lambda: [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 66 |
)
|
| 67 |
else:
|
| 68 |
noisy_circ = self.add_noise(circuit, wires)
|
|
|
|
| 69 |
@qml.qnode(self.device)
|
| 70 |
def qnode(*params: Any, n_qubits: Optional[int] = None) -> List[float]:
|
| 71 |
noisy_circ(*params, n_qubits=n_qubits)
|
| 72 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
|
|
|
| 73 |
return qnode
|
| 74 |
|
| 75 |
-
import pennylane as qml
|
| 76 |
-
from pennylane import numpy as np
|
| 77 |
-
from typing import Callable, Dict, List, Tuple, Union, Optional, Any
|
| 78 |
|
| 79 |
class NoisyQNodeBuilder:
|
| 80 |
"""
|
|
@@ -142,12 +150,15 @@ class NoisyQNodeBuilder:
|
|
| 142 |
gamma: Noise parameter.
|
| 143 |
wires: Wires on which to apply the unitary.
|
| 144 |
"""
|
| 145 |
-
U = np.array(
|
| 146 |
-
[
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
| 151 |
qml.QubitUnitary(U, wires=wires)
|
| 152 |
|
| 153 |
@staticmethod
|
|
@@ -170,6 +181,7 @@ class NoisyQNodeBuilder:
|
|
| 170 |
Returns:
|
| 171 |
8x8 complex unitary matrix.
|
| 172 |
"""
|
|
|
|
| 173 |
def apply_X(s: int) -> Tuple[int, float]:
|
| 174 |
return (1 - s), 1.0
|
| 175 |
|
|
@@ -220,7 +232,7 @@ class NoisyQNodeBuilder:
|
|
| 220 |
n_system_wires: int,
|
| 221 |
noise_channels: List[Tuple[Union[str, Any], float, List[int]]],
|
| 222 |
measurement_fn: Optional[Callable] = None,
|
| 223 |
-
device_kwargs: Optional[Dict[str, Any]] = None
|
| 224 |
) -> qml.QNode:
|
| 225 |
"""
|
| 226 |
Constructs a QNode that runs a noiseless circuit on the system wires,
|
|
@@ -239,20 +251,28 @@ class NoisyQNodeBuilder:
|
|
| 239 |
"""
|
| 240 |
noise_channels = cls._normalize_noise_channels(noise_channels)
|
| 241 |
|
| 242 |
-
for
|
| 243 |
if noise_type not in cls.NOISE_CHANNEL_METHODS:
|
| 244 |
-
raise ValueError(
|
|
|
|
|
|
|
| 245 |
|
| 246 |
ancilla_requirements = cls._calculate_ancilla_requirements(noise_channels)
|
| 247 |
total_ancillas = sum(ancilla_requirements)
|
| 248 |
|
| 249 |
def quantum_function(*args: Any, **kwargs: Any) -> Any:
|
| 250 |
noiseless_circuit(*args, **kwargs)
|
| 251 |
-
current_ancilla_start =
|
|
|
|
|
|
|
| 252 |
|
| 253 |
-
for i, (noise_type, noise_param, wires_to_noise) in enumerate(
|
|
|
|
|
|
|
| 254 |
noise_fn = cls.NOISE_CHANNEL_METHODS[noise_type]
|
| 255 |
-
anc_per_wire =
|
|
|
|
|
|
|
| 256 |
|
| 257 |
for j, sys_wire in enumerate(wires_to_noise):
|
| 258 |
anc_start = current_ancilla_start + j * anc_per_wire
|
|
@@ -275,8 +295,13 @@ class NoisyQNodeBuilder:
|
|
| 275 |
cls, noise_channels: List[Tuple[Union[str, Any], float, List[int]]]
|
| 276 |
) -> List[Tuple[str, float, List[int]]]:
|
| 277 |
transformed = []
|
| 278 |
-
for
|
| 279 |
-
noise_type_str =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
transformed.append((noise_type_str, noise_param, wires_to_noise))
|
| 281 |
return transformed
|
| 282 |
|
|
@@ -285,12 +310,21 @@ class NoisyQNodeBuilder:
|
|
| 285 |
cls, noise_channels: List[Tuple[str, float, List[int]]]
|
| 286 |
) -> List[int]:
|
| 287 |
requirements = []
|
| 288 |
-
for
|
| 289 |
-
anc_per_wire =
|
|
|
|
|
|
|
| 290 |
requirements.append(anc_per_wire * len(wires_to_noise))
|
| 291 |
return requirements
|
| 292 |
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
"""
|
| 295 |
Helper function to print test results and circuit diagrams.
|
| 296 |
"""
|
|
@@ -302,5 +336,3 @@ def print_results(title: str, stine_res: Any, naive_res: Any, qnode_stine: qml.Q
|
|
| 302 |
print("\nNaive approach circuit diagram:")
|
| 303 |
print(qml.draw(qnode_naive)())
|
| 304 |
print("-" * 60)
|
| 305 |
-
|
| 306 |
-
|
|
|
|
| 1 |
import pennylane as qml
|
| 2 |
+
from pennylane import numpy as np
|
| 3 |
+
from typing import Callable, Dict, List, Tuple, Union, Optional, Any
|
| 4 |
|
| 5 |
|
| 6 |
class NoisyCircuit:
|
|
|
|
| 14 |
List of noise operations as (noise_gate, probability, target_wires).
|
| 15 |
"""
|
| 16 |
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
device: qml.Device,
|
| 20 |
+
noise_operations: Optional[List[Tuple[Callable, float, List[int]]]] = None,
|
| 21 |
+
) -> None:
|
| 22 |
"""
|
| 23 |
Args:
|
| 24 |
device: The PennyLane quantum device.
|
|
|
|
| 38 |
Returns:
|
| 39 |
A new circuit function that runs the original circuit then applies noise.
|
| 40 |
"""
|
| 41 |
+
|
| 42 |
def noisy_circuit(*params: Any, n_qubits: Optional[int] = None) -> None:
|
| 43 |
# Run the noiseless circuit.
|
| 44 |
circuit(*params, n_qubits=n_qubits)
|
|
|
|
| 46 |
for noise_op, prob, target_wires in self.noise_operations:
|
| 47 |
for w in target_wires:
|
| 48 |
noise_op(prob, wires=[w])
|
| 49 |
+
|
| 50 |
return noisy_circuit
|
| 51 |
|
| 52 |
+
def noisy_qnode(
|
| 53 |
+
self, circuit: Callable, wires: List[int], use_qasm: bool = True
|
| 54 |
+
) -> qml.QNode:
|
| 55 |
"""
|
| 56 |
Constructs a QNode that applies a noiseless circuit and then injects noise.
|
| 57 |
|
|
|
|
| 71 |
noiseless_circuit=circuit,
|
| 72 |
n_system_wires=len(wires),
|
| 73 |
noise_channels=self.noise_operations,
|
| 74 |
+
measurement_fn=lambda: [qml.expval(qml.PauliZ(w)) for w in wires],
|
| 75 |
)
|
| 76 |
else:
|
| 77 |
noisy_circ = self.add_noise(circuit, wires)
|
| 78 |
+
|
| 79 |
@qml.qnode(self.device)
|
| 80 |
def qnode(*params: Any, n_qubits: Optional[int] = None) -> List[float]:
|
| 81 |
noisy_circ(*params, n_qubits=n_qubits)
|
| 82 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 83 |
+
|
| 84 |
return qnode
|
| 85 |
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
class NoisyQNodeBuilder:
|
| 88 |
"""
|
|
|
|
| 150 |
gamma: Noise parameter.
|
| 151 |
wires: Wires on which to apply the unitary.
|
| 152 |
"""
|
| 153 |
+
U = np.array(
|
| 154 |
+
[
|
| 155 |
+
[1, 0, 0, 0],
|
| 156 |
+
[0, 1, np.sqrt(gamma), 0],
|
| 157 |
+
[0, 0, np.sqrt(1 - gamma), 0],
|
| 158 |
+
[0, 0, 0, 1],
|
| 159 |
+
],
|
| 160 |
+
dtype=complex,
|
| 161 |
+
)
|
| 162 |
qml.QubitUnitary(U, wires=wires)
|
| 163 |
|
| 164 |
@staticmethod
|
|
|
|
| 181 |
Returns:
|
| 182 |
8x8 complex unitary matrix.
|
| 183 |
"""
|
| 184 |
+
|
| 185 |
def apply_X(s: int) -> Tuple[int, float]:
|
| 186 |
return (1 - s), 1.0
|
| 187 |
|
|
|
|
| 232 |
n_system_wires: int,
|
| 233 |
noise_channels: List[Tuple[Union[str, Any], float, List[int]]],
|
| 234 |
measurement_fn: Optional[Callable] = None,
|
| 235 |
+
device_kwargs: Optional[Dict[str, Any]] = None,
|
| 236 |
) -> qml.QNode:
|
| 237 |
"""
|
| 238 |
Constructs a QNode that runs a noiseless circuit on the system wires,
|
|
|
|
| 251 |
"""
|
| 252 |
noise_channels = cls._normalize_noise_channels(noise_channels)
|
| 253 |
|
| 254 |
+
for noise_type, _, _ in noise_channels:
|
| 255 |
if noise_type not in cls.NOISE_CHANNEL_METHODS:
|
| 256 |
+
raise ValueError(
|
| 257 |
+
f"Unknown noise type '{noise_type}'. Available types: {list(cls.NOISE_CHANNEL_METHODS.keys())}"
|
| 258 |
+
)
|
| 259 |
|
| 260 |
ancilla_requirements = cls._calculate_ancilla_requirements(noise_channels)
|
| 261 |
total_ancillas = sum(ancilla_requirements)
|
| 262 |
|
| 263 |
def quantum_function(*args: Any, **kwargs: Any) -> Any:
|
| 264 |
noiseless_circuit(*args, **kwargs)
|
| 265 |
+
current_ancilla_start = (
|
| 266 |
+
n_system_wires # System wires are 0 .. n_system_wires-1
|
| 267 |
+
)
|
| 268 |
|
| 269 |
+
for i, (noise_type, noise_param, wires_to_noise) in enumerate(
|
| 270 |
+
noise_channels
|
| 271 |
+
):
|
| 272 |
noise_fn = cls.NOISE_CHANNEL_METHODS[noise_type]
|
| 273 |
+
anc_per_wire = (
|
| 274 |
+
2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1
|
| 275 |
+
)
|
| 276 |
|
| 277 |
for j, sys_wire in enumerate(wires_to_noise):
|
| 278 |
anc_start = current_ancilla_start + j * anc_per_wire
|
|
|
|
| 295 |
cls, noise_channels: List[Tuple[Union[str, Any], float, List[int]]]
|
| 296 |
) -> List[Tuple[str, float, List[int]]]:
|
| 297 |
transformed = []
|
| 298 |
+
for noise_type, noise_param, wires_to_noise in noise_channels:
|
| 299 |
+
noise_type_str = (
|
| 300 |
+
noise_type.__name__
|
| 301 |
+
if isinstance(noise_type, type)
|
| 302 |
+
and issubclass(noise_type, qml.operation.Operation)
|
| 303 |
+
else str(noise_type)
|
| 304 |
+
)
|
| 305 |
transformed.append((noise_type_str, noise_param, wires_to_noise))
|
| 306 |
return transformed
|
| 307 |
|
|
|
|
| 310 |
cls, noise_channels: List[Tuple[str, float, List[int]]]
|
| 311 |
) -> List[int]:
|
| 312 |
requirements = []
|
| 313 |
+
for noise_type, _, wires_to_noise in noise_channels:
|
| 314 |
+
anc_per_wire = (
|
| 315 |
+
2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1
|
| 316 |
+
)
|
| 317 |
requirements.append(anc_per_wire * len(wires_to_noise))
|
| 318 |
return requirements
|
| 319 |
|
| 320 |
+
|
| 321 |
+
def print_results(
|
| 322 |
+
title: str,
|
| 323 |
+
stine_res: Any,
|
| 324 |
+
naive_res: Any,
|
| 325 |
+
qnode_stine: qml.QNode,
|
| 326 |
+
qnode_naive: qml.QNode,
|
| 327 |
+
) -> None:
|
| 328 |
"""
|
| 329 |
Helper function to print test results and circuit diagrams.
|
| 330 |
"""
|
|
|
|
| 336 |
print("\nNaive approach circuit diagram:")
|
| 337 |
print(qml.draw(qnode_naive)())
|
| 338 |
print("-" * 60)
|
|
|
|
|
|
src/quantum_circuits/noisy_qasm_runner.py
CHANGED
|
@@ -10,11 +10,15 @@ class NoisyQASMRunner:
|
|
| 10 |
"""
|
| 11 |
Runs noisy quantum circuits derived from OpenQASM code with specified noise operations.
|
| 12 |
"""
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
Args:
|
| 16 |
openqasm_code: Valid OpenQASM 2.0 code.
|
| 17 |
-
noise_dict_list: List of noise dictionaries
|
|
|
|
| 18 |
verbose: Print verbose output.
|
| 19 |
"""
|
| 20 |
self.openqasm_code = openqasm_code
|
|
@@ -27,11 +31,11 @@ class NoisyQASMRunner:
|
|
| 27 |
else:
|
| 28 |
self.logger.setLevel(logging.WARNING)
|
| 29 |
|
| 30 |
-
|
| 31 |
@staticmethod
|
| 32 |
def translate_noise_types(noise_dict_list: List[Dict[str, Any]]) -> List[tuple]:
|
| 33 |
"""
|
| 34 |
-
Translates a list of noise dictionaries into a list of tuples:
|
|
|
|
| 35 |
Args:
|
| 36 |
noise_dict_list: List of dictionaries with keys "operation", "probability", "wires".
|
| 37 |
Returns:
|
|
@@ -100,11 +104,14 @@ class NoisyQASMRunner:
|
|
| 100 |
noisy_qnode = noisy_circ.noisy_qnode(circuit, wires, use_qasm=False)
|
| 101 |
|
| 102 |
noisy_result = noisy_qnode(dummy_params, n_qubits=n_qubits)
|
| 103 |
-
result_json = json.dumps(
|
|
|
|
|
|
|
| 104 |
self.logger.info("Noisy circuit expectation values:")
|
| 105 |
self.logger.info(result_json)
|
| 106 |
return noisy_result
|
| 107 |
|
|
|
|
| 108 |
if __name__ == "__main__":
|
| 109 |
sample_qasm = """
|
| 110 |
OPENQASM 2.0;
|
|
@@ -119,4 +126,4 @@ if __name__ == "__main__":
|
|
| 119 |
result_no_noise = runner_no_noise.run()
|
| 120 |
result_no_noise_2 = runner_no_noise.run()
|
| 121 |
print(result_no_noise)
|
| 122 |
-
print(result_no_noise_2)
|
|
|
|
| 10 |
"""
|
| 11 |
Runs noisy quantum circuits derived from OpenQASM code with specified noise operations.
|
| 12 |
"""
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self, openqasm_code: str, noise_dict_list: List[Dict[str, Any]], verbose=False
|
| 16 |
+
) -> None:
|
| 17 |
"""
|
| 18 |
Args:
|
| 19 |
openqasm_code: Valid OpenQASM 2.0 code.
|
| 20 |
+
noise_dict_list: List of noise dictionaries
|
| 21 |
+
(each with "operation", "probability", "wires").
|
| 22 |
verbose: Print verbose output.
|
| 23 |
"""
|
| 24 |
self.openqasm_code = openqasm_code
|
|
|
|
| 31 |
else:
|
| 32 |
self.logger.setLevel(logging.WARNING)
|
| 33 |
|
|
|
|
| 34 |
@staticmethod
|
| 35 |
def translate_noise_types(noise_dict_list: List[Dict[str, Any]]) -> List[tuple]:
|
| 36 |
"""
|
| 37 |
+
Translates a list of noise dictionaries into a list of tuples:
|
| 38 |
+
(noise_op, probability, wires).
|
| 39 |
Args:
|
| 40 |
noise_dict_list: List of dictionaries with keys "operation", "probability", "wires".
|
| 41 |
Returns:
|
|
|
|
| 104 |
noisy_qnode = noisy_circ.noisy_qnode(circuit, wires, use_qasm=False)
|
| 105 |
|
| 106 |
noisy_result = noisy_qnode(dummy_params, n_qubits=n_qubits)
|
| 107 |
+
result_json = json.dumps(
|
| 108 |
+
{"expectation_values": [float(val) for val in noisy_result]}
|
| 109 |
+
)
|
| 110 |
self.logger.info("Noisy circuit expectation values:")
|
| 111 |
self.logger.info(result_json)
|
| 112 |
return noisy_result
|
| 113 |
|
| 114 |
+
|
| 115 |
if __name__ == "__main__":
|
| 116 |
sample_qasm = """
|
| 117 |
OPENQASM 2.0;
|
|
|
|
| 126 |
result_no_noise = runner_no_noise.run()
|
| 127 |
result_no_noise_2 = runner_no_noise.run()
|
| 128 |
print(result_no_noise)
|
| 129 |
+
print(result_no_noise_2)
|
src/scripts/error_mitigation_eval.py
CHANGED
|
@@ -2,7 +2,7 @@ import json
|
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
|
| 4 |
# Load the JSONL data
|
| 5 |
-
|
| 6 |
|
| 7 |
original_distances = []
|
| 8 |
qwen_optimized_distances = []
|
|
@@ -17,7 +17,7 @@ phi_better_count = 0
|
|
| 17 |
qwen_worse_count = 0
|
| 18 |
phi_worse_count = 0
|
| 19 |
|
| 20 |
-
with open(
|
| 21 |
json_list = [json.loads(line.strip()) for line in f]
|
| 22 |
|
| 23 |
for res in json_list:
|
|
@@ -52,31 +52,57 @@ for res in json_list:
|
|
| 52 |
|
| 53 |
# --- FUNCTIONS FOR PLOTTING ---
|
| 54 |
|
|
|
|
| 55 |
def plot_scatter_overall():
|
| 56 |
"""Scatter Plot: Overall Improvement vs Worse"""
|
| 57 |
plt.figure(figsize=(8, 6))
|
| 58 |
|
| 59 |
-
for orig, opt in zip(
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
color = "green" if opt < orig else "red"
|
| 62 |
plt.scatter(orig, opt, color=color, alpha=0.7)
|
| 63 |
|
| 64 |
# No improvement reference line
|
| 65 |
-
plt.plot(
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# Position text in the top-right with some spacing
|
| 69 |
max_x = max(original_distances)
|
| 70 |
-
max_y = max(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
print(max_x, max_y)
|
| 72 |
-
plt.text(
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
plt.xlabel("Original Distance")
|
| 78 |
plt.ylabel("Optimized Distance")
|
| 79 |
-
plt.title(
|
|
|
|
|
|
|
| 80 |
plt.legend()
|
| 81 |
plt.grid(True, linestyle="--", alpha=0.7)
|
| 82 |
plt.show()
|
|
@@ -85,7 +111,9 @@ def plot_scatter_overall():
|
|
| 85 |
def plot_bar_improvement():
|
| 86 |
"""Bar Chart: Overall Improvement Breakdown"""
|
| 87 |
plt.figure(figsize=(8, 6))
|
| 88 |
-
plt.bar(
|
|
|
|
|
|
|
| 89 |
plt.ylabel("Count")
|
| 90 |
plt.title("Overall Improvement Breakdown")
|
| 91 |
plt.grid(axis="y", linestyle="--", alpha=0.7)
|
|
@@ -95,8 +123,24 @@ def plot_bar_improvement():
|
|
| 95 |
def plot_histogram(original, optimized, title, color):
|
| 96 |
"""Histogram: Original vs Optimized Distances with Original on Top"""
|
| 97 |
plt.figure(figsize=(8, 6))
|
| 98 |
-
plt.hist(
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
plt.xlabel("Distance")
|
| 102 |
plt.ylabel("Frequency")
|
|
@@ -109,8 +153,11 @@ def plot_histogram(original, optimized, title, color):
|
|
| 109 |
def plot_boxplot():
|
| 110 |
"""Box Plot: Distance Distributions"""
|
| 111 |
plt.figure(figsize=(8, 6))
|
| 112 |
-
plt.boxplot(
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
plt.ylabel("Distance")
|
| 116 |
plt.title("Distance Distributions (Original vs Optimized)")
|
|
@@ -126,12 +173,18 @@ def plot_scatter_single_model(optimized_distances, model_name, color):
|
|
| 126 |
dot_color = "green" if opt < orig else "red"
|
| 127 |
plt.scatter(orig, opt, color=dot_color, alpha=0.7)
|
| 128 |
|
| 129 |
-
plt.plot(
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
plt.xlabel("Original Distance")
|
| 133 |
plt.ylabel(f"{model_name} Optimized Distance")
|
| 134 |
-
plt.title(
|
|
|
|
|
|
|
| 135 |
plt.legend()
|
| 136 |
plt.grid(True, linestyle="--", alpha=0.7)
|
| 137 |
plt.show()
|
|
|
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
|
| 4 |
# Load the JSONL data
|
| 5 |
+
JSON_PATH = "output_old.jsonl"
|
| 6 |
|
| 7 |
original_distances = []
|
| 8 |
qwen_optimized_distances = []
|
|
|
|
| 17 |
qwen_worse_count = 0
|
| 18 |
phi_worse_count = 0
|
| 19 |
|
| 20 |
+
with open(JSON_PATH, "r", encoding="utf-8") as f:
|
| 21 |
json_list = [json.loads(line.strip()) for line in f]
|
| 22 |
|
| 23 |
for res in json_list:
|
|
|
|
| 52 |
|
| 53 |
# --- FUNCTIONS FOR PLOTTING ---
|
| 54 |
|
| 55 |
+
|
| 56 |
def plot_scatter_overall():
|
| 57 |
"""Scatter Plot: Overall Improvement vs Worse"""
|
| 58 |
plt.figure(figsize=(8, 6))
|
| 59 |
|
| 60 |
+
for orig, opt in zip(
|
| 61 |
+
original_distances,
|
| 62 |
+
[min(q, p) for q, p in zip(qwen_optimized_distances, phi_optimized_distances)],
|
| 63 |
+
):
|
| 64 |
color = "green" if opt < orig else "red"
|
| 65 |
plt.scatter(orig, opt, color=color, alpha=0.7)
|
| 66 |
|
| 67 |
# No improvement reference line
|
| 68 |
+
plt.plot(
|
| 69 |
+
[min(original_distances), max(original_distances)],
|
| 70 |
+
[min(original_distances), max(original_distances)],
|
| 71 |
+
"k--",
|
| 72 |
+
label="No Improvement Line (y = x)",
|
| 73 |
+
)
|
| 74 |
|
| 75 |
# Position text in the top-right with some spacing
|
| 76 |
max_x = max(original_distances)
|
| 77 |
+
max_y = max(
|
| 78 |
+
[
|
| 79 |
+
q if q < p else p
|
| 80 |
+
for (q, p) in zip(qwen_optimized_distances, phi_optimized_distances)
|
| 81 |
+
]
|
| 82 |
+
)
|
| 83 |
print(max_x, max_y)
|
| 84 |
+
plt.text(
|
| 85 |
+
max_x * 0.8,
|
| 86 |
+
max_y * 0.9,
|
| 87 |
+
f"↓ Better: {better_count}",
|
| 88 |
+
color="green",
|
| 89 |
+
fontsize=12,
|
| 90 |
+
fontweight="bold",
|
| 91 |
+
)
|
| 92 |
+
plt.text(
|
| 93 |
+
max_x * 0.8,
|
| 94 |
+
max_y * 0.8,
|
| 95 |
+
f"↑ Worse: {worse_count}",
|
| 96 |
+
color="red",
|
| 97 |
+
fontsize=12,
|
| 98 |
+
fontweight="bold",
|
| 99 |
+
)
|
| 100 |
|
| 101 |
plt.xlabel("Original Distance")
|
| 102 |
plt.ylabel("Optimized Distance")
|
| 103 |
+
plt.title(
|
| 104 |
+
"Original vs Optimized Distances\n(Green Below = Better, Red Above = Worse)"
|
| 105 |
+
)
|
| 106 |
plt.legend()
|
| 107 |
plt.grid(True, linestyle="--", alpha=0.7)
|
| 108 |
plt.show()
|
|
|
|
| 111 |
def plot_bar_improvement():
|
| 112 |
"""Bar Chart: Overall Improvement Breakdown"""
|
| 113 |
plt.figure(figsize=(8, 6))
|
| 114 |
+
plt.bar(
|
| 115 |
+
["Improved", "Worsened"], [better_count, worse_count], color=["green", "red"]
|
| 116 |
+
)
|
| 117 |
plt.ylabel("Count")
|
| 118 |
plt.title("Overall Improvement Breakdown")
|
| 119 |
plt.grid(axis="y", linestyle="--", alpha=0.7)
|
|
|
|
| 123 |
def plot_histogram(original, optimized, title, color):
|
| 124 |
"""Histogram: Original vs Optimized Distances with Original on Top"""
|
| 125 |
plt.figure(figsize=(8, 6))
|
| 126 |
+
plt.hist(
|
| 127 |
+
optimized,
|
| 128 |
+
bins=30,
|
| 129 |
+
alpha=0.7,
|
| 130 |
+
label="Optimized",
|
| 131 |
+
color=color,
|
| 132 |
+
edgecolor="black",
|
| 133 |
+
stacked=True,
|
| 134 |
+
)
|
| 135 |
+
plt.hist(
|
| 136 |
+
original,
|
| 137 |
+
bins=30,
|
| 138 |
+
alpha=0.4,
|
| 139 |
+
label="Original",
|
| 140 |
+
color="blue",
|
| 141 |
+
edgecolor="black",
|
| 142 |
+
stacked=True,
|
| 143 |
+
)
|
| 144 |
|
| 145 |
plt.xlabel("Distance")
|
| 146 |
plt.ylabel("Frequency")
|
|
|
|
| 153 |
def plot_boxplot():
|
| 154 |
"""Box Plot: Distance Distributions"""
|
| 155 |
plt.figure(figsize=(8, 6))
|
| 156 |
+
plt.boxplot(
|
| 157 |
+
[original_distances, qwen_optimized_distances, phi_optimized_distances],
|
| 158 |
+
labels=["Original", "Qwen Optimized", "Phi Optimized"],
|
| 159 |
+
patch_artist=True,
|
| 160 |
+
)
|
| 161 |
|
| 162 |
plt.ylabel("Distance")
|
| 163 |
plt.title("Distance Distributions (Original vs Optimized)")
|
|
|
|
| 173 |
dot_color = "green" if opt < orig else "red"
|
| 174 |
plt.scatter(orig, opt, color=dot_color, alpha=0.7)
|
| 175 |
|
| 176 |
+
plt.plot(
|
| 177 |
+
[min(original_distances), max(original_distances)],
|
| 178 |
+
[min(original_distances), max(original_distances)],
|
| 179 |
+
"k--",
|
| 180 |
+
label="No Improvement Line (y = x)",
|
| 181 |
+
)
|
| 182 |
|
| 183 |
plt.xlabel("Original Distance")
|
| 184 |
plt.ylabel(f"{model_name} Optimized Distance")
|
| 185 |
+
plt.title(
|
| 186 |
+
f"Original vs {model_name} Optimized Distances\n(Green Below = Better, Red Above = Worse)"
|
| 187 |
+
)
|
| 188 |
plt.legend()
|
| 189 |
plt.grid(True, linestyle="--", alpha=0.7)
|
| 190 |
plt.show()
|
src/scripts/generate_random_circuits.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
from quantum_circuits import CircuitManager
|
| 2 |
-
from pennylane import numpy as np
|
| 3 |
import random
|
| 4 |
-
import pennylane as qml
|
| 5 |
from typing import Callable, Optional, Any
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
##############################################################################
|
| 8 |
# Static and Dynamic Circuit Definitions
|
|
@@ -66,7 +67,9 @@ def circuit_7(params: Any, n_qubits: int = 3) -> None:
|
|
| 66 |
def circuit_8(params: Any, n_qubits: int = 2) -> None:
|
| 67 |
"""Amplitude Embedding on 2 qubits."""
|
| 68 |
wires = list(range(n_qubits))
|
| 69 |
-
qml.templates.AmplitudeEmbedding(
|
|
|
|
|
|
|
| 70 |
|
| 71 |
|
| 72 |
def circuit_9(params: Any, n_qubits: int = 3) -> None:
|
|
@@ -103,9 +106,19 @@ def create_dynamic_temp_circuit(num_qubits: int) -> Callable:
|
|
| 103 |
|
| 104 |
# Layer 1: Parameterized rotations.
|
| 105 |
for i in range(n):
|
| 106 |
-
rx_angle =
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
qml.RX(rx_angle, wires=i)
|
| 110 |
qml.RY(ry_angle, wires=i)
|
| 111 |
qml.RZ(rz_angle, wires=i)
|
|
@@ -137,11 +150,36 @@ static_circuits = [
|
|
| 137 |
(circuit_2, [np.array([])], "Circuit_2 (Static, 2 qubits)", [0, 1]),
|
| 138 |
(circuit_3, [np.array([0.5])], "Circuit_3 (Static, 2 qubits)", [0, 1]),
|
| 139 |
(circuit_4, [np.random.rand(3)], "Circuit_4 (Static, 1 qubit)", [0]),
|
| 140 |
-
(
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
]
|
| 146 |
|
| 147 |
# Useful circuits that are applicable for dynamic qubit counts.
|
|
@@ -156,12 +194,15 @@ for n in range(2, 13):
|
|
| 156 |
wires = list(range(n))
|
| 157 |
dynamic_circ = create_dynamic_temp_circuit(n)
|
| 158 |
dynamic_params = np.random.rand(n)
|
| 159 |
-
circuits.append(
|
|
|
|
|
|
|
| 160 |
|
| 161 |
# For each useful circuit, use the same parameter vector.
|
| 162 |
for circuit in useful_circuits:
|
| 163 |
circuits.append((circuit, [dynamic_params], circuit.__name__, wires))
|
| 164 |
|
|
|
|
| 165 |
def main():
|
| 166 |
device_name = "default.mixed"
|
| 167 |
use_qasm = True
|
|
@@ -174,4 +215,4 @@ def main():
|
|
| 174 |
|
| 175 |
# Run each circuit with 10 noisy variations.
|
| 176 |
for circuit_func, params, name, wires in circuits:
|
| 177 |
-
manager.run_circuit(circuit_func, params, name, wires, num_variations=10)
|
|
|
|
|
|
|
|
|
|
| 1 |
import random
|
|
|
|
| 2 |
from typing import Callable, Optional, Any
|
| 3 |
+
import pennylane as qml
|
| 4 |
+
from pennylane import numpy as np
|
| 5 |
+
from quantum_circuits.circuit_manager import CircuitManager
|
| 6 |
+
|
| 7 |
|
| 8 |
##############################################################################
|
| 9 |
# Static and Dynamic Circuit Definitions
|
|
|
|
| 67 |
def circuit_8(params: Any, n_qubits: int = 2) -> None:
|
| 68 |
"""Amplitude Embedding on 2 qubits."""
|
| 69 |
wires = list(range(n_qubits))
|
| 70 |
+
qml.templates.AmplitudeEmbedding(
|
| 71 |
+
params, wires=wires, normalize=True
|
| 72 |
+
).decomposition()
|
| 73 |
|
| 74 |
|
| 75 |
def circuit_9(params: Any, n_qubits: int = 3) -> None:
|
|
|
|
| 106 |
|
| 107 |
# Layer 1: Parameterized rotations.
|
| 108 |
for i in range(n):
|
| 109 |
+
rx_angle = (
|
| 110 |
+
params[3 * i] if len(params) > 3 * i else random.uniform(0, 2 * np.pi)
|
| 111 |
+
)
|
| 112 |
+
ry_angle = (
|
| 113 |
+
params[3 * i + 1]
|
| 114 |
+
if len(params) > 3 * i + 1
|
| 115 |
+
else random.uniform(0, 2 * np.pi)
|
| 116 |
+
)
|
| 117 |
+
rz_angle = (
|
| 118 |
+
params[3 * i + 2]
|
| 119 |
+
if len(params) > 3 * i + 2
|
| 120 |
+
else random.uniform(0, 2 * np.pi)
|
| 121 |
+
)
|
| 122 |
qml.RX(rx_angle, wires=i)
|
| 123 |
qml.RY(ry_angle, wires=i)
|
| 124 |
qml.RZ(rz_angle, wires=i)
|
|
|
|
| 150 |
(circuit_2, [np.array([])], "Circuit_2 (Static, 2 qubits)", [0, 1]),
|
| 151 |
(circuit_3, [np.array([0.5])], "Circuit_3 (Static, 2 qubits)", [0, 1]),
|
| 152 |
(circuit_4, [np.random.rand(3)], "Circuit_4 (Static, 1 qubit)", [0]),
|
| 153 |
+
(
|
| 154 |
+
circuit_8,
|
| 155 |
+
[np.random.rand(2**2)],
|
| 156 |
+
"Circuit_8 (Static, Amplitude Embedding, 2 qubits)",
|
| 157 |
+
[0, 1],
|
| 158 |
+
),
|
| 159 |
+
(
|
| 160 |
+
circuit_8,
|
| 161 |
+
[np.random.rand(2**3)],
|
| 162 |
+
"Circuit_8 (Static, Amplitude Embedding, 3 qubits)",
|
| 163 |
+
[0, 1, 2],
|
| 164 |
+
),
|
| 165 |
+
(
|
| 166 |
+
circuit_10,
|
| 167 |
+
[np.random.rand(2, 3, 3)],
|
| 168 |
+
"Circuit_10 (Static, Strongly Entangling, 3 qubits)",
|
| 169 |
+
[0, 1, 2],
|
| 170 |
+
),
|
| 171 |
+
(
|
| 172 |
+
circuit_10,
|
| 173 |
+
[np.random.rand(2, 4, 3)],
|
| 174 |
+
"Circuit_10 (Static, Strongly Entangling, 4 qubits)",
|
| 175 |
+
[0, 1, 2, 3],
|
| 176 |
+
),
|
| 177 |
+
(
|
| 178 |
+
circuit_10,
|
| 179 |
+
[np.random.rand(2, 5, 3)],
|
| 180 |
+
"Circuit_10 (Static, Strongly Entangling, 5 qubits)",
|
| 181 |
+
[0, 1, 2, 3, 4],
|
| 182 |
+
),
|
| 183 |
]
|
| 184 |
|
| 185 |
# Useful circuits that are applicable for dynamic qubit counts.
|
|
|
|
| 194 |
wires = list(range(n))
|
| 195 |
dynamic_circ = create_dynamic_temp_circuit(n)
|
| 196 |
dynamic_params = np.random.rand(n)
|
| 197 |
+
circuits.append(
|
| 198 |
+
(dynamic_circ, [dynamic_params], f"Dynamic_Circuit_{n}_qubits", wires)
|
| 199 |
+
)
|
| 200 |
|
| 201 |
# For each useful circuit, use the same parameter vector.
|
| 202 |
for circuit in useful_circuits:
|
| 203 |
circuits.append((circuit, [dynamic_params], circuit.__name__, wires))
|
| 204 |
|
| 205 |
+
|
| 206 |
def main():
|
| 207 |
device_name = "default.mixed"
|
| 208 |
use_qasm = True
|
|
|
|
| 215 |
|
| 216 |
# Run each circuit with 10 noisy variations.
|
| 217 |
for circuit_func, params, name, wires in circuits:
|
| 218 |
+
manager.run_circuit(circuit_func, params, name, wires, num_variations=10)
|
src/scripts/run_error_mitigation.py
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
|
|
|
|
|
| 1 |
import duckdb
|
| 2 |
from quantum_circuits.circuit_error_mitigator import process_circuit
|
| 3 |
-
from
|
| 4 |
-
|
|
|
|
| 5 |
def main():
|
| 6 |
# Connect to the database file
|
| 7 |
-
database_location =
|
|
|
|
|
|
|
| 8 |
con = duckdb.connect(database_location)
|
| 9 |
|
| 10 |
# Read data from a table (replace 'your_table' with the actual table name)
|
|
@@ -12,17 +17,24 @@ def main():
|
|
| 12 |
|
| 13 |
for i, row in enumerate(df.itertuples()):
|
| 14 |
try:
|
| 15 |
-
|
|
|
|
| 16 |
res_qwen = process_circuit(i, df, model="qwen2.5:14b")
|
| 17 |
res_phi = process_circuit(i, df, model="phi4")
|
| 18 |
-
result = {
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
f.write(json.dumps(result) + "\n")
|
| 21 |
except Exception as e:
|
| 22 |
-
with open("output.jsonl", "a") as f:
|
| 23 |
f.write(json.dumps({"error": str(e), "db_index": i}) + "\n")
|
| 24 |
|
| 25 |
con.close()
|
| 26 |
|
|
|
|
| 27 |
if __name__ == "__main__":
|
| 28 |
main()
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from pathlib import Path
|
| 3 |
import duckdb
|
| 4 |
from quantum_circuits.circuit_error_mitigator import process_circuit
|
| 5 |
+
from utils.qasm_utils import get_qasm_circuit_depth
|
| 6 |
+
|
| 7 |
+
|
| 8 |
def main():
|
| 9 |
# Connect to the database file
|
| 10 |
+
database_location = (
|
| 11 |
+
Path(__file__).parent.parent / "database" / "quantum_circuits.duckdb"
|
| 12 |
+
)
|
| 13 |
con = duckdb.connect(database_location)
|
| 14 |
|
| 15 |
# Read data from a table (replace 'your_table' with the actual table name)
|
|
|
|
| 17 |
|
| 18 |
for i, row in enumerate(df.itertuples()):
|
| 19 |
try:
|
| 20 |
+
circuit_depth = get_qasm_circuit_depth(df.qasm[i])
|
| 21 |
+
if i > 100 and circuit_depth < 10:
|
| 22 |
res_qwen = process_circuit(i, df, model="qwen2.5:14b")
|
| 23 |
res_phi = process_circuit(i, df, model="phi4")
|
| 24 |
+
result = {
|
| 25 |
+
"qwen": res_qwen.model_dump(),
|
| 26 |
+
"phi": res_phi.model_dump(),
|
| 27 |
+
"db_index": i,
|
| 28 |
+
"circuit_depth": circuit_depth,
|
| 29 |
+
}
|
| 30 |
+
with open("output.jsonl", "a", encoding="utf-8") as f:
|
| 31 |
f.write(json.dumps(result) + "\n")
|
| 32 |
except Exception as e:
|
| 33 |
+
with open("output.jsonl", "a", encoding="utf-8") as f:
|
| 34 |
f.write(json.dumps({"error": str(e), "db_index": i}) + "\n")
|
| 35 |
|
| 36 |
con.close()
|
| 37 |
|
| 38 |
+
|
| 39 |
if __name__ == "__main__":
|
| 40 |
main()
|
src/tests/test_circuits.py
CHANGED
|
@@ -5,7 +5,9 @@ import pennylane as qml
|
|
| 5 |
|
| 6 |
|
| 7 |
# Test 1: Multiple Noise Channels (BitFlip, Depolarizing, PhaseFlip)
|
| 8 |
-
def my_clean_circuit(
|
|
|
|
|
|
|
| 9 |
qml.Hadamard(wires=0)
|
| 10 |
qml.CNOT(wires=[0, 1])
|
| 11 |
qml.RX(0.2, wires=0)
|
|
@@ -14,7 +16,7 @@ def my_clean_circuit(params: Optional[Any] = None, n_qubits: Optional[int] = Non
|
|
| 14 |
noise_ops1: List[Tuple[Callable, float, List[int]]] = [
|
| 15 |
(qml.BitFlip, 0.1, [0, 1]),
|
| 16 |
(qml.DepolarizingChannel, 0.05, [0]),
|
| 17 |
-
(qml.PhaseFlip, 0.2, [1])
|
| 18 |
]
|
| 19 |
|
| 20 |
# Device with enough wires (2 system + ancillas)
|
|
@@ -27,8 +29,13 @@ qnode_naive1 = nc1.noisy_qnode(circuit=my_clean_circuit, wires=[0, 1], use_qasm=
|
|
| 27 |
res_stine1 = np.round(qnode_stine1(), 3)
|
| 28 |
res_naive1 = np.round(qnode_naive1(), 3)
|
| 29 |
|
| 30 |
-
print_results(
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
|
| 34 |
##################################################################
|
|
@@ -39,9 +46,7 @@ def my_clean_circuit2(params=None, n_qubits=None):
|
|
| 39 |
qml.CNOT(wires=[0, 1])
|
| 40 |
|
| 41 |
|
| 42 |
-
noise_ops2 = [
|
| 43 |
-
(qml.AmplitudeDamping, 0.3, [0, 1])
|
| 44 |
-
]
|
| 45 |
|
| 46 |
dev_naive2 = qml.device("default.mixed", wires=4, shots=None)
|
| 47 |
nc2 = NoisyCircuit(device=dev_naive2, noise_operations=noise_ops2)
|
|
@@ -52,8 +57,13 @@ qnode_naive2 = nc2.noisy_qnode(circuit=my_clean_circuit2, wires=[0, 1], use_qasm
|
|
| 52 |
res_stine2 = np.round(qnode_stine2(), 3)
|
| 53 |
res_naive2 = np.round(qnode_naive2(), 3)
|
| 54 |
|
| 55 |
-
print_results(
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
|
| 59 |
##################################################################
|
|
@@ -76,8 +86,13 @@ qnode_naive3 = nc3.noisy_qnode(circuit=my_clean_circuit3, wires=[0, 1], use_qasm
|
|
| 76 |
res_stine3 = np.round(qnode_stine3(), 3)
|
| 77 |
res_naive3 = np.round(qnode_naive3(), 3)
|
| 78 |
|
| 79 |
-
print_results(
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
##################################################################
|
|
@@ -94,7 +109,7 @@ noise_ops4 = [
|
|
| 94 |
(qml.PhaseFlip, 0.05, [1]),
|
| 95 |
(qml.DepolarizingChannel, 0.05, [0, 1]),
|
| 96 |
(qml.AmplitudeDamping, 0.1, [0]),
|
| 97 |
-
(qml.PhaseDamping, 0.1, [1])
|
| 98 |
]
|
| 99 |
|
| 100 |
# Total wires: 2 system wires + (1 + 1 + 2 + 1 + 1) = 7 wires.
|
|
@@ -107,8 +122,13 @@ qnode_naive4 = nc4.noisy_qnode(circuit=my_clean_circuit4, wires=[0, 1], use_qasm
|
|
| 107 |
res_stine4 = np.round(qnode_stine4(), 3)
|
| 108 |
res_naive4 = np.round(qnode_naive4(), 3)
|
| 109 |
|
| 110 |
-
print_results(
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
##################################################################
|
|
@@ -126,18 +146,27 @@ noise_ops5 = [
|
|
| 126 |
(qml.PhaseFlip, 0.15, [1, 2]),
|
| 127 |
(qml.DepolarizingChannel, 0.1, [0, 2]),
|
| 128 |
(qml.AmplitudeDamping, 0.25, [0]),
|
| 129 |
-
(qml.PhaseDamping, 0.2, [2])
|
| 130 |
]
|
| 131 |
|
| 132 |
# Total wires: 3 system wires + (2 + 2 + 2 + 1 + 1) = 11 wires.
|
| 133 |
dev_naive5 = qml.device("default.mixed", wires=11, shots=None)
|
| 134 |
nc5 = NoisyCircuit(device=dev_naive5, noise_operations=noise_ops5)
|
| 135 |
|
| 136 |
-
qnode_stine5 = nc5.noisy_qnode(
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
res_stine5 = np.round(qnode_stine5(), 3)
|
| 140 |
res_naive5 = np.round(qnode_naive5(), 3)
|
| 141 |
|
| 142 |
-
print_results(
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
# Test 1: Multiple Noise Channels (BitFlip, Depolarizing, PhaseFlip)
|
| 8 |
+
def my_clean_circuit(
|
| 9 |
+
params: Optional[Any] = None, n_qubits: Optional[int] = None
|
| 10 |
+
) -> None:
|
| 11 |
qml.Hadamard(wires=0)
|
| 12 |
qml.CNOT(wires=[0, 1])
|
| 13 |
qml.RX(0.2, wires=0)
|
|
|
|
| 16 |
noise_ops1: List[Tuple[Callable, float, List[int]]] = [
|
| 17 |
(qml.BitFlip, 0.1, [0, 1]),
|
| 18 |
(qml.DepolarizingChannel, 0.05, [0]),
|
| 19 |
+
(qml.PhaseFlip, 0.2, [1]),
|
| 20 |
]
|
| 21 |
|
| 22 |
# Device with enough wires (2 system + ancillas)
|
|
|
|
| 29 |
res_stine1 = np.round(qnode_stine1(), 3)
|
| 30 |
res_naive1 = np.round(qnode_naive1(), 3)
|
| 31 |
|
| 32 |
+
print_results(
|
| 33 |
+
"Test 1: Multiple Noise Channels (BitFlip, Depolarizing, PhaseFlip)",
|
| 34 |
+
res_stine1,
|
| 35 |
+
res_naive1,
|
| 36 |
+
qnode_stine1,
|
| 37 |
+
qnode_naive1,
|
| 38 |
+
)
|
| 39 |
|
| 40 |
|
| 41 |
##################################################################
|
|
|
|
| 46 |
qml.CNOT(wires=[0, 1])
|
| 47 |
|
| 48 |
|
| 49 |
+
noise_ops2 = [(qml.AmplitudeDamping, 0.3, [0, 1])]
|
|
|
|
|
|
|
| 50 |
|
| 51 |
dev_naive2 = qml.device("default.mixed", wires=4, shots=None)
|
| 52 |
nc2 = NoisyCircuit(device=dev_naive2, noise_operations=noise_ops2)
|
|
|
|
| 57 |
res_stine2 = np.round(qnode_stine2(), 3)
|
| 58 |
res_naive2 = np.round(qnode_naive2(), 3)
|
| 59 |
|
| 60 |
+
print_results(
|
| 61 |
+
"Test 2: Single Noise Channel (AmplitudeDamping = 0.3)",
|
| 62 |
+
res_stine2,
|
| 63 |
+
res_naive2,
|
| 64 |
+
qnode_stine2,
|
| 65 |
+
qnode_naive2,
|
| 66 |
+
)
|
| 67 |
|
| 68 |
|
| 69 |
##################################################################
|
|
|
|
| 86 |
res_stine3 = np.round(qnode_stine3(), 3)
|
| 87 |
res_naive3 = np.round(qnode_naive3(), 3)
|
| 88 |
|
| 89 |
+
print_results(
|
| 90 |
+
"Test 3: No Noise Channels (Noiseless Circuit)",
|
| 91 |
+
res_stine3,
|
| 92 |
+
res_naive3,
|
| 93 |
+
qnode_stine3,
|
| 94 |
+
qnode_naive3,
|
| 95 |
+
)
|
| 96 |
|
| 97 |
|
| 98 |
##################################################################
|
|
|
|
| 109 |
(qml.PhaseFlip, 0.05, [1]),
|
| 110 |
(qml.DepolarizingChannel, 0.05, [0, 1]),
|
| 111 |
(qml.AmplitudeDamping, 0.1, [0]),
|
| 112 |
+
(qml.PhaseDamping, 0.1, [1]),
|
| 113 |
]
|
| 114 |
|
| 115 |
# Total wires: 2 system wires + (1 + 1 + 2 + 1 + 1) = 7 wires.
|
|
|
|
| 122 |
res_stine4 = np.round(qnode_stine4(), 3)
|
| 123 |
res_naive4 = np.round(qnode_naive4(), 3)
|
| 124 |
|
| 125 |
+
print_results(
|
| 126 |
+
"Test 4: All Noise Channels Applied Together",
|
| 127 |
+
res_stine4,
|
| 128 |
+
res_naive4,
|
| 129 |
+
qnode_stine4,
|
| 130 |
+
qnode_naive4,
|
| 131 |
+
)
|
| 132 |
|
| 133 |
|
| 134 |
##################################################################
|
|
|
|
| 146 |
(qml.PhaseFlip, 0.15, [1, 2]),
|
| 147 |
(qml.DepolarizingChannel, 0.1, [0, 2]),
|
| 148 |
(qml.AmplitudeDamping, 0.25, [0]),
|
| 149 |
+
(qml.PhaseDamping, 0.2, [2]),
|
| 150 |
]
|
| 151 |
|
| 152 |
# Total wires: 3 system wires + (2 + 2 + 2 + 1 + 1) = 11 wires.
|
| 153 |
dev_naive5 = qml.device("default.mixed", wires=11, shots=None)
|
| 154 |
nc5 = NoisyCircuit(device=dev_naive5, noise_operations=noise_ops5)
|
| 155 |
|
| 156 |
+
qnode_stine5 = nc5.noisy_qnode(
|
| 157 |
+
circuit=my_clean_circuit5, wires=[0, 1, 2], use_qasm=True
|
| 158 |
+
)
|
| 159 |
+
qnode_naive5 = nc5.noisy_qnode(
|
| 160 |
+
circuit=my_clean_circuit5, wires=[0, 1, 2], use_qasm=False
|
| 161 |
+
)
|
| 162 |
|
| 163 |
res_stine5 = np.round(qnode_stine5(), 3)
|
| 164 |
res_naive5 = np.round(qnode_naive5(), 3)
|
| 165 |
|
| 166 |
+
print_results(
|
| 167 |
+
"Test 5: Multiple Noise Channels with Varying Probabilities",
|
| 168 |
+
res_stine5,
|
| 169 |
+
res_naive5,
|
| 170 |
+
qnode_stine5,
|
| 171 |
+
qnode_naive5,
|
| 172 |
+
)
|
src/tests/test_db_handler.py
CHANGED
|
@@ -10,7 +10,9 @@ def test_extract_circuit_data():
|
|
| 10 |
"qasm": ["test_qasm"],
|
| 11 |
"noise_data": [json.dumps(json.dumps({"error_rates": [0.01, 0.02]}))],
|
| 12 |
"noisy_result": [json.dumps(json.dumps({"expectation_values": [0.8, 0.6]}))],
|
| 13 |
-
"noiseless_result": [
|
|
|
|
|
|
|
| 14 |
}
|
| 15 |
df = pd.DataFrame(test_data)
|
| 16 |
|
|
@@ -24,5 +26,5 @@ def test_extract_circuit_data():
|
|
| 24 |
"qasm_circuit": "test_qasm",
|
| 25 |
"noise_data": {"error_rates": [0.01, 0.02]},
|
| 26 |
"noisy_result": [0.8, 0.6],
|
| 27 |
-
"noiseless_result": [0.9, 0.7]
|
| 28 |
}
|
|
|
|
| 10 |
"qasm": ["test_qasm"],
|
| 11 |
"noise_data": [json.dumps(json.dumps({"error_rates": [0.01, 0.02]}))],
|
| 12 |
"noisy_result": [json.dumps(json.dumps({"expectation_values": [0.8, 0.6]}))],
|
| 13 |
+
"noiseless_result": [
|
| 14 |
+
json.dumps(json.dumps({"expectation_values": [0.9, 0.7]}))
|
| 15 |
+
],
|
| 16 |
}
|
| 17 |
df = pd.DataFrame(test_data)
|
| 18 |
|
|
|
|
| 26 |
"qasm_circuit": "test_qasm",
|
| 27 |
"noise_data": {"error_rates": [0.01, 0.02]},
|
| 28 |
"noisy_result": [0.8, 0.6],
|
| 29 |
+
"noiseless_result": [0.9, 0.7],
|
| 30 |
}
|
src/tests/test_noisy_qasm_runner.py
CHANGED
|
@@ -20,16 +20,13 @@ def sample_qasm():
|
|
| 20 |
def sample_noise():
|
| 21 |
return [
|
| 22 |
{"operation": "PhaseFlip", "probability": 0.08, "wires": [0]},
|
| 23 |
-
{"operation": "AmplitudeDamping", "probability": 0.03, "wires": [1, 2]}
|
| 24 |
]
|
| 25 |
|
| 26 |
|
| 27 |
def test_translate_noise_types(sample_noise):
|
| 28 |
"""Test that noise dictionaries are correctly translated into tuples."""
|
| 29 |
-
expected = [
|
| 30 |
-
(qml.PhaseFlip, 0.08, [0]),
|
| 31 |
-
(qml.AmplitudeDamping, 0.03, [1, 2])
|
| 32 |
-
]
|
| 33 |
translated = NoisyQASMRunner.translate_noise_types(sample_noise)
|
| 34 |
assert translated == expected
|
| 35 |
|
|
|
|
| 20 |
def sample_noise():
|
| 21 |
return [
|
| 22 |
{"operation": "PhaseFlip", "probability": 0.08, "wires": [0]},
|
| 23 |
+
{"operation": "AmplitudeDamping", "probability": 0.03, "wires": [1, 2]},
|
| 24 |
]
|
| 25 |
|
| 26 |
|
| 27 |
def test_translate_noise_types(sample_noise):
|
| 28 |
"""Test that noise dictionaries are correctly translated into tuples."""
|
| 29 |
+
expected = [(qml.PhaseFlip, 0.08, [0]), (qml.AmplitudeDamping, 0.03, [1, 2])]
|
|
|
|
|
|
|
|
|
|
| 30 |
translated = NoisyQASMRunner.translate_noise_types(sample_noise)
|
| 31 |
assert translated == expected
|
| 32 |
|
src/utils/metrics.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import math
|
| 2 |
|
|
|
|
| 3 |
def euclidean_distance(list1, list2):
|
| 4 |
"""
|
| 5 |
Computes the Euclidean distance between two lists of numbers.
|
|
@@ -11,4 +12,4 @@ def euclidean_distance(list1, list2):
|
|
| 11 |
if len(list1) != len(list2):
|
| 12 |
raise ValueError("Both lists must be of the same length")
|
| 13 |
squared_diff = sum((a - b) ** 2 for a, b in zip(list1, list2))
|
| 14 |
-
return math.sqrt(squared_diff)
|
|
|
|
| 1 |
import math
|
| 2 |
|
| 3 |
+
|
| 4 |
def euclidean_distance(list1, list2):
|
| 5 |
"""
|
| 6 |
Computes the Euclidean distance between two lists of numbers.
|
|
|
|
| 12 |
if len(list1) != len(list2):
|
| 13 |
raise ValueError("Both lists must be of the same length")
|
| 14 |
squared_diff = sum((a - b) ** 2 for a, b in zip(list1, list2))
|
| 15 |
+
return math.sqrt(squared_diff)
|
src/utils/qasm_utils.py
CHANGED
|
@@ -1,4 +1,51 @@
|
|
| 1 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
def remove_measurements(qasm_code: str) -> str:
|
| 4 |
"""
|
|
@@ -7,13 +54,13 @@ def remove_measurements(qasm_code: str) -> str:
|
|
| 7 |
:param qasm_code: The input QASM code as a string.
|
| 8 |
:return: The QASM code without measurement lines.
|
| 9 |
"""
|
| 10 |
-
cleaned_code = re.sub(r
|
| 11 |
-
return re.sub(r
|
|
|
|
| 12 |
|
| 13 |
def extract_qasm_from_llm_output(text):
|
| 14 |
# Compile a regex pattern to match content between the markers.
|
| 15 |
-
pattern = re.compile(r
|
| 16 |
matches = pattern.findall(text)
|
| 17 |
# Return the last match if available, otherwise None.
|
| 18 |
return matches[-1].strip() if matches else None
|
| 19 |
-
|
|
|
|
| 1 |
import re
|
| 2 |
+
from qiskit.qasm2 import loads
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_qasm_circuit_depth(qasm_str: str) -> int:
|
| 6 |
+
"""
|
| 7 |
+
Given a QASM circuit string from PennyLane, return the depth of the circuit.
|
| 8 |
+
|
| 9 |
+
:param qasm_str: The QASM string representation of the circuit.
|
| 10 |
+
:return: Depth of the quantum circuit.
|
| 11 |
+
"""
|
| 12 |
+
try:
|
| 13 |
+
qiskit_circuit = loads(fix_qasm(qasm_str))
|
| 14 |
+
return qiskit_circuit.depth()
|
| 15 |
+
except Exception as e:
|
| 16 |
+
print(e)
|
| 17 |
+
return -1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def fix_qasm(qasm_code: str) -> str:
|
| 21 |
+
fixed_lines = []
|
| 22 |
+
for line in qasm_code.splitlines():
|
| 23 |
+
# Fix expressions like rx([value]) to rx(value)
|
| 24 |
+
fixed_line = re.sub(r"([a-z]+)\(\[(.*?)\]\)", r"\1(\2)", line)
|
| 25 |
+
fixed_lines.append(fixed_line)
|
| 26 |
+
|
| 27 |
+
return remove_measurements(replace_swap_gates("\n".join(fixed_lines)))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def replace_swap_gates(qasm_code: str) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Replaces all occurrences of `swap` gates in QASM 2.0 with their
|
| 33 |
+
equivalent decomposition using CNOT gates.
|
| 34 |
+
"""
|
| 35 |
+
# Regular expression to match 'swap q[x],q[y];'
|
| 36 |
+
swap_pattern = re.compile(r"swap\s+q\[(\d+)\],\s*q\[(\d+)\];")
|
| 37 |
+
|
| 38 |
+
def swap_replacement(match):
|
| 39 |
+
q1, q2 = match.groups()
|
| 40 |
+
return f"""
|
| 41 |
+
cx q[{q1}], q[{q2}];
|
| 42 |
+
cx q[{q2}], q[{q1}];
|
| 43 |
+
cx q[{q1}], q[{q2}];
|
| 44 |
+
""".strip()
|
| 45 |
+
|
| 46 |
+
# Replace all swap occurrences in the QASM code
|
| 47 |
+
return swap_pattern.sub(swap_replacement, qasm_code)
|
| 48 |
+
|
| 49 |
|
| 50 |
def remove_measurements(qasm_code: str) -> str:
|
| 51 |
"""
|
|
|
|
| 54 |
:param qasm_code: The input QASM code as a string.
|
| 55 |
:return: The QASM code without measurement lines.
|
| 56 |
"""
|
| 57 |
+
cleaned_code = re.sub(r"^measure .*$", "", qasm_code, flags=re.MULTILINE)
|
| 58 |
+
return re.sub(r"\n+", "\n", cleaned_code).strip()
|
| 59 |
+
|
| 60 |
|
| 61 |
def extract_qasm_from_llm_output(text):
|
| 62 |
# Compile a regex pattern to match content between the markers.
|
| 63 |
+
pattern = re.compile(r"<QASM START>(.*?)<QASM END>", re.DOTALL)
|
| 64 |
matches = pattern.findall(text)
|
| 65 |
# Return the last match if available, otherwise None.
|
| 66 |
return matches[-1].strip() if matches else None
|
|
|
src/utils/visualization.py
CHANGED
|
@@ -1,9 +1,17 @@
|
|
| 1 |
import pennylane as qml
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
Visualize a quantum circuit with customizable styling options.
|
| 9 |
|
|
|
|
| 1 |
import pennylane as qml
|
| 2 |
import matplotlib.pyplot as plt
|
| 3 |
|
| 4 |
+
|
| 5 |
+
def visualize_circuit(
|
| 6 |
+
qnode_func,
|
| 7 |
+
params,
|
| 8 |
+
title="Quantum Circuit Visualization",
|
| 9 |
+
fig_bg_color="lightblue",
|
| 10 |
+
ax_bg_color="whitesmoke",
|
| 11 |
+
text_color="darkblue",
|
| 12 |
+
font_size=12,
|
| 13 |
+
save_path=None,
|
| 14 |
+
):
|
| 15 |
"""
|
| 16 |
Visualize a quantum circuit with customizable styling options.
|
| 17 |
|