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
QPilotService(url: str, log_cout: bool = None, api_key: str = None)The underlying C++ base class QPilotServiceBase provides two overloaded constructors:
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
| Parameter | Type | Default | Description |
|---|---|---|---|
| url | str | required | QPilotOS service URL |
| log_cout | bool | None | Whether to print log messages to stdout |
| api_key | str | None | API 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
init_config(url: str, log_cout: bool) -> NoneInitialize the service configuration.
| Parameter | Type | Description |
|---|---|---|
| url | str | QPilotOS service URL |
| log_cout | bool | Whether to print log messages to stdout |
get_token
get_token(rep_json: str) -> ErrorCodeExtract an authentication token from a response JSON string returned by the authentication endpoint.
| Parameter | Type | Description |
|---|---|---|
| rep_json | str | Response JSON returned by the authentication endpoint |
set_config
set_config(max_qubit: int = None, max_cbit: int = None) -> NoneSet the maximum number of qubits and classical bits available on the quantum machine.
Message Building
build_init_msg
build_init_msg(api_key: str) -> strBuild an initialization message.
| Parameter | Type | Description |
|---|---|---|
| api_key | str | API key used for authentication |
build_task_msg
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) -> strBuild a real-chip measurement task message body. All parameters are positional and required.
| Parameter | Type | Description |
|---|---|---|
| prog | list[QProg] | Quantum programs to submit |
| shot | int | Number of measurement shots |
| chip_id | str | Target chip ID |
| is_amend | bool | Whether to enable measurement amendment |
| is_mapping | bool | Whether to enable qubit mapping |
| is_optimization | bool | Whether to enable circuit optimization |
| specified_block | list[int] | Specific hardware block IDs to use |
| task_describe | str | Task description |
| point_lable | int | Point label used by the service |
| priority | int | Task priority |
build_task_proto_msg
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) -> strBuild a real-chip measurement task message in protobuf-compatible form. All parameters are positional and required.
build_expectation_task_msg
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 = '') -> strBuild an expectation-estimation task message body.
| Parameter | Type | Default | Description |
|---|---|---|---|
| prog | QProg | required | Quantum program to submit |
| hamiltonian | str | required | Hamiltonian expression for expectation estimation |
| qubits | list[int] | [] | Qubits involved in the expectation task |
| shot | int | 1000 | Number of measurement shots |
| chip_id | str | 'any_quantum_chip' | Target chip ID |
| is_amend | bool | True | Whether to enable measurement amendment |
| is_mapping | bool | True | Whether to enable qubit mapping |
| is_optimization | bool | True | Whether to enable circuit optimization |
| specified_block | list[int] | [] | Specific hardware block IDs to use |
| task_describe | str | '' | Task description |
build_qst_task_msg
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 = '') -> strBuild a quantum-state-tomography (QST) task message body.
build_query_msg
build_query_msg(task_id: str) -> strBuild a task-query message body.
| Parameter | Type | Description |
|---|---|---|
| task_id | str | Task ID to query |
Execution -- Synchronous
run
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) -> listSubmit a quantum program synchronously through the Python wrapper. Accepts QProg, OriginIR str, list[QProg], or list[str] as prog.
| Parameter | Type | Default | Description |
|---|---|---|---|
| prog | QProg, str, list[QProg], or list[str] | required | Quantum program(s) or OriginIR string(s) to submit |
| shot | int | 1000 | Number of measurement shots |
| chip_id | str | None | Target chip ID |
| is_amend | bool | True | Whether to enable measurement amendment |
| is_mapping | bool | True | Whether to enable qubit mapping |
| is_optimization | bool | True | Whether to enable circuit optimization |
| specified_block | list[int] | [] | Specific hardware block IDs to use |
| describe | str | '' | Task description |
| point_label | int | 0 | Point label used by the service |
| priority | int | 0 | Task 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
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:
| Parameter | Type | Description |
|---|---|---|
| prog | QProg | Quantum program to simulate |
| arg | int 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:
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
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.
| Parameter | Type | Default | Description |
|---|---|---|---|
| prog | QProg or list[QProg] | required | Quantum program(s) |
| ir | str or list[str] | required | OriginIR program string(s) |
| shot | int | 1000 | Number of measurement shots |
| chip_id | str | 'any_quantum_chip' | Target chip ID |
| is_mapping | bool | True | Whether to enable qubit mapping |
| is_optimization | bool | True | Whether to enable circuit optimization |
| specified_block | list[int] | [] | Specific hardware block IDs to use |
| describe | str | '' | Task description |
| point_lable | int | 0 | Point label used by the service |
Returns: dict[str, int] for single program input, or list[dict[str, int]] for batch input.
real_chip_expectation
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 = '') -> floatSubmit 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
runorasync_runinstead.
Execution -- Asynchronous
async_run
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) -> strSubmit a quantum program asynchronously through the Python wrapper. Accepts the same prog types as run.
| Parameter | Type | Default | Description |
|---|---|---|---|
| prog | QProg, str, list[QProg], or list[str] | required | Quantum program(s) or OriginIR string(s) to submit |
| shot | int | 1000 | Number of measurement shots |
| chip_id | str | None | Target chip ID |
| is_amend | bool | True | Whether to enable measurement amendment |
| is_mapping | bool | True | Whether to enable qubit mapping |
| is_optimization | bool | True | Whether to enable circuit optimization |
| specified_block | list[int] | [] | Specific hardware block IDs to use |
| describe | str | '' | Task description |
| point_label | int | 0 | Point label used by the service |
| priority | int | 0 | Task 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
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 = '') -> strSubmit 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_runinstead.
Quantum State Tomography
async_real_chip_qst
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 = '') -> strSubmit 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
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) -> strSubmit an asynchronous QST density-matrix task. Inherited directly from QPilotServiceBase. Returns the submitted task ID.
async_real_chip_qst_fidelity
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) -> strSubmit an asynchronous QST fidelity task. Inherited directly from QPilotServiceBase. Returns the submitted task ID.
Error Mitigation
noise_learning
noise_learning(parameter_json: str = ...) -> strRun noise-learning with a parameter JSON string.
| Parameter | Type | Description |
|---|---|---|
| parameter_json | str | JSON string containing noise-learning parameters |
Returns: Noise-learning task result or submitted task ID.
em_compute
em_compute(parameter_json: str) -> list[float]Run an error-mitigation compute task synchronously.
| Parameter | Type | Description |
|---|---|---|
| parameter_json | str | JSON string containing error-mitigation parameters |
async_em_compute
async_em_compute(parameter_json: str) -> strSubmit an asynchronous error-mitigation compute task. Returns the submitted task ID.
Result Retrieval
query_result
query_result(task_id: str, file_path: str = None) -> dictQuery the result of a task by its ID through the Python wrapper.
| Parameter | Type | Default | Description |
|---|---|---|---|
| task_id | str | required | Task ID returned by asynchronous submission |
| file_path | str | None | If 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]:
QPilotServiceBase.query_result(task_id: str) -> list
QPilotServiceBase.query_result(task_id: str, is_save: bool, file_path: str = '') -> listquery_task_state_vec
query_task_state_vec(task_id: str) -> listQuery a task state vector by task ID. Returns a four-element list [state, result_vec, err_code, err_info].
query_compile_prog
query_compile_prog(task_id: str, without_compensate: bool = True) -> listQuery a compiled program by task ID.
| Parameter | Type | Default | Description |
|---|---|---|---|
| task_id | str | required | Task ID returned by asynchronous submission |
| without_compensate | bool | True | Whether to return the compiled program without angle compensation |
Returns: A three-element list [err_code, err_info, compile_prog].
get_measure_result
get_measure_result(task_id: str) -> listGet 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
get_expectation_result(task_id: str) -> listGet an expectation task result. Returns a three-element list [expectation, err_code, err_info].
get_qst_result
get_qst_result(task_id: str) -> listGet 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
_get_qst_result(task_id: str) -> listBase-class method to retrieve a QST measurement result by task ID. Returns a list.
_get_qst_density_result
_get_qst_density_result(task_id: str) -> listBase-class method to retrieve a QST density-matrix result by task ID. Returns a list.
_get_qst_fidelity_result
_get_qst_fidelity_result(task_id: str) -> listBase-class method to retrieve a QST fidelity result by task ID. Returns a list.
Result Parsing
parse_task_result
parse_task_result(result_str: str) -> dict[str, float]Parse a task result string into a probability map.
parse_probability_result
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
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
parser_sync_result(json_str: str) -> list[dict[str, float]]Parse a synchronous probability result JSON string.
parser_expectation_result
parser_expectation_result(json_str: str) -> listParse an expectation result JSON string. Returns a one-element list containing the parsed expectation values.
Deprecated: Use Python's
jsonlibrary instead.
Network
tcp_recv
tcp_recv(ip: str, port: int, task_id: str) -> listReceive a task response through TCP.
| Parameter | Type | Description |
|---|---|---|
| ip | str | Remote TCP endpoint IP address |
| port | int | Remote TCP endpoint port |
| task_id | str | Task 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
output_version() -> strGet 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.
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:
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:
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.1See Also
- PilotNoiseParams -- Noise parameter configuration
- ErrorCode -- Error code enumeration
- qcloud Module -- Higher-level cloud service interface