Dvirmor100 commited on
Commit
fc34b65
·
1 Parent(s): 94a1e47

refactor(circuits): remove, reorganize and merge the circuit builder module

Browse files
src/circuit_builder/__init__.py DELETED
@@ -1 +0,0 @@
1
- from .circuit_manager import CircuitManager, circuits
 
 
src/circuit_builder/circuit_manager.py DELETED
@@ -1,243 +0,0 @@
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
- """
14
- Manages circuit execution, optional noise injection, and optional error mitigation.
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
-
32
- def run_circuit(self, circuit_func, params, circuit_name, wires):
33
- """
34
- Execute a circuit, adding noise and applying optional mitigation.
35
-
36
- Args:
37
- circuit_func (callable): Circuit function to execute.
38
- params (list): Parameters to pass to the circuit.
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
46
- @qml.qnode(dev)
47
- def get_expectation_value(*params):
48
- # Call the circuit function to apply the gates
49
- circuit_func(*params)
50
- # Return the expectation values of PauliZ for all wires
51
- return [qml.expval(qml.PauliZ(w)) for w in wires]
52
-
53
-
54
- # Run the noiseless circuit
55
- noiseless_result = get_expectation_value(*params)
56
- # Convert tensors to raw Python floats
57
- result_json = json.dumps({
58
- "expectation_values": [float(value) for value in noiseless_result]
59
- })
60
-
61
- noiseless_qasm = get_expectation_value.qtape.to_openqasm()
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)
69
- noisy_result_json = json.dumps({
70
- "expectation_values": [float(value) for value in noisy_result]
71
- })
72
- self.db.insert_noisy_circuit(circuit_id, noisy_types_json, noisy_result_json)
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
-
94
- # Display results
95
- print(f"Circuit: {circuit_name}")
96
- print(f"Noiseless Result: {result_json}")
97
- print(f"Noisy Result: {noisy_result_json}")
98
- if mitigated_result:
99
- print(f"Mitigated Result: {mitigated_result}")
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
-
174
- # Circuit list with parameter details
175
- circuits = [
176
- (circuit_1, [np.array([0.1, 0.2, 0.3])], "Circuit_1", [0, 1, 2]),
177
- (circuit_2, [np.array([])], "Circuit_2", [0, 1]),
178
- (circuit_3, [np.array([0.5])], "Circuit_3", [0, 1]),
179
- (circuit_4, [np.array([])], "Circuit_4", [0, 1, 2]),
180
- (circuit_5, [np.array([0.3, 0.2, 0.1])], "Circuit_5", [0]),
181
- (circuit_6, [np.random.rand(3, 3)], "Circuit_6", [0, 1, 2]),
182
- (circuit_7, [np.array([])], "Circuit_7", [0, 1, 2]),
183
- (circuit_8, [np.random.rand(4)], "Circuit_8", [0, 1]),
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):
203
- """
204
- Convert a list of noise operations and their parameters into JSON format.
205
-
206
- Args:
207
- noise_types (list): A list of tuples where each tuple contains a noise operation
208
- (e.g., qml.BitFlip) and a dictionary of parameters.
209
-
210
- Returns:
211
- str: A JSON-formatted string representing the noise types and their parameters.
212
- """
213
- noise_list = []
214
- for noise_op, params in noise_types:
215
- noise_list.append({
216
- "operation": noise_op.__name__, # Convert the noise operation to its name
217
- "parameters": params # Keep the parameters as they are
218
- })
219
- return json.dumps(noise_list, indent=4) # Serialize the list to a JSON string with indentation
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
-
241
- # Execute all circuits
242
- for circuit_func, params, name, wires in circuits:
243
- manager.run_circuit(circuit_func, params, name, wires)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/circuit_builder/circuits_helpers.py DELETED
@@ -1,91 +0,0 @@
1
- import pennylane as qml
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.
19
- ax_bg_color (str): Background color for the axis.
20
- text_color (str): Color for the text labels.
21
- font_size (int): Font size for the text labels.
22
- save_path (str): File path to save the visualization (optional).
23
-
24
- Returns:
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)
32
- ax.set_facecolor(ax_bg_color)
33
-
34
- # Customize text labels
35
- for text in ax.texts:
36
- text.set_color(text_color)
37
- text.set_fontsize(font_size)
38
-
39
- # Add title
40
- ax.set_title(title, color=text_color, fontsize=font_size + 2)
41
-
42
- if save_path:
43
- fig.savefig(save_path, dpi=300, bbox_inches="tight")
44
- else:
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
-
52
- Parameters:
53
- circuit_info (tuple): A tuple containing (circuit_function, params, name, wires).
54
- device_name (str): Name of the device to use.
55
-
56
- Returns:
57
- function: A QNode function that evaluates the expectation values.
58
- """
59
- circuit_func, params, name, wires = circuit_info
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
78
-
79
- if __name__ == "__main__":
80
- circuit_func, params, name, wires = circuits[0]
81
-
82
- # Build the quantum circuit
83
- constructed_circuit = build_quantum_circuit((circuit_func, params, name, wires))
84
-
85
- # Execute the circuit
86
- result = constructed_circuit(*params)
87
- print("Expectation values:", result)
88
-
89
- # Visualize the circuit
90
- visualize_circuit(constructed_circuit, *params, title="My Quantum Circuit",
91
- save_path=None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/circuit_builder/duckdb_dao.py DELETED
@@ -1,146 +0,0 @@
1
- import duckdb
2
- import json
3
-
4
-
5
- class DuckDBDAO:
6
- """
7
- A DAO (Data Access Object) for storing and retrieving quantum circuit data in DuckDB,
8
- using a JSON 'result' column. This lets you store arbitrary metrics as JSON,
9
- such as expected_value, fidelity, or any other key-value data.
10
-
11
- Tables managed:
12
- 1) original_circuits -> (original_id, qasm, result)
13
- 2) noisy_circuits -> (noisy_id, original_id, noise_data, result)
14
- 3) mitigated_circuits -> (mitigated_id, noisy_id, result, mitigation_strategy)
15
- """
16
-
17
- def __init__(self, db_path=':memory:'):
18
- self.db_path = db_path
19
- self.conn = duckdb.connect(self.db_path)
20
- self._create_sequences()
21
- self._create_tables()
22
-
23
- def _create_sequences(self):
24
- """Create sequences for auto-incremented primary keys."""
25
- self.conn.execute("CREATE SEQUENCE IF NOT EXISTS original_circuits_seq START 1;")
26
- self.conn.execute("CREATE SEQUENCE IF NOT EXISTS noisy_circuits_seq START 1;")
27
- self.conn.execute("CREATE SEQUENCE IF NOT EXISTS mitigated_circuits_seq START 1;")
28
-
29
- def _create_tables(self):
30
- """Create required tables for circuit management."""
31
- self.conn.execute("""
32
- CREATE TABLE IF NOT EXISTS original_circuits (
33
- original_id INTEGER PRIMARY KEY DEFAULT nextval('original_circuits_seq'),
34
- qasm TEXT NOT NULL,
35
- result JSON
36
- );
37
- """)
38
- self.conn.execute("""
39
- CREATE TABLE IF NOT EXISTS noisy_circuits (
40
- noisy_id INTEGER PRIMARY KEY DEFAULT nextval('noisy_circuits_seq'),
41
- original_id INTEGER NOT NULL,
42
- noise_data JSON NOT NULL,
43
- result JSON,
44
- FOREIGN KEY (original_id) REFERENCES original_circuits(original_id)
45
- );
46
- """)
47
- self.conn.execute("""
48
- CREATE TABLE IF NOT EXISTS mitigated_circuits (
49
- mitigated_id INTEGER PRIMARY KEY DEFAULT nextval('mitigated_circuits_seq'),
50
- noisy_id INTEGER NOT NULL,
51
- result JSON,
52
- mitigation_strategy TEXT NOT NULL,
53
- FOREIGN KEY (noisy_id) REFERENCES noisy_circuits(noisy_id)
54
- );
55
- """)
56
-
57
- def insert_original_circuit(self, qasm: str, result: dict = None):
58
- """Insert an original circuit and return its ID."""
59
- result_json = json.dumps(result) if result else None
60
- query = """
61
- INSERT INTO original_circuits (qasm, result) VALUES (?, ?)
62
- RETURNING original_id;
63
- """
64
- row = self.conn.execute(query, [qasm, result_json]).fetchone()
65
- return row[0]
66
-
67
- def insert_noisy_circuit(self, original_id: int, noise_data: dict, result: dict = None):
68
- """Insert a noisy circuit and return its ID."""
69
- noise_data_json = json.dumps(noise_data)
70
- result_json = json.dumps(result) if result else None
71
- query = """
72
- INSERT INTO noisy_circuits (original_id, noise_data, result) VALUES (?, ?, ?)
73
- RETURNING noisy_id;
74
- """
75
- row = self.conn.execute(query, [original_id, noise_data_json, result_json]).fetchone()
76
- return row[0]
77
-
78
- def insert_mitigated_circuit(self, noisy_id: int, mitigation_strategy: str, result: dict = None):
79
- """Insert a mitigated circuit and return its ID."""
80
- result_json = json.dumps(result) if result else None
81
- query = """
82
- INSERT INTO mitigated_circuits (noisy_id, result, mitigation_strategy) VALUES (?, ?, ?)
83
- RETURNING mitigated_id;
84
- """
85
- row = self.conn.execute(query, [noisy_id, result_json, mitigation_strategy]).fetchone()
86
- return row[0]
87
-
88
- def get_by_qasm(self, qasm: str):
89
- """Retrieve all circuits by their QASM representation."""
90
- query = """
91
- SELECT * FROM original_circuits WHERE qasm = ?;
92
- """
93
- rows = self.conn.execute(query, [qasm]).fetchall()
94
- return [
95
- {'original_id': row[0], 'qasm': row[1], 'result': json.loads(row[2]) if row[2] else None}
96
- for row in rows
97
- ]
98
-
99
- def get_by_qasm_with_noise(self, qasm: str, noise_data: dict):
100
- """Retrieve noisy circuits by QASM and noise data."""
101
- noise_data_json = json.dumps(noise_data)
102
- query = """
103
- SELECT nc.noisy_id, nc.result, nc.noise_data
104
- FROM noisy_circuits nc
105
- INNER JOIN original_circuits oc ON nc.original_id = oc.original_id
106
- WHERE oc.qasm = ? AND nc.noise_data = ?;
107
- """
108
- rows = self.conn.execute(query, [qasm, noise_data_json]).fetchall()
109
- return [
110
- {'noisy_id': row[0], 'result': json.loads(row[1]) if row[1] else None, 'noise_data': json.loads(row[2])}
111
- for row in rows
112
- ]
113
-
114
- def get_original_circuit(self, original_id: int):
115
- """Retrieve an original circuit by its ID."""
116
- query = "SELECT * FROM original_circuits WHERE original_id = ?;"
117
- row = self.conn.execute(query, [original_id]).fetchone()
118
- if row:
119
- return {'original_id': row[0], 'qasm': row[1], 'result': json.loads(row[2]) if row[2] else None}
120
- return None
121
-
122
- def get_noisy_circuit(self, noisy_id: int):
123
- """Retrieve a noisy circuit by its ID."""
124
- query = "SELECT * FROM noisy_circuits WHERE noisy_id = ?;"
125
- row = self.conn.execute(query, [noisy_id]).fetchone()
126
- if row:
127
- return {
128
- 'noisy_id': row[0],
129
- 'original_id': row[1],
130
- 'noise_data': json.loads(row[2]),
131
- 'result': json.loads(row[3]) if row[3] else None
132
- }
133
- return None
134
-
135
- def get_mitigated_circuit(self, mitigated_id: int):
136
- """Retrieve a mitigated circuit by its ID."""
137
- query = "SELECT * FROM mitigated_circuits WHERE mitigated_id = ?;"
138
- row = self.conn.execute(query, [mitigated_id]).fetchone()
139
- if row:
140
- return {
141
- 'mitigated_id': row[0],
142
- 'noisy_id': row[1],
143
- 'result': json.loads(row[2]) if row[2] else None,
144
- 'mitigation_strategy': row[3]
145
- }
146
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/circuit_builder/migration_strategy.py DELETED
@@ -1,77 +0,0 @@
1
- from pennylane import numpy as np
2
- import pennylane as qml
3
- from mitiq import zne
4
- from mitiq.zne.scaling import fold_gates_at_random
5
- from typing import Callable
6
-
7
-
8
- class MitiqPennyLaneWrapper:
9
- """
10
- A wrapper for integrating PennyLane with Mitiq error mitigation techniques.
11
-
12
- Attributes:
13
- n_qubits (int): Number of qubits in the circuit.
14
- device (qml.Device): PennyLane device for circuit execution.
15
- scale_factors (list[float]): Noise scale factors for ZNE.
16
- """
17
-
18
- def __init__(self, n_qubits: int, device: qml.Device, scale_factors: list[float] = [1.0, 2.0, 3.0]):
19
- self.n_qubits = n_qubits
20
- self.device = device
21
- self.scale_factors = scale_factors
22
- self._circuit = None
23
-
24
- def create_circuit(self, circuit_func: Callable[[qml.Device, int], Callable[[float], float]]) -> None:
25
- """
26
- Defines a sample quantum circuit with dependency injection.
27
-
28
- Args:
29
- circuit_func: A callable that takes a PennyLane device and the number of qubits as inputs and returns a quantum circuit function.
30
- """
31
- self._circuit = circuit_func(self.device, self.n_qubits)
32
-
33
- def execute_with_zne(self, gamma: float) -> float:
34
- """
35
- Executes the quantum circuit with Zero-Noise Extrapolation (ZNE).
36
-
37
- Args:
38
- gamma: Variational parameter for the quantum circuit.
39
-
40
- Returns:
41
- float: Mitigated expectation value using ZNE.
42
- """
43
- folding = fold_gates_at_random
44
- extrapolate = zne.RichardsonFactory(scale_factors=self.scale_factors).extrapolate
45
-
46
- mitigated_circuit = qml.transforms.mitigate_with_zne(
47
- self._circuit,
48
- scale_factors=self.scale_factors,
49
- folding=folding,
50
- extrapolate=extrapolate,
51
- )
52
-
53
- return mitigated_circuit(gamma)
54
-
55
- # Example Circuit Function
56
- def example_circuit(device, n_qubits):
57
- @qml.qnode(device)
58
- def circuit(gamma: float):
59
- for i in range(n_qubits):
60
- qml.RX(gamma, wires=i)
61
- qml.CNOT(wires=[0, 1])
62
- return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
63
-
64
- return circuit
65
-
66
- # Example Usage
67
- if __name__ == "__main__":
68
- n_qubits = 2
69
- gamma = 0.1
70
-
71
- device = qml.device("default.qubit", wires=n_qubits)
72
- wrapper = MitiqPennyLaneWrapper(n_qubits=n_qubits, device=device)
73
- wrapper.create_circuit(example_circuit)
74
-
75
- mitigated_result = wrapper.execute_with_zne(gamma)
76
-
77
- print(f"Mitigated Result: {mitigated_result}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/circuit_builder/noisy_circuit.py DELETED
@@ -1,119 +0,0 @@
1
- import random
2
-
3
- import pennylane as qml
4
- from pennylane import numpy as np
5
- from typing import Callable, List, Tuple
6
-
7
-
8
- class NoisyCircuit:
9
- """
10
- A class to add customizable noise to a quantum circuit in PennyLane.
11
-
12
- Attributes:
13
- device (qml.Device): The PennyLane device to run the circuit.
14
- noise_operations (List[Tuple[Callable, dict]]): A list of noise operations and their parameters.
15
- """
16
-
17
- def __init__(self, device: qml.Device, noise_operations: List[Tuple[Callable, dict]] = None):
18
- """
19
- Initializes the NoisyCircuit class.
20
-
21
- Args:
22
- device (qml.Device): The quantum device for circuit execution.
23
- noise_operations (List[Tuple[Callable, dict]]): A list of noise operations with parameters.
24
- """
25
- self.device = device
26
- self.noise_operations = noise_operations if noise_operations else []
27
-
28
- def add_noise(self, circuit: Callable, wires: List[int]):
29
- """
30
- Adds specified noise gates to the circuit and returns the noisy circuit.
31
-
32
- Args:
33
- circuit (Callable): The quantum circuit function to add noise to.
34
- wires (List[int]): List of wires where noise will be applied.
35
-
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/quantum_circuits/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from quantum_circuits.circuit_manager import CircuitManager
src/quantum_circuits/circuit_error_mitigator.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from database.db_handler import extract_circuit_data
3
+ 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(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
8
+ logger = logging.getLogger(__name__)
9
+ logger.setLevel(logging.WARNING)
10
+
11
+ class CircuitErrorMitigator(BaseModel):
12
+ original_qasm: str
13
+ optimized_qasm: str
14
+ noise_data: list
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": circuit_data.noisy_result,
27
+ "results": circuit_data.noiseless_result
28
+ }
29
+
30
+ optimized_qasm = generate_qasm_with_llm(circuit_data_for_llm, is_refine=False, model=model)
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(circuit_data.noisy_result, circuit_data.noiseless_result)
36
+ enhanced_dist = euclidean_distance(optimized_results, circuit_data.noiseless_result)
37
+
38
+ if original_dist < enhanced_dist:
39
+ logger.info("Make a refinement")
40
+ refine_data = {
41
+ "original_qasm": circuit_data.qasm_circuit,
42
+ "enhanced_qasm": optimized_qasm,
43
+ "noisy_operations": circuit_data.noise_data,
44
+ "original_noisy_results": circuit_data.noisy_result,
45
+ "enhanced_noisy_results": optimized_results,
46
+ "results": circuit_data.noiseless_result
47
+ }
48
+ optimized_qasm = generate_qasm_with_llm(refine_data, is_refine=True, model=model)
49
+ refinement_results = run_noisy_qasm(optimized_qasm, circuit_data.noise_data)
50
+ enhanced_dist = euclidean_distance(refinement_results, circuit_data.noiseless_result)
51
+
52
+ return CircuitErrorMitigator(
53
+ original_qasm=circuit_data.qasm_circuit,
54
+ optimized_qasm=optimized_qasm,
55
+ noise_data=circuit_data.noise_data,
56
+ original_distance=original_dist,
57
+ optimized_distance=enhanced_dist,
58
+ )
59
+
60
+
61
+
src/quantum_circuits/circuit_manager.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
13
+
14
+ For each circuit, this class:
15
+ 1. Executes a noiseless circuit and records its expectation values and QASM.
16
+ 2. Generates several noisy variations by randomly selecting noise channels.
17
+ 3. Saves the noiseless and noisy results (plus the noise specifications and QASM, if available)
18
+ in a DuckDB database.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ db_path: str = ":memory:",
24
+ device_name: str = "default.qubit",
25
+ noise_types: Optional[List[Any]] = None,
26
+ use_qasm: bool = False,
27
+ ) -> None:
28
+ """
29
+ Args:
30
+ db_path: Path to the DuckDB database file.
31
+ device_name: The quantum device name.
32
+ noise_types: List of noise model classes to apply (if any).
33
+ use_qasm: Whether to use QASM-based noise injection.
34
+ """
35
+ self.db = DuckDBDAO(db_path)
36
+ self.device_name = device_name
37
+ self.use_qasm = use_qasm
38
+ self.noise_types = noise_types or []
39
+
40
+ @staticmethod
41
+ def get_random_noise_types(wires: List[int], num_noises: int = 2) -> List[Tuple[Callable, float, List[int]]]:
42
+ """
43
+ Randomly selects noise operations from a predefined set and assigns
44
+ random probabilities and target wires.
45
+
46
+ Args:
47
+ wires: List of available system wires.
48
+ num_noises: Maximum number of different noise channels to apply.
49
+
50
+ Returns:
51
+ A list of tuples (noise_op, probability, target_wires).
52
+ """
53
+ possible_noises = [qml.BitFlip, qml.PhaseFlip, qml.AmplitudeDamping, qml.PhaseDamping]
54
+ num_noises = min(num_noises, len(possible_noises))
55
+ selected_noises = []
56
+ for noise_op in random.sample(possible_noises, num_noises):
57
+ prob = random.uniform(0.005, 0.05)
58
+ n_targets = random.randint(1, min(5, len(wires)))
59
+ target_wires = random.sample(wires, n_targets)
60
+ selected_noises.append((noise_op, prob, target_wires))
61
+ return selected_noises
62
+
63
+ def run_circuit(
64
+ self,
65
+ circuit_func: Callable,
66
+ params: Any,
67
+ circuit_name: str,
68
+ wires: List[int],
69
+ num_variations: int = 3,
70
+ ) -> None:
71
+ """
72
+ Runs a noiseless circuit and several noisy variations, then saves results to the database.
73
+
74
+ Args:
75
+ circuit_func: The circuit function that accepts (params, n_qubits).
76
+ params: Parameters for the circuit.
77
+ circuit_name: A name for the circuit.
78
+ wires: List of system wires.
79
+ num_variations: Number of noisy variations to generate.
80
+ """
81
+ # Create a device with specified number of wires and 1000 shots.
82
+ dev = qml.device(self.device_name, wires=len(wires), shots=1000)
83
+
84
+ @qml.qnode(dev)
85
+ def get_z_expectation_value(*params: Any) -> list[ExpectationMP]:
86
+ # Execute the noiseless circuit.
87
+ circuit_func(*params, n_qubits=len(wires))
88
+ # Extra rotation to bias the state.
89
+ for w in wires:
90
+ qml.RZ(0.1, wires=w)
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({"expectation_values": [float(val) for val in noiseless_result]})
95
+ noiseless_qasm = get_z_expectation_value.qtape.to_openqasm()
96
+
97
+ print(f"Circuit: {circuit_name}")
98
+ print("Noiseless Result:", result_json)
99
+ print("-" * 30)
100
+
101
+ # Generate noisy variations.
102
+ for variation in range(num_variations):
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(circuit_func, wires, use_qasm_for_noise)
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({"expectation_values": [float(val) for val in noisy_result]})
110
+ noise_qasm = noisy_qnode.qtape.to_openqasm() if use_qasm_for_noise else None
111
+
112
+ # Save the results in the database.
113
+ self.db.insert_circuit_result(
114
+ noiseless_qasm,
115
+ result_json,
116
+ noisy_types_json,
117
+ noisy_result_json,
118
+ noise_qasm,
119
+ )
120
+
121
+ print(f"Variation {variation + 1} with noise:")
122
+ print(noisy_types_json)
123
+ print("Noisy Result:", noisy_result_json)
124
+ print("-" * 30)
125
+
126
+ @staticmethod
127
+ def noise_types_to_json(noise_types: List[Tuple[Callable, float, List[int]]]) -> str:
128
+ """
129
+ Converts a list of noise operation tuples into a JSON-formatted string.
130
+
131
+ Args:
132
+ noise_types: List of tuples (noise_op, probability, wires).
133
+
134
+ Returns:
135
+ JSON-formatted noise specifications.
136
+ """
137
+ noise_list = [
138
+ {"operation": noise_op.__name__, "probability": prob, "wires": wires}
139
+ for noise_op, prob, wires in noise_types
140
+ ]
141
+ return json.dumps(noise_list, indent=4)
142
+
src/quantum_circuits/noisy_circuit_generator.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pennylane as qml
2
+ from typing import Callable, List, Tuple, Optional
3
+
4
+
5
+ class NoisyCircuit:
6
+ """
7
+ Adds customizable noise to a quantum circuit in PennyLane using either a
8
+ naive noise injection approach or an advanced QASM-based injection.
9
+
10
+ Attributes:
11
+ device (qml.Device): The quantum device.
12
+ noise_operations (List[Tuple[Callable, float, List[int]]]):
13
+ List of noise operations as (noise_gate, probability, target_wires).
14
+ """
15
+
16
+ def __init__(self, device: qml.Device, noise_operations: Optional[List[Tuple[Callable, float, List[int]]]] = None) -> None:
17
+ """
18
+ Args:
19
+ device: The PennyLane quantum device.
20
+ noise_operations: List of noise operations; if None, defaults to an empty list.
21
+ """
22
+ self.device = device
23
+ self.noise_operations = noise_operations if noise_operations is not None else []
24
+
25
+ def add_noise(self, circuit: Callable, wires: List[int]) -> Callable:
26
+ """
27
+ Naively adds the specified noise gates directly to the circuit.
28
+
29
+ Args:
30
+ circuit: The user-defined noiseless circuit function.
31
+ wires: List of system wires on which the circuit acts.
32
+
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)
39
+ # Apply each noise gate to its target wires.
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(self, circuit: Callable, wires: List[int], use_qasm: bool = True) -> qml.QNode:
46
+ """
47
+ Constructs a QNode that applies a noiseless circuit and then injects noise.
48
+
49
+ If use_qasm is True, the advanced QASM-based injection via NoisyQNodeBuilder is used;
50
+ otherwise, a naive approach is taken.
51
+
52
+ Args:
53
+ circuit: The noiseless circuit function.
54
+ wires: List of system wires (e.g. [0, 1]).
55
+ use_qasm: Whether to use QASM-based noise injection. Defaults to True.
56
+
57
+ Returns:
58
+ A QNode that returns expectation values of PauliZ on each system wire.
59
+ """
60
+ if use_qasm:
61
+ return NoisyQNodeBuilder.build_noisy_qnode_with_injections(
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
+ """
81
+ Constructs noisy QNodes by injecting noise channels (via Stinespring dilation)
82
+ into a noiseless circuit.
83
+
84
+ Supported noise channels:
85
+ - BitFlip
86
+ - PhaseFlip
87
+ - PhaseDamping
88
+ - AmplitudeDamping
89
+ - Depolarizing (and alias DepolarizingChannel)
90
+
91
+ The QNode is built on a device whose total wires equal the number of system wires plus
92
+ the ancilla wires required for noise injection.
93
+ """
94
+
95
+ @staticmethod
96
+ def BitFlip(gamma: float, wires: List[int]) -> None:
97
+ """
98
+ Applies a BitFlip noise channel via Stinespring dilation.
99
+ Args:
100
+ gamma: Flip probability.
101
+ wires: [system_wire, ancilla_wire].
102
+ """
103
+ sys_wire, anc_wire = wires
104
+ theta = 2 * np.arcsin(np.sqrt(gamma))
105
+ qml.RY(theta, wires=anc_wire)
106
+ qml.CNOT(wires=[anc_wire, sys_wire])
107
+
108
+ @staticmethod
109
+ def PhaseFlip(gamma: float, wires: List[int]) -> None:
110
+ """
111
+ Applies a PhaseFlip noise channel via Stinespring dilation.
112
+ Args:
113
+ gamma: Noise parameter.
114
+ wires: [system_wire, ancilla_wire].
115
+ """
116
+ sys_wire, anc_wire = wires
117
+ theta = 2 * np.arcsin(np.sqrt(gamma))
118
+ qml.RY(theta, wires=anc_wire)
119
+ qml.CZ(wires=[anc_wire, sys_wire])
120
+
121
+ @staticmethod
122
+ def PhaseDamping(gamma: float, wires: List[int]) -> None:
123
+ """
124
+ Applies a PhaseDamping noise channel via Stinespring dilation.
125
+ Args:
126
+ gamma: Noise parameter.
127
+ wires: [system_wire, ancilla_wire].
128
+ """
129
+ sys_wire, anc_wire = wires
130
+ qml.PauliX(wires=anc_wire)
131
+ qml.CNOT(wires=[anc_wire, sys_wire])
132
+ alpha = 2 * np.arccos(np.sqrt(1 - gamma))
133
+ qml.RZ(alpha, wires=sys_wire)
134
+ qml.CNOT(wires=[anc_wire, sys_wire])
135
+ qml.PauliX(wires=anc_wire)
136
+
137
+ @staticmethod
138
+ def AmplitudeDamping(gamma: float, wires: List[int]) -> None:
139
+ """
140
+ Applies an AmplitudeDamping noise channel using a custom unitary.
141
+ Args:
142
+ gamma: Noise parameter.
143
+ wires: Wires on which to apply the unitary.
144
+ """
145
+ U = np.array([
146
+ [1, 0, 0, 0],
147
+ [0, 1, np.sqrt(gamma), 0],
148
+ [0, 0, np.sqrt(1 - gamma), 0],
149
+ [0, 0, 0, 1]
150
+ ], dtype=complex)
151
+ qml.QubitUnitary(U, wires=wires)
152
+
153
+ @staticmethod
154
+ def Depolarizing(p: float, wires: List[int]) -> None:
155
+ """
156
+ Applies a Depolarizing noise channel via a 3-qubit unitary.
157
+ Args:
158
+ p: Depolarizing probability.
159
+ wires: [system_wire, ancilla1, ancilla2].
160
+ """
161
+ U = NoisyQNodeBuilder._build_depolarizing_3qubit_unitary(p)
162
+ qml.QubitUnitary(U, wires=wires)
163
+
164
+ @staticmethod
165
+ def _build_depolarizing_3qubit_unitary(p: float) -> np.ndarray:
166
+ """
167
+ Constructs an 8x8 unitary for the depolarizing channel.
168
+ Args:
169
+ p: Depolarizing probability.
170
+ Returns:
171
+ 8x8 complex unitary matrix.
172
+ """
173
+ def apply_X(s: int) -> Tuple[int, float]:
174
+ return (1 - s), 1.0
175
+
176
+ def apply_Z(s: int) -> Tuple[int, float]:
177
+ phase = -1.0 if s == 1 else 1.0
178
+ return s, phase
179
+
180
+ def apply_Y(s: int) -> Tuple[int, complex]:
181
+ return (1, 1.0j) if s == 0 else (0, -1.0j)
182
+
183
+ amp_I = np.sqrt(1 - p)
184
+ amp_X = amp_Y = amp_Z = np.sqrt(p / 3)
185
+ U = np.zeros((8, 8), dtype=complex)
186
+
187
+ def idx(s: int, a1: int, a2: int) -> int:
188
+ return 4 * s + 2 * a1 + a2
189
+
190
+ for s in [0, 1]:
191
+ for a1 in [0, 1]:
192
+ for a2 in [0, 1]:
193
+ col = idx(s, a1, a2)
194
+ if (a1, a2) != (0, 0):
195
+ row = idx(s, a1, a2)
196
+ U[row, col] = 1.0
197
+ else:
198
+ U[idx(s, 0, 0), col] += amp_I
199
+ sX, phX = apply_X(s)
200
+ U[idx(sX, 0, 1), col] += amp_X * phX
201
+ sY, phY = apply_Y(s)
202
+ U[idx(sY, 1, 0), col] += amp_Y * phY
203
+ sZ, phZ = apply_Z(s)
204
+ U[idx(sZ, 1, 1), col] += amp_Z * phZ
205
+ return U
206
+
207
+ NOISE_CHANNEL_METHODS: Dict[str, Callable] = {
208
+ "BitFlip": BitFlip.__func__,
209
+ "PhaseFlip": PhaseFlip.__func__,
210
+ "PhaseDamping": PhaseDamping.__func__,
211
+ "AmplitudeDamping": AmplitudeDamping.__func__,
212
+ "Depolarizing": Depolarizing.__func__,
213
+ "DepolarizingChannel": Depolarizing.__func__,
214
+ }
215
+
216
+ @classmethod
217
+ def build_noisy_qnode_with_injections(
218
+ cls,
219
+ noiseless_circuit: Callable,
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,
227
+ then sequentially injects noise channels (using fresh ancilla qubits), and finally
228
+ performs a measurement.
229
+
230
+ Args:
231
+ noiseless_circuit: The noiseless circuit function.
232
+ n_system_wires: Number of system wires.
233
+ noise_channels: List of noise channel specifications in the form (noise_type, noise_param, wires_to_noise).
234
+ measurement_fn: Function returning measurement result (defaults to qml.state() if not provided).
235
+ device_kwargs: Additional device parameters.
236
+
237
+ Returns:
238
+ A PennyLane QNode representing the noisy circuit.
239
+ """
240
+ noise_channels = cls._normalize_noise_channels(noise_channels)
241
+
242
+ for (noise_type, _, _) in noise_channels:
243
+ if noise_type not in cls.NOISE_CHANNEL_METHODS:
244
+ raise ValueError(f"Unknown noise type '{noise_type}'. Available types: {list(cls.NOISE_CHANNEL_METHODS.keys())}")
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 = n_system_wires # System wires are 0 .. n_system_wires-1
252
+
253
+ for i, (noise_type, noise_param, wires_to_noise) in enumerate(noise_channels):
254
+ noise_fn = cls.NOISE_CHANNEL_METHODS[noise_type]
255
+ anc_per_wire = 2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1
256
+
257
+ for j, sys_wire in enumerate(wires_to_noise):
258
+ anc_start = current_ancilla_start + j * anc_per_wire
259
+ anc_wires = list(range(anc_start, anc_start + anc_per_wire))
260
+ noise_fn(noise_param, wires=[sys_wire] + anc_wires)
261
+
262
+ current_ancilla_start += ancilla_requirements[i]
263
+
264
+ return measurement_fn() if measurement_fn else qml.state()
265
+
266
+ total_wires = n_system_wires + total_ancillas
267
+ device_params = {"wires": total_wires, "shots": None}
268
+ if device_kwargs:
269
+ device_params.update(device_kwargs)
270
+ dev = qml.device("default.mixed", **device_params)
271
+ return qml.QNode(quantum_function, dev)
272
+
273
+ @classmethod
274
+ def _normalize_noise_channels(
275
+ cls, noise_channels: List[Tuple[Union[str, Any], float, List[int]]]
276
+ ) -> List[Tuple[str, float, List[int]]]:
277
+ transformed = []
278
+ for (noise_type, noise_param, wires_to_noise) in noise_channels:
279
+ noise_type_str = noise_type.__name__ if isinstance(noise_type, type) and issubclass(noise_type, qml.operation.Operation) else str(noise_type)
280
+ transformed.append((noise_type_str, noise_param, wires_to_noise))
281
+ return transformed
282
+
283
+ @classmethod
284
+ def _calculate_ancilla_requirements(
285
+ cls, noise_channels: List[Tuple[str, float, List[int]]]
286
+ ) -> List[int]:
287
+ requirements = []
288
+ for (noise_type, _, wires_to_noise) in noise_channels:
289
+ anc_per_wire = 2 if noise_type in ("Depolarizing", "DepolarizingChannel") else 1
290
+ requirements.append(anc_per_wire * len(wires_to_noise))
291
+ return requirements
292
+
293
+ def print_results(title: str, stine_res: Any, naive_res: Any, qnode_stine: qml.QNode, qnode_naive: qml.QNode) -> None:
294
+ """
295
+ Helper function to print test results and circuit diagrams.
296
+ """
297
+ print(f"\n--- {title} ---")
298
+ print("Stinespring result on wires [0,1]:", stine_res)
299
+ print("Naive result on wires [0,1]: ", naive_res)
300
+ print("\nStinespring circuit diagram:")
301
+ print(qml.draw(qnode_stine)())
302
+ print("\nNaive approach circuit diagram:")
303
+ print(qml.draw(qnode_naive)())
304
+ print("-" * 60)
305
+
306
+
src/quantum_circuits/noisy_qasm_runner.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import json
3
+ import pennylane as qml
4
+ from typing import List, Dict, Any
5
+ import logging
6
+ from quantum_circuits.noisy_circuit_generator import NoisyCircuit
7
+
8
+
9
+ class NoisyQASMRunner:
10
+ """
11
+ Runs noisy quantum circuits derived from OpenQASM code with specified noise operations.
12
+ """
13
+ def __init__(self, openqasm_code: str, noise_dict_list: List[Dict[str, Any]], verbose=False) -> None:
14
+ """
15
+ Args:
16
+ openqasm_code: Valid OpenQASM 2.0 code.
17
+ noise_dict_list: List of noise dictionaries (each with "operation", "probability", "wires").
18
+ verbose: Print verbose output.
19
+ """
20
+ self.openqasm_code = openqasm_code
21
+ self.noise_dict_list = noise_dict_list
22
+ self.verbose = verbose
23
+ self.logger = logging.getLogger(self.__class__.__name__)
24
+
25
+ if self.verbose:
26
+ self.logger.setLevel(logging.INFO)
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: (noise_op, probability, wires).
35
+ Args:
36
+ noise_dict_list: List of dictionaries with keys "operation", "probability", "wires".
37
+ Returns:
38
+ List of tuples with the corresponding PennyLane noise operators.
39
+ """
40
+ op_mapping = {
41
+ "BitFlip": qml.BitFlip,
42
+ "PhaseFlip": qml.PhaseFlip,
43
+ "AmplitudeDamping": qml.AmplitudeDamping,
44
+ "PhaseDamping": qml.PhaseDamping,
45
+ }
46
+ translated = []
47
+ for noise in noise_dict_list:
48
+ op_name = noise.get("operation")
49
+ prob = noise.get("probability")
50
+ wires = noise.get("wires")
51
+ noise_op = op_mapping.get(op_name)
52
+ if noise_op is None:
53
+ raise ValueError(f"Unknown noise operation: {op_name}")
54
+ translated.append((noise_op, prob, wires))
55
+ return translated
56
+
57
+ @staticmethod
58
+ def count_qubits_in_qasm(qasm_code: str) -> int:
59
+ """
60
+ Counts the total number of qubits declared in an OpenQASM string.
61
+ Args:
62
+ qasm_code: Valid OpenQASM 2.0 code.
63
+ Returns:
64
+ The total number of qubits.
65
+ """
66
+ pattern = r"qreg\s+\w+\[(\d+)\];"
67
+ matches = re.findall(pattern, qasm_code)
68
+ return sum(int(num) for num in matches)
69
+
70
+ def run(self) -> List[float]:
71
+ """
72
+ Executes the noisy quantum circuit.
73
+ Steps:
74
+ 1. Convert QASM to a quantum function.
75
+ 2. Print the drawn circuit.
76
+ 3. Count qubits and create wires and dummy parameters.
77
+ 4. Translate noise specifications.
78
+ 5. Create a device and wrap it in a NoisyCircuit.
79
+ 6. Build and execute a noisy QNode.
80
+ 7. Print and return the expectation values.
81
+ """
82
+ # Convert QASM to quantum function.
83
+ qfunc = qml.from_qasm(self.openqasm_code)
84
+ self.logger.info("Quantum circuit derived from QASM:")
85
+ self.logger.info(qml.draw(qfunc)())
86
+
87
+ # Define a circuit function (dummy parameters not used).
88
+ def circuit(params, n_qubits=None):
89
+ return qfunc()
90
+
91
+ n_qubits = self.count_qubits_in_qasm(self.openqasm_code)
92
+ wires = list(range(n_qubits))
93
+ dummy_params = [0] * n_qubits
94
+
95
+ noise_ops = self.translate_noise_types(self.noise_dict_list)
96
+ dev = qml.device("default.mixed", wires=wires, shots=100_000)
97
+
98
+ noisy_circ = NoisyCircuit(dev, noise_ops)
99
+ # Here we choose to use the naive noise injection (use_qasm=False)
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({"expectation_values": [float(val) for val in noisy_result]})
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;
111
+ include "qelib1.inc";
112
+ qreg q[3];
113
+ creg c[3];
114
+ h q[0];
115
+ cx q[0], q[1];
116
+ cx q[1], q[2];
117
+ """
118
+ runner_no_noise = NoisyQASMRunner(sample_qasm, [], verbose=True)
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)