qpanda3_runtime.utils#

Utility functions for QPanda3 Runtime client.

This module provides various utility functions for data conversion, type handling, and serialization in quantum computing applications.

Modules#

convert_json_bytes : Functions for JSON serialization of bytes data convert_json_ndarray : Functions for JSON serialization of NumPy arrays union_type : Type definitions and conversion functions for quantum objects exception : Custom exception classes for error handling

Notes

All functions follow NumPy-style documentation format for consistency.

Submodules#

Functions#

bytes_to_json_safe(data)

Convert data containing bytes to JSON-safe format.

json_safe_to_bytes(data)

Restore bytes data from JSON-safe format.

demo_bytes_serialization()

Demonstrate bytes serialization and deserialization.

ndarray_to_binary_json(arr)

Convert NumPy array to binary JSON format.

binary_json_to_ndarray(json_data)

Restore NumPy array from binary JSON format.

demo_basic_conversion()

Demonstrate basic binary conversion for NumPy arrays.

get_qprog(prog, res_type)

Convert quantum program to specified representation format.

get_observable(observable, res_type)

Convert quantum observable to specified representation format.

Package Contents#

qpanda3_runtime.utils.bytes_to_json_safe(data)#

Convert data containing bytes to JSON-safe format.

This function recursively traverses the data structure and converts any bytes objects to a JSON-safe dictionary format using base64 encoding.

Parameters:

data (any) – The input data that may contain bytes objects. Can be a simple value, list, tuple, or dictionary.

Returns:

JSON-safe data structure where bytes objects are replaced with dictionaries containing base64-encoded strings.

Return type:

any

Notes

  • Bytes objects are encoded as dictionaries with ‘__bytes__’: True key and base64-encoded ‘data’ field

  • The function handles nested structures recursively

  • Use json_safe_to_bytes to restore the original data

Examples

>>> data = {"text": "Hello", "binary": b""}
>>> json_safe = bytes_to_json_safe(data)
>>> json_str = json.dumps(json_safe)
qpanda3_runtime.utils.json_safe_to_bytes(data)#

Restore bytes data from JSON-safe format.

This function recursively traverses the JSON-safe data structure and restores bytes objects from the base64-encoded dictionary format.

Parameters:

data (any) – JSON-safe data structure that may contain dictionaries with ‘__bytes__’: True key and base64-encoded ‘data’ field.

Returns:

Original data structure with bytes objects restored.

Return type:

any

Raises:

ValueError – If the base64 decoding fails for any reason.

Notes

  • This function is the inverse of bytes_to_json_safe

  • It handles nested structures recursively

  • The input should be the output of bytes_to_json_safe or compatible format

Examples

>>> json_safe = {"text": "Hello", "binary": {"__bytes__": True, "data": "AAEC"}}
>>> restored = json_safe_to_bytes(json_safe)
>>> restored["binary"] == b""
True
qpanda3_runtime.utils.demo_bytes_serialization()#

Demonstrate bytes serialization and deserialization.

This function shows a complete example of converting data containing bytes to JSON-safe format and restoring it back.

Examples

>>> demo_bytes_serialization()
=== Bytes Serialization Demo ===
Original data:
  binary_data: b'\x00\x01\x02\x03\x04\x05'
  nested.image_data: b'fake_image_data_here'
...
qpanda3_runtime.utils.ndarray_to_binary_json(arr)#

Convert NumPy array to binary JSON format.

This function serializes a NumPy array into a JSON-safe dictionary containing the array’s data, dtype, and shape encoded in base64.

Parameters:

arr (numpy.ndarray) – The NumPy array to be serialized.

Returns:

JSON-safe dictionary with the following keys: - ‘__ndarray__’: True (identifier for ndarray data) - ‘dtype’: string representation of array dtype - ‘shape’: tuple of array dimensions - ‘data’: base64-encoded array bytes

Return type:

dict

Notes

  • The array is converted to bytes using tobytes() method

  • Base64 encoding ensures JSON compatibility

  • Use binary_json_to_ndarray to restore the array

Examples

