File size: 5,439 Bytes
43d8df7
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
43d8df7
 
 
 
 
 
 
 
 
 
e0d7f28
43d8df7
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
43d8df7
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
 
 
 
 
 
 
43d8df7
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
43d8df7
 
 
 
 
 
 
 
e0d7f28
 
 
43d8df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
 
43d8df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
 
43d8df7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
43d8df7
 
 
 
 
e0d7f28
43d8df7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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,
    )