Spaces:
Runtime error
Runtime error
Commit ·
5db11bc
1
Parent(s): ded0705
feat: add noisy visualization to gradio
Browse files- requirements.txt +0 -0
- src/app.py +23 -6
- src/circuit_builder/circuit_manager.py +77 -47
- src/circuit_builder/circuits_helpers.py +10 -6
- src/circuit_builder/noisy_circuit.py +62 -6
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|
src/app.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
from circuit_builder import CircuitManager, circuits
|
| 3 |
from circuit_builder.circuits_helpers import visualize_circuit, build_quantum_circuit
|
|
|
|
|
|
|
| 4 |
|
| 5 |
def run_selected_circuit(circuit_index, randomize=False):
|
| 6 |
"""
|
|
@@ -14,32 +17,46 @@ def run_selected_circuit(circuit_index, randomize=False):
|
|
| 14 |
"""
|
| 15 |
try:
|
| 16 |
circuit_func, params, circuit_name, wires = circuits[circuit_index]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# Build the quantum circuit
|
| 18 |
-
constructed_circuit = build_quantum_circuit((circuit_func, params, circuit_name, wires)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Visualize the circuit
|
| 20 |
visualize_circuit(constructed_circuit, *params, title=circuit_name,
|
| 21 |
save_path="output.png")
|
| 22 |
-
return "success", "output.png"
|
| 23 |
|
| 24 |
except IndexError:
|
| 25 |
-
return "Invalid circuit selection", None
|
| 26 |
|
| 27 |
|
| 28 |
# Gradio app interface
|
| 29 |
def run_app():
|
| 30 |
iface = gr.Interface(
|
| 31 |
fn=lambda circuit_choice, randomize: run_selected_circuit(
|
| 32 |
-
int(circuit_choice)-1, randomize),
|
| 33 |
inputs=[
|
| 34 |
gr.Radio(
|
| 35 |
-
choices=[str(i+1) for i in range(len(circuits))],
|
| 36 |
label="Choose Circuit Type"
|
| 37 |
),
|
| 38 |
-
gr.Checkbox(label="Randomize Circuit", visible=
|
| 39 |
],
|
| 40 |
outputs=[
|
| 41 |
gr.Textbox(label="Circuit Info"),
|
| 42 |
gr.Image(type="filepath", label="Circuit Image"),
|
|
|
|
| 43 |
],
|
| 44 |
title="Quantum Circuit Visualizer",
|
| 45 |
description="Visualize circuits from the module or generate a randomized quantum circuit.",
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import pennylane as qml
|
| 3 |
from circuit_builder import CircuitManager, circuits
|
| 4 |
from circuit_builder.circuits_helpers import visualize_circuit, build_quantum_circuit
|
| 5 |
+
from circuit_builder.noisy_circuit import NoisyCircuit
|
| 6 |
+
|
| 7 |
|
| 8 |
def run_selected_circuit(circuit_index, randomize=False):
|
| 9 |
"""
|
|
|
|
| 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.",
|
src/circuit_builder/circuit_manager.py
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
|
|
|
|
|
| 1 |
import pennylane as qml
|
| 2 |
from pennylane import numpy as np
|
| 3 |
from circuit_builder.duckdb_dao import DuckDBDAO
|
| 4 |
import matplotlib.pyplot as plt
|
|
|
|
| 5 |
from circuit_builder.noisy_circuit import NoisyCircuit
|
| 6 |
import json
|
|
|
|
| 7 |
|
| 8 |
class CircuitManager:
|
| 9 |
"""
|
|
@@ -11,16 +15,17 @@ class CircuitManager:
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
|
| 14 |
-
def __init__(self, db_path=':memory:', device_name='default.
|
| 15 |
"""
|
| 16 |
Args:
|
| 17 |
db_path (str): Path to the DuckDB database file.
|
| 18 |
device_name (str): The name of the quantum device (simulator or hardware backend).
|
| 19 |
noise_types (list): A list of noise model classes to apply to the circuits.
|
| 20 |
-
mitigation_strategy (
|
| 21 |
"""
|
| 22 |
self.db = DuckDBDAO(db_path)
|
| 23 |
self.device_name = device_name
|
|
|
|
| 24 |
self.noise_types = noise_types or []
|
| 25 |
self.mitigation_strategy = mitigation_strategy
|
| 26 |
|
|
@@ -34,7 +39,7 @@ class CircuitManager:
|
|
| 34 |
circuit_name (str): Name of the circuit.
|
| 35 |
wires (list): Wires used in the circuit.
|
| 36 |
"""
|
| 37 |
-
dev = qml.device(self.device_name, wires=len(wires))
|
| 38 |
noisy_circuit = NoisyCircuit(dev, self.noise_types)
|
| 39 |
|
| 40 |
# Define the noiseless circuit
|
|
@@ -57,7 +62,7 @@ class CircuitManager:
|
|
| 57 |
circuit_id = self.db.insert_original_circuit(noiseless_qasm, result_json)
|
| 58 |
|
| 59 |
# Run the noisy circuit
|
| 60 |
-
noisy_qnode = noisy_circuit.noisy_qnode(circuit_func, wires)
|
| 61 |
noisy_result = noisy_qnode(*params)
|
| 62 |
# Convert noise types data to JSON, list if PennyLane's noise to dict
|
| 63 |
noisy_types_json = noise_types_to_json(self.noise_types)
|
|
@@ -68,10 +73,21 @@ class CircuitManager:
|
|
| 68 |
|
| 69 |
# Apply error mitigation (if provided)
|
| 70 |
if self.mitigation_strategy:
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
else:
|
| 76 |
mitigated_result = None
|
| 77 |
|
|
@@ -84,81 +100,74 @@ class CircuitManager:
|
|
| 84 |
print("-" * 30)
|
| 85 |
|
| 86 |
|
|
|
|
|
|
|
|
|
|
| 87 |
def circuit_1(params):
|
| 88 |
"""Basic RX-RZ-RY circuit."""
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
return circuit
|
| 94 |
|
| 95 |
|
| 96 |
def circuit_2(params):
|
| 97 |
"""Bell state circuit."""
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
return circuit
|
| 102 |
|
| 103 |
|
| 104 |
def circuit_3(params):
|
| 105 |
"""Simple entangled state."""
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
return circuit
|
| 111 |
|
| 112 |
|
| 113 |
def circuit_4(params):
|
| 114 |
"""GHZ state preparation."""
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
return circuit
|
| 120 |
|
| 121 |
|
| 122 |
def circuit_5(params):
|
| 123 |
"""Arbitrary single-qubit rotations."""
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
return circuit
|
| 127 |
|
| 128 |
|
| 129 |
def circuit_6(params):
|
| 130 |
"""Variational Ansatz."""
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
return circuit
|
| 134 |
|
| 135 |
|
| 136 |
def circuit_7(params):
|
| 137 |
"""Quantum Fourier Transform (QFT) circuit."""
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
return circuit
|
| 141 |
|
| 142 |
|
| 143 |
def circuit_8(params):
|
| 144 |
"""Amplitude Embedding Circuit."""
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
return circuit
|
| 148 |
|
| 149 |
|
| 150 |
def circuit_9(params):
|
| 151 |
"""Angle Embedding Circuit."""
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
return circuit
|
| 155 |
|
| 156 |
|
| 157 |
def circuit_10(params):
|
| 158 |
"""Strongly Entangling Layers."""
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
return circuit
|
| 162 |
|
| 163 |
|
| 164 |
|
|
@@ -175,6 +184,19 @@ circuits = [
|
|
| 175 |
(circuit_9, [np.random.rand(3)], "Circuit_9", [0, 1, 2]),
|
| 176 |
(circuit_10, [np.random.rand(2, 3, 3)], "Circuit_10", [0, 1, 2]),
|
| 177 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
|
| 180 |
def noise_types_to_json(noise_types):
|
|
@@ -198,13 +220,21 @@ def noise_types_to_json(noise_types):
|
|
| 198 |
|
| 199 |
if __name__ == "__main__":
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
# Initialize CircuitManager
|
| 202 |
manager = CircuitManager(
|
| 203 |
db_path="quantum_circuits.duckdb",
|
|
|
|
|
|
|
|
|
|
| 204 |
noise_types=[
|
| 205 |
-
(
|
| 206 |
-
(
|
| 207 |
-
(
|
| 208 |
],
|
| 209 |
)
|
| 210 |
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from mitiq import zne
|
| 3 |
import pennylane as qml
|
| 4 |
from pennylane import numpy as np
|
| 5 |
from circuit_builder.duckdb_dao import DuckDBDAO
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
+
from pennylane_cirq import ops as cirq_ops
|
| 8 |
from circuit_builder.noisy_circuit import NoisyCircuit
|
| 9 |
import json
|
| 10 |
+
from mitiq.zne.scaling import fold_gates_at_random
|
| 11 |
|
| 12 |
class CircuitManager:
|
| 13 |
"""
|
|
|
|
| 15 |
"""
|
| 16 |
|
| 17 |
|
| 18 |
+
def __init__(self, db_path=':memory:', device_name='default.qubit', noise_types=None, mitigation_strategy=False, use_qasm=False):
|
| 19 |
"""
|
| 20 |
Args:
|
| 21 |
db_path (str): Path to the DuckDB database file.
|
| 22 |
device_name (str): The name of the quantum device (simulator or hardware backend).
|
| 23 |
noise_types (list): A list of noise model classes to apply to the circuits.
|
| 24 |
+
mitigation_strategy (bool): A function implementing the error mitigation strategy.
|
| 25 |
"""
|
| 26 |
self.db = DuckDBDAO(db_path)
|
| 27 |
self.device_name = device_name
|
| 28 |
+
self.use_qasm = use_qasm
|
| 29 |
self.noise_types = noise_types or []
|
| 30 |
self.mitigation_strategy = mitigation_strategy
|
| 31 |
|
|
|
|
| 39 |
circuit_name (str): Name of the circuit.
|
| 40 |
wires (list): Wires used in the circuit.
|
| 41 |
"""
|
| 42 |
+
dev = qml.device(self.device_name, wires=len(wires), shots=1000)
|
| 43 |
noisy_circuit = NoisyCircuit(dev, self.noise_types)
|
| 44 |
|
| 45 |
# Define the noiseless circuit
|
|
|
|
| 62 |
circuit_id = self.db.insert_original_circuit(noiseless_qasm, result_json)
|
| 63 |
|
| 64 |
# Run the noisy circuit
|
| 65 |
+
noisy_qnode = noisy_circuit.noisy_qnode(circuit_func, wires, self.use_qasm)
|
| 66 |
noisy_result = noisy_qnode(*params)
|
| 67 |
# Convert noise types data to JSON, list if PennyLane's noise to dict
|
| 68 |
noisy_types_json = noise_types_to_json(self.noise_types)
|
|
|
|
| 73 |
|
| 74 |
# Apply error mitigation (if provided)
|
| 75 |
if self.mitigation_strategy:
|
| 76 |
+
extrapolate = zne.RichardsonFactory(scale_factors=[1.0, 2.0, 3.0]).extrapolate
|
| 77 |
+
folding = fold_gates_at_random
|
| 78 |
+
|
| 79 |
+
mitigated_circuit = qml.transforms.mitigate_with_zne(
|
| 80 |
+
noisy_qnode,
|
| 81 |
+
scale_factors=[1.0, 2.0, 3.0],
|
| 82 |
+
folding=folding,
|
| 83 |
+
extrapolate=extrapolate,
|
| 84 |
)
|
| 85 |
+
|
| 86 |
+
mitigated_result = mitigated_circuit(*params)
|
| 87 |
+
print(mitigated_result)
|
| 88 |
+
# self.db.insert_mitigated_circuit(
|
| 89 |
+
# 1, noiseless_qasm, "MitigationStrategy", {"expectation_value": mitigated_result}
|
| 90 |
+
# )
|
| 91 |
else:
|
| 92 |
mitigated_result = None
|
| 93 |
|
|
|
|
| 100 |
print("-" * 30)
|
| 101 |
|
| 102 |
|
| 103 |
+
def circuit_0(params):
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
def circuit_1(params):
|
| 107 |
"""Basic RX-RZ-RY circuit."""
|
| 108 |
+
qml.RX(params[0], wires=0)
|
| 109 |
+
qml.RZ(params[1], wires=1)
|
| 110 |
+
qml.RY(params[2], wires=2)
|
| 111 |
+
|
|
|
|
| 112 |
|
| 113 |
|
| 114 |
def circuit_2(params):
|
| 115 |
"""Bell state circuit."""
|
| 116 |
+
qml.Hadamard(wires=0)
|
| 117 |
+
qml.CNOT(wires=[0, 1])
|
| 118 |
+
|
|
|
|
| 119 |
|
| 120 |
|
| 121 |
def circuit_3(params):
|
| 122 |
"""Simple entangled state."""
|
| 123 |
+
qml.Hadamard(wires=0)
|
| 124 |
+
qml.CNOT(wires=[0, 1])
|
| 125 |
+
qml.RX(params[0], wires=0)
|
| 126 |
+
|
|
|
|
| 127 |
|
| 128 |
|
| 129 |
def circuit_4(params):
|
| 130 |
"""GHZ state preparation."""
|
| 131 |
+
qml.Hadamard(wires=0)
|
| 132 |
+
qml.CNOT(wires=[0, 1])
|
| 133 |
+
qml.CNOT(wires=[1, 2])
|
| 134 |
+
|
|
|
|
| 135 |
|
| 136 |
|
| 137 |
def circuit_5(params):
|
| 138 |
"""Arbitrary single-qubit rotations."""
|
| 139 |
+
qml.Rot(params[0], params[1], params[2], wires=0).decomposition()
|
| 140 |
+
|
|
|
|
| 141 |
|
| 142 |
|
| 143 |
def circuit_6(params):
|
| 144 |
"""Variational Ansatz."""
|
| 145 |
+
qml.templates.BasicEntanglerLayers(params, wires=[0, 1, 2]).decomposition()
|
| 146 |
+
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
def circuit_7(params):
|
| 150 |
"""Quantum Fourier Transform (QFT) circuit."""
|
| 151 |
+
qml.QFT(wires=[0, 1, 2]).decomposition()
|
| 152 |
+
|
|
|
|
| 153 |
|
| 154 |
|
| 155 |
def circuit_8(params):
|
| 156 |
"""Amplitude Embedding Circuit."""
|
| 157 |
+
qml.templates.AmplitudeEmbedding(params, wires=[0, 1], normalize=True).decomposition()
|
| 158 |
+
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
def circuit_9(params):
|
| 162 |
"""Angle Embedding Circuit."""
|
| 163 |
+
qml.templates.AngleEmbedding(params, wires=[0, 1, 2]).decomposition()
|
| 164 |
+
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
def circuit_10(params):
|
| 168 |
"""Strongly Entangling Layers."""
|
| 169 |
+
qml.templates.StronglyEntanglingLayers(params, wires=[0, 1, 2]).decomposition()
|
| 170 |
+
|
|
|
|
| 171 |
|
| 172 |
|
| 173 |
|
|
|
|
| 184 |
(circuit_9, [np.random.rand(3)], "Circuit_9", [0, 1, 2]),
|
| 185 |
(circuit_10, [np.random.rand(2, 3, 3)], "Circuit_10", [0, 1, 2]),
|
| 186 |
]
|
| 187 |
+
# circuits = [
|
| 188 |
+
# (circuit_0, [np.array([1, 1, 1])], "Circuit_0", [0, 1, 2]),
|
| 189 |
+
# (circuit_1, [np.array([math.pi, 0, 0])], "Circuit_1", [0, 1, 2]),
|
| 190 |
+
# # (circuit_2, [np.array([])], "Circuit_2", [0, 1]),
|
| 191 |
+
# # (circuit_3, [np.array([0])], "Circuit_3", [0, 1]),
|
| 192 |
+
# # (circuit_4, [np.array([])], "Circuit_4", [0, 1, 2]),
|
| 193 |
+
# # (circuit_5, [np.array([0, 0, 0])], "Circuit_5", [0]),
|
| 194 |
+
# # (circuit_6, [np.random.rand(3, 3)], "Circuit_6", [0, 1, 2]),
|
| 195 |
+
# # (circuit_7, [np.array([])], "Circuit_7", [0, 1, 2]),
|
| 196 |
+
# # (circuit_8, [np.random.rand(4)], "Circuit_8", [0, 1]),
|
| 197 |
+
# # (circuit_9, [np.random.rand(3)], "Circuit_9", [0, 1, 2]),
|
| 198 |
+
# # (circuit_10, [np.random.rand(0, 0, 0)], "Circuit_10", [0, 1, 2]),
|
| 199 |
+
# ]
|
| 200 |
|
| 201 |
|
| 202 |
def noise_types_to_json(noise_types):
|
|
|
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
|
| 223 |
+
device_name = "cirq.mixedsimulator"
|
| 224 |
+
use_qasm = False
|
| 225 |
+
mitigation_strategy = True
|
| 226 |
+
|
| 227 |
+
|
| 228 |
# Initialize CircuitManager
|
| 229 |
manager = CircuitManager(
|
| 230 |
db_path="quantum_circuits.duckdb",
|
| 231 |
+
use_qasm=use_qasm,
|
| 232 |
+
device_name=device_name,
|
| 233 |
+
mitigation_strategy=mitigation_strategy,
|
| 234 |
noise_types=[
|
| 235 |
+
(cirq_ops.BitFlip, {"prob": 0.05}),
|
| 236 |
+
(cirq_ops.PhaseFlip, {"prob": 0.05}),
|
| 237 |
+
# (cirq_ops.DepolarizingChannel, {"prob": 0.05}),
|
| 238 |
],
|
| 239 |
)
|
| 240 |
|
src/circuit_builder/circuits_helpers.py
CHANGED
|
@@ -2,15 +2,17 @@ import pennylane as qml
|
|
| 2 |
from pennylane import numpy as np
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
|
|
|
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
fig_bg_color="lightblue", ax_bg_color="whitesmoke",
|
| 8 |
text_color="darkblue", font_size=12, save_path=None):
|
| 9 |
"""
|
| 10 |
Visualize a quantum circuit with customizable styling options.
|
| 11 |
|
| 12 |
Args:
|
| 13 |
-
|
| 14 |
params (array): Parameters to pass to the quantum node.
|
| 15 |
title (str): Title for the circuit diagram.
|
| 16 |
fig_bg_color (str): Background color for the figure.
|
|
@@ -23,7 +25,7 @@ def visualize_circuit(qnode, params, title="Quantum Circuit Visualization",
|
|
| 23 |
None: Displays or saves the circuit visualization.
|
| 24 |
"""
|
| 25 |
# Generate the matplotlib figure
|
| 26 |
-
fig, ax = qml.draw_mpl(
|
| 27 |
|
| 28 |
# Customize the figure
|
| 29 |
fig.patch.set_facecolor(fig_bg_color)
|
|
@@ -43,7 +45,7 @@ def visualize_circuit(qnode, params, title="Quantum Circuit Visualization",
|
|
| 43 |
plt.show()
|
| 44 |
|
| 45 |
|
| 46 |
-
def build_quantum_circuit(circuit_info, device_name="default.qubit"):
|
| 47 |
"""
|
| 48 |
Build and execute a quantum circuit.
|
| 49 |
|
|
@@ -58,16 +60,18 @@ def build_quantum_circuit(circuit_info, device_name="default.qubit"):
|
|
| 58 |
|
| 59 |
# Create a device
|
| 60 |
dev = qml.device(device_name, wires=len(wires))
|
|
|
|
|
|
|
| 61 |
|
| 62 |
# Define a QNode
|
| 63 |
@qml.qnode(dev)
|
| 64 |
def quantum_circuit(*params):
|
| 65 |
# Call the circuit function and apply the gates
|
| 66 |
-
circuit_func(*params)
|
| 67 |
# Return the expectation values of PauliZ for all wires
|
| 68 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 69 |
|
| 70 |
-
return quantum_circuit
|
| 71 |
|
| 72 |
|
| 73 |
from circuit_builder.circuit_manager import circuits
|
|
|
|
| 2 |
from pennylane import numpy as np
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
|
| 5 |
+
from circuit_builder.noisy_circuit import NoisyCircuit
|
| 6 |
|
| 7 |
+
|
| 8 |
+
def visualize_circuit(qnode_func, params, title="Quantum Circuit Visualization",
|
| 9 |
fig_bg_color="lightblue", ax_bg_color="whitesmoke",
|
| 10 |
text_color="darkblue", font_size=12, save_path=None):
|
| 11 |
"""
|
| 12 |
Visualize a quantum circuit with customizable styling options.
|
| 13 |
|
| 14 |
Args:
|
| 15 |
+
qnode_func: The quantum node representing the circuit.
|
| 16 |
params (array): Parameters to pass to the quantum node.
|
| 17 |
title (str): Title for the circuit diagram.
|
| 18 |
fig_bg_color (str): Background color for the figure.
|
|
|
|
| 25 |
None: Displays or saves the circuit visualization.
|
| 26 |
"""
|
| 27 |
# Generate the matplotlib figure
|
| 28 |
+
fig, ax = qml.draw_mpl(qnode_func)(params)
|
| 29 |
|
| 30 |
# Customize the figure
|
| 31 |
fig.patch.set_facecolor(fig_bg_color)
|
|
|
|
| 45 |
plt.show()
|
| 46 |
|
| 47 |
|
| 48 |
+
def build_quantum_circuit(circuit_info, noises=None, device_name="default.qubit"):
|
| 49 |
"""
|
| 50 |
Build and execute a quantum circuit.
|
| 51 |
|
|
|
|
| 60 |
|
| 61 |
# Create a device
|
| 62 |
dev = qml.device(device_name, wires=len(wires))
|
| 63 |
+
noisy_circuit = NoisyCircuit(dev, noises)
|
| 64 |
+
noisy_qnode = noisy_circuit.noisy_qnode(circuit_func, wires)
|
| 65 |
|
| 66 |
# Define a QNode
|
| 67 |
@qml.qnode(dev)
|
| 68 |
def quantum_circuit(*params):
|
| 69 |
# Call the circuit function and apply the gates
|
| 70 |
+
circuit_func(*params)
|
| 71 |
# Return the expectation values of PauliZ for all wires
|
| 72 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 73 |
|
| 74 |
+
return quantum_circuit, noisy_qnode
|
| 75 |
|
| 76 |
|
| 77 |
from circuit_builder.circuit_manager import circuits
|
src/circuit_builder/noisy_circuit.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import pennylane as qml
|
| 2 |
from pennylane import numpy as np
|
| 3 |
from typing import Callable, List, Tuple
|
|
@@ -34,30 +36,84 @@ class NoisyCircuit:
|
|
| 34 |
Returns:
|
| 35 |
callable: Noisy quantum circuit without measuring.
|
| 36 |
"""
|
|
|
|
| 37 |
def noisy_circuit(*params):
|
| 38 |
circuit(*params)
|
| 39 |
for wire in wires:
|
| 40 |
for noise_op, noise_params in self.noise_operations:
|
| 41 |
-
|
| 42 |
-
|
| 43 |
return noisy_circuit
|
| 44 |
|
| 45 |
-
def
|
| 46 |
"""
|
| 47 |
-
|
| 48 |
|
| 49 |
Args:
|
| 50 |
circuit (Callable): The quantum circuit function to add noise to.
|
| 51 |
wires (List[int]): List of wires where noise will be applied.
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
Returns:
|
| 54 |
qml.QNode: A noisy quantum circuit with expected value measurements.
|
| 55 |
"""
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
@qml.qnode(self.device)
|
| 59 |
def qnode(*params):
|
| 60 |
noisy_circuit(*params)
|
| 61 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 62 |
|
| 63 |
-
return qnode
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
|
| 3 |
import pennylane as qml
|
| 4 |
from pennylane import numpy as np
|
| 5 |
from typing import Callable, List, Tuple
|
|
|
|
| 36 |
Returns:
|
| 37 |
callable: Noisy quantum circuit without measuring.
|
| 38 |
"""
|
| 39 |
+
|
| 40 |
def noisy_circuit(*params):
|
| 41 |
circuit(*params)
|
| 42 |
for wire in wires:
|
| 43 |
for noise_op, noise_params in self.noise_operations:
|
| 44 |
+
noise_op(noise_params["prob"], wires=wire)
|
| 45 |
+
|
| 46 |
return noisy_circuit
|
| 47 |
|
| 48 |
+
def add_qasm_noise(self, circuit: Callable, wires: List[int]):
|
| 49 |
"""
|
| 50 |
+
Dynamically adds specified noise channels compatible with OpenQASM export.
|
| 51 |
|
| 52 |
Args:
|
| 53 |
circuit (Callable): The quantum circuit function to add noise to.
|
| 54 |
wires (List[int]): List of wires where noise will be applied.
|
| 55 |
|
| 56 |
+
Returns:
|
| 57 |
+
callable: Noisy quantum circuit compatible with OpenQASM export.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def noisy_circuit(*params):
|
| 61 |
+
circuit(*params) # Apply the original circuit
|
| 62 |
+
|
| 63 |
+
for noise, noise_params in self.noise_operations:
|
| 64 |
+
prob = noise_params.get("prob", 0.0)
|
| 65 |
+
|
| 66 |
+
if noise.__name__ == "BitFlip":
|
| 67 |
+
for wire in wires:
|
| 68 |
+
if random.random() < prob:
|
| 69 |
+
qml.PauliX(wires=wire)
|
| 70 |
+
|
| 71 |
+
elif noise.__name__ == "PhaseFlip":
|
| 72 |
+
for wire in wires:
|
| 73 |
+
if random.random() < prob:
|
| 74 |
+
qml.PauliZ(wires=wire)
|
| 75 |
+
|
| 76 |
+
elif noise.__name__ == "DepolarizingChannel":
|
| 77 |
+
|
| 78 |
+
for wire in wires:
|
| 79 |
+
if random.random() < prob:
|
| 80 |
+
# Apply probabilistic X
|
| 81 |
+
qml.PauliX(wires=wire)
|
| 82 |
+
|
| 83 |
+
if random.random() < prob:
|
| 84 |
+
# Apply probabilistic Y
|
| 85 |
+
qml.PauliY(wires=wire)
|
| 86 |
+
|
| 87 |
+
if random.random() < prob:
|
| 88 |
+
# Apply probabilistic Z
|
| 89 |
+
qml.PauliZ(wires=wire)
|
| 90 |
+
|
| 91 |
+
else:
|
| 92 |
+
raise ValueError(f"Unsupported noise type: {noise.__name__}")
|
| 93 |
+
|
| 94 |
+
return
|
| 95 |
+
|
| 96 |
+
return noisy_circuit
|
| 97 |
+
|
| 98 |
+
def noisy_qnode(self, circuit: Callable, wires: List[int], use_qasm: bool = True):
|
| 99 |
+
"""
|
| 100 |
+
Converts the noisy circuit into a QNode with expected value measurement.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
circuit (Callable): The quantum circuit function to add noise to.
|
| 104 |
+
wires (List[int]): List of wires where noise will be applied.
|
| 105 |
+
use_qasm (bool): Whether to use qasm or not.
|
| 106 |
Returns:
|
| 107 |
qml.QNode: A noisy quantum circuit with expected value measurements.
|
| 108 |
"""
|
| 109 |
+
if use_qasm:
|
| 110 |
+
noisy_circuit = self.add_qasm_noise(circuit, wires)
|
| 111 |
+
else:
|
| 112 |
+
noisy_circuit = self.add_noise(circuit, wires)
|
| 113 |
|
| 114 |
@qml.qnode(self.device)
|
| 115 |
def qnode(*params):
|
| 116 |
noisy_circuit(*params)
|
| 117 |
return [qml.expval(qml.PauliZ(w)) for w in wires]
|
| 118 |
|
| 119 |
+
return qnode
|