Spaces:
Runtime error
Runtime error
Download src/database/db_handler.py from QuantumGenAI/ErrorMitigation: direct link, hf CLI and curl.
- Browser
- Download file 5.44 kB
-
https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/database/db_handler.py
- Command line
-
hf download hf://spaces/QuantumGenAI/ErrorMitigation/src/database/db_handler.py
-
curl -L -o db_handler.py https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/database/db_handler.py
5.44 kB
| from pydantic import BaseModel | |
| import pandas as pd | |
| import duckdb | |
| import json | |
| from utils.qasm_utils import remove_measurements | |
| class CircuitData(BaseModel): | |
| qasm_circuit: str | |
| noise_data: list | |
| noisy_result: list | |
| noiseless_result: list | |
| class DuckDBDAO: | |
| """ | |
| A DAO (Data Access Object) for storing and retrieving quantum circuit data in DuckDB. | |
| This version does not handle mitigation and saves both the noiseless and noisy results in the same row. | |
| If a noise_qasm string is provided, it is stored as well. | |
| Managed table: | |
| circuits -> (circuit_id, qasm, noise_data, noiseless_result, noisy_result, noise_qasm) | |
| """ | |
| def __init__(self, db_path=":memory:"): | |
| self.db_path = db_path | |
| self.conn = duckdb.connect(self.db_path) | |
| self._create_sequences() | |
| self._create_tables() | |
| def _create_sequences(self): | |
| """Create a sequence for auto-incremented primary keys.""" | |
| self.conn.execute("CREATE SEQUENCE IF NOT EXISTS circuits_seq START 1;") | |
| def _create_tables(self): | |
| """Create the circuits table for storing circuit data.""" | |
| self.conn.execute( | |
| """ | |
| CREATE TABLE IF NOT EXISTS circuits ( | |
| circuit_id INTEGER PRIMARY KEY DEFAULT nextval('circuits_seq'), | |
| qasm TEXT NOT NULL, | |
| noise_data JSON, | |
| noiseless_result JSON, | |
| noisy_result JSON, | |
| noise_qasm TEXT | |
| ); | |
| """ | |
| ) | |
| def insert_circuit_result( | |
| self, | |
| qasm: str, | |
| noiseless_result: dict = None, | |
| noise_data: dict = None, | |
| noisy_result: dict = None, | |
| noise_qasm: str = None, | |
| ): | |
| """ | |
| Insert a circuit row that contains the QASM, noiseless result, noise data, noisy result, | |
| and (optionally) the noise_qasm string. | |
| Args: | |
| qasm (str): QASM representation of the original circuit. | |
| noiseless_result (dict, optional): Dictionary of noiseless circuit metrics. | |
| noise_data (dict, optional): Dictionary of noise model details. | |
| noisy_result (dict, optional): Dictionary of noisy circuit metrics. | |
| noise_qasm (str, optional): QASM representation of the noisy circuit. | |
| Returns: | |
| int: The auto-generated circuit_id. | |
| """ | |
| noiseless_json = ( | |
| json.dumps(noiseless_result) if noiseless_result is not None else None | |
| ) | |
| noise_data_json = json.dumps(noise_data) if noise_data is not None else None | |
| noisy_json = json.dumps(noisy_result) if noisy_result is not None else None | |
| query = """ | |
| INSERT INTO circuits (qasm, noise_data, noiseless_result, noisy_result, noise_qasm) | |
| VALUES (?, ?, ?, ?, ?) | |
| RETURNING circuit_id; | |
| """ | |
| row = self.conn.execute( | |
| query, [qasm, noise_data_json, noiseless_json, noisy_json, noise_qasm] | |
| ).fetchone() | |
| return row[0] | |
| def get_by_qasm(self, qasm: str): | |
| """ | |
| Retrieve all circuit rows with the specified QASM. | |
| Args: | |
| qasm (str): The QASM string to search for. | |
| Returns: | |
| list: A list of dictionaries, each representing a circuit row. | |
| """ | |
| query = "SELECT * FROM circuits WHERE qasm = ?;" | |
| rows = self.conn.execute(query, [qasm]).fetchall() | |
| return [ | |
| { | |
| "circuit_id": row[0], | |
| "qasm": row[1], | |
| "noise_data": json.loads(row[2]) if row[2] else None, | |
| "noiseless_result": json.loads(row[3]) if row[3] else None, | |
| "noisy_result": json.loads(row[4]) if row[4] else None, | |
| "noise_qasm": row[5], | |
| } | |
| for row in rows | |
| ] | |
| def get_circuit(self, circuit_id: int): | |
| """ | |
| Retrieve a single circuit row by its circuit_id. | |
| Args: | |
| circuit_id (int): The primary key of the circuit row. | |
| Returns: | |
| dict or None: A dictionary representing the circuit row, or None if not found. | |
| """ | |
| query = "SELECT * FROM circuits WHERE circuit_id = ?;" | |
| row = self.conn.execute(query, [circuit_id]).fetchone() | |
| if row: | |
| return { | |
| "circuit_id": row[0], | |
| "qasm": row[1], | |
| "noise_data": json.loads(row[2]) if row[2] else None, | |
| "noiseless_result": json.loads(row[3]) if row[3] else None, | |
| "noisy_result": json.loads(row[4]) if row[4] else None, | |
| "noise_qasm": row[5], | |
| } | |
| return None | |
| def extract_circuit_data(df: pd.DataFrame, i: int) -> CircuitData: | |
| """ | |
| Extracts and processes circuit data from a DataFrame. | |
| Parameters: | |
| df (pd.DataFrame): DataFrame containing circuit data. | |
| i (int): Index of the row to extract data from. | |
| Returns: | |
| CircuitData | |
| """ | |
| qasm_circuit = remove_measurements(df.qasm[i]) | |
| noise_data = json.loads(json.loads(df.noise_data[i])) | |
| noisy_result = json.loads(json.loads(df.noisy_result[i]))["expectation_values"] | |
| noiseless_result = json.loads(json.loads(df.noiseless_result[i]))[ | |
| "expectation_values" | |
| ] | |
| return CircuitData( | |
| qasm_circuit=qasm_circuit, | |
| noise_data=noise_data, | |
| noisy_result=noisy_result, | |
| noiseless_result=noiseless_result, | |
| ) | |