Skip to content

QPilotService ​

QPilotService is the main service class for interacting with the QPilotOS quantum computing platform. It is a Python wrapper (defined in pyqpanda3.pilot_service.QPilotOSService) that inherits from the C++ QPilotServiceBase and provides methods for submitting quantum programs, querying results, and managing tasks on simulators and real quantum chips.

Signature ​

python
QPilotService(url: str, log_cout: bool = None, api_key: str = None)

The underlying C++ base class QPilotServiceBase provides two overloaded constructors:

python
QPilotServiceBase(url: str, log_cout: bool = False, api_key: str = None)
QPilotServiceBase(url: str, log_cout: bool = False, username: str = None, password: str = None)

Parameters ​

ParameterTypeDefaultDescription
urlstrrequiredQPilotOS service URL
log_coutboolNoneWhether to print log messages to stdout
api_keystrNoneAPI key used for authentication

The QPilotServiceBase parent class also accepts username and password instead of api_key for credential-based authentication. Since 0.5.0, omitting api_key (or passing None explicitly) is normalized internally instead of raising a string-conversion error.

Methods ​

Configuration ​

init_config ​

python
init_config(url: str, log_cout: bool) -> None

Initialize the service configuration.

ParameterTypeDescription
urlstrQPilotOS service URL
log_coutboolWhether to print log messages to stdout

get_token ​

python
get_token(rep_json: str) -> ErrorCode

Extract an authentication token from a response JSON string returned by the authentication endpoint.

ParameterTypeDescription
rep_jsonstrResponse JSON returned by the authentication endpoint

set_config ​

python
set_config(max_qubit: int = None, max_cbit: int = None) -> None

Set the maximum number of qubits and classical bits available on the quantum machine.

Message Building ​

build_init_msg ​

python
build_init_msg(api_key: str) -> str

Build an initialization message.

ParameterTypeDescription
api_keystrAPI key used for authentication

build_task_msg ​

python
build_task_msg(prog: list[QProg], shot: int, chip_id: str, is_amend: bool,
               is_mapping: bool, is_optimization: bool,
               specified_block: list[int], task_describe: str,
               point_lable: int, priority: int) -> str

Build a real-chip measurement task message body. All parameters are positional and required.

ParameterTypeDescription
proglist[QProg]Quantum programs to submit
shotintNumber of measurement shots
chip_idstrTarget chip ID
is_amendboolWhether to enable measurement amendment
is_mappingboolWhether to enable qubit mapping
is_optimizationboolWhether to enable circuit optimization
specified_blocklist[int]Specific hardware block IDs to use
task_describestrTask description
point_lableintPoint label used by the service
priorityintTask priority

build_task_proto_msg ​

python
build_task_proto_msg(shot: int, chip_id: str, is_amend: bool,
                     is_mapping: bool, is_optimization: bool,
                     specified_block: list[int], task_describe: str,
                     task_type: int, point_lable: int, priority: int) -> str

Build a real-chip measurement task message in protobuf-compatible form. All parameters are positional and required.

build_expectation_task_msg ​

python
build_expectation_task_msg(prog: QProg, hamiltonian: str,
                           qubits: list[int] = [], shot: int = 1000,
                           chip_id: str = 'any_quantum_chip',
                           is_amend: bool = True, is_mapping: bool = True,
                           is_optimization: bool = True,
                           specified_block: list[int] = [],
                           task_describe: str = '') -> str

Build an expectation-estimation task message body.

ParameterTypeDefaultDescription
progQProgrequiredQuantum program to submit
hamiltonianstrrequiredHamiltonian expression for expectation estimation
qubitslist[int][]Qubits involved in the expectation task
shotint1000Number of measurement shots
chip_idstr'any_quantum_chip'Target chip ID
is_amendboolTrueWhether to enable measurement amendment
is_mappingboolTrueWhether to enable qubit mapping
is_optimizationboolTrueWhether to enable circuit optimization
specified_blocklist[int][]Specific hardware block IDs to use
task_describestr''Task description

build_qst_task_msg ​

python
build_qst_task_msg(prog: QProg, shot: int = 1000,
                   chip_id: str = 'any_quantum_chip',
                   is_amend: bool = True, is_mapping: bool = True,
                   is_optimization: bool = True,
                   specified_block: list[int] = [],
                   task_describe: str = '') -> str

Build a quantum-state-tomography (QST) task message body.

build_query_msg ​

python
build_query_msg(task_id: str) -> str

Build a task-query message body.

ParameterTypeDescription
task_idstrTask ID to query

Execution -- Synchronous ​

run ​

python
run(prog: Union[List[str], List[QProg], str, QProg],
    shot: int = 1000,
    chip_id: str = None,
    is_amend: bool = True,
    is_mapping: bool = True,
    is_optimization: bool = True,
    specified_block: list[int] = [],
    describe: str = '',
    point_label: int = 0,
    priority: int = 0) -> list

Submit a quantum program synchronously through the Python wrapper. Accepts QProg, OriginIR str, list[QProg], or list[str] as prog.

ParameterTypeDefaultDescription
progQProg, str, list[QProg], or list[str]requiredQuantum program(s) or OriginIR string(s) to submit
shotint1000Number of measurement shots
chip_idstrNoneTarget chip ID
is_amendboolTrueWhether to enable measurement amendment
is_mappingboolTrueWhether to enable qubit mapping
is_optimizationboolTrueWhether to enable circuit optimization
specified_blocklist[int][]Specific hardware block IDs to use
describestr''Task description
point_labelint0Point label used by the service
priorityint0Task priority (range 0--10)

Returns: A list of probability dictionaries (one per submitted program). Use parse_probability_result or parse_task_result for further processing if needed.

The underlying C++ base method QPilotServiceBase.run is an overloaded function with seven signatures (single/multi QProg, single/multi OriginIR str, and a (prog: list[QProg], config_str: str) -> str variant taking a pre-built JSON configuration). The C++ overloads use parameter name point_lable and do not include priority.

run_simulator ​

python
run_simulator(prog: QProg, arg: Union[int, list[int]]) -> dict[str, float]

Run a quantum program on the local simulator. The wrapper dispatches on the type of arg:

ParameterTypeDescription
progQProgQuantum program to simulate
argint or list[int]When int, the number of measurement shots; when list[int], the qubit indices to measure (probabilistic measurement)

Equivalent C++ overloads on the base class:

python
QPilotServiceBase.run_simulator(prog: QProg, shot: int) -> dict[str, float]
QPilotServiceBase.run_simulator(prog: QProg, qubit_vec: list[int]) -> dict[str, float]

real_chip_measure_prob_count ​

python
real_chip_measure_prob_count(ir: str, shot: int = 1000,
                             chip_id: str = 'any_quantum_chip',
                             is_mapping: bool = True, is_optimization: bool = True,
                             specified_block: list[int] = [], describe: str = '',
                             point_lable: int = 0) -> dict[str, int]

real_chip_measure_prob_count(prog: QProg, shot: int = 1000,
                             chip_id: str = 'any_quantum_chip',
                             is_mapping: bool = True, is_optimization: bool = True,
                             specified_block: list[int] = [], describe: str = '',
                             point_lable: int = 0) -> dict[str, int]

real_chip_measure_prob_count(ir: list[str], shot: int = 1000,
                             chip_id: str = 'any_quantum_chip',
                             is_mapping: bool = True, is_optimization: bool = True,
                             specified_block: list[int] = [], describe: str = '',
                             point_lable: int = 0) -> list[dict[str, int]]

real_chip_measure_prob_count(prog: list[QProg], shot: int = 1000,
                             chip_id: str = 'any_quantum_chip',
                             is_mapping: bool = True, is_optimization: bool = True,
                             specified_block: list[int] = [], describe: str = '',
                             point_lable: int = 0) -> list[dict[str, int]]

Submit a quantum program (or OriginIR string) and return measurement counts. Note this C++ overload uses parameter name point_lable (with the typo preserved by the binding) and has no is_amend or priority parameter.

ParameterTypeDefaultDescription
progQProg or list[QProg]requiredQuantum program(s)
irstr or list[str]requiredOriginIR program string(s)
shotint1000Number of measurement shots
chip_idstr'any_quantum_chip'Target chip ID
is_mappingboolTrueWhether to enable qubit mapping
is_optimizationboolTrueWhether to enable circuit optimization
specified_blocklist[int][]Specific hardware block IDs to use
describestr''Task description
point_lableint0Point label used by the service

Returns: dict[str, int] for single program input, or list[dict[str, int]] for batch input.

real_chip_expectation ​

python
real_chip_expectation(prog: Union[QProg, str], hamiltonian: str,
                      qubits: list[int] = None,
                      shot: int = None, chip_id: str = None,
                      is_amend: bool = True, is_mapping: bool = True,
                      is_optimization: bool = True,
                      specified_block: list[int] = [],
                      task_describe: str = '') -> float

Submit a real-chip expectation task and wait for the result. Wrapper signature; the base C++ method defaults qubits=[], shot=1000, and chip_id='any_quantum_chip'.

Deprecated: Use run or async_run instead.

Execution -- Asynchronous ​

async_run ​

python
async_run(prog: Union[List[str], List[QProg], str, QProg],
          shot: int = 1000,
          chip_id: str = None,
          is_amend: bool = True,
          is_mapping: bool = True,
          is_optimization: bool = True,
          specified_block: list[int] = [],
          describe: str = '',
          point_label: int = 0,
          priority: int = 0) -> str

Submit a quantum program asynchronously through the Python wrapper. Accepts the same prog types as run.

ParameterTypeDefaultDescription
progQProg, str, list[QProg], or list[str]requiredQuantum program(s) or OriginIR string(s) to submit
shotint1000Number of measurement shots
chip_idstrNoneTarget chip ID
is_amendboolTrueWhether to enable measurement amendment
is_mappingboolTrueWhether to enable qubit mapping
is_optimizationboolTrueWhether to enable circuit optimization
specified_blocklist[int][]Specific hardware block IDs to use
describestr''Task description
point_labelint0Point label used by the service
priorityint0Task priority (range 0--10)

Returns: The submitted task ID string.

The C++ base method QPilotServiceBase.async_run is an overloaded function with seven signatures. The base overloads add an additional is_prob_counts: bool = True parameter that controls whether the result includes probability counts, use parameter name point_lable (with chip_id='any_quantum_chip' default), and include a (prog: list[QProg], config_str: str) -> str variant taking a pre-built JSON configuration. They do not include priority.

async_real_chip_expectation ​

python
async_real_chip_expectation(prog: Union[QProg, str], hamiltonian: str,
                            qubits: list[int] = None,
                            shot: int = None, chip_id: str = None,
                            is_amend: bool = True, is_mapping: bool = True,
                            is_optimization: bool = True,
                            specified_block: list[int] = [],
                            task_describe: str = '') -> str

Submit a real-chip expectation task asynchronously. Wrapper signature; the base C++ method defaults qubits=[], shot=1000, and chip_id='any_quantum_chip'.

Deprecated: Use async_run instead.

Quantum State Tomography ​

async_real_chip_qst ​

python
async_real_chip_qst(prog: Union[str, QProg], shot: int = 1000,
                    chip_id: str = None,
                    is_amend: bool = True, is_mapping: bool = True,
                    is_optimization: bool = True,
                    specified_block: list[int] = [],
                    describe: str = '') -> str

Submit an asynchronous quantum-state-tomography task. The Python wrapper returns the submitted task ID string.

The base C++ method QPilotServiceBase.async_real_chip_qst adds a point_lable: int = 0 parameter and uses chip_id='any_quantum_chip' as the default.

async_real_chip_qst_density ​

python
async_real_chip_qst_density(prog: QProg, shot: int = 1000,
                            chip_id: str = 'any_quantum_chip',
                            is_amend: bool = True, is_mapping: bool = True,
                            is_optimization: bool = True,
                            specified_block: list[int] = [],
                            describe: str = '', point_lable: int = 0) -> str

Submit an asynchronous QST density-matrix task. Inherited directly from QPilotServiceBase. Returns the submitted task ID.

async_real_chip_qst_fidelity ​

python
async_real_chip_qst_fidelity(prog: QProg, shot: int = 1000,
                             chip_id: str = 'any_quantum_chip',
                             is_amend: bool = True, is_mapping: bool = True,
                             is_optimization: bool = True,
                             specified_block: list[int] = [],
                             describe: str = '', point_lable: int = 0) -> str

Submit an asynchronous QST fidelity task. Inherited directly from QPilotServiceBase. Returns the submitted task ID.

Error Mitigation ​

noise_learning ​

python
noise_learning(parameter_json: str = ...) -> str

Run noise-learning with a parameter JSON string.

ParameterTypeDescription
parameter_jsonstrJSON string containing noise-learning parameters

Returns: Noise-learning task result or submitted task ID.

em_compute ​

python
em_compute(parameter_json: str) -> list[float]

Run an error-mitigation compute task synchronously.

ParameterTypeDescription
parameter_jsonstrJSON string containing error-mitigation parameters

async_em_compute ​

python
async_em_compute(parameter_json: str) -> str

Submit an asynchronous error-mitigation compute task. Returns the submitted task ID.

Result Retrieval ​

query_result ​

python
query_result(task_id: str, file_path: str = None) -> dict

Query the result of a task by its ID through the Python wrapper.

ParameterTypeDefaultDescription
task_idstrrequiredTask ID returned by asynchronous submission
file_pathstrNoneIf non-None, the response is also saved to this path

Returns: A dictionary with keys such as taskState, errCode, errInfo, taskResult, and (when available) probCount. Use parse_probability_result or parse_prob_counts_result to process the result data.

The C++ base method QPilotServiceBase.query_result has two overloads returning a four-element list[state, result_vec, err_code, err_info]:

python
QPilotServiceBase.query_result(task_id: str) -> list
QPilotServiceBase.query_result(task_id: str, is_save: bool, file_path: str = '') -> list

query_task_state_vec ​

python
query_task_state_vec(task_id: str) -> list

Query a task state vector by task ID. Returns a four-element list [state, result_vec, err_code, err_info].

query_compile_prog ​

python
query_compile_prog(task_id: str, without_compensate: bool = True) -> list

Query a compiled program by task ID.

ParameterTypeDefaultDescription
task_idstrrequiredTask ID returned by asynchronous submission
without_compensateboolTrueWhether to return the compiled program without angle compensation

Returns: A three-element list [err_code, err_info, compile_prog].

get_measure_result ​

python
get_measure_result(task_id: str) -> list

Get a measurement result for a completed task. Overloaded: one variant returns probability values, another returns counts. Both return a three-element list [result, err_code, err_info].

get_expectation_result ​

python
get_expectation_result(task_id: str) -> list

Get an expectation task result. Returns a three-element list [expectation, err_code, err_info].

get_qst_result ​

python
get_qst_result(task_id: str) -> list

Get the QST measurement result for a completed task. Provided by the wrapper as a convenience over the base method _get_qst_result. Returns a list.

_get_qst_result ​

python
_get_qst_result(task_id: str) -> list

Base-class method to retrieve a QST measurement result by task ID. Returns a list.

_get_qst_density_result ​

python
_get_qst_density_result(task_id: str) -> list

Base-class method to retrieve a QST density-matrix result by task ID. Returns a list.

_get_qst_fidelity_result ​

python
_get_qst_fidelity_result(task_id: str) -> list

Base-class method to retrieve a QST fidelity result by task ID. Returns a list.

Result Parsing ​

parse_task_result ​

python
parse_task_result(result_str: str) -> dict[str, float]

Parse a task result string into a probability map.

parse_probability_result ​

python
parse_probability_result(result_str: list[str]) -> list[dict[str, float]]

Parse probability result strings into a list of probability maps.

parse_prob_counts_result ​

python
parse_prob_counts_result(result_str: list[str]) -> list[dict[str, int]]

Parse probability-count result strings into a list of count maps.

parser_sync_result ​

python
parser_sync_result(json_str: str) -> list[dict[str, float]]

Parse a synchronous probability result JSON string.

parser_expectation_result ​

python
parser_expectation_result(json_str: str) -> list

Parse an expectation result JSON string. Returns a one-element list containing the parsed expectation values.

Deprecated: Use Python's json library instead.

Network ​

tcp_recv ​

python
tcp_recv(ip: str, port: int, task_id: str) -> list

Receive a task response through TCP.

ParameterTypeDescription
ipstrRemote TCP endpoint IP address
portintRemote TCP endpoint port
task_idstrTask ID to receive

Returns: A two-element list [is_ok, response] where is_ok is a bool and response is the response string.

Utility ​

output_version ​

python
output_version() -> str

Get the QPilotService client version string.

Examples ​

The following examples show typical usage. run(), async_run(), and query_result() require a connection to a running QPilotOS server with valid authentication.

python
from pyqpanda3.pilot_service import QPilotService
from pyqpanda3.core import QProg, QCircuit, H, CNOT, measure

# Initialize with API key
service = QPilotService(
    url="https://qpilot.originquantum.cn",
    api_key="your_api_key"
)

# Create a program
circuit = QCircuit(2)
circuit << H(0) << CNOT(0, 1)
prog = QProg()
prog << circuit << measure([0, 1], [0, 1])

# Synchronous execution
result = service.run(prog, shot=1000, chip_id="simulation")

# Asynchronous execution
task_id = service.async_run(prog, shot=1000, chip_id="real_chip")

# Query result
result_dict = service.query_result(task_id)
print(f"State: {result_dict['taskState']}, Results: {result_dict['taskResult']}")

# Parse results
if result_dict['taskState'] == "3":  # Finished
    parsed = service.parse_probability_result(result_dict['taskResult'])
    print(f"Parsed results: {parsed}")

Example output (query_result dict):

{
    'taskState': '3',
    'errCode': 0,
    'errInfo': '',
    'taskResult': [
        '{"key":["00","01","10","11"],"value":[0.017,0.5,0.017,0.466]}'
    ]
}

Offline Usage ​

The run_simulator() method runs circuits on the local simulator and does not require network access:

python
from pyqpanda3.pilot_service import QPilotService
from pyqpanda3.core import QProg, QCircuit, H, CNOT, measure

# Initialize without authentication (local simulator only)
service = QPilotService(url=None, log_cout=False, api_key=None)

# Create a Bell state circuit
circuit = QCircuit(2)
circuit << H(0) << CNOT(0, 1)
prog = QProg()
prog << circuit << measure([0, 1], [0, 1])

# Run on local simulator
result = service.run_simulator(prog, arg=1000)
print(f"Simulator result (1000 shots): {result}")

# Partial measurement (measure specific qubits)
prog2 = QProg()
prog2 << QCircuit(2) << H(0) << CNOT(0, 1)
result_partial = service.run_simulator(prog2, arg=[0])  # measure qubit 0 only
print(f"Partial measurement result: {result_partial}")

Output (probabilities vary per run):

Simulator result (1000 shots): {'00': 0.512, '01': 0.0, '10': 0.0, '11': 0.488}
Partial measurement result: {'0': 0.512, '1': 0.488}

Parsing Methods (Offline) ​

The result parsing methods work on any machine without network access:

python
from pyqpanda3.pilot_service.pilot_service import QPilotServiceBase

# Create a base instance for parsing (no network needed)
service = QPilotServiceBase(url="", log_cout=False, api_key="")

# Parse a single result string
parsed = service.parse_task_result(
    '{"key":["00","01","10","11"],"value":[0.25,0.25,0.25,0.25]}'
)
print(f"Parsed: {parsed}")

# Parse probability results
parsed_probs = service.parse_probability_result([
    '{"key":["00","01"],"value":[0.5,0.5]}'
])
print(f"Probabilities: {parsed_probs}")

# Parse count results
counts = service.parse_prob_counts_result([
    '{"key":["00","01"],"value":[500,500]}'
])
print(f"Counts: {counts}")

# Get version
print(f"Version: {service.output_version()}")

Output:

Parsed: {'00': 0.25, '01': 0.25, '10': 0.25, '11': 0.25}
Probabilities: [{'00': 0.5, '01': 0.5}]
Counts: [{'00': 500, '01': 500}]
Version: Version: 1.1

See Also ​

Released under the MIT License.