qpanda3_runtime.device#

Quantum device interfaces for QPanda3 Runtime.

This module provides interfaces to quantum computing devices, including real quantum backends and simulated fake backends for testing and development.

Classes#

QDeviceclass

Interface to quantum computing devices (real or simulated).

FakeBackendclass

Simulated quantum backend for testing without real hardware.

Examples

>>> from qpanda3_runtime.device import QDevice, FakeBackend
>>> # Connect to a real quantum device
>>> real_device = QDevice('quantum_backend_url', access_token='token')
>>> result = real_device.run(circuit, shots=1000)
>>> # Use a fake backend for testing
>>> fake_device = FakeBackend()
>>> test_result = fake_device.run(test_circuit, shots=100)
QDevice.run(circuit, shots=1000, \*\*kwargs)#

Execute a quantum circuit on the device.

Parameters:
  • circuit (QuantumCircuit or str) – Quantum circuit to execute.

  • shots (int, optional) – Number of measurement shots (default: 1000).

  • **kwargs (dict) – Additional device-specific parameters.

Returns:

Measurement results and metadata.

Return type:

dict

FakeBackend.run(circuit, shots=100, noise_model=None)#

Execute a circuit on a simulated backend.

Parameters:
  • circuit (QuantumCircuit) – Circuit to simulate.

  • shots (int, optional) – Number of shots (default: 100).

  • noise_model (dict, optional) – Noise model for simulation.

See also

qpanda3_runtime.runtime_service

Main service client for device management.

pyqpanda3

Core quantum circuit library.

Notes

  • Real quantum devices require valid access tokens and backend URLs.

  • Fake backends are useful for algorithm development and testing.

  • Device calibration and availability may vary by provider.

Submodules#

Classes#

QDevice

Interface to real quantum computing devices.

FakeBackend

Simulated quantum backend that mimics a real quantum computer/chip.

Package Contents#

class qpanda3_runtime.device.QDevice(runtime_service, dev_info, update_basic_info=True)#

Bases: qpanda3_runtime.device.device_abc.DeviceABC

Interface to real quantum computing devices.

Represents a physical quantum computer/chip backend, providing access to device information, configuration, and the ability to create simulated counterparts for testing.

Parameters:
  • runtime_service (RuntimeService) – Local management object for the QPanda3 Runtime Service, used for defining and submitting quantum computing tasks.

  • dev_info (Dict) – Metadata dictionary containing device information such as: - ‘chip_id’: Unique identifier for the device - ‘channel’: Access channel identifier - ‘nameDetail’: Human-readable device name - ‘qubitNum’: Number of qubits (may be populated later)

  • update_basic_info (bool, optional) – Whether to immediately update device information from the server. Default is True.

Variables:
  • _basic_info (Dict) – Basic device information (name, ID, qubit count, etc.).

  • _config_info (Dict) – Detailed configuration information (topology, gates, noise, etc.).

  • _runtime_service (RuntimeService) – Runtime service for device management and task submission.

Notes

  • This class represents actual quantum hardware, not simulations.

  • Device information is lazily loaded when accessed.

  • Can generate a FakeBackend for simulation based on real device data.

  • Implements the DeviceABC interface for serialization.

Examples

>>> from qpanda3_runtime import RuntimeService
>>> from qpanda3_runtime.device import QDevice
>>>
>>> # Create a QDevice from device list
>>> runtime = RuntimeService()
>>> devices = runtime.list_devices()
>>> real_device = QDevice(runtime, devices[0].basic_info())
>>>
>>> # Access device information
>>> print(f"Device: {real_device.name()}, Qubits: {real_device.qubit_num()}")
>>>
>>> # Create a simulated version for testing
>>> fake_device = real_device.fake_backend()

See also

FakeBackend

Simulated version of a quantum device.

DeviceABC

Abstract base class for quantum devices.

RuntimeService.list_devices

Get available quantum devices.

channel()#

Get the access channel for the quantum device.

Returns:

Access channel identifier (e.g., ‘qcloud’, ‘local_simulator’).

Return type:

str

Notes

  • The channel determines how the device is accessed (cloud, local, etc.).

  • Used internally for routing quantum computing tasks.

  • Typically set during device initialization.

Examples

>>> device = QDevice(runtime, dev_info)
>>> print(f"Access channel: {device.channel()}")
chip_id()#

Get the unique identifier of the quantum device.

Returns:

Unique device identifier (e.g., ‘chip_001’, ‘quantum_backend_1’).

Return type:

str

Notes

  • The chip ID is used to uniquely identify the device in the system.

  • Required for device-specific operations and configuration queries.

  • Should be present in the dev_info provided during initialization.

Examples

>>> device = QDevice(runtime, dev_info)
>>> print(f"Device ID: {device.chip_id()}")
basic_info()#

Get the basic information dictionary for the quantum device.

Returns:

Dictionary containing basic device information, typically including: - ‘chip_id’: Unique device identifier - ‘channel’: Access channel - ‘nameDetail’: Human-readable name - ‘qubitNum’: Number of qubits (may be None initially) - Other device-specific metadata

Return type:

Dict

Notes

  • This is the same dictionary passed during initialization.

  • May be updated by update_basic_info().

  • Useful for debugging or displaying device information.

Examples

>>> device = QDevice(runtime, dev_info)
>>> info = device.basic_info()
>>> print(f"Device info keys: {list(info.keys())}")
update_basic_info()#

Update basic device information from the server.

Fetches the latest device information from the runtime service and updates the local basic_info dictionary.

Notes

  • Queries the server for the most up-to-date device information.

  • Updates fields like nameDetail, qubitNum, and other metadata.

  • Called automatically during initialization if update_basic_info=True.

  • Can be called manually to refresh device information.

Examples

>>> device = QDevice(runtime, dev_info, update_basic_info=False)
>>> # Later, update information
>>> device.update_basic_info()
>>> print(f"Updated name: {device.name()}")

See also

basic_info

Get the current basic information.

name

Get the device name (calls update_basic_info if needed).

name()#

Get the human-readable name of the quantum device.

Returns:

Device name (e.g., ‘Origin Quantum Chip v1.0’, ‘IBM Quantum Montreal’).

Return type:

str

Notes

  • The name is stored in the ‘nameDetail’ field of basic_info.

  • If not available locally, updates basic_info from the server.

  • Useful for user interfaces and logging.

Examples

>>> device = QDevice(runtime, dev_info)
>>> print(f"Device name: {device.name()}")
available_qubits()#

Get the list of available qubits on the quantum device.

Returns:

List of qubit indices that are available for use.

Return type:

list

config_info()#

Get the detailed configuration information dictionary.

Returns:

Dictionary containing detailed device configuration, typically including: - ‘BasicQGate’: List of supported basic quantum gates - ‘CompensateAngle’: Angle compensation mapping - ‘adjMatrix’: Adjacency matrix for qubit connectivity - ‘QGateClock’: Gate timing information - ‘QubitParamsOrigin’: Qubit-specific parameters (T1, T2, etc.)

Return type:

Dict

Notes

  • Configuration information is lazily loaded on first access.

  • Contains technical details needed for circuit compilation.

  • Used by FakeBackend to create accurate simulations.

Examples

>>> device = QDevice(runtime, dev_info)
>>> config = device.config_info()
>>> print(f"Supported gates: {config.get('BasicQGate', [])}")
update_config_info()#

Update configuration information from the server.

Fetches the latest device configuration from the runtime service and updates the local config_info dictionary.

Notes

  • Queries the server for detailed device configuration.

  • Updates fields like gate set, topology, noise parameters.

  • Called automatically when configuration information is first accessed.

  • Can be called manually to refresh configuration.

Examples

>>> device = QDevice(runtime, dev_info)
>>> # Force update of configuration
>>> device.update_config_info()
>>> print(f"Updated gate set: {device.basic_gates()}")

See also

config_info

Get the current configuration information.

basic_gates

Get supported gates (calls update_config_info if needed).

basic_gates(update_info: bool = False)#

Get the basic quantum gates supported by the device.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

List of basic quantum gate names supported at the physical level.

Return type:

List[str]

Notes

  • These are the gates that can be directly executed on the hardware.

  • Circuit transpilation decomposes higher-level gates into these.

  • Information is cached after first retrieval.

Examples

>>> device = QDevice(runtime, dev_info)
>>> gates = device.basic_gates()
>>> print(f"Device supports: {gates}")
>>>
>>> # Force update from server
>>> gates = device.basic_gates(update_info=True)
compensate_angle_map(update_info: bool = False)#

Get the angle compensation mapping for two-qubit gates.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

Dictionary mapping qubit pairs to angle compensation values. Used to correct systematic errors in two-qubit gate operations.

Return type:

Dict

Notes

  • Compensation angles are device-specific calibration data.

  • Applied during circuit transpilation to improve gate fidelity.

  • Information is cached after first retrieval.

Examples

>>> device = QDevice(runtime, dev_info)
>>> comp_map = device.compensate_angle_map()
>>> print(f"Compensation map has {len(comp_map)} entries")
chip_topo_adjoint_matrix(update_info: bool = False)#

Get the qubit connectivity as an adjacency matrix.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

Adjacency matrix representation of qubit connectivity. Keys are qubit indices, values are lists of connected qubits with additional information (e.g., {‘v’: connected_qubit_index}).

Return type:

Dict[int, List[Dict[str, int]]]

Notes

  • Represents which qubit pairs can directly interact.

  • Used for circuit compilation and qubit mapping.

  • Information is cached after first retrieval.

Examples

>>> device = QDevice(runtime, dev_info)
>>> adj_matrix = device.chip_topo_adjoint_matrix()
>>> print(f"Qubit 0 connects to: {adj_matrix.get(0, [])}")
chip_topo_edges(update_info: bool = False)#

Get the qubit connectivity as a list of edges.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

List of edges representing qubit connectivity. Each edge is [q1, q2] where q1 < q2 and qubits can directly interact.

Return type:

List[List[int]]

Notes

  • Derived from the adjacency matrix for easier processing.

  • Each edge appears only once (q1 < q2).

  • Used by FakeBackend and circuit transpilation algorithms.

  • Information is cached after first computation.

Examples

>>> device = QDevice(runtime, dev_info)
>>> edges = device.chip_topo_edges()
>>> print(f"Device has {len(edges)} direct connections")
>>> for q1, q2 in edges[:5]:
>>>     print(f"  {q1} -- {q2}")
gate_clock(update_info: bool = False)#

Get the timing information for quantum gate operations.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

Dictionary containing gate timing information, typically including execution times for different gate types (single-qubit, two-qubit, etc.).

Return type:

Dict

Notes

  • Gate timing affects decoherence error modeling in simulations.

  • Used by FakeBackend to create accurate noise models.

  • Information is cached after first retrieval.

Examples

>>> device = QDevice(runtime, dev_info)
>>> clock_info = device.gate_clock()
>>> print(f"Gate timing: {clock_info}")
qubit_info(update_info: bool = False)#

Get detailed information about individual qubits.

Parameters:

update_info (bool, optional) – If True, force an update from the server before returning. If False, use cached information if available. Default is False.

Returns:

Dictionary mapping qubit indices (as strings) to qubit parameter dictionaries. Each qubit dictionary typically includes: - ‘T1’: T1 decoherence time - ‘T2’: T2 decoherence time - ‘FidelityMat’: Readout fidelity matrix - Other qubit-specific calibration data

Return type:

Dict[str, Dict]

Notes

  • Used for noise modeling in simulations.

  • Qubit parameters vary across the device due to manufacturing variations.

  • Information is cached after first retrieval.

Examples

>>> device = QDevice(runtime, dev_info)
>>> qubits = device.qubit_info()
>>> q0_info = qubits.get('0', {})
>>> print(f"Qubit 0 T1: {q0_info.get('T1', 'N/A')}")
fake_backend()#

Create a simulated version of this quantum device.

Returns:

A FakeBackend object configured with this device’s topology, gate set, and noise characteristics.

Return type:

FakeBackend

Notes

  • The FakeBackend uses the same configuration as this real device.

  • Useful for testing algorithms before running on real hardware.

  • Noise models are derived from device calibration data.

Examples

>>> device = QDevice(runtime, dev_info)
>>> # Create a simulated version for testing
>>> simulator = device.fake_backend()
>>> # Test circuit on simulator
>>> result = simulator.sample(test_circuit, shots=1000)

See also

FakeBackend

The simulated quantum device class.

to_json_dict()#

Serialize the QDevice to a JSON-serializable dictionary.

Returns:

Dictionary containing all necessary information to reconstruct the QDevice, including: - ‘type’: Always ‘QDevice’ - ‘basic_info’: Basic device information - ‘config_info’: Detailed configuration information

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.

  • Configuration information may be empty if not yet loaded.

See also

from_json_dict

Reconstruct a QDevice from serialized data.

DeviceABC.to_json_dict

Abstract base class method.

static from_json_dict(runtime_service, dev_data)#

Reconstruct a QDevice from serialized data.

Parameters:
  • runtime_service (RuntimeService) – Runtime service for device management.

  • dev_data (Dict) – Dictionary containing serialized QDevice data, as returned by to_json_dict().

Returns:

Reconstructed QDevice object.

Return type:

QDevice

Notes

  • This is a static method for object reconstruction.

  • The reconstructed device will have cached configuration if present.

  • Basic information update is disabled during reconstruction.

See also

to_json_dict

Serialize a QDevice to dictionary.

class qpanda3_runtime.device.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.DeviceABC

Simulated 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

QDevice

Real quantum device interface.

DeviceABC

Abstract 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_info

Get noise information as a dictionary.

pyqpanda3.core.NoiseModel

The 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_model

Get 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.

See also

transpile

Safer 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

estimate

Calculate 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.PauliOperator

The 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

sample

Perform sampling measurements on a circuit.

pyqpanda3.core.expval_pauli_operator

Low-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.

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_dict

Reconstruct a FakeBackend from serialized data.

DeviceABC.to_json_dict

Abstract 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:

FakeBackend

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_dict

Serialize 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.