Skip to content

QPilotService ​

QPilotService 是与 QPilotOS 量子计算平台交互的主要服务类。它是一个 Python 包装类(定义于 pyqpanda3.pilot_service.QPilotOSService),继承自 C++ QPilotServiceBase,提供了在模拟器和真实量子芯片上提交量子程序、查询结果和管理任务的方法。

签名 ​

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

底层 C++ 基类 QPilotServiceBase 提供两个重载构造函数:

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)

参数 ​

参数类型默认值描述
urlstr必填QPilotOS 服务 URL
log_coutboolNone是否将日志输出到 stdout
api_keystrNone用于身份验证的 API 密钥

父类 QPilotServiceBase 还接受 username 和 password 替代 api_key 进行基于凭据的身份验证。自 0.5.0 起,省略 api_key(或显式传入 None)会在内部被归一化处理,不再抛出字符串转换错误。

方法 ​

配置 ​

init_config ​

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

初始化服务配置。

参数类型描述
urlstrQPilotOS 服务 URL
log_coutbool是否将日志输出到 stdout

get_token ​

python
get_token(rep_json: str) -> ErrorCode

从身份验证端点返回的响应 JSON 字符串中提取身份验证令牌。

参数类型描述
rep_jsonstr来自身份验证端点的 JSON 响应

set_config ​

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

设置量子机最大可用的量子比特和经典比特数。

消息构建 ​

build_init_msg ​

python
build_init_msg(api_key: str) -> str

构建初始化消息。

参数类型描述
api_keystr用于身份验证的 API 密钥

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

构建真实芯片测量任务消息体。所有参数均为位置参数且必填。

参数类型描述
proglist[QProg]要提交的量子程序
shotint测量次数
chip_idstr目标芯片 ID
is_amendbool是否启用测量修正
is_mappingbool是否启用量子比特映射
is_optimizationbool是否启用线路优化
specified_blocklist[int]指定使用的硬件块 ID
task_describestr任务描述
point_lableint服务使用的点标签
priorityint任务优先级

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

以与 Protobuf 兼容的形式构建真实芯片测量任务消息。所有参数均为位置参数且必填。

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

构建期望值估计任务消息体。

参数类型默认值描述
progQProg必填要提交的量子程序
hamiltonianstr必填期望值估计的哈密顿量表达式
qubitslist[int][]参与期望值任务的量子比特
shotint1000测量次数
chip_idstr'any_quantum_chip'目标芯片 ID
is_amendboolTrue是否启用测量修正
is_mappingboolTrue是否启用量子比特映射
is_optimizationboolTrue是否启用线路优化
specified_blocklist[int][]指定使用的硬件块 ID
task_describestr''任务描述

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

构建量子态层析(QST)任务消息体。

build_query_msg ​

python
build_query_msg(task_id: str) -> str

构建任务查询消息体。

参数类型描述
task_idstr要查询的任务 ID

执行 -- 同步 ​

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

通过 Python 包装器同步提交量子程序。prog 接受 QProg、OriginIR str、list[QProg] 或 list[str]。

参数类型默认值描述
progQProg、str、list[QProg] 或 list[str]必填要提交的量子程序或 OriginIR 字符串
shotint1000测量次数
chip_idstrNone目标芯片 ID
is_amendboolTrue是否启用测量修正
is_mappingboolTrue是否启用量子比特映射
is_optimizationboolTrue是否启用线路优化
specified_blocklist[int][]指定使用的硬件块 ID
describestr''任务描述
point_labelint0服务使用的点标签
priorityint0任务优先级(范围 0--10)

返回值: 概率字典列表(每个提交的程序对应一个)。如需进一步处理,可使用 parse_probability_result 或 parse_task_result。

底层 C++ 基类方法 QPilotServiceBase.run 是具有七种签名的重载函数(单/多 QProg、单/多 OriginIR str,以及接受预构建 JSON 配置的 (prog: list[QProg], config_str: str) -> str 变体)。C++ 重载使用参数名 point_lable 且不包含 priority。

run_simulator ​

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

在本地模拟器上运行量子程序。包装器根据 arg 类型进行分派:

参数类型描述
progQProg要模拟的量子程序
argint 或 list[int]为 int 时表示测量次数;为 list[int] 时表示要测量的量子比特索引(概率测量)

基类上的等效 C++ 重载:

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]]

提交量子程序(或 OriginIR 字符串)并返回测量计数。注意此 C++ 重载使用参数名 point_lable(绑定保留拼写错误),且没有 is_amend 或 priority 参数。

参数类型默认值描述
progQProg 或 list[QProg]必填量子程序
irstr 或 list[str]必填OriginIR 程序字符串
shotint1000测量次数
chip_idstr'any_quantum_chip'目标芯片 ID
is_mappingboolTrue是否启用量子比特映射
is_optimizationboolTrue是否启用线路优化
specified_blocklist[int][]指定使用的硬件块 ID
describestr''任务描述
point_lableint0服务使用的点标签

返回值: 单个程序输入返回 dict[str, int],批量输入返回 list[dict[str, int]]。

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

提交真实芯片期望值任务并等待结果。包装器签名;基类 C++ 方法默认 qubits=[]、shot=1000、chip_id='any_quantum_chip'。

已弃用:请改用 run 或 async_run。

执行 -- 异步 ​

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

通过 Python 包装器异步提交量子程序。prog 接受与 run 相同的类型。