>>> import numpy as np
>>> arr = np.array([[1, 2], [3, 4]], dtype=np.float32)
>>> json_data = ndarray_to_binary_json(arr)
>>> json_str = json.dumps(json_data)
qpanda3_runtime.utils.binary_json_to_ndarray(json_data)#

Restore NumPy array from binary JSON format.

This function deserializes a JSON-safe dictionary back into a NumPy array by decoding the base64-encoded data and reconstructing the array with its original dtype and shape.

Parameters:

json_data (dict) – JSON-safe dictionary containing ndarray data. Must have the following keys: - ‘__ndarray__’: True (identifier for ndarray data) - ‘dtype’: string representation of array dtype - ‘shape’: tuple of array dimensions - ‘data’: base64-encoded array bytes

Returns:

Restored NumPy array with original data, dtype, and shape.

Return type:

numpy.ndarray

Raises:
  • ValueError – If the input dictionary does not contain ‘__ndarray__’: True key.

  • TypeError – If the dtype string cannot be parsed or the shape is invalid.

Notes

  • This function is the inverse of ndarray_to_binary_json

  • The dtype string is parsed using numpy’s dtype constructor

  • Missing shape information results in a 1D array

Examples

>>> json_data = {
...     '__ndarray__': True,
...     'dtype': 'float32',
...     'shape': [2, 2],
...     'data': 'AACAPwAAAEAAAEBA'
... }
>>> arr = binary_json_to_ndarray(json_data)
>>> arr.shape
(2, 2)
qpanda3_runtime.utils.demo_basic_conversion()#

Demonstrate basic binary conversion for NumPy arrays.

This function shows a complete example of converting a NumPy array to JSON format and restoring it back.

Examples

>>> demo_basic_conversion()
=== Basic Binary Conversion Demo ===
Original array:
[[1. 2. 3.]
 [4. 5. 6.]]
Shape: (2, 3), dtype: float32
...
qpanda3_runtime.utils.get_qprog(prog: QProgUnionType, res_type: str)#

Convert quantum program to specified representation format.

This function normalizes quantum program input to a consistent output format based on the requested representation type.

Parameters:
  • prog (QProgUnionType) – Quantum program input in any supported format: - QProg object - String representation - QCircuit object

  • res_type (str) – Desired output format. Valid values: - ‘object’: Return QProg object - ‘ir’ or ‘originir’: Return string representation

Returns:

Quantum program in the requested format.

Return type:

QProg or str

Raises:

RuntimeError – If res_type is not one of the valid options.

Notes

  • For ‘object’ output, string inputs are converted to QProg objects

  • For ‘ir’/’originir’ output, QProg objects are converted to strings with 15-digit precision

  • QCircuit objects are automatically wrapped in QProg when needed

Examples

>>> prog_str = "H 0\nCNOT 0 1"
>>> qprog = get_qprog(prog_str, 'object')
>>> isinstance(qprog, QProg)
True
qpanda3_runtime.utils.get_observable(observable: ObservableUnionType, res_type: str)#

Convert quantum observable to specified representation format.

This function normalizes quantum observable input to a consistent output format based on the requested representation type.

Parameters:
  • observable (ObservableUnionType) – Quantum observable input in any supported format: - Hamiltonian object - PauliOperator object - String representation

  • res_type (str) – Desired output format. Valid values: - ‘hamiltonian’: Return Hamiltonian object - ‘paulioperator’: Return PauliOperator object - ‘str’: Return string representation

Returns:

Quantum observable in the requested format.

Return type:

Hamiltonian, PauliOperator, or str

Raises:

RuntimeError – If res_type is not one of the valid options.

Notes

  • String inputs are parsed assuming comma-separated key:value pairs

  • Quotes in Pauli operator strings are automatically removed

  • Complex coefficients in string format are supported

  • For ‘str’ output, coefficients are formatted as real numbers

Examples

>>> obs_str = "Z0: 1.0, X0: 0.5"
>>> hamiltonian = get_observable(obs_str, 'hamiltonian')
>>> isinstance(hamiltonian, Hamiltonian)
True