QPilotService
QPilotService 是与 QPilotOS 量子计算平台交互的主要服务类。它是一个 Python 包装类(定义于 pyqpanda3.pilot_service.QPilotOSService),继承自 C++ QPilotServiceBase,提供了在模拟器和真实量子芯片上提交量子程序、查询结果和管理任务的方法。
签名
QPilotService(url: str, log_cout: bool = None, api_key: str = None)底层 C++ 基类 QPilotServiceBase 提供两个重载构造函数:
QPilotServiceBase(url: str, log_cout: bool = False, api_key: str = None)
QPilotServiceBase(url: str, log_cout: bool = False, username: str = None, password: str = None)参数
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| url | str | 必填 | QPilotOS 服务 URL |
| log_cout | bool | None | 是否将日志输出到 stdout |
| api_key | str | None | 用于身份验证的 API 密钥 |
父类 QPilotServiceBase 还接受 username 和 password 替代 api_key 进行基于凭据的身份验证。自 0.5.0 起,省略 api_key(或显式传入 None)会在内部被归一化处理,不再抛出字符串转换错误。
方法
配置
init_config
init_config(url: str, log_cout: bool) -> None初始化服务配置。
| 参数 | 类型 | 描述 |
|---|---|---|
| url | str | QPilotOS 服务 URL |
| log_cout | bool | 是否将日志输出到 stdout |
get_token
get_token(rep_json: str) -> ErrorCode从身份验证端点返回的响应 JSON 字符串中提取身份验证令牌。
| 参数 | 类型 | 描述 |
|---|---|---|
| rep_json | str | 来自身份验证端点的 JSON 响应 |
set_config
set_config(max_qubit: int = None, max_cbit: int = None) -> None设置量子机最大可用的量子比特和经典比特数。
消息构建
build_init_msg
build_init_msg(api_key: str) -> str构建初始化消息。
| 参数 | 类型 | 描述 |
|---|---|---|
| api_key | str | 用于身份验证的 API 密钥 |
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) -> str构建真实芯片测量任务消息体。所有参数均为位置参数且必填。
| 参数 | 类型 | 描述 |
|---|---|---|
| prog | list[QProg] | 要提交的量子程序 |
| shot | int | 测量次数 |
| chip_id | str | 目标芯片 ID |
| is_amend | bool | 是否启用测量修正 |
| is_mapping | bool | 是否启用量子比特映射 |
| is_optimization | bool | 是否启用线路优化 |
| specified_block | list[int] | 指定使用的硬件块 ID |
| task_describe | str | 任务描述 |
| point_lable | int | 服务使用的点标签 |
| priority | int | 任务优先级 |
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) -> str以与 Protobuf 兼容的形式构建真实芯片测量任务消息。所有参数均为位置参数且必填。
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 = '') -> str构建期望值估计任务消息体。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| prog | QProg | 必填 | 要提交的量子程序 |
| hamiltonian | str | 必填 | 期望值估计的哈密顿量表达式 |
| qubits | list[int] | [] | 参与期望值任务的量子比特 |
| shot | int | 1000 | 测量次数 |
| chip_id | str | 'any_quantum_chip' | 目标芯片 ID |
| is_amend | bool | True | 是否启用测量修正 |
| is_mapping | bool | True | 是否启用量子比特映射 |
| is_optimization | bool | True | 是否启用线路优化 |
| specified_block | list[int] | [] | 指定使用的硬件块 ID |
| task_describe | str | '' | 任务描述 |
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 = '') -> str构建量子态层析(QST)任务消息体。
build_query_msg
build_query_msg(task_id: str) -> str构建任务查询消息体。
| 参数 | 类型 | 描述 |
|---|---|---|
| task_id | str | 要查询的任务 ID |
执行 -- 同步
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) -> list通过 Python 包装器同步提交量子程序。prog 接受 QProg、OriginIR str、list[QProg] 或 list[str]。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| prog | QProg、str、list[QProg] 或 list[str] | 必填 | 要提交的量子程序或 OriginIR 字符串 |
| shot | int | 1000 | 测量次数 |
| chip_id | str | None | 目标芯片 ID |
| is_amend | bool | True | 是否启用测量修正 |
| is_mapping | bool | True | 是否启用量子比特映射 |
| is_optimization | bool | True | 是否启用线路优化 |
| specified_block | list[int] | [] | 指定使用的硬件块 ID |
| describe | str | '' | 任务描述 |
| point_label | int | 0 | 服务使用的点标签 |
| priority | int | 0 | 任务优先级(范围 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
run_simulator(prog: QProg, arg: Union[int, list[int]]) -> dict[str, float]在本地模拟器上运行量子程序。包装器根据 arg 类型进行分派:
| 参数 | 类型 | 描述 |
|---|---|---|
| prog | QProg | 要模拟的量子程序 |
| arg | int 或 list[int] | 为 int 时表示测量次数;为 list[int] 时表示要测量的量子比特索引(概率测量) |
基类上的等效 C++ 重载:
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]]提交量子程序(或 OriginIR 字符串)并返回测量计数。注意此 C++ 重载使用参数名 point_lable(绑定保留拼写错误),且没有 is_amend 或 priority 参数。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| prog | QProg 或 list[QProg] | 必填 | 量子程序 |
| ir | str 或 list[str] | 必填 | OriginIR 程序字符串 |
| shot | int | 1000 | 测量次数 |
| chip_id | str | 'any_quantum_chip' | 目标芯片 ID |
| is_mapping | bool | True | 是否启用量子比特映射 |
| is_optimization | bool | True | 是否启用线路优化 |
| specified_block | list[int] | [] | 指定使用的硬件块 ID |
| describe | str | '' | 任务描述 |
| point_lable | int | 0 | 服务使用的点标签 |
返回值: 单个程序输入返回 dict[str, int],批量输入返回 list[dict[str, int]]。
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 = '') -> float提交真实芯片期望值任务并等待结果。包装器签名;基类 C++ 方法默认 qubits=[]、shot=1000、chip_id='any_quantum_chip'。
已弃用:请改用
run或async_run。
执行 -- 异步
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) -> str通过 Python 包装器异步提交量子程序。prog 接受与 run 相同的类型。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| prog | QProg、str、list[QProg] 或 list[str] | 必填 | 要提交的量子程序或 OriginIR 字符串 |
| shot | int | 1000 | 测量次数 |
| chip_id | str | None | 目标芯片 ID |
| is_amend | bool | True | 是否启用测量修正 |
| is_mapping | bool | True | 是否启用量子比特映射 |
| is_optimization | bool | True | 是否启用线路优化 |
| specified_block | list[int] | [] | 指定使用的硬件块 ID |
| describe | str | '' | 任务描述 |
| point_label | int | 0 | 服务使用的点标签 |
| priority | int | 0 | 任务优先级(范围 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
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
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
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
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
noise_learning(parameter_json: str = ...) -> str使用参数 JSON 字符串运行噪声学习任务。
| 参数 | 类型 | 描述 |
|---|---|---|
| parameter_json | str | 包含噪声学习参数的 JSON 字符串 |
返回值: 噪声学习任务结果或提交的任务 ID。
em_compute
em_compute(parameter_json: str) -> list[float]同步运行错误缓解(Error Mitigation)计算任务。
| 参数 | 类型 | 描述 |
|---|---|---|
| parameter_json | str | 包含错误缓解参数的 JSON 字符串 |
async_em_compute
async_em_compute(parameter_json: str) -> str异步提交错误缓解计算任务。返回提交的任务 ID。
结果检索
query_result
query_result(task_id: str, file_path: str = None) -> dict通过 Python 包装器根据任务 ID 查询任务结果。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| task_id | str | 必填 | 异步提交返回的任务 ID |
| file_path | str | None | 非 None 时,响应会同时保存至该路径 |
返回值: 包含 taskState、errCode、errInfo、taskResult 以及(可用时)probCount 等键的字典。可使用 parse_probability_result 或 parse_prob_counts_result 处理结果数据。
C++ 基类方法 QPilotServiceBase.query_result 有两个重载,返回四元素列表 [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) -> list根据任务 ID 查询任务状态向量。返回四元素列表 [state, result_vec, err_code, err_info]。
query_compile_prog
query_compile_prog(task_id: str, without_compensate: bool = True) -> list根据任务 ID 查询编译后的程序。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| task_id | str | 必填 | 异步提交返回的任务 ID |
| without_compensate | bool | True | 是否返回不带角度补偿的编译后程序 |
返回值: 三元素列表 [err_code, err_info, compile_prog]。
get_measure_result
get_measure_result(task_id: str) -> list获取已完成任务的测量结果。重载:一个变体返回概率值,另一个返回计数。两者均返回三元素列表 [result, err_code, err_info]。
get_expectation_result
get_expectation_result(task_id: str) -> list获取期望值任务结果。返回三元素列表 [expectation, err_code, err_info]。
get_qst_result
get_qst_result(task_id: str) -> list获取已完成任务的 QST 测量结果。包装器在基类方法 _get_qst_result 之上提供的便捷接口。返回列表。
_get_qst_result
_get_qst_result(task_id: str) -> list通过任务 ID 检索 QST 测量结果的基类方法。返回列表。
_get_qst_density_result
_get_qst_density_result(task_id: str) -> list通过任务 ID 检索 QST 密度矩阵结果的基类方法。返回列表。
_get_qst_fidelity_result
_get_qst_fidelity_result(task_id: str) -> list通过任务 ID 检索 QST 保真度结果的基类方法。返回列表。
结果解析
parse_task_result
parse_task_result(result_str: str) -> dict[str, float]将任务结果字符串解析为概率映射。
parse_probability_result
parse_probability_result(result_str: list[str]) -> list[dict[str, float]]将概率结果字符串解析为概率映射列表。
parse_prob_counts_result
parse_prob_counts_result(result_str: list[str]) -> list[dict[str, int]]将概率计数结果字符串解析为计数映射列表。
parser_sync_result
parser_sync_result(json_str: str) -> list[dict[str, float]]解析同步概率结果 JSON 字符串。
parser_expectation_result
parser_expectation_result(json_str: str) -> list解析期望值结果 JSON 字符串。返回包含已解析期望值的单元素列表。
已弃用:请改用 Python 的
json库。
网络
tcp_recv
tcp_recv(ip: str, port: int, task_id: str) -> list通过 TCP 接收任务响应。
| 参数 | 类型 | 描述 |
|---|---|---|
| ip | str | 远端 TCP IP 地址 |
| port | int | 远端 TCP 端口 |
| task_id | str | 要接收的任务 ID |
返回值: 两元素列表 [is_ok, response],其中 is_ok 是布尔值,response 是响应字符串。
工具
output_version
output_version() -> str获取 QPilotService 客户端版本字符串。
示例
以下示例展示典型用法。run()、async_run() 和 query_result() 需要连接到运行中的 QPilotOS 服务器并进行有效身份验证。
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() 方法在本地模拟器上运行电路,无需网络访问:
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}解析方法(离线)
结果解析方法可在任何机器上使用,无需网络访问:
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另见
- PilotNoiseParams -- 噪声参数配置
- ErrorCode -- 错误代码枚举
- qcloud 模块 -- 更高层的云服务接口