qpanda3_runtime#

QPanda3 Runtime Client Package.

This package provides the client-side interface for QPanda3 quantum computing runtime services. It includes modules for quantum device management, task execution, and runtime service interaction.

Modules#

runtime_serviceRuntimeService

Main client manager class for quantum runtime services.

access_serviceAccess service modules

Network communication and channel management.

deviceQuantum device modules

Quantum device interfaces and fake backends.

toolboxUtility tools

Checkpointing, tracking, and debugging utilities.

taskTask management

Quantum task execution and session management.

utilsUtility functions

Helper functions and exception handling.

Examples

>>> from qpanda3_runtime import RuntimeService
>>> service = RuntimeService('https://localhost:8080')
>>> device = service.get_device('quantum_backend')
>>> task = device.run(circuit, shots=1000)

See also

qpanda3_runtime_server

Server-side package for QPanda3 runtime services.

pyqpanda3

Core quantum computing library.

Notes

  • This package requires a running QPanda3 runtime server.

  • Authentication tokens are managed automatically by the RuntimeService.

  • All quantum operations are tracked for debugging and monitoring.

Submodules#

Classes#

RuntimeService

QPanda3 Runtime Service Client Manager Class.

QDevice

Interface to real quantum computing devices.

FakeBackend

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

CheckPoint

Manual checkpointing and recovery tool for quantum computation states.

Tracker

User interface for tracking operations with three usage patterns.

TraceAnalyzer

Trace data analyzer for rule-based analysis of tracking traces.

TrackerRef

Reference wrapper for tracker instances in decorator scenarios.

QTaskManager

Quantum Computing Task Manager for QPanda3 Runtime Service.

VQSession

Concrete implementation of variational quantum computing session.

FakeVQSession

Fake variational quantum session for local testing and simulation.

AnsatzParamsBinding

Binding manager for ansatz circuits and gate parameters.

CircuitObservableBinding

Binding manager for quantum circuits and observables.

AnsatzObservableBinding

Binding manager for ansatz-parameter combinations and observables.

Functions#

tracker(service[, ref, data])

Decorator for automatic function tracking.

Package Contents#

class qpanda3_runtime.RuntimeService(url_or_cfgfile: str = 'https://qpanda3-runtime.qpanda.cn', trace_record_file: str = None, auto_track: bool = False)#

Bases: qpanda3_runtime.toolbox.tracker.TrackerSystem

QPanda3 Runtime Service Client Manager Class.

Manages user requests and response data for quantum runtime services.

