File size: 4,511 Bytes
fc34b65
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
 
fc34b65
 
 
e0d7f28
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
 
 
fc34b65
 
 
 
e0d7f28
fc34b65
 
 
 
 
 
 
 
 
 
 
 
 
 
e0d7f28
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
import re
import json
import pennylane as qml
from typing import List, Dict, Any
import logging
from quantum_circuits.noisy_circuit_generator import NoisyCircuit


class NoisyQASMRunner:
    """
    Runs noisy quantum circuits derived from OpenQASM code with specified noise operations.
    """

    def __init__(
        self, openqasm_code: str, noise_dict_list: List[Dict[str, Any]], verbose=False
    ) -> None:
        """
        Args:
            openqasm_code: Valid OpenQASM 2.0 code.
            noise_dict_list: List of noise dictionaries
                (each with "operation", "probability", "wires").
            verbose: Print verbose output.
        """
        self.openqasm_code = openqasm_code
        self.noise_dict_list = noise_dict_list
        self.verbose = verbose
        self.logger = logging.getLogger(self.__class__.__name__)

        if self.verbose:
            self.logger.setLevel(logging.INFO)
        else:
            self.logger.setLevel(logging.WARNING)

    @staticmethod
    def translate_noise_types(noise_dict_list: List[Dict[str, Any]]) -> List[tuple]:
        """
        Translates a list of noise dictionaries into a list of tuples:
            (noise_op, probability, wires).
        Args:
            noise_dict_list: List of dictionaries with keys "operation", "probability", "wires".
        Returns:
            List of tuples with the corresponding PennyLane noise operators.
        """
        op_mapping = {
            "BitFlip": qml.BitFlip,
            "PhaseFlip": qml.PhaseFlip,
            "AmplitudeDamping": qml.AmplitudeDamping,
            "PhaseDamping": qml.PhaseDamping,
        }
        translated = []
        for noise in noise_dict_list:
            op_name = noise.get("operation")
            prob = noise.get("probability")
            wires = noise.get("wires")
            noise_op = op_mapping.get(op_name)
            if noise_op is None:
                raise ValueError(f"Unknown noise operation: {op_name}")
            translated.append((noise_op, prob, wires))
        return translated

    @staticmethod
    def count_qubits_in_qasm(qasm_code: str) -> int:
        """
        Counts the total number of qubits declared in an OpenQASM string.
        Args:
            qasm_code: Valid OpenQASM 2.0 code.
        Returns:
            The total number of qubits.
        """
        pattern = r"qreg\s+\w+\[(\d+)\];"
        matches = re.findall(pattern, qasm_code)
        return sum(int(num) for num in matches)

    def run(self) -> List[float]:
        """
        Executes the noisy quantum circuit.
        Steps:
          1. Convert QASM to a quantum function.
          2. Print the drawn circuit.
          3. Count qubits and create wires and dummy parameters.
          4. Translate noise specifications.
          5. Create a device and wrap it in a NoisyCircuit.
          6. Build and execute a noisy QNode.
          7. Print and return the expectation values.
        """
        # Convert QASM to quantum function.
        qfunc = qml.from_qasm(self.openqasm_code)
        self.logger.info("Quantum circuit derived from QASM:")
        self.logger.info(qml.draw(qfunc)())

        # Define a circuit function (dummy parameters not used).
        def circuit(params, n_qubits=None):
            return qfunc()

        n_qubits = self.count_qubits_in_qasm(self.openqasm_code)
        wires = list(range(n_qubits))
        dummy_params = [0] * n_qubits

        noise_ops = self.translate_noise_types(self.noise_dict_list)
        dev = qml.device("default.mixed", wires=wires, shots=100_000)

        noisy_circ = NoisyCircuit(dev, noise_ops)
        # Here we choose to use the naive noise injection (use_qasm=False)
        noisy_qnode = noisy_circ.noisy_qnode(circuit, wires, use_qasm=False)

        noisy_result = noisy_qnode(dummy_params, n_qubits=n_qubits)
        result_json = json.dumps(
            {"expectation_values": [float(val) for val in noisy_result]}
        )
        self.logger.info("Noisy circuit expectation values:")
        self.logger.info(result_json)
        return noisy_result


if __name__ == "__main__":
    sample_qasm = """
    OPENQASM 2.0;
    include "qelib1.inc";
    qreg q[3];
    creg c[3];
    h q[0];
    cx q[0], q[1];
    cx q[1], q[2];
    """
    runner_no_noise = NoisyQASMRunner(sample_qasm, [], verbose=True)
    result_no_noise = runner_no_noise.run()
    result_no_noise_2 = runner_no_noise.run()
    print(result_no_noise)
    print(result_no_noise_2)