Dvirmor100 commited on
Commit
43d8df7
·
1 Parent(s): 4258877

feat(database): move db handling for its own module

Browse files
src/app.py DELETED
@@ -1,70 +0,0 @@
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
- """
10
- Run and visualize a selected circuit from the module.
11
-
12
- Args:
13
- circuit_index (int): Index of the circuit to run.
14
-
15
- Returns:
16
- tuple: Circuit information and visualization image.
17
- """
18
- try:
19
- circuit_func, params, circuit_name, wires = circuits[circuit_index]
20
- noise_types = [
21
- (qml.BitFlip, {"prob": 0.05}),
22
- (qml.PhaseFlip, {"prob": 0.05}),
23
- (qml.DepolarizingChannel, {"prob": 0.05}),
24
- ]
25
- # Build the quantum circuit
26
- constructed_circuit, noisy_qnode = build_quantum_circuit((circuit_func, params, circuit_name, wires),
27
- noise_types)
28
-
29
- noisy_path = None
30
- if randomize:
31
- visualize_circuit(noisy_qnode, *params, title=circuit_name,
32
- save_path="noise.png")
33
- noisy_path = "noise.png"
34
-
35
- # Visualize the circuit
36
- visualize_circuit(constructed_circuit, *params, title=circuit_name,
37
- save_path="output.png")
38
- return "success", "output.png", noisy_path
39
-
40
- except IndexError:
41
- return "Invalid circuit selection", None, None
42
-
43
-
44
- # Gradio app interface
45
- def run_app():
46
- iface = gr.Interface(
47
- fn=lambda circuit_choice, randomize: run_selected_circuit(
48
- int(circuit_choice) - 1, randomize),
49
- inputs=[
50
- gr.Radio(
51
- choices=[str(i + 1) for i in range(len(circuits))],
52
- label="Choose Circuit Type"
53
- ),
54
- gr.Checkbox(label="Randomize Circuit", visible=True)
55
- ],
56
- outputs=[
57
- gr.Textbox(label="Circuit Info"),
58
- gr.Image(type="filepath", label="Circuit Image"),
59
- gr.Image(type="filepath", label="Noisy Circuit Image")
60
- ],
61
- title="Quantum Circuit Visualizer",
62
- description="Visualize circuits from the module or generate a randomized quantum circuit.",
63
- )
64
-
65
- # Launch interface
66
- iface.launch()
67
-
68
-
69
- if __name__ == "__main__":
70
- run_app()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/database/__init__.py ADDED
File without changes
src/database/db_handler.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ import pandas as pd
3
+ import duckdb
4
+ import json
5
+
6
+ from utils.qasm_utils import remove_measurements
7
+
8
+
9
+ class CircuitData(BaseModel):
10
+ qasm_circuit: str
11
+ noise_data: list
12
+ noisy_result: list
13
+ noiseless_result: list
14
+
15
+ class DuckDBDAO:
16
+ """
17
+ A DAO (Data Access Object) for storing and retrieving quantum circuit data in DuckDB.
18
+ This version does not handle mitigation and saves both the noiseless and noisy results in the same row.
19
+ If a noise_qasm string is provided, it is stored as well.
20
+
21
+ Managed table:
22
+ circuits -> (circuit_id, qasm, noise_data, noiseless_result, noisy_result, noise_qasm)
23
+ """
24
+
25
+ def __init__(self, db_path=':memory:'):
26
+ self.db_path = db_path
27
+ self.conn = duckdb.connect(self.db_path)
28
+ self._create_sequences()
29
+ self._create_tables()
30
+
31
+ def _create_sequences(self):
32
+ """Create a sequence for auto-incremented primary keys."""
33
+ self.conn.execute("CREATE SEQUENCE IF NOT EXISTS circuits_seq START 1;")
34
+
35
+ def _create_tables(self):
36
+ """Create the circuits table for storing circuit data."""
37
+ self.conn.execute("""
38
+ CREATE TABLE IF NOT EXISTS circuits (
39
+ circuit_id INTEGER PRIMARY KEY DEFAULT nextval('circuits_seq'),
40
+ qasm TEXT NOT NULL,
41
+ noise_data JSON,
42
+ noiseless_result JSON,
43
+ noisy_result JSON,
44
+ noise_qasm TEXT
45
+ );
46
+ """)
47
+
48
+ def insert_circuit_result(self, qasm: str, noiseless_result: dict = None,
49
+ noise_data: dict = None, noisy_result: dict = None,
50
+ noise_qasm: str = None):
51
+ """
52
+ Insert a circuit row that contains the QASM, noiseless result, noise data, noisy result,
53
+ and (optionally) the noise_qasm string.
54
+
55
+ Args:
56
+ qasm (str): QASM representation of the original circuit.
57
+ noiseless_result (dict, optional): Dictionary of noiseless circuit metrics.
58
+ noise_data (dict, optional): Dictionary of noise model details.
59
+ noisy_result (dict, optional): Dictionary of noisy circuit metrics.
60
+ noise_qasm (str, optional): QASM representation of the noisy circuit.
61
+
62
+ Returns:
63
+ int: The auto-generated circuit_id.
64
+ """
65
+ noiseless_json = json.dumps(noiseless_result) if noiseless_result is not None else None
66
+ noise_data_json = json.dumps(noise_data) if noise_data is not None else None
67
+ noisy_json = json.dumps(noisy_result) if noisy_result is not None else None
68
+
69
+ query = """
70
+ INSERT INTO circuits (qasm, noise_data, noiseless_result, noisy_result, noise_qasm)
71
+ VALUES (?, ?, ?, ?, ?)
72
+ RETURNING circuit_id;
73
+ """
74
+ row = self.conn.execute(query, [qasm, noise_data_json, noiseless_json, noisy_json, noise_qasm]).fetchone()
75
+ return row[0]
76
+
77
+ def get_by_qasm(self, qasm: str):
78
+ """
79
+ Retrieve all circuit rows with the specified QASM.
80
+
81
+ Args:
82
+ qasm (str): The QASM string to search for.
83
+
84
+ Returns:
85
+ list: A list of dictionaries, each representing a circuit row.
86
+ """
87
+ query = "SELECT * FROM circuits WHERE qasm = ?;"
88
+ rows = self.conn.execute(query, [qasm]).fetchall()
89
+ return [
90
+ {
91
+ 'circuit_id': row[0],
92
+ 'qasm': row[1],
93
+ 'noise_data': json.loads(row[2]) if row[2] else None,
94
+ 'noiseless_result': json.loads(row[3]) if row[3] else None,
95
+ 'noisy_result': json.loads(row[4]) if row[4] else None,
96
+ 'noise_qasm': row[5]
97
+ }
98
+ for row in rows
99
+ ]
100
+
101
+ def get_circuit(self, circuit_id: int):
102
+ """
103
+ Retrieve a single circuit row by its circuit_id.
104
+
105
+ Args:
106
+ circuit_id (int): The primary key of the circuit row.
107
+
108
+ Returns:
109
+ dict or None: A dictionary representing the circuit row, or None if not found.
110
+ """
111
+ query = "SELECT * FROM circuits WHERE circuit_id = ?;"
112
+ row = self.conn.execute(query, [circuit_id]).fetchone()
113
+ if row:
114
+ return {
115
+ 'circuit_id': row[0],
116
+ 'qasm': row[1],
117
+ 'noise_data': json.loads(row[2]) if row[2] else None,
118
+ 'noiseless_result': json.loads(row[3]) if row[3] else None,
119
+ 'noisy_result': json.loads(row[4]) if row[4] else None,
120
+ 'noise_qasm': row[5]
121
+ }
122
+ return None
123
+
124
+
125
+
126
+ def extract_circuit_data(df: pd.DataFrame, i: int) -> CircuitData:
127
+ """
128
+ Extracts and processes circuit data from a DataFrame.
129
+
130
+ Parameters:
131
+ df (pd.DataFrame): DataFrame containing circuit data.
132
+ i (int): Index of the row to extract data from.
133
+
134
+ Returns:
135
+ CircuitData
136
+ """
137
+
138
+ qasm_circuit = remove_measurements(df.qasm[i])
139
+ noise_data = json.loads(json.loads(df.noise_data[i]))
140
+ noisy_result = json.loads(json.loads(df.noisy_result[i]))["expectation_values"]
141
+ noiseless_result = json.loads(json.loads(df.noiseless_result[i]))["expectation_values"]
142
+
143
+ return CircuitData(
144
+ qasm_circuit=qasm_circuit,
145
+ noise_data=noise_data,
146
+ noisy_result=noisy_result,
147
+ noiseless_result=noiseless_result
148
+ )
149
+