File size: 5,728 Bytes
fc34b65
 
 
e0d7f28
fc34b65
 
 
 
 
e0d7f28
fc34b65
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
 
fc34b65
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
f0f7dac
fc34b65
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
fc34b65
 
e0d7f28
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import random
from typing import Callable, List, Tuple, Optional, Any
import pennylane as qml
from pennylane.measurements import ExpectationMP

from database.db_handler import DuckDBDAO
from quantum_circuits.noisy_circuit_generator import NoisyCircuit


class CircuitManager:
    """
    Manages circuit execution and noise injection.

    For each circuit, this class:
      1. Executes a noiseless circuit and records its expectation values and QASM.
      2. Generates several noisy variations by randomly selecting noise channels.
      3. Saves the noiseless and noisy results (plus the noise specifications and QASM, if available)
         in a DuckDB database.
    """

    def __init__(
        self,
        db_path: str = ":memory:",
        device_name: str = "default.qubit",
        noise_types: Optional[List[Any]] = None,
        use_qasm: bool = False,
    ) -> None:
        """
        Args:
            db_path: Path to the DuckDB database file.
            device_name: The quantum device name.
            noise_types: List of noise model classes to apply (if any).
            use_qasm: Whether to use QASM-based noise injection.
        """
        self.db = DuckDBDAO(db_path)
        self.device_name = device_name
        self.use_qasm = use_qasm
        self.noise_types = noise_types or []

    @staticmethod
    def get_random_noise_types(
        wires: List[int], num_noises: int = 2
    ) -> List[Tuple[Callable, float, List[int]]]:
        """
        Randomly selects noise operations from a predefined set and assigns
        random probabilities and target wires.

        Args:
            wires: List of available system wires.
            num_noises: Maximum number of different noise channels to apply.

        Returns:
            A list of tuples (noise_op, probability, target_wires).
        """
        possible_noises = [
            qml.BitFlip,
            qml.PhaseFlip,
            qml.AmplitudeDamping,
            qml.PhaseDamping,
        ]
        num_noises = min(num_noises, len(possible_noises))
        selected_noises = []
        for noise_op in random.sample(possible_noises, num_noises):
            prob = random.uniform(0.005, 0.05)
            n_targets = random.randint(1, min(5, len(wires)))
            target_wires = random.sample(wires, n_targets)
            selected_noises.append((noise_op, prob, target_wires))
        return selected_noises

    def run_circuit(
        self,
        circuit_func: Callable,
        params: Any,
        circuit_name: str,
        wires: List[int],
        num_variations: int = 3,
    ) -> None:
        """
        Runs a noiseless circuit and several noisy variations, then saves results to the database.

        Args:
            circuit_func: The circuit function that accepts (params, n_qubits).
            params: Parameters for the circuit.
            circuit_name: A name for the circuit.
            wires: List of system wires.
            num_variations: Number of noisy variations to generate.
        """
        # Create a device with specified number of wires and 1000 shots.
        dev = qml.device(self.device_name, wires=len(wires), shots=100_000)

        @qml.qnode(dev)
        def get_z_expectation_value(*params: Any) -> list[ExpectationMP]:
            # Execute the noiseless circuit.
            circuit_func(*params, n_qubits=len(wires))
            # Extra rotation to bias the state.
            for w in wires:
                qml.RZ(0.1, wires=w)
            return [qml.expval(qml.PauliZ(w)) for w in wires]

        noiseless_result = get_z_expectation_value(*params)
        result_json = json.dumps(
            {"expectation_values": [float(val) for val in noiseless_result]}
        )
        noiseless_qasm = get_z_expectation_value.qtape.to_openqasm()

        print(f"Circuit: {circuit_name}")
        print("Noiseless Result:", result_json)
        print("-" * 30)

        # Generate noisy variations.
        for variation in range(num_variations):
            random_noise = self.get_random_noise_types(wires)
            noisy_circ = NoisyCircuit(dev, random_noise)
            use_qasm_for_noise = self.use_qasm and len(wires) < 5
            noisy_qnode = noisy_circ.noisy_qnode(
                circuit_func, wires, use_qasm_for_noise
            )
            noisy_result = noisy_qnode(*params, n_qubits=len(wires))
            noisy_types_json = self.noise_types_to_json(random_noise)
            noisy_result_json = json.dumps(
                {"expectation_values": [float(val) for val in noisy_result]}
            )
            noise_qasm = noisy_qnode.qtape.to_openqasm() if use_qasm_for_noise else None

            # Save the results in the database.
            self.db.insert_circuit_result(
                noiseless_qasm,
                result_json,
                noisy_types_json,
                noisy_result_json,
                noise_qasm,
            )

            print(f"Variation {variation + 1} with noise:")
            print(noisy_types_json)
            print("Noisy Result:", noisy_result_json)
            print("-" * 30)

    @staticmethod
    def noise_types_to_json(
        noise_types: List[Tuple[Callable, float, List[int]]],
    ) -> str:
        """
        Converts a list of noise operation tuples into a JSON-formatted string.

        Args:
            noise_types: List of tuples (noise_op, probability, wires).

        Returns:
            JSON-formatted noise specifications.
        """
        noise_list = [
            {"operation": noise_op.__name__, "probability": prob, "wires": wires}
            for noise_op, prob, wires in noise_types
        ]
        return json.dumps(noise_list, indent=4)