Dvirmor100 commited on
Commit
a0918a5
·
1 Parent(s): 61fa0e7

Refactor project structure and update quantum circuit methods.

Browse files

Moved files to a new "src" directory for better organization. Updated quantum circuit methods to use `.decomposition()` for explicit operation breakdowns. Adjusted imports to reflect the new module structure.

{circuit-builder → src}/__init__.py RENAMED
File without changes
src/circuit_builder/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .circuit_manager import CircuitManager, circuits
{circuit-builder → src/circuit_builder}/circuit_manager.py RENAMED
@@ -1,213 +1,213 @@
1
- import pennylane as qml
2
- from pennylane import numpy as np
3
- from duckdb_dao import DuckDBDAO
4
- import matplotlib.pyplot as plt
5
- from noisy_circuit import NoisyCircuit
6
- import json
7
-
8
- class CircuitManager:
9
- """
10
- Manages circuit execution, optional noise injection, and optional error mitigation.
11
- """
12
-
13
-
14
- def __init__(self, db_path=':memory:', device_name='default.mixed', noise_types=None, mitigation_strategy=None):
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 (callable, optional): A function implementing the error 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
-
27
- def run_circuit(self, circuit_func, params, circuit_name, wires):
28
- """
29
- Execute a circuit, adding noise and applying optional mitigation.
30
-
31
- Args:
32
- circuit_func (callable): Circuit function to execute.
33
- params (list): Parameters to pass to the circuit.
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
41
- @qml.qnode(dev)
42
- def get_expectation_value(*params):
43
- # Call the circuit function to apply the gates
44
- circuit_func(*params)
45
- # Return the expectation values of PauliZ for all wires
46
- return [qml.expval(qml.PauliZ(w)) for w in wires]
47
-
48
-
49
- # Run the noiseless circuit
50
- noiseless_result = get_expectation_value(*params)
51
- # Convert tensors to raw Python floats
52
- result_json = json.dumps({
53
- "expectation_values": [float(value) for value in noiseless_result]
54
- })
55
-
56
- noiseless_qasm = get_expectation_value.qtape.to_openqasm()
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)
64
- noisy_result_json = json.dumps({
65
- "expectation_values": [float(value) for value in noisy_result]
66
- })
67
- self.db.insert_noisy_circuit(circuit_id, noisy_types_json, noisy_result_json)
68
-
69
- # Apply error mitigation (if provided)
70
- if self.mitigation_strategy:
71
- mitigated_result = self.mitigation_strategy(get_expectation_value, *params)
72
- self.db.insert_mitigated_circuit(
73
- 1, noiseless_qasm, "MitigationStrategy", {"expectation_value": mitigated_result}
74
- )
75
- else:
76
- mitigated_result = None
77
-
78
- # Display results
79
- print(f"Circuit: {circuit_name}")
80
- print(f"Noiseless Result: {result_json}")
81
- print(f"Noisy Result: {noisy_result_json}")
82
- if mitigated_result:
83
- print(f"Mitigated Result: {mitigated_result}")
84
- print("-" * 30)
85
-
86
-
87
- def circuit_1(params):
88
- """Basic RX-RZ-RY circuit."""
89
- def circuit():
90
- qml.RX(params[0], wires=0)
91
- qml.RZ(params[1], wires=1)
92
- qml.RY(params[2], wires=2)
93
- return circuit
94
-
95
-
96
- def circuit_2(params):
97
- """Bell state circuit."""
98
- def circuit():
99
- qml.Hadamard(wires=0)
100
- qml.CNOT(wires=[0, 1])
101
- return circuit
102
-
103
-
104
- def circuit_3(params):
105
- """Simple entangled state."""
106
- def circuit():
107
- qml.Hadamard(wires=0)
108
- qml.CNOT(wires=[0, 1])
109
- qml.RX(params[0], wires=0)
110
- return circuit
111
-
112
-
113
- def circuit_4(params):
114
- """GHZ state preparation."""
115
- def circuit():
116
- qml.Hadamard(wires=0)
117
- qml.CNOT(wires=[0, 1])
118
- qml.CNOT(wires=[1, 2])
119
- return circuit
120
-
121
-
122
- def circuit_5(params):
123
- """Arbitrary single-qubit rotations."""
124
- def circuit():
125
- qml.Rot(params[0], params[1], params[2], wires=0)
126
- return circuit
127
-
128
-
129
- def circuit_6(params):
130
- """Variational Ansatz."""
131
- def circuit():
132
- qml.templates.BasicEntanglerLayers(params, wires=[0, 1, 2])
133
- return circuit
134
-
135
-
136
- def circuit_7(params):
137
- """Quantum Fourier Transform (QFT) circuit."""
138
- def circuit():
139
- qml.QFT(wires=[0, 1, 2])
140
- return circuit
141
-
142
-
143
- def circuit_8(params):
144
- """Amplitude Embedding Circuit."""
145
- def circuit():
146
- qml.templates.AmplitudeEmbedding(params, wires=[0, 1], normalize=True)
147
- return circuit
148
-
149
-
150
- def circuit_9(params):
151
- """Angle Embedding Circuit."""
152
- def circuit():
153
- qml.templates.AngleEmbedding(params, wires=[0, 1, 2])
154
- return circuit
155
-
156
-
157
- def circuit_10(params):
158
- """Strongly Entangling Layers."""
159
- def circuit():
160
- qml.templates.StronglyEntanglingLayers(params, wires=[0, 1, 2])
161
- return circuit
162
-
163
-
164
-
165
- # Circuit list with parameter details
166
- circuits = [
167
- (circuit_1, [np.array([0.1, 0.2, 0.3])], "Circuit_1", [0, 1, 2]),
168
- (circuit_2, [np.array([])], "Circuit_2", [0, 1]),
169
- (circuit_3, [np.array([0.5])], "Circuit_3", [0, 1]),
170
- (circuit_4, [np.array([])], "Circuit_4", [0, 1, 2]),
171
- (circuit_5, [np.array([0.3, 0.2, 0.1])], "Circuit_5", [0]),
172
- (circuit_6, [np.random.rand(3, 3)], "Circuit_6", [0, 1, 2]),
173
- (circuit_7, [np.array([])], "Circuit_7", [0, 1, 2]),
174
- (circuit_8, [np.random.rand(4)], "Circuit_8", [0, 1]),
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):
181
- """
182
- Convert a list of noise operations and their parameters into JSON format.
183
-
184
- Args:
185
- noise_types (list): A list of tuples where each tuple contains a noise operation
186
- (e.g., qml.BitFlip) and a dictionary of parameters.
187
-
188
- Returns:
189
- str: A JSON-formatted string representing the noise types and their parameters.
190
- """
191
- noise_list = []
192
- for noise_op, params in noise_types:
193
- noise_list.append({
194
- "operation": noise_op.__name__, # Convert the noise operation to its name
195
- "parameters": params # Keep the parameters as they are
196
- })
197
- return json.dumps(noise_list, indent=4) # Serialize the list to a JSON string with indentation
198
-
199
- if __name__ == "__main__":
200
-
201
- # Initialize CircuitManager
202
- manager = CircuitManager(
203
- db_path="quantum_circuits.duckdb",
204
- noise_types=[
205
- (qml.BitFlip, {"prob": 0.05}),
206
- (qml.PhaseFlip, {"prob": 0.05}),
207
- (qml.DepolarizingChannel, {"prob": 0.05}),
208
- ],
209
- )
210
-
211
- # Execute all circuits
212
- for circuit_func, params, name, wires in circuits:
213
- manager.run_circuit(circuit_func, params, name, wires)
 
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
+ """
10
+ Manages circuit execution, optional noise injection, and optional error mitigation.
11
+ """
12
+
13
+
14
+ def __init__(self, db_path=':memory:', device_name='default.mixed', noise_types=None, mitigation_strategy=None):
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 (callable, optional): A function implementing the error 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
+
27
+ def run_circuit(self, circuit_func, params, circuit_name, wires):
28
+ """
29
+ Execute a circuit, adding noise and applying optional mitigation.
30
+
31
+ Args:
32
+ circuit_func (callable): Circuit function to execute.
33
+ params (list): Parameters to pass to the circuit.
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
41
+ @qml.qnode(dev)
42
+ def get_expectation_value(*params):
43
+ # Call the circuit function to apply the gates
44
+ circuit_func(*params)
45
+ # Return the expectation values of PauliZ for all wires
46
+ return [qml.expval(qml.PauliZ(w)) for w in wires]
47
+
48
+
49
+ # Run the noiseless circuit
50
+ noiseless_result = get_expectation_value(*params)
51
+ # Convert tensors to raw Python floats
52
+ result_json = json.dumps({
53
+ "expectation_values": [float(value) for value in noiseless_result]
54
+ })
55
+
56
+ noiseless_qasm = get_expectation_value.qtape.to_openqasm()
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)
64
+ noisy_result_json = json.dumps({
65
+ "expectation_values": [float(value) for value in noisy_result]
66
+ })
67
+ self.db.insert_noisy_circuit(circuit_id, noisy_types_json, noisy_result_json)
68
+
69
+ # Apply error mitigation (if provided)
70
+ if self.mitigation_strategy:
71
+ mitigated_result = self.mitigation_strategy(get_expectation_value, *params)
72
+ self.db.insert_mitigated_circuit(
73
+ 1, noiseless_qasm, "MitigationStrategy", {"expectation_value": mitigated_result}
74
+ )
75
+ else:
76
+ mitigated_result = None
77
+
78
+ # Display results
79
+ print(f"Circuit: {circuit_name}")
80
+ print(f"Noiseless Result: {result_json}")
81
+ print(f"Noisy Result: {noisy_result_json}")
82
+ if mitigated_result:
83
+ print(f"Mitigated Result: {mitigated_result}")
84
+ print("-" * 30)
85
+
86
+
87
+ def circuit_1(params):
88
+ """Basic RX-RZ-RY circuit."""
89
+ def circuit():
90
+ qml.RX(params[0], wires=0)
91
+ qml.RZ(params[1], wires=1)
92
+ qml.RY(params[2], wires=2)
93
+ return circuit
94
+
95
+
96
+ def circuit_2(params):
97
+ """Bell state circuit."""
98
+ def circuit():
99
+ qml.Hadamard(wires=0)
100
+ qml.CNOT(wires=[0, 1])
101
+ return circuit
102
+
103
+
104
+ def circuit_3(params):
105
+ """Simple entangled state."""
106
+ def circuit():
107
+ qml.Hadamard(wires=0)
108
+ qml.CNOT(wires=[0, 1])
109
+ qml.RX(params[0], wires=0)
110
+ return circuit
111
+
112
+
113
+ def circuit_4(params):
114
+ """GHZ state preparation."""
115
+ def circuit():
116
+ qml.Hadamard(wires=0)
117
+ qml.CNOT(wires=[0, 1])
118
+ qml.CNOT(wires=[1, 2])
119
+ return circuit
120
+
121
+
122
+ def circuit_5(params):
123
+ """Arbitrary single-qubit rotations."""
124
+ def circuit():
125
+ qml.Rot(params[0], params[1], params[2], wires=0).decomposition()
126
+ return circuit
127
+
128
+
129
+ def circuit_6(params):
130
+ """Variational Ansatz."""
131
+ def circuit():
132
+ qml.templates.BasicEntanglerLayers(params, wires=[0, 1, 2]).decomposition()
133
+ return circuit
134
+
135
+
136
+ def circuit_7(params):
137
+ """Quantum Fourier Transform (QFT) circuit."""
138
+ def circuit():
139
+ qml.QFT(wires=[0, 1, 2]).decomposition()
140
+ return circuit
141
+
142
+
143
+ def circuit_8(params):
144
+ """Amplitude Embedding Circuit."""
145
+ def circuit():
146
+ qml.templates.AmplitudeEmbedding(params, wires=[0, 1], normalize=True).decomposition()
147
+ return circuit
148
+
149
+
150
+ def circuit_9(params):
151
+ """Angle Embedding Circuit."""
152
+ def circuit():
153
+ qml.templates.AngleEmbedding(params, wires=[0, 1, 2]).decomposition()
154
+ return circuit
155
+
156
+
157
+ def circuit_10(params):
158
+ """Strongly Entangling Layers."""
159
+ def circuit():
160
+ qml.templates.StronglyEntanglingLayers(params, wires=[0, 1, 2]).decomposition()
161
+ return circuit
162
+
163
+
164
+
165
+ # Circuit list with parameter details
166
+ circuits = [
167
+ (circuit_1, [np.array([0.1, 0.2, 0.3])], "Circuit_1", [0, 1, 2]),
168
+ (circuit_2, [np.array([])], "Circuit_2", [0, 1]),
169
+ (circuit_3, [np.array([0.5])], "Circuit_3", [0, 1]),
170
+ (circuit_4, [np.array([])], "Circuit_4", [0, 1, 2]),
171
+ (circuit_5, [np.array([0.3, 0.2, 0.1])], "Circuit_5", [0]),
172
+ (circuit_6, [np.random.rand(3, 3)], "Circuit_6", [0, 1, 2]),
173
+ (circuit_7, [np.array([])], "Circuit_7", [0, 1, 2]),
174
+ (circuit_8, [np.random.rand(4)], "Circuit_8", [0, 1]),
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):
181
+ """
182
+ Convert a list of noise operations and their parameters into JSON format.
183
+
184
+ Args:
185
+ noise_types (list): A list of tuples where each tuple contains a noise operation
186
+ (e.g., qml.BitFlip) and a dictionary of parameters.
187
+
188
+ Returns:
189
+ str: A JSON-formatted string representing the noise types and their parameters.
190
+ """
191
+ noise_list = []
192
+ for noise_op, params in noise_types:
193
+ noise_list.append({
194
+ "operation": noise_op.__name__, # Convert the noise operation to its name
195
+ "parameters": params # Keep the parameters as they are
196
+ })
197
+ return json.dumps(noise_list, indent=4) # Serialize the list to a JSON string with indentation
198
+
199
+ if __name__ == "__main__":
200
+
201
+ # Initialize CircuitManager
202
+ manager = CircuitManager(
203
+ db_path="quantum_circuits.duckdb",
204
+ noise_types=[
205
+ (qml.BitFlip, {"prob": 0.05}),
206
+ (qml.PhaseFlip, {"prob": 0.05}),
207
+ (qml.DepolarizingChannel, {"prob": 0.05}),
208
+ ],
209
+ )
210
+
211
+ # Execute all circuits
212
+ for circuit_func, params, name, wires in circuits:
213
+ manager.run_circuit(circuit_func, params, name, wires)
{circuit-builder → src/circuit_builder}/duckdb_dao.py RENAMED
@@ -1,146 +1,146 @@
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
 
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
{circuit-builder → src/circuit_builder}/migration_strategy.py RENAMED
@@ -1,77 +1,77 @@
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}")
 
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}")
{circuit-builder → src/circuit_builder}/noisy_circuit.py RENAMED
@@ -1,63 +1,63 @@
1
- import pennylane as qml
2
- from pennylane import numpy as np
3
- from typing import Callable, List, Tuple
4
-
5
-
6
- class NoisyCircuit:
7
- """
8
- A class to add customizable noise to a quantum circuit in PennyLane.
9
-
10
- Attributes:
11
- device (qml.Device): The PennyLane device to run the circuit.
12
- noise_operations (List[Tuple[Callable, dict]]): A list of noise operations and their parameters.
13
- """
14
-
15
- def __init__(self, device: qml.Device, noise_operations: List[Tuple[Callable, dict]] = None):
16
- """
17
- Initializes the NoisyCircuit class.
18
-
19
- Args:
20
- device (qml.Device): The quantum device for circuit execution.
21
- noise_operations (List[Tuple[Callable, dict]]): A list of noise operations with parameters.
22
- """
23
- self.device = device
24
- self.noise_operations = noise_operations if noise_operations else []
25
-
26
- def add_noise(self, circuit: Callable, wires: List[int]):
27
- """
28
- Adds specified noise gates to the circuit and returns the noisy circuit.
29
-
30
- Args:
31
- circuit (Callable): The quantum circuit function to add noise to.
32
- wires (List[int]): List of wires where noise will be applied.
33
-
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
- noise_op(wires=wire, p=noise_params["prob"])
42
-
43
- return noisy_circuit
44
-
45
- def noisy_qnode(self, circuit: Callable, wires: List[int]):
46
- """
47
- Converts the noisy circuit into a QNode with expected value measurement.
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
- noisy_circuit = self.add_noise(circuit, wires)
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 pennylane as qml
2
+ from pennylane import numpy as np
3
+ from typing import Callable, List, Tuple
4
+
5
+
6
+ class NoisyCircuit:
7
+ """
8
+ A class to add customizable noise to a quantum circuit in PennyLane.
9
+
10
+ Attributes:
11
+ device (qml.Device): The PennyLane device to run the circuit.
12
+ noise_operations (List[Tuple[Callable, dict]]): A list of noise operations and their parameters.
13
+ """
14
+
15
+ def __init__(self, device: qml.Device, noise_operations: List[Tuple[Callable, dict]] = None):
16
+ """
17
+ Initializes the NoisyCircuit class.
18
+
19
+ Args:
20
+ device (qml.Device): The quantum device for circuit execution.
21
+ noise_operations (List[Tuple[Callable, dict]]): A list of noise operations with parameters.
22
+ """
23
+ self.device = device
24
+ self.noise_operations = noise_operations if noise_operations else []
25
+
26
+ def add_noise(self, circuit: Callable, wires: List[int]):
27
+ """
28
+ Adds specified noise gates to the circuit and returns the noisy circuit.
29
+
30
+ Args:
31
+ circuit (Callable): The quantum circuit function to add noise to.
32
+ wires (List[int]): List of wires where noise will be applied.
33
+
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
+ noise_op(wires=wire, p=noise_params["prob"])
42
+
43
+ return noisy_circuit
44
+
45
+ def noisy_qnode(self, circuit: Callable, wires: List[int]):
46
+ """
47
+ Converts the noisy circuit into a QNode with expected value measurement.
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
+ noisy_circuit = self.add_noise(circuit, wires)
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