Spaces:
Runtime error
Runtime error
Download src/quantum_circuits/circuit_manager.py from QuantumGenAI/ErrorMitigation: direct link, hf CLI and curl.
- Browser
- Download file 5.73 kB
-
https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/quantum_circuits/circuit_manager.py
- Command line
-
hf download hf://spaces/QuantumGenAI/ErrorMitigation/src/quantum_circuits/circuit_manager.py
-
curl -L -o circuit_manager.py https://huggingface.co/spaces/QuantumGenAI/ErrorMitigation/resolve/main/src/quantum_circuits/circuit_manager.py
5.73 kB
| 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 [] | |
| 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) | |
| 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) | |
| 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) | |