qpanda3_runtime.device.fake_backend#
Classes#
Simulated quantum backend that mimics a real quantum computer/chip. |
Module Contents#
- class qpanda3_runtime.device.fake_backend.FakeBackend(runtime_service, real_device: str | qpanda3_runtime.device.qdevice.QDevice, channel='local_simulator', noise_info: Dict | None = None)#
Bases:
qpanda3_runtime.device.device_abc.DeviceABCSimulated quantum backend that mimics a real quantum computer/chip.
This class creates a simulated quantum device with topology and noise characteristics based on configuration information from a real quantum device. It can be used for algorithm development, testing, and debugging without requiring access to actual quantum hardware.
- Parameters:
runtime_service (
RuntimeService) – Local management object for the QPanda3 Runtime Service, used for defining and submitting quantum computing tasks, and for generating a QTaskManager.real_device (
Union[str,QDevice]) – Reference to the real quantum device being simulated. - QDevice: The real quantum computer/chip object. - str: The ID of the real quantum computer/chip.channel (
str, optional) – The access channel to the real quantum computer/chip. Default is ‘local_simulator’.noise_info (
Union[Dict,None], optional) – Custom noise model metadata for simulation. If provided, this overrides the noise information from the real device configuration. Default is None (use real device noise information).
- Variables:
_real_device (
Union[str,QDevice]) – Reference to the real quantum device._runtime_service (
RuntimeService) – Runtime service for device management._chip_topology_edges (
List[List[int]]) – Physical qubit topology edges._basic_gates (
List[str]) – Basic quantum gates supported by the device._compensate_angle_map (
dict) – Angle compensation mapping for gate operations._noise_info (
Union[Dict,None]) – Custom noise model information._qubit_params_origin (
dict) – Original qubit parameters from device configuration._channel (
str) – Access channel identifier.
Notes
The simulated backend uses the same topology and gate set as the real device.
Noise models can be customized or derived from real device statistics.
Useful for testing quantum algorithms before running on real hardware.
Supports both sampling and expectation value calculations.
Examples
>>> from qpanda3_runtime.device import FakeBackend >>> from qpanda3_runtime import RuntimeService >>> >>> # Create a fake backend based on a real device ID >>> runtime = RuntimeService() >>> fake_device = FakeBackend(runtime, 'quantum_chip_001') >>> >>> # Run a sampling calculation >>> result = fake_device.sample(quantum_circuit, shots=1000) >>> >>> # Calculate expectation value >>> expectation = fake_device.estimate(quantum_circuit, observable, shots=1000)
See also
QDeviceReal quantum device interface.
DeviceABCAbstract base class for quantum devices.
- real_device()#
Get the reference to the real quantum device being simulated.
- Returns:
Reference to the real quantum device: - QDevice: The real quantum computer/chip object. - str: The ID of the real quantum computer/chip.
- Return type:
Union[str,QDevice]
Notes
This method returns the original reference passed during initialization.
Useful for tracking which real device the simulation is based on.
Can be used to switch between simulated and real execution.
Examples
>>> fake_backend = FakeBackend(runtime, 'chip_001') >>> device_ref = fake_backend.real_device() >>> print(f"Simulating device: {device_ref}")
- noise_model(remap_qubits: dict | None = None)#
Generate a noise model for quantum circuit simulation.
Creates a NoiseModel object based on statistical information from the real quantum device, simulating its noise environment for more realistic simulations.
- Parameters:
remap_qubits (
Union[dict,None], optional) – Dictionary for qubit index remapping. Keys are original qubit indices, values are new indices. If None, uses identity mapping. Default is None.- Returns:
A noise model object containing decoherence errors and readout errors based on the real device’s statistical information.
- Return type:
NoiseModel
Notes
The noise model includes T1/T2 decoherence times and readout fidelity matrices.
If custom noise_info was provided during initialization, it overrides the device’s statistical information.
Qubit remapping allows simulating circuits with different qubit indexing.
Examples
>>> # Get noise model with default qubit mapping >>> noise_model = fake_backend.noise_model() >>> >>> # Get noise model with custom qubit remapping >>> remap = {0: 2, 1: 3, 2: 0, 3: 1} >>> noise_model = fake_backend.noise_model(remap_qubits=remap)
See also
noise_infoGet noise information as a dictionary.
pyqpanda3.core.NoiseModelThe noise model class from pyqpanda3.
- noise_info(remap_qubits: dict | None = None)#
Get noise information as a dictionary.
Retrieves noise model information in dictionary format, containing decoherence errors and readout errors based on the real device’s statistical data.
- Parameters:
remap_qubits (
Union[dict,None], optional) – Dictionary for qubit index remapping. Keys are original qubit indices, values are new indices. If None, uses identity mapping. Default is None.- Returns:
Dictionary containing noise information with the following structure: - ‘decoherence_error’: List of dictionaries with T1, T2, time, gatetype, qbits - ‘qubit_read_error’: List of dictionaries with qbit and fidelity_mat
- Return type:
Dict
Notes
Returns the same information as noise_model() but in dictionary format.
Useful for inspecting noise parameters or custom noise model creation.
If custom noise_info was provided during initialization, returns that instead.
Examples
>>> # Get noise information >>> noise_data = fake_backend.noise_info() >>> print(f"Decoherence errors: {noise_data.get('decoherence_error', [])}") >>> print(f"Readout errors: {noise_data.get('qubit_read_error', [])}")
See also
noise_modelGet noise information as a NoiseModel object.
- topo_deges(specified_block: List[int] | None = None)#
Get the qubit topology as a set of edges.
Returns the connectivity graph of physical qubits as a list of edges, where each edge is a pair of qubit indices that can interact directly.
- Parameters:
specified_block (
Optional[List[int]], optional) – List of qubit indices to filter the topology. Only edges where both vertices are in this list will be included. If None or empty, returns all edges. Default is None.- Returns:
List of edges representing the qubit topology. Each edge is a list of two qubit indices [q1, q2] where q1 < q2.
- Return type:
List[List[int]]- Raises:
RuntimeError – If specified_block is provided but no edges contain only qubits from the specified block.
Notes
The topology is derived from the real device’s adjacency matrix.
Useful for circuit compilation and qubit mapping algorithms.
Filtering by specified_block enables subgraph selection for compilation.
Examples
>>> # Get full topology >>> edges = fake_backend.topo_deges() >>> print(f"Device has {len(edges)} connections") >>> >>> # Get topology for specific qubits >>> sub_edges = fake_backend.topo_deges(specified_block=[0, 1, 2]) >>> print(f"Subgraph has {len(sub_edges)} connections")
- static transpile_(prog: str, chip_topology_edges: List[List[int]], basic_gates: List[str], compensate_angle_map_json: str, specified_block: List[int], optim_level: int)#
Transpile a quantum circuit for a specific quantum backend.
Compiles a quantum circuit to match the constraints of a target quantum device, including topology, gate set, and compensation angles.
- Parameters:
prog (
str) – Quantum circuit to transpile in OriginIR format.chip_topology_edges (
List[List[int]]) – Physical qubit connectivity as a list of edges [q1, q2].basic_gates (
List[str]) – Set of basic quantum gates supported by the physical device.compensate_angle_map_json (
str) – JSON string containing angle compensation mapping for two-qubit gates.specified_block (
List[int]) – Physical qubit indices where the circuit should be placed. Must be a subset of vertices in the chip_topology_edges graph.optim_level (
int) – Transpilation optimization level (0-2, higher means more optimization).
- Returns:
Transpiled quantum circuit in OriginIR format.
- Return type:
str- Raises:
RuntimeError – If transpilation fails due to unsupported gates or topology constraints.
Notes
This is a low-level static method that performs actual transpilation.
Uses pyqpanda3’s Transpiler and ChipBackend for compilation.
If transpilation fails, the program may terminate immediately.
For safer transpilation, use the instance method transpile() instead.
References
Quantum Circuit Transpiler Tutorial: https://qcloud.originqc.com.cn/document/qpanda-3/cn/d3/df1/tutorial_quantum_circuit_transpiler.html
OriginIR Format Documentation: https://qcloud.originqc.com.cn/document/qpanda-3/cn/d7/d65/tutorial_quantum_program_of_content__origin_i_r.html
See also
transpileSafer instance method for circuit transpilation.
- sample(prog: qpanda3_runtime.utils.union_type.QProgUnionType, shots: int = 1)#
Perform sampling calculation on a quantum circuit.
Executes the quantum circuit multiple times (shots) and returns the measurement outcome probabilities, simulating the behavior of a real quantum device with noise.
- Parameters:
prog (
QProgUnionType) – Quantum circuit to execute. Can be a QProg object or OriginIR string.shots (
int, optional) – Number of measurement shots (circuit executions). Default is 1.
- Returns:
Dictionary mapping measurement bitstrings to their probabilities. Keys are binary strings (e.g., ‘0101’), values are probabilities.
- Return type:
Dict[str,float]
Notes
Uses CPUQVM for simulation with the device’s noise model.
Automatically handles qubit remapping for the simulation.
The noise model includes decoherence and readout errors.
For noiseless simulation, create a FakeBackend with noise_info=None.
Examples
>>> # Sample a quantum circuit >>> circuit = QProg() << H(0) << CNOT(0, 1) << Measure([0, 1]) >>> results = fake_backend.sample(circuit, shots=1000) >>> print(f"Measurement probabilities: {results}")
See also
estimateCalculate expectation values of observables.
- static remap_qbits_pauli(pauli_op: pyqpanda3.hamiltonian.PauliOperator, remap_qbits: Dict[int, int]) pyqpanda3.hamiltonian.PauliOperator#
Remap qubit indices in a Pauli operator.
Creates a new PauliOperator with qubit indices remapped according to the provided mapping. The original operator is not modified.
- Parameters:
pauli_op (
PauliOperator) – Original Pauli operator to remap.remap_qbits (
Dict[int,int]) – Qubit index mapping dictionary. Keys are original qubit indices, values are new qubit indices.
- Returns:
New Pauli operator with remapped qubit indices.
- Return type:
PauliOperator
Notes
The original PauliOperator is not modified.
Useful when circuit qubits are remapped for simulation.
Maintains the same coefficients and Pauli terms, only changes qubit indices.
Examples
>>> # Original Pauli operator >>> pauli = PauliOperator([("Z0 Z1", 1.0), ("X2", 0.5)]) >>> >>> # Remap qubits 0->2, 1->3, 2->0 >>> remap = {0: 2, 1: 3, 2: 0} >>> remapped = FakeBackend.remap_qbits_pauli(pauli, remap) >>> # Result: Z2 Z3 with coefficient 1.0, X0 with coefficient 0.5
See also
pyqpanda3.hamiltonian.PauliOperatorThe Pauli operator class.
- estimate(prog: qpanda3_runtime.utils.union_type.QProgUnionType, observable: pyqpanda3.hamiltonian.PauliOperator, shots: int = 1)#
Calculate the expectation value of an observable on a quantum circuit.
Computes the expectation value ⟨ψ|O|ψ⟩ where |ψ⟩ is the state prepared by the circuit and O is the observable (Pauli operator).
- Parameters:
prog (
QProgUnionType) – Quantum circuit that prepares the state |ψ⟩. Can be a QProg object or OriginIR string.observable (
PauliOperator) – Observable operator O whose expectation value is to be calculated.shots (
int, optional) – Number of measurement shots for expectation value estimation. Default is 1.
- Returns:
Expectation value ⟨ψ|O|ψ⟩.
- Return type:
float
Notes
Uses the device’s noise model for realistic simulation.
Automatically handles qubit remapping and identity gate insertion.
For variational algorithms, this is typically the cost function.
Examples
>>> # Define a simple circuit >>> circuit = QProg() << H(0) << CNOT(0, 1) >>> >>> # Define an observable (Z0 Z1) >>> observable = PauliOperator([("Z0 Z1", 1.0)]) >>> >>> # Calculate expectation value >>> expectation = fake_backend.estimate(circuit, observable, shots=1000) >>> print(f"Expectation value: {expectation}")
See also
samplePerform sampling measurements on a circuit.
pyqpanda3.core.expval_pauli_operatorLow-level expectation value function.
- transpile(progs: List[qpanda3_runtime.utils.union_type.QProgUnionType], specified_block: List[int] | None = None, is_optimization: bool = True)#
Transpile multiple quantum circuits safely.
Compiles quantum circuits to match the device constraints using a safe multiprocessing approach that isolates exceptions. This method should be called within if __name__ == ‘__main__’: block due to Python’s multiprocessing restrictions.
- Parameters:
progs (
List[QProgUnionType]) – List of quantum circuits to transpile.specified_block (
Optional[List[int]], optional) – Physical qubit indices where circuits should be placed. Default is None (use all available qubits).is_optimization (
bool, optional) – Whether to enable circuit optimization during transpilation. Default is True.
- Returns:
A tuple containing: - List[str]: Successfully transpiled circuits in OriginIR format. - List[str]: Circuits that failed to transpile.
- Return type:
Tuple[List[str],List[str]]- Raises:
RuntimeError – If any circuit fails to transpile.
Notes
Uses multiprocessing for isolation and safety.
Must be called within if __name__ == ‘__main__’: block.
Delegates to runtime_service.transpile_safe for actual transpilation.
Returns both successful and failed circuits for error handling.
References
Quantum Circuit Transpiler Tutorial: https://qcloud.originqc.com.cn/document/qpanda-3/cn/d3/df1/tutorial_quantum_circuit_transpiler.html
OriginIR Format Documentation: https://qcloud.originqc.com.cn/document/qpanda-3/cn/d7/d65/tutorial_quantum_program_of_content__origin_i_r.html
Examples
>>> if __name__ == '__main__': >>> circuits = [circuit1, circuit2, circuit3] >>> transpiled, failed = fake_backend.transpile(circuits) >>> print(f"Transpiled {len(transpiled)} circuits, failed: {len(failed)}")
See also
transpile_Low-level static method for single circuit transpilation.
- to_json_dict()#
Serialize the FakeBackend to a JSON-serializable dictionary.
- Returns:
Dictionary containing all necessary information to reconstruct the FakeBackend, including: - ‘type’: Always ‘FakeBackend’ - ‘real_device’: ID of the real device being simulated - ‘chip_topology_edges’: Physical qubit connectivity - ‘basic_gates’: Supported gate set - ‘compensate_angle_map’: Angle compensation data - ‘noise_info’: Noise model information - ‘qubit_params_origin’: Original qubit parameters - ‘channel’: Access channel identifier
- Return type:
Dict
Notes
Implements the abstract method from DeviceABC.
The dictionary is JSON-serializable for storage or transmission.
Can be used with from_json_dict to recreate the object.
See also
from_json_dictReconstruct a FakeBackend from serialized data.
DeviceABC.to_json_dictAbstract base class method.
- static from_json_dict(runtime_service, dev_data)#
Reconstruct a FakeBackend from serialized data.
- Parameters:
runtime_service (
RuntimeService) – Runtime service for device management.dev_data (
Dict) – Dictionary containing serialized FakeBackend data, as returned by to_json_dict().
- Returns:
Reconstructed FakeBackend object.
- Return type:
Notes
This is a static method for object reconstruction.
Requires a runtime_service for device configuration queries.
The noise_info from dev_data overrides device statistics.
See also
to_json_dictSerialize a FakeBackend to dictionary.
- channel()#
Get the channel for quantum device communication.
- Returns:
The channel used for communicating with the quantum device.
- Return type:
Any
Notes
This attribute is set during FakeBackend initialization.
It represents the communication channel for device operations.