Parameters:
  • url_or_cfgfile (str) – Either a URL address or a path to a YAML configuration file. - URL: Quantum runtime server access address (e.g., ‘https://localhost:8080’) - File path: YAML file containing server URL and API key credentials

  • trace_record_file (str, optional) – Path to trace record file for tracking operations. Required if auto_track is True.

  • auto_track (bool, optional) – Whether to automatically track operations. Default is False.

Variables:
  • tokens (dict) – Currently logged-in compute backend access channels and their corresponding access tokens.

  • base_url (str) – QPanda3 Runtime server URL.

Examples

Method 1: Direct URL

>>> service = RuntimeService('https://localhost:8080')

Method 2: Configuration file

>>> # config.yml
... api_key: '9B41FB6534584E45BD6BE0E6'
... server_url: 'https://localhost:8080'
>>> service = RuntimeService(r'config.yml')
tokens#

Currently logged-in compute backend access channels and their corresponding access tokens.

base_url = None#

QPanda3 Runtime server URL

login(api_key, channel: str = default_channel)#

Authenticate to the specified compute backend access channel.

Parameters:
  • api_key (str) – API key credentials for authentication.

  • channel (str, optional) – Compute backend access channel. Default is default_channel.

Returns:

Access token for the specified compute backend.

Return type:

str

Raises:

RuntimeError – If authentication fails or server returns unexpected response.

Examples

>>> service = RuntimeService('https://localhost:8080')
>>> token = service.login('9B41FB6534584E45BD6BE0E6')
query_task(channel: str, task_id: list, additional_info: List[str] | None = None, using_http=True, timeout: float = 600)#

Query execution results and related information for specified compute tasks.

Parameters:
  • channel (str) – Compute backend access channel.

  • task_id (List[str]) – List of subtask IDs uniquely identifying the compute task.

  • additional_info (Optional[List[str]], optional) – Additional query fields for task execution information. Refer to compute backend documentation for available fields.

  • using_http (bool, optional) – Protocol to use for query transmission. - True: Use HTTP protocol (default) - False: Use TCP protocol

Returns:

Execution results and related information for each task.

Return type:

list

Raises:

RuntimeError – If channel is not logged in or query fails.

list_devices(channel=default_channel, target: int | str = '')#

List quantum computing devices available on the specified compute backend.

Parameters:
  • channel (str, optional) – Compute backend access channel. Default is default_channel.

  • target (Union[int, str], optional) – Single device ID to retrieve. If empty, returns all devices.

Returns:

  • If target is empty: List of all available QDevice objects

  • If target is specified: Single QDevice object for the specified device

Return type:

Union[List[QDevice], QDevice]

Raises:

RuntimeError – If target device is not available or server returns unexpected response.

query_device_config(dev: qpanda3_runtime.device.qdevice.QDevice)#

Query configuration and parameter information of the specified quantum computing device.

Parameters:

dev (QDevice) – Quantum computing device to query.

Returns:

Device configuration and parameter information, including: - Quantum topology structure - Noise statistics (T1, T2, readout error rates) - Other device-specific parameters

Return type:

dict

Raises:

RuntimeError – If query fails or server returns unexpected response.

sample(circuits: qpanda3_runtime.utils.union_type.QProgUnionType | List[qpanda3_runtime.utils.union_type.QProgUnionType] | qpanda3_runtime.task.program_set.gate_params_bind_rule.AnsatzParamsBinding | Tuple[pyqpanda3.vqcircuit.VQCircuit, List[numpy.ndarray]], device: qpanda3_runtime.device.qdevice.QDevice | qpanda3_runtime.device.fake_backend.FakeBackend, measure_qubits: List[int] | None = None, specified_block: List[int] | None = None, shots: int = 10, is_amend: bool = True, is_mapping: bool = True, is_optimization: bool = True, point_label: int = 0, task_describe: str = '') → qpanda3_runtime.task.qtask_manager.QTaskManager#

Submit sampling computation task to quantum runtime server.

Core quantum computing operation for sampling measurement results.

Parameters:
  • circuits (Union[QProgUnionType, List[QProgUnionType], AnsatzParamsBinding, Tuple[VQCircuit, List[numpy.ndarray]]]) – Quantum circuits for sampling task. - QProgUnionType: Single quantum program - List[QProgUnionType]: Multiple quantum programs - AnsatzParamsBinding: Parameterized ansatz circuits - Tuple[VQCircuit, List[numpy.ndarray]]: VQCircuit with parameter arrays

  • device (Union[QDevice, FakeBackend]) – Quantum computing device. - QDevice: Real quantum computer/chip - FakeBackend: Local simulation with noise models

  • measure_qubits (Optional[List[int]], optional) – Qubits to measure. If circuit has measurement nodes, replaces them. If circuit has no measurement nodes, must be provided.

  • specified_block (Optional[List[int]], optional) – Physical qubit indices to use. Empty list enables automatic selection.

  • shots (int, optional) – Number of sampling trials. Default is 10.

  • is_amend (bool, optional) – Enable error mitigation amendment. Default is True.

  • is_mapping (bool, optional) – Enable qubit mapping. Default is True.

  • is_optimization (bool, optional) – Enable circuit optimization. Default is True.

  • point_label (int, optional) – Currently disabled parameter.

  • task_describe (str, optional) – Currently disabled parameter.

Returns:

Local task manager for monitoring and retrieving results.

Return type:

QTaskManager

Raises:

RuntimeError – If parameters are invalid or task submission fails.

estimate(circuit_with_observable: Tuple[qpanda3_runtime.utils.union_type.QProgUnionType | List[qpanda3_runtime.utils.union_type.QProgUnionType], qpanda3_runtime.utils.union_type.ObservableUnionType] | qpanda3_runtime.task.program_set.observable_bind_rule.CircuitObservableBinding | qpanda3_runtime.task.program_set.observable_bind_rule.AnsatzObservableBinding, device: qpanda3_runtime.device.qdevice.QDevice | qpanda3_runtime.device.fake_backend.FakeBackend, specified_block: List[int] | None = None, shots: int = 1000, is_amend: bool = True, is_mapping: bool = True, is_optimization: bool = True, task_describe: str = '') → qpanda3_runtime.task.qtask_manager.QTaskManager#

Submit Hamiltonian expectation estimation task to quantum runtime server.

Core quantum computing operation for estimating observable expectations.

Parameters:
  • circuit_with_observable (Union[Tuple[Union[QProgUnionType, List[QProgUnionType]], ObservableUnionType], CircuitObservableBinding, AnsatzObservableBinding]) – Quantum circuits and observables for expectation estimation. - Tuple: (circuit(s), observable) - CircuitObservableBinding: Pre-bound circuit-observable pairs - AnsatzObservableBinding: Parameterized ansatz with observables

  • device (Union[QDevice, FakeBackend]) – Quantum computing device. - QDevice: Real quantum computer/chip - FakeBackend: Local simulation with noise models

  • specified_block (Optional[List[int]], optional) – Physical qubit indices to use. Empty list enables automatic selection.

  • shots (int, optional) – Number of sampling trials. Default is 1000.

  • is_amend (bool, optional) – Enable error mitigation amendment. Default is True.

  • is_mapping (bool, optional) – Enable qubit mapping. Default is True.

  • is_optimization (bool, optional) – Enable circuit optimization. Default is True.

  • task_describe (str, optional) – Currently disabled parameter.

Returns:

Local task manager for monitoring and retrieving results.

Return type:

QTaskManager

Raises:

RuntimeError – If parameters are invalid or task submission fails.

get_task(task_id: str | List[str], channel=default_channel)#

Create local task management object for existing computation tasks.

Parameters:
  • task_id (Union[str, List[str]]) – Computation task ID(s). - str: Single task ID - List[str]: Collection of subtask IDs

  • channel (str, optional) – Backend access channel where the task resides. Default is default_channel.

Returns:

Local task management object for monitoring and retrieving results.

Return type:

QTaskManager

Notes

This method creates a management object for tasks already submitted to the runtime server.

device(chip_id: int | str, channel=default_channel) → qpanda3_runtime.device.qdevice.QDevice#

Create local management object for quantum computing device.

Parameters:
  • chip_id (Union[int, str]) – Device identifier.

  • channel (str, optional) – Backend access channel. Default is default_channel.

Returns:

Local device management object.

Return type:

QDevice

Raises:

RuntimeError – If chip_id is empty or device creation fails.

fake_backend(real_device: qpanda3_runtime.device.qdevice.QDevice, channel='local_simulator', noise_info: dict | None = None) → qpanda3_runtime.device.fake_backend.FakeBackend#

Create FakeBackend for local simulation of real quantum device.

Parameters:
  • real_device (QDevice) – Real quantum computer/chip to simulate.

  • channel (str, optional) – Simulation channel. Currently must be ‘local_simulator’.

  • noise_info (Union[dict, None], optional) – Noise model dictionary for simulation. - None: Use noise data from corresponding real device - dict: Custom noise model parameters

Returns:

Local simulation backend with noise models.

Return type:

FakeBackend

static transpile_safe(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 quantum circuits using multi-processing for exception isolation.

This method executes locally on the client side and must be called within __name__ == ‘__main__’ environment due to Python multiprocessing restrictions.

Parameters:
  • prog (str) – Quantum circuit to transpile (OriginIR format).

  • chip_topology_edges (List[List[int]]) – Physical qubit topology edges of the quantum computing backend.

  • basic_gates (List[str]) – Basic quantum gates supported at physical level.

  • compensate_angle_map_json (str) – Compensation angle mapping data in JSON format.

  • specified_block (List[int]) – Physical qubit indices for circuit placement. Empty list enables automatic selection.

  • optim_level (int) – Transpilation optimization level.

Returns:

Transpiled quantum circuit in OriginIR format.

Return type:

str

Raises:

RuntimeError – If transpilation fails or times out.

vqsession(vqcircuit: pyqpanda3.vqcircuit.VQCircuit, device: qpanda3_runtime.device.qdevice.QDevice | qpanda3_runtime.device.fake_backend.FakeBackend, shots=1000, life_time=360, observable: qpanda3_runtime.utils.union_type.ObservableUnionType | None = None)#

Request variational quantum computing session from runtime service.

Parameters:
  • vqcircuit (VQCircuit) – Variational quantum circuit (Ansatz structure) for parameterized circuits.

  • device (Union[QDevice, FakeBackend]) – Quantum computing device for the session. - QDevice: Real quantum computer/chip - FakeBackend: Local simulation

  • shots (int, optional) – Number of sampling trials per circuit. Default is 1000.

  • life_time (float, optional) – Session lifespan in seconds. Default is 360.

  • observable (Union[ObservableUnionType, None], optional) – Observable for expectation estimation tasks.

Returns:

Local session management object.

Return type:

Union[VQSession, FakeVQSession]

Notes

Use the with statement to manage VQSession context lifecycle.

run_vqtask(session_id, gate_params, measure_list: list = [], channel=default_channel, return_type: str = 'QTaskManager')#

Add quantum computing task to variational computing session.

Parameters:
  • session_id (str) – Variational computing session ID.

  • gate_params (array-like) – Quantum gate parameters for Ansatz structure.

  • measure_list (list, optional) – Qubit indices to measure. Default is empty list.

  • channel (str, optional) – Access channel to quantum computing device. Default is default_channel.

  • return_type (str, optional) – Return value type control. - ‘QTaskManager’: Returns QTaskManager object (default) - Other: Returns dictionary with task information

Returns:

Task management object or task information dictionary.

Return type:

Union[QTaskManager, dict]

Raises:

RuntimeError – If session is invalid or task submission fails.

release_session(session_id: str, chip_id: str, channel: str = default_channel)#

Release quantum runtime service session.

Parameters:
  • session_id (str) – Quantum runtime service session ID.

  • chip_id (str) – Quantum runtime service chip ID ID.

  • channel (str, optional) – Access channel of the session. Default is default_channel.

Returns:

Server response data.

Return type:

dict

Raises:

RuntimeError – If session release fails.

recover_qtask_manager(checkpoint_file: str, recover_completely: bool = True) → qpanda3_runtime.task.qtask_manager.QTaskManager#

Recover QTaskManager object from checkpoint file.

Parameters:
  • checkpoint_file (str) – Checkpoint file path.

  • recover_completely (bool, optional) – Recovery mode. - True: Complete recovery, task_state must contain all information (default) - False: Partial recovery, allow default values for missing fields

Returns:

Recovered task management object.

Return type:

QTaskManager

Raises:
  • FileNotFoundError – If checkpoint file does not exist.

  • ValueError – If recover_completely is True and task_state is missing required fields.

  • RuntimeError – Other exceptions during recovery process.

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

class qpanda3_runtime.CheckPoint#

Manual checkpointing and recovery tool for quantum computation states.

A non-semantic key-value container where users are responsible for knowing what they store and how to interpret it. No automatic operations are performed, and no decisions are made on behalf of the user.

Notes

  • Two access channels: recovery (load) with strict version checking, and export (export_data) without version checking

  • Version strategy: uses global package version, immutable per instance

  • Storage strategy: local filesystem only, no backend abstraction

  • Task state acquisition: supports dict or objects with get_task_state()

See also

qpanda3_runtime.runtime_service

Main runtime service client.

qpanda3_runtime.device

Quantum device interfaces.

Examples

>>> from qpanda3_runtime.toolbox import CheckPoint
>>> checkpoint = CheckPoint()
>>> filepath = checkpoint.save(task_state=quantum_state, user_data={'algorithm': 'VQE'})
>>> loaded_data = checkpoint.load(filepath)
property version#

Current software version, read-only.

Type:

str

save(filepath: str | None = None, task_state: Any = None, user_data: Dict | None = None) → str#

Save checkpoint data to file.

Parameters:
  • filepath (str, optional) – Checkpoint file save path. If None, generates default filename in current working directory.

  • task_state (any, optional) – Task state. Supports: - dict: Direct reference, no copy performed - Object with get_task_state() method: Returns state dict - None or other types: Treated as no task state

  • user_data (dict, optional) – User-defined data dictionary. Values must be JSON-serializable.

Returns:

Actual written file path (absolute path).

Return type:

str

Raises:

TypeError – If task_state is non-dict and does not implement get_task_state() method, or if user_data is not a dict.

Notes

  • System does not manage checkpoint identifiers or guarantee filename uniqueness

  • Default filename format: checkpoint_YYYYMMDD_HHMMSS.json

  • When task_state is dict, it is directly referenced (no copy)

  • Version is automatically injected into metadata

  • Existing files are overwritten

  • Not thread-safe for concurrent writes to same file

load(filepath: str) → Dict#

Load checkpoint data with strict version checking (recovery channel).

Parameters:

filepath (str) – Checkpoint file path, must exist and be readable.

Returns:

Dictionary with three fixed keys: - ‘meta’: dict - Read-only metadata, including version, creation time - ‘task_state’: dict - Task state dictionary, may be empty - ‘user_data’: dict - User-defined data

Return type:

dict

Raises:
  • VersionMismatchError – If checkpoint version does not match self.version.

  • FileNotFoundError – If checkpoint file not found.

  • JSONDecodeError – If file content is not valid JSON format.

Notes

  • Strict version checking: version in metadata must equal self.version

  • System does not maintain checkpoint index

  • No automatic recovery operations performed

export_data(filepath: str) → Dict#

Export checkpoint data without version checking (export channel).

Parameters:

filepath (str) – Checkpoint file path, must exist and be readable.

Returns:

Dictionary with following keys: - ‘meta’: dict - Complete built-in metadata, including version - ‘user_data’: dict - Complete user-defined data - ‘task_state_available’: bool - Whether task state data exists

Return type:

dict

Raises:
  • FileNotFoundError – If checkpoint file not found.

  • JSONDecodeError – If file content is not valid JSON format.

Notes

  • No version checking: can be called across versions

  • Never returns task_state content

  • Read-only operation, does not modify data

  • Metadata includes version information for version comparison

class qpanda3_runtime.Tracker(service: qpanda3_runtime.toolbox.tracker.tracker_system.TrackerSystem, name: str = None, data: Dict[str, Any] = None)#

User interface for tracking operations with three usage patterns.

This class provides a unified interface for tracking operations with support for manual tracking, context manager usage, and decorator-based tracking.

Variables:

is_active (bool) – Indicates whether the tracker is currently active.

Examples

>>> # Manual tracking
>>> tracker = Tracker(service)
>>> tracker.start("operation_name")
>>> tracker.record({"key": "value"})
>>> tracker.end()
>>> # Context manager usage
>>> with Tracker(service, name="operation") as t:
...     t.record({"data": 123})
>>> # Decorator usage
>>> @tracker(service)
... def my_function():
...     pass
start(context_name: str, labels: List[str] = None, data: Dict[str, Any] = None) → Tracker#

Start tracking an operation.

Parameters:
  • context_name (str) – Name of the operation or context being tracked.

  • labels (List[str], optional) – List of labels to categorize the tracking session.

  • data (Dict[str, Any], optional) – Initial data to record for this tracking session.

Returns:

Self reference for method chaining.

Return type:

Tracker

Raises:

RuntimeError – If the tracker is already active or service is not available.

end(result_data: Dict[str, Any] = None, labels: List[str] = None) → Tracker#

End the current tracking session.

Parameters:
  • result_data (Dict[str, Any], optional) – Result data to record at the end of the operation.

  • labels (List[str], optional) – Additional labels to apply to the end record.

Returns:

Self reference for method chaining.

Return type:

Tracker

Notes

If the tracker is not active, this method does nothing and returns the tracker instance unchanged.

record(data: Dict[str, Any], labels: List[str] = None) → Tracker#

Record data during an active tracking session.

Parameters:
  • data (Dict[str, Any]) – Data to record in the current tracking session.

  • labels (List[str], optional) – Labels to associate with this data record.

Returns:

Self reference for method chaining.

Return type:

Tracker

Raises:

RuntimeError – If the tracker is not active when attempting to record data.

exit_broken_context() → None#

Exit a broken context when used as a context manager.

This method is called internally when a context manager exits due to an exception. It ensures proper cleanup of tracking state.

property is_active: bool#

Check if the tracker is currently active.

Returns:

True if the tracker is actively tracking, False otherwise.

Return type:

bool

get_current_record() → qpanda3_runtime.toolbox.tracker.tracker_trace.TrackerTrace#

Get the current tracking record.

Returns:

The current trace record if tracking is active.

Return type:

TrackerTrace

Notes

Returns None if no tracking session is active or if the service does not have a current trace.

qpanda3_runtime.tracker(service: qpanda3_runtime.toolbox.tracker.tracker_system.TrackerSystem, ref: TrackerRef | None = None, data: Any = None)#

Decorator for automatic function tracking.

This decorator automatically tracks function execution including start time, end time, and any exceptions that occur.

Parameters:
  • service (TrackerSystem) – The tracking system service to use.

  • ref (TrackerRef, optional) – Tracker reference for accessing the tracker from within the decorated function.

  • data (Any, optional) – Additional data to associate with the tracking session.

Returns:

Decorator function that wraps the original function.

Return type:

function

Examples

>>> @tracker(service)
... def process_data(data):
...     return data * 2
>>> ref = TrackerRef()
>>> @tracker(service, ref=ref)
... def complex_operation():
...     ref.record({"step": "started"})
...     # operation logic
class qpanda3_runtime.TraceAnalyzer#

Trace data analyzer for rule-based analysis of tracking traces.

This class provides analysis capabilities for tracking trace files using registered analysis rules. It supports automatic rule selection and manual rule specification.

Variables:
  • _rules (TrackingRules) – Manager for tracking analysis rules

  • _trace (TrackerTrace) – Currently loaded trace data for analysis

Examples

>>> analyzer = TraceAnalyzer()
>>> result = analyzer.analyze_file("trace.jsonl")
>>> available_rules = analyzer.get_available_rules()
analyze_file(file_path: str, rule_id: str = None) → Any#

Analyze historical trace file using specified or automatic rule.

Parameters:
  • file_path (str) – Path to the trace file to analyze

  • rule_id (str, optional) – ID of the rule to use for analysis. If None, automatic rule selection is performed based on default rule.

Returns:

Analysis result, format depends on the rule used

Return type:

Any

Raises:
  • FileNotFoundError – If the specified trace file does not exist

  • ValueError – If the specified rule_id is not registered

Notes

  • Trace files are loaded with history records enabled

  • Analysis results are printed to console for debugging

get_available_rules() → List[str]#

Get list of available analysis rule IDs.

Returns:

List of registered rule IDs

Return type:

List[str]

Examples

>>> analyzer = TraceAnalyzer()
>>> rules = analyzer.get_available_rules()
>>> print(rules)
['default', 'qtask_failure']
register_rule(rule: qpanda3_runtime.toolbox.tracker.tracking_rule.TrackingRule) → None#

Register a new analysis rule.

Parameters:

rule (TrackingRule) – Rule instance to register

Notes

  • Registered rules become available for analyze_file()

  • Rules must have unique rule_id values

class qpanda3_runtime.TrackerRef(name: str = '')#

Reference wrapper for tracker instances in decorator scenarios.

This class provides a way to reference a tracker instance from within a decorated function without direct access to the tracker object.

Variables:
  • name (str) – Reference name for identification.

  • is_active (bool) – Indicates whether the referenced tracker is currently active.

Examples

>>> ref = TrackerRef("my_tracker")
>>> @tracker(service, ref=ref)
... def my_function():
...     ref.record({"data": "value"})
name = ''#
tracker = None#
record(data: Dict[str, Any], labels: List[str] = None) → None#

Record data through the referenced tracker.

Parameters:
  • data (Dict[str, Any]) – Data to record in the current tracking session.

  • labels (List[str], optional) – Labels to associate with this data record.

Raises:

RuntimeError – If the tracker reference is not properly initialized or if no tracker is currently active.

property is_active: bool#

Check if the referenced tracker is active.

Returns:

True if the referenced tracker exists and is active.

Return type:

bool

class qpanda3_runtime.QTaskManager(runtime_service, task_data, used_remote_backend=True, used_fake_backend=False, used_program_set=False)#

Quantum Computing Task Manager for QPanda3 Runtime Service.

This class provides local management for quantum computing tasks, including task submission, result retrieval, and state management. It supports synchronous, asynchronous, and background execution modes.

Parameters:
  • runtime_service (RuntimeService) – Runtime service instance for task execution and communication.

  • task_data (Dict) – Task metadata containing task ID, session information, and other configuration parameters.

  • used_remote_backend (bool, default True) – Whether the task uses a remote computational backend.

  • used_fake_backend (bool, default False) – Whether the task uses a FakeBackend simulator.

  • used_program_set (bool, default False) – Whether the task uses ProgramSet for parameterized circuits.

Variables:
  • _runtime_service (RuntimeService) – Reference to the runtime service.

  • _id (Union[str, List[str]]) – Task ID or list of sub-task IDs.

  • _session_id (str) – Session identifier for variational algorithms.

  • _data (Dict) – Original task metadata.

  • _used_remote_backend (bool) – Remote backend usage flag.

  • _used_program_set (bool) – ProgramSet usage flag.

  • _client_task_id (Optional[str]) – Client-generated task identifier.

  • _sub_task_id__result_id (Dict[str, int]) – Mapping from sub-task ID to result index.

  • _result (List[Any]) – Task execution results.

  • _is_transpile_successed (bool) – Circuit transpilation success flag.

  • _processing_sub_task_ids (List[str]) – List of sub-task IDs still being processed.

  • _used_fake_backend (bool) – FakeBackend usage flag.

  • _data_lock (threading.Lock) – Thread lock for concurrent access.

  • _result_fetching_thread (Optional[threading.Thread]) – Background result fetching thread.

Examples

>>> from qpanda3_runtime import RuntimeService
>>> from qpanda3_runtime.task import QTaskManager
>>> # Create task manager for submitted task
>>> runtime_service = RuntimeService()
>>> task_data = {'task_id': 'task_123', 'channel': 'qcloud'}
>>> task_manager = QTaskManager(runtime_service, task_data)
>>> # Retrieve results
>>> results, finished, progress = task_manager.try_get_result()

Notes

  • Thread-safe design for concurrent access

  • Supports checkpoint saving and recovery

  • Provides multiple result retrieval strategies

  • Integrates with tracking system for monitoring

try_get_result(additional_info: List[str] | None = None, timeout: float = 600)#

Query task execution results with incremental strategy.

This method queries the current status of computational tasks and returns available results. It only queries unfinished subtasks but returns all currently obtained result data. Subsequent calls use incremental strategy, storing fetched results internally.

Parameters:
  • additional_info (Optional[List[str]], default None) – Additional query fields for task execution information. Refer to backend documentation for supported fields.

  • timeout (float, default 600) – Timeout in seconds for each query request.

Returns:

Three-element tuple containing: - List of task results (unavailable results marked as “Status:Processing”) - Boolean indicating if all results are complete - String showing completion percentage (e.g., “finished 75%”)

Return type:

Tuple[List[Any], bool, str]

Raises:

RuntimeError – If task query fails or returns error response.

Notes

  • Uses incremental fetching: only queries unfinished subtasks

  • Results are cached internally for subsequent calls

  • For batch tasks, queries all sub-task results

  • Integrates with tracking system for monitoring

Examples

>>> results, finished, progress = task_manager.try_get_result()
>>> while not finished:
...     print(f"Progress: {progress}")
...     time.sleep(5)
...     results, finished, progress = task_manager.try_get_result()
>>> print(f"Final results: {results}")
async get_result_async(additional_info: List[str] | None = None, timeout=1800)#

A coroutine function wrapped for the asyncio asynchronous library.

Parameters:
  • additional_info (Optional[List[str]]) – Query fields related to compute task execution information. For specific details about these fields, please refer to the support documentation of the respective compute backend.

  • timeout (int) – The maximum duration for querying the task process. Once this time length (in seconds) is exceeded, the system will start canceling the query requests for the task.

Returns:

The execution results of the computational task

Return type:

list

get_result_sync(additional_info: List[str] | None = None, timeout=1000 * 1800, using_http=True)#

Synchronously query task execution results with blocking behavior.

This method blocks the client program until all result data is returned or timeout is reached. It continuously polls for results until completion.

Parameters:
  • additional_info (Optional[List[str]], default None) – Additional query fields for task execution information.

  • timeout (int, default 1,800,000) – Maximum query duration in seconds before raising timeout error.

  • using_http (bool, default True) – Protocol to use for query: - True: HTTP protocol - False: TCP protocol

Returns:

Complete task execution results.

Return type:

List[Any]

Raises:

RuntimeError – If query timeout is exceeded or task execution fails.

Notes

  • Blocks until all results are available or timeout

  • Uses polling strategy with adaptive wait times

  • Supports both HTTP and TCP protocols

  • Timeout value should be sufficiently large for quantum tasks

Examples

>>> # Block until results are available (up to 30 minutes)
>>> results = task_manager.get_result_sync(timeout=1800)
>>> print(f"Synchronous results: {results}")
get_result_background(call_back: Callable[[Any], None], additional_info: List[str] | None = None, timeout=1800)#

Use a sub-thread to pull the execution results of the computational task in the background.

Termination of the sub‑thread

The sub‑thread ends after returning all result data, or is terminated when the main thread ends.

Monitoring the status of the sub‑thread

QTaskManager.get_result_background returns a monitoring function. The return value of the monitoring function is a Boolean: True indicates that the background sub‑thread has ended; otherwise, it returns False.

Parameters:
  • call_back (Callable[[Any], None]) – A callback function can be passed to QTaskManager.get_result_background.

  • additional_info (Optional[List[str]]) – Query fields related to compute task execution information. For specific details about these fields, please refer to the support documentation of the respective compute backend.

  • timeout (int) – The maximum duration for querying the task process. Once this time length (in seconds) is exceeded, the system will start canceling the query requests for the task.

Returns:

The execution results of the computational task

Return type:

list

id()#

Get the ID of the computational task (represented by the set of subtask IDs).

Returns:

  • list – The ID of the computational task, a set of subtask IDs.

  • str – The ID of the computational task,a subtask’s id.

progs()#

Retrieve all quantum circuits from the metadata of the quantum computing task.

Returns:

All quantum circuits from the metadata of the quantum computing task

Return type:

list

used_remote_backend()#

Determine whether the quantum computing task uses a remote computing backend.

Returns:

True: Yes

False: No

Return type:

bool

used_fake_backend()#

Determine whether the quantum computing task uses a FakeBackend.

Returns:

True: Yes

False: No

Return type:

bool

run_on_real_device(shots=1000)#

Execute pre-verified task on real quantum hardware.

Submit a quantum computing task that was previously verified on a FakeBackend to real quantum hardware for execution. This method is only available when the current task uses a FakeBackend and transpilation was successful.

Parameters:

shots (int, default 1000) – Number of measurement shots for the experiment.

Returns:

New task manager for the real hardware execution.

Return type:

QTaskManager

Raises:

RuntimeError – If task doesn’t use FakeBackend or transpilation failed.

Notes

  • Requires successful transpilation on FakeBackend

  • Creates new task on real quantum hardware

  • Preserves all task parameters except backend

  • Useful for simulation-to-hardware workflow

Examples

>>> # First run on FakeBackend for verification
>>> fake_task = runtime_service.sample(circuit, fake_backend, shots=100)
>>> # If successful, run on real hardware
>>> if fake_task.used_fake_backend():
...     real_task = fake_task.run_on_real_device(shots=1000)
...     results = real_task.get_result_sync()
channel()#

For getting the backend access channel where the computation task resides

Returns:

The backend access channel where the computation task resides

Return type:

str

get_task_state() → Dict#

Get serializable state of quantum computing task.

Returns a dictionary containing serializable members of QTaskManager instance, used for checkpoint saving and recovery.

Returns:

Dictionary containing the following serializable members: - qtask_manager_init_time: QTaskManager initialization time (timestamp) - session_id: Session ID - data: Task metadata - used_remote_backend: Whether remote backend is used - used_program_set: Whether ProgramSet is used - sub_task_id__result_id: Mapping from sub-task ID to result ID - result: Task execution result - is_transpile_successed: Whether transpilation succeeded - processing_sub_task_ids: List of sub-task IDs being processed - used_fake_backend: Whether FakeBackend is used

Return type:

dict

check_point(filepath: str | None = None, user_data: Dict | None = None) → str#

Save checkpoint data for quantum computing task.

Saves the current task state to a checkpoint file using the CheckPoint.save method, enabling task state recovery later.

Parameters:
  • filepath (str, optional) – Checkpoint file save path. If None, system generates a default filename and writes to current working directory.

  • user_data (Dict, optional) – User-defined data dictionary with JSON-serializable values.

Returns:

Absolute path to the written checkpoint file.

Return type:

str

Raises:
  • TypeError – If task_state is not a dict and lacks get_task_state() method.

  • Exception – Original exception from get_task_state() is propagated.

Notes

  • System does not manage checkpoint identifiers or guarantee filename uniqueness

  • Default filename format: checkpoint_YYYYMMDD_HHMMSS.json

  • Default filename does not guarantee global uniqueness

  • When filepath exists, it is overwritten by default

  • Not thread-safe/process-safe for concurrent writes

  • File deletion is user’s responsibility

Warning

  • Concurrent writes to same file may cause data corruption

  • User must handle filename uniqueness in concurrent scenarios

  • user_data must be JSON-serializable

Examples

>>> # Save checkpoint with default filename
>>> checkpoint_path = task_manager.check_point()
>>> print(f"Checkpoint saved to: {checkpoint_path}")
>>>
>>> # Save checkpoint with custom filename and user data
>>> user_data = {'experiment_id': 'exp_123', 'note': 'VQE iteration 50'}
>>> checkpoint_path = task_manager.check_point(
...     filepath='vqe_iteration_50.json',
...     user_data=user_data
... )
static from_task_state(runtime_service, task_state, recover_completely=True)#

Create QTaskManager object from task state and RuntimeService instance.

Parameters:
  • runtime_service (RuntimeService) – RuntimeService instance used for executing quantum computing tasks.

  • task_state (dict) – Task state dictionary returned by get_task_state method.

  • recover_completely (bool, optional) – Whether to completely recover task state. Default is True. - True: Completely recover original task state, task_state must contain all information - False: Create a new task using state data, allow default values

Returns:

QTaskManager instance created from task state.

Return type:

QTaskManager

Raises:

ValueError – If recover_completely is True and task_state is missing required fields.

class qpanda3_runtime.VQSession(runtime_service, session_id: str, chip_id: str, task_ids: list, channel: str = default_channel, info=Union[Dict, None])#

Bases: qpanda3_runtime.task.session.vqsession_abc.VQSessionABC

Concrete implementation of variational quantum computing session.

A client-side management object for variational quantum computing sessions that interfaces with QPanda3 quantum computing runtime service.

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

  • session_id (str) – Unique identifier for the variational computing session.

  • task_ids (list) – List of IDs for quantum computing tasks in the session.

  • channel (str, optional) – Access channel for variational quantum computing sessions (default: default_channel).

  • info (dict or None, optional) – Additional session information (reserved for future use, default: None).

Notes

This class should be used within a context manager (with statement) to ensure proper resource cleanup. Instances are typically created through the RuntimeService.vqsession() factory method.

Examples

>>> from qpanda3_runtime import RuntimeService
>>> service = RuntimeService('config.yml')
>>> with service.vqsession(vqcircuit=ansatz, device=quantum_device) as session:
...     task = session.run_vqtask(gate_params, measure_list=[0, 1])
...     result = task.get_result_sync()
run_vqtask(gate_params, measure_list: list) → qpanda3_runtime.task.qtask_manager.QTaskManager#

Submit a variational quantum task to the session.

Parameters:
  • gate_params (array-like) – Quantum gate parameters adapted to the Ansatz structure. Used for generating quantum computing tasks.

  • measure_list (list) – List of qubit indices to measure.

Returns:

Client management object for the computing task.

Return type:

QTaskManager

Raises:

RuntimeError – If called outside of a session context.

Notes

This method can only be called within a VQSession context manager. The submitted task is automatically added to the session’s task list.

See also

QTaskManager

Task management interface for submitted tasks.

release()#

Release the quantum runtime service session.

Requests the release of the quantum runtime service session using the specified session ID. This method is automatically called when exiting the session context.

Notes

This method is idempotent and can be called multiple times safely. It only takes effect when called within a session context.

class qpanda3_runtime.FakeVQSession(runtime_service, vqcircuit: pyqpanda3.vqcircuit.VQCircuit, device: qpanda3_runtime.device.fake_backend.FakeBackend, channel=default_channel, info=Union[Dict, None])#

Bases: qpanda3_runtime.task.session.vqsession_abc.VQSessionABC

Fake variational quantum session for local testing and simulation.

This class provides a mock implementation of VQSessionABC that runs quantum circuits locally using a fake backend device, without requiring remote quantum computing services.

Parameters:
  • runtime_service (object) – Runtime service instance for task management.

  • vqcircuit (VQCircuit) – Variational quantum circuit (ansatz) structure.

  • device (FakeBackend) – Fake backend device for local quantum circuit simulation.

  • channel (object, optional) – Communication channel (default is default_channel).

  • info (Dict or None, optional) – Additional session information.

Variables:
  • _ansatz (VQCircuit) – Internal storage for the variational quantum circuit.

  • _device (FakeBackend) – Internal storage for the fake backend device.

run_vqtask(gate_params, measure_list: list) → qpanda3_runtime.task.qtask_manager.QTaskManager#

Execute a variational quantum task using the session’s ansatz structure.

This method generates quantum circuits from the variational ansatz using the provided gate parameters, transpiles them for the fake backend device, and simulates quantum measurements.

Parameters:
  • gate_params (array-like) – Quantum gate parameters adapted to the ansatz structure. Used for generating quantum computing tasks.

  • measure_list (list) – List of qubit indices to be measured.

Returns:

Task manager object for the computing task.

Return type:

QTaskManager

Raises:

RuntimeError – If called outside of a VQSession context manager.

Notes

This method must be called within a VQSession context manager. The generated circuits are transpiled for the fake backend device before simulation.

Examples

>>> with FakeVQSession(...) as session:
...     task_manager = session.run_vqtask(gate_params, [0, 1])
...     result = task_manager.get_result()
release()#

Release the fake variational quantum session.

This method is a no-op for fake sessions as they don’t require remote resource cleanup.

Notes

Fake sessions don’t hold remote resources, so this method doesn’t perform any actual cleanup operations.

class qpanda3_runtime.AnsatzParamsBinding(ansatzs: [pyqpanda3.vqcircuit.VQCircuit], gate_params_s: List)#

Binding manager for ansatz circuits and gate parameters.

This class provides flexible binding rules (zip and product) to combine variational quantum circuits (ansatzs) with their corresponding gate parameters.

Parameters:
  • ansatzs (List[VQCircuit]) – List of variational quantum circuits (ansatzs).

  • gate_params_s (List) – List of gate parameter sets corresponding to the ansatzs.

Variables:
  • _ansatzs (List[VQCircuit]) – Internal storage for ansatz circuits.

  • _gate_params_s (List) – Internal storage for gate parameter sets.

  • _bind_rules (List[Tuple[List[int], List[int], int]]) – Binding rules where 0 represents zip rule and 1 represents product rule.

  • _circuits (List) – Generated quantum circuits after applying binding rules.

Examples

>>> ansatzs = [vqcircuit1, vqcircuit2]
>>> params = [[0.1, 0.2], [0.3, 0.4]]
>>> binder = AnsatzParamsBinding(ansatzs, params)
>>> binder.zip([0, 1], [0, 1])  # One-to-one binding
>>> binder.product([0], [0, 1])  # Cartesian product binding
zip(ansatz_idx_s, gate_params_idx_s)#

Add a zip binding rule (one-to-one correspondence).

This method creates a binding rule where ansatzs and gate parameters are paired in one-to-one correspondence, similar to Python’s zip function.

Parameters:
  • ansatz_idx_s (List[int]) – Indices of ansatzs to bind.

  • gate_params_idx_s (List[int]) – Indices of gate parameter sets to bind.

Raises:

RuntimeError – If any index exceeds the bounds of the corresponding list.

Notes

The two lists must have the same length for proper one-to-one binding.

product(ansatz_idx_s, gate_params_idx_s)#

Add a product binding rule (Cartesian product).

This method creates a binding rule where all combinations of specified ansatzs and gate parameters are generated, similar to Python’s itertools.product.

Parameters:
  • ansatz_idx_s (List[int]) – Indices of ansatzs to bind.

  • gate_params_idx_s (List[int]) – Indices of gate parameter sets to bind.

Notes

This generates all possible combinations between the specified ansatzs and gate parameters, unlike zip which creates one-to-one pairs.

ansatzs(serialized=True, encode_type: str = 'b64_ascii')#

Get the ansatz circuits.

Parameters:
  • serialized (bool, optional) – If True, return serialized representation of ansatzs. If False, return the original VQCircuit objects.

  • encode_type (str, optional) – Encoding type for serialization. Currently only ‘b64_ascii’ is supported.

Returns:

If serialized is True: List of serialized ansatz strings. If serialized is False: List of VQCircuit objects.

Return type:

List

Notes

Serialization converts VQCircuit objects to base64-encoded strings for transmission or storage purposes.

rules()#

Get all binding rules.

Returns:

List of binding rules where each rule is a tuple containing: - List[int]: Ansatz indices - List[int]: Gate parameter indices - int: Binding type (0 for zip, 1 for product)

Return type:

List[Tuple[List[int], List[int], int]]

gate_params(flatten)#

Get gate parameters.

Parameters:

flatten (bool) – If True, flatten the gate parameters and return both flattened lists and their dimensions. If False, return the original parameter structure.

Returns:

If flatten is False: Original gate parameter structure. If flatten is True: Tuple containing:

  • List[List[float]]: Flattened parameter lists

  • List[int]: Dimensions of each parameter list

Return type:

Union[List, Tuple[List, List]]

Notes

Flattening is useful for serialization or when parameters need to be transmitted as flat arrays.

circuits()#

Generate quantum circuits by applying all binding rules.

Returns:

List of generated quantum circuits.

Return type:

List

Notes

This method applies all registered binding rules to generate the final quantum circuits. The circuits are cached internally after generation.

data()#

Get internal data representation.

Returns:

Dictionary containing: - ‘gate_params_s’: Gate parameters - ‘bind_rules’: Binding rules - ‘ansatzs’: Ansatz circuits

Return type:

Dict

to_json_dict()#

Convert to JSON-serializable dictionary.

Returns:

JSON-serializable dictionary containing: - ‘gate_params_s’: Binary JSON representation of gate parameters - ‘bind_rules’: Binding rules - ‘ansatzs’: JSON-safe byte representation of ansatz circuits

Return type:

Dict

Notes

This method prepares the data for JSON serialization by converting binary data to JSON-safe formats.

static from_json_dict(json_data)#

Create AnsatzParamsBinding instance from JSON dictionary.

Parameters:

json_data (Dict) – JSON dictionary containing: - ‘bind_rules’: Binding rules - ‘ansatzs’: JSON-safe byte representation of ansatz circuits - ‘gate_params_s’: Binary JSON representation of gate parameters

Returns:

Reconstructed AnsatzParamsBinding instance.

Return type:

AnsatzParamsBinding

Notes

This is the inverse operation of to_json_dict().

get_prog_groups_with_measure(max_circuit_num_per_group, measure_qubits: list, return_originir: bool = True)#

Get quantum programs grouped with measurement operations.

Parameters:
  • max_circuit_num_per_group (int) – Maximum number of circuits per group.

  • measure_qubits (List[int]) – List of qubit indices to measure.

  • return_originir (bool, optional) – If True, return programs as OriginIR strings. If False, return QProg objects.

Returns:

List of program groups where each group contains: - ‘ansatz_id__gate_params_id_s’: List of (ansatz_id, gate_params_id) pairs - ‘progs’: List of quantum programs with measurement operations

Return type:

List[Dict]

Notes

This method adds measurement operations to all specified qubits and groups the resulting programs for batch processing.

get_progs(return_originir: bool = True)#

Get all quantum programs generated by binding rules.

Parameters:

return_originir (bool, optional) – If True, return programs as OriginIR strings. If False, return QProg objects.

Returns:

List of dictionaries where each contains: - ‘ansatz_id__gate_params_id’: Tuple of (ansatz_id, gate_params_id) - ‘progs’: List of quantum programs

Return type:

List[Dict]

Notes

This method applies all binding rules to generate the complete set of quantum programs with their corresponding ansatz-parameter mappings.

get_all_ansatz_params_pair()#

Get all ansatz-parameter pairs according to binding rules.

Returns:

List of (ansatz_index, parameter_index) pairs generated by applying all registered binding rules.

Return type:

List[Tuple[int, int]]

Raises:

RuntimeError – If an unknown binding type is encountered.

get_ansatz_params_group(max_circuit_num_per_group)#

Group ansatz-parameter pairs for batch processing.

Parameters:

max_circuit_num_per_group (int) – Maximum number of pairs per group.

Returns:

List of groups where each group contains up to max_circuit_num_per_group ansatz-parameter pairs.

Return type:

List[List[Tuple[int, int]]]

Notes

This method is useful for dividing large sets of quantum circuits into manageable batches for parallel or sequential execution.

class qpanda3_runtime.CircuitObservableBinding(circuits: List[qpanda3_runtime.utils.union_type.QProgUnionType] | None = None, observables: List[qpanda3_runtime.utils.union_type.ObservableUnionType] | None = None)#

Binding manager for quantum circuits and observables.

This class provides flexible binding rules (zip and product) to combine quantum circuits with their corresponding observables in quantum multi-objective decision-making scenarios.

Parameters:
  • circuits (Optional[List[QProgUnionType]]) – List of exploratory quantum circuits.

  • observables (Optional[List[ObservableUnionType]]) – List of target observables.

Variables:
  • _circuits (List[QProg]) – Internal storage for quantum circuits.

  • _observables (List[Hamiltonian]) – Internal storage for observables.

  • _bind_rules (List[Tuple[List[int], List[int], int]]) – Binding rules where 0 represents zip rule and 1 represents product rule.

  • _max_qubit_idx (int) – Maximum qubit index across all circuits and observables.

Raises:

RuntimeError – If circuits and observables are not provided together. If circuits and observables don’t share the same maximum qubit index.

Examples

>>> circuits = [qprog1, qprog2]
>>> observables = [hamiltonian1, hamiltonian2]
>>> binder = CircuitObservableBinding(circuits, observables)
>>> binder.zip([0, 1], [0, 1])  # One-to-one binding
>>> binder.product([0], [0, 1])  # Cartesian product binding
max_qubit_idx()#

Get the maximum qubit index across all circuits and observables.

Returns:

Maximum qubit index value.

Return type:

int

Notes

This value is validated during initialization to ensure all circuits and observables operate on the same qubit register.

static from_tuple(circuit_with_observable: Tuple[qpanda3_runtime.utils.union_type.QProgUnionType | List[qpanda3_runtime.utils.union_type.QProgUnionType], qpanda3_runtime.utils.union_type.ObservableUnionType])#

Create CircuitObservableBinding from a tuple.

Parameters:

circuit_with_observable (Tuple[Union[QProgUnionType, List[QProgUnionType]], ObservableUnionType]) – Tuple containing: - First element: Single quantum circuit or list of quantum circuits - Second element: Single observable

Returns:

Binding object with product rule applied between circuits and observable.

Return type:

CircuitObservableBinding

Notes

This convenience method automatically applies a product binding rule between all provided circuits and the single observable.

zip(circuit_idx_s, observable_idx_s)#

Add a zip binding rule (one-to-one correspondence).

This method creates a binding rule where circuits and observables are paired in one-to-one correspondence, similar to Python’s zip function.

Parameters:
  • circuit_idx_s (List[int]) – Indices of circuits to bind.

  • observable_idx_s (List[int]) – Indices of observables to bind.

Raises:

RuntimeError – If any index exceeds the bounds of the corresponding list.

Notes

The two lists must have the same length for proper one-to-one binding.

product(circuit_idx_s, observable_idx_s)#

Add a product binding rule (Cartesian product).

This method creates a binding rule where all combinations of specified circuits and observables are generated, similar to Python’s itertools.product.

Parameters:
  • circuit_idx_s (List[int]) – Indices of circuits to bind.

  • observable_idx_s (List[int]) – Indices of observables to bind.

Notes

This generates all possible combinations between the specified circuits and observables, unlike zip which creates one-to-one pairs.

observables(serialized=True)#

Get the observables.

Parameters:

serialized (bool, optional) – If True, return serialized representation of observables. If False, return the original Hamiltonian objects.

Returns:

If serialized is True: List of serialized observable strings. If serialized is False: List of Hamiltonian objects.

Return type:

Union[List[Hamiltonian], List[str]]

Notes

Serialization converts Hamiltonian objects to string representations for transmission or storage purposes.

circuits(serialized=True)#

Get the quantum circuits.

Parameters:

serialized (bool, optional) – If True, return serialized representation of circuits. If False, return the original QProg objects.

Returns:

If serialized is True: List of OriginIR strings. If serialized is False: List of QProg objects.

Return type:

Union[List[QProg], List[str]]

Notes

Serialization converts QProg objects to OriginIR strings for transmission or storage purposes.

data()#

Get internal data representation.

Returns:

Dictionary containing: - ‘observables’: Observable objects - ‘bind_rules’: Binding rules - ‘circuits’: Quantum circuit objects

Return type:

Dict

rules()#

Get all binding rules.

Returns:

List of binding rules where each rule is a tuple containing: - List[int]: Circuit indices - List[int]: Observable indices - int: Binding type (0 for zip, 1 for product)

Return type:

List[Tuple[List[int], List[int], int]]

get_all_circuit_observable_id_pairs()#

Get all circuit-observable pairs according to binding rules.

Returns:

List of (circuit_index, observable_index) pairs generated by applying all registered binding rules.

Return type:

List[Tuple[int, int]]

Notes

This method applies both zip and product rules to generate the complete set of circuit-observable combinations.

to_json_dict() → Dict#

Convert to JSON-serializable dictionary.

Returns:

JSON-serializable dictionary containing: - ‘type’: ‘CircuitObservableBinding’ - ‘circuits’: OriginIR strings of quantum circuits - ‘observables’: String representations of observables - ‘bind_rules’: Binding rules - ‘max_qubit_idx’: Maximum qubit index

Return type:

Dict

Notes

This method prepares the data for JSON serialization by converting quantum objects to string representations.

static from_json_dict(data: Dict)#

Create CircuitObservableBinding instance from JSON dictionary.

Parameters:

data (Dict) – JSON dictionary containing: - ‘circuits’: OriginIR strings of quantum circuits - ‘observables’: String representations of observables - ‘bind_rules’: Binding rules - ‘max_qubit_idx’: Maximum qubit index

Returns:

Reconstructed CircuitObservableBinding instance.

Return type:

CircuitObservableBinding

Notes

This is the inverse operation of to_json_dict().

class qpanda3_runtime.AnsatzObservableBinding(ansatz_with_params: qpanda3_runtime.task.program_set.gate_params_bind_rule.AnsatzParamsBinding, observables: List[qpanda3_runtime.utils.union_type.ObservableUnionType])#

Binding manager for ansatz-parameter combinations and observables.

This class provides flexible binding rules (zip and product) to combine ansatz-parameter combinations (from AnsatzParamsBinding) with observables.

Parameters:
  • ansatz_with_params (AnsatzParamsBinding) – Binding object containing ansatz circuits and their parameters.

  • observables (List[ObservableUnionType]) – List of target observables.

Variables:
  • _ansatz_with_params (AnsatzParamsBinding) – Internal storage for ansatz-parameter bindings.

  • _observables (List[Hamiltonian]) – Internal storage for observables.

  • _bind_rules (List[Tuple[List[int], List[int], int]]) – Binding rules where 0 represents zip rule and 1 represents product rule.

  • _max_qubit_idx (int) – Maximum qubit index across all ansatzs and observables.

Examples

>>> ansatz_binder = AnsatzParamsBinding(ansatzs, params)
>>> observables = [hamiltonian1, hamiltonian2]
>>> binder = AnsatzObservableBinding(ansatz_binder, observables)
>>> binder.zip([0, 1], [0, 1])  # One-to-one binding
>>> binder.product([0], [0, 1])  # Cartesian product binding
max_qubit_idx()#

Get the maximum qubit index across all ansatzs and observables.

Returns:

Maximum qubit index value.

Return type:

int

ansatzs(serialized=True, encode_type: str = 'b64_ascii')#

Get the ansatz circuits.

Parameters:
  • serialized (bool, optional) – If True, return serialized representation of ansatzs. If False, return the original VQCircuit objects.

  • encode_type (str, optional) – Encoding type for serialization.

Returns:

Result from underlying AnsatzParamsBinding.ansatzs() method.

Return type:

List

gate_params(flatten)#

Get the gate parameters.

Parameters:

flatten (bool) – If True, flatten the gate parameters.

Returns:

Result from underlying AnsatzParamsBinding.gate_params() method.

Return type:

Union[List, Tuple[List, List]]

ansatz_params_bind_rules()#

Get ansatz-parameter binding rules.

Returns:

Binding rules from the underlying AnsatzParamsBinding object.

Return type:

List[Tuple[List[int], List[int], int]]

observables(serialized=True)#

Get the observables.

Parameters:

serialized (bool, optional) – If True, return serialized representation of observables. If False, return the original Hamiltonian objects.

Returns:

If serialized is True: List of serialized observable strings. If serialized is False: List of Hamiltonian objects.

Return type:

Union[List[Hamiltonian], List[str]]

rules()#

Get all binding rules.

Returns:

List of binding rules where each rule is a tuple containing: - List[int]: Ansatz-parameter combination indices - List[int]: Observable indices - int: Binding type (0 for zip, 1 for product)

Return type:

List[Tuple[List[int], List[int], int]]

zip(ansatz_with_param_idx_s, observable_idx_s)#

Add a zip binding rule (one-to-one correspondence).

Parameters:
  • ansatz_with_param_idx_s (List[int]) – Indices of ansatz-parameter combinations to bind.

  • observable_idx_s (List[int]) – Indices of observables to bind.

Raises:

RuntimeError – If any index exceeds the bounds of the corresponding list.

Notes

The two lists must have the same length for proper one-to-one binding.

product(ansatz_with_param_idx_s, observable_idx_s)#

Add a product binding rule (Cartesian product).

Parameters:
  • ansatz_with_param_idx_s (List[int]) – Indices of ansatz-parameter combinations to bind.

  • observable_idx_s (List[int]) – Indices of observables to bind.

Notes

This generates all possible combinations between the specified ansatz-parameter combinations and observables.

data()#

Get internal data representation.

Returns:

Dictionary containing: - ‘observables’: Observable objects - ‘bind_rules’: Binding rules - ‘ansatz_with_params’: AnsatzParamsBinding object

Return type:

Dict

get_all_ansatz_observable_id_pairs()#

Get all ansatz-observable pairs according to binding rules.

Returns:

List of (ansatz_index, observable_index) pairs generated by applying all registered binding rules.

Return type:

List[Tuple[int, int]]

get_observables()#

Get the observables.

Returns:

List of Hamiltonian objects.

Return type:

List[Hamiltonian]

get_progs_grouped_by_ansatz_with_params(using_originir: bool = True)#

Get quantum programs grouped by ansatz-parameter combinations.

Parameters:

using_originir (bool, optional) – If True, return programs as OriginIR strings. If False, return QProg objects.

Returns:

Result from underlying AnsatzParamsBinding.get_progs() method.

Return type:

List[Dict]

to_json_dict() → Dict#

Convert to JSON-serializable dictionary.

Returns:

JSON-serializable dictionary containing: - ‘type’: ‘AnsatzObservableBinding’ - ‘ansatz_with_params’: JSON representation from AnsatzParamsBinding - ‘observables’: String representations of observables - ‘bind_rules’: Binding rules - ‘max_qubit_idx’: Maximum qubit index

Return type:

Dict

Notes

This method prepares the data for JSON serialization by converting quantum objects to string representations.

static from_json_dict(data: Dict)#

Create AnsatzObservableBinding instance from JSON dictionary.

Parameters:

data (Dict) – JSON dictionary containing: - ‘ansatz_with_params’: JSON representation from AnsatzParamsBinding - ‘observables’: String representations of observables - ‘bind_rules’: Binding rules - ‘max_qubit_idx’: Maximum qubit index

Returns:

Reconstructed AnsatzObservableBinding instance.

Return type:

AnsatzObservableBinding

Notes

This is the inverse operation of to_json_dict().