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)