参数类型默认值描述
progQProg、str、list[QProg] 或 list[str]必填要提交的量子程序或 OriginIR 字符串
shotint1000测量次数
chip_idstrNone目标芯片 ID
is_amendboolTrue是否启用测量修正
is_mappingboolTrue是否启用量子比特映射
is_optimizationboolTrue是否启用线路优化
specified_blocklist[int][]指定使用的硬件块 ID
describestr''任务描述
point_labelint0服务使用的点标签
priorityint0任务优先级(范围 0--10)

返回值: 提交的任务 ID 字符串。

C++ 基类方法 QPilotServiceBase.async_run 是具有七种签名的重载函数。基类重载额外添加 is_prob_counts: bool = True 参数,用于控制返回结果是否包含概率计数,使用参数名 point_lable(默认 chip_id='any_quantum_chip'),并包含接受预构建 JSON 配置的 (prog: list[QProg], config_str: str) -> str 变体。它们不包含 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

异步提交真实芯片期望值任务。包装器签名;基类 C++ 方法默认 qubits=[]、shot=1000、chip_id='any_quantum_chip'。

已弃用:请改用 async_run。

量子态层析 ​

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

提交异步量子态层析任务。Python 包装器返回提交的任务 ID 字符串。

基类 C++ 方法 QPilotServiceBase.async_real_chip_qst 额外添加 point_lable: int = 0 参数,并使用 chip_id='any_quantum_chip' 作为默认值。

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

提交异步 QST 密度矩阵任务。直接继承自 QPilotServiceBase。返回提交的任务 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

提交异步 QST 保真度任务。直接继承自 QPilotServiceBase。返回提交的任务 ID。

错误缓解 ​

noise_learning ​

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

使用参数 JSON 字符串运行噪声学习任务。

参数类型描述
parameter_jsonstr包含噪声学习参数的 JSON 字符串

返回值: 噪声学习任务结果或提交的任务 ID。

em_compute ​

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

同步运行错误缓解(Error Mitigation)计算任务。

参数类型描述
parameter_jsonstr包含错误缓解参数的 JSON 字符串

async_em_compute ​

python
async_em_compute(parameter_json: str) -> str

异步提交错误缓解计算任务。返回提交的任务 ID。

结果检索 ​

query_result ​

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

通过 Python 包装器根据任务 ID 查询任务结果。

参数类型默认值描述
task_idstr必填异步提交返回的任务 ID
file_pathstrNone非 None 时,响应会同时保存至该路径

返回值: 包含 taskState、errCode、errInfo、taskResult 以及(可用时)probCount 等键的字典。可使用 parse_probability_result 或 parse_prob_counts_result 处理结果数据。

C++ 基类方法 QPilotServiceBase.query_result 有两个重载,返回四元素列表 [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

根据任务 ID 查询任务状态向量。返回四元素列表 [state, result_vec, err_code, err_info]。

query_compile_prog ​

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

根据任务 ID 查询编译后的程序。

参数类型默认值描述
task_idstr必填异步提交返回的任务 ID
without_compensateboolTrue是否返回不带角度补偿的编译后程序

返回值: 三元素列表 [err_code, err_info, compile_prog]。

get_measure_result ​

python
get_measure_result(task_id: str) -> list

获取已完成任务的测量结果。重载:一个变体返回概率值,另一个返回计数。两者均返回三元素列表 [result, err_code, err_info]。

get_expectation_result ​

python
get_expectation_result(task_id: str) -> list

获取期望值任务结果。返回三元素列表 [expectation, err_code, err_info]。

get_qst_result ​

python
get_qst_result(task_id: str) -> list

获取已完成任务的 QST 测量结果。包装器在基类方法 _get_qst_result 之上提供的便捷接口。返回列表。

_get_qst_result ​

python
_get_qst_result(task_id: str) -> list

通过任务 ID 检索 QST 测量结果的基类方法。返回列表。

_get_qst_density_result ​

python
_get_qst_density_result(task_id: str) -> list

通过任务 ID 检索 QST 密度矩阵结果的基类方法。返回列表。

_get_qst_fidelity_result ​

python
_get_qst_fidelity_result(task_id: str) -> list

通过任务 ID 检索 QST 保真度结果的基类方法。返回列表。

结果解析 ​

parse_task_result ​

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

将任务结果字符串解析为概率映射。

parse_probability_result ​

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

将概率结果字符串解析为概率映射列表。

parse_prob_counts_result ​

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

将概率计数结果字符串解析为计数映射列表。

parser_sync_result ​

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

解析同步概率结果 JSON 字符串。

parser_expectation_result ​

python
parser_expectation_result(json_str: str) -> list

解析期望值结果 JSON 字符串。返回包含已解析期望值的单元素列表。

已弃用:请改用 Python 的 json 库。

网络 ​

tcp_recv ​

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

通过 TCP 接收任务响应。

参数类型描述
ipstr远端 TCP IP 地址
portint远端 TCP 端口
task_idstr要接收的任务 ID

返回值: 两元素列表 [is_ok, response],其中 is_ok 是布尔值,response 是响应字符串。

工具 ​

output_version ​

python
output_version() -> str

获取 QPilotService 客户端版本字符串。

示例 ​

以下示例展示典型用法。run()、async_run() 和 query_result() 需要连接到运行中的 QPilotOS 服务器并进行有效身份验证。

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}")

示例输出(query_result 字典):

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

离线使用 ​

run_simulator() 方法在本地模拟器上运行电路,无需网络访问:

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}")

输出(每次运行的概率略有不同):

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}

解析方法(离线) ​

结果解析方法可在任何机器上使用,无需网络访问:

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()}")

输出:

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

另见 ​

Released under the MIT License.