新手教程-使用真机-云平台或者SDK#
用例描述#
通过旅行商问题(TravelingSalesmanProblem,TSP)展示从建模、提交Qubo矩阵到云平台、从云平台获取计算结果的全流程
方式一:通过云平台上传QUBO矩阵计算#
代码建模并生成qubo矩阵#
# Import distance matrix
w = np.array([[0, 1, 2],
[1, 0, 0],
[2, 0, 0]])
# Get the number of nodes
n = w.shape[0]
# Create qubo variable matrix
x = kw.qubo.ndarray((n, n), "x", kw.qubo.Binary)
# Get sets of edge and non-edge pairs
edges = [(u, v) for u in range(n) for v in range(n) if w[u, v] != 0]
no_edges = [(u, v) for u in range(n) for v in range(n) if w[u, v] == 0]
def is_edge_used(x, u, v):
return kw.qubo.quicksum([x[u, j] * x[v, j + 1] for j in range(-1, n - 1)])
qubo_model = kw.qubo.QuboModel()
# TSP path cost
qubo_model.set_objective(kw.qubo.quicksum([w[u, v] * is_edge_used(x, u, v) for u, v in edges]))
# Node constraint: Each node must belong to exactly one position
qubo_model.add_constraint(x.sum(axis=0) == 1, "sequence_cons", penalty=5)
# Position constraint: Each position can have only one node
qubo_model.add_constraint(x.sum(axis=1) == 1, "node_cons", penalty=5)
# Edge constraint: Pairs without edges cannot appear in the path
qubo_model.add_constraint(kw.qubo.quicksum([is_edge_used(x, u, v) for u, v in no_edges]),
"connect_cons", penalty=20)
qubo_mat = qubo_model.get_qubo_matrix()
pd.DataFrame(qubo_mat).to_csv("tsp.csv", index=False, header=False)
登录云平台上传矩阵#
登录光量子云计算平台后进入控制台,选择真机后点击新建任务
进入任务配置页面后,填写任务名称、上传矩阵,确认后点击下一步
进入确认配置页面,确认任务和真机信息后点击确定按钮
进入提交任务页面,显示提交成功
返回控制台,任务正在校验中
校验成功后任务进入排队中状态
任务完成后点击详情进入结果详情页面
查看结果详情(qubo解向量、qubo value演化曲线、任务执行时间等)
方式二:直接使用SDK调用真机#
下面是同样一个TSP的问题,使用SDK直接调用真机求解的例子。 由于量子计算机有精度限制,例子中用SDK自带的PrecisionReducer进行精度适配。 想了解更多的关于精度的知识,
参见
import kaiwu as kw
import numpy as np
def solve_tsp():
# 定义距离矩阵
w = np.array([[0, 0, 1, 1, 0],
[0, 0, 1, 0, 1],
[1, 1, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 1, 1, 1, 0]])
n = w.shape[0] # 节点数量
# 创建 QUBO 变量矩阵 (n x n)
x = kw.qubo.ndarray((n, n), "x", kw.qubo.Binary)
# 生成边集合和非边集合
edges = [(u, v) for u in range(n) for v in range(n) if w[u, v] != 0]
no_edges = [(u, v) for u in range(n) for v in range(n) if w[u, v] == 0]
# 定义边使用判断函数
def is_edge_used(x, u, v):
return kw.qubo.quicksum([x[u, j] * x[v, (j + 1) % n] for j in range(n)])
# 初始化 QUBO 模型
qubo_model = kw.qubo.QuboModel()
# 设置目标函数:最小化路径成本
path_cost = kw.qubo.quicksum([w[u, v] * is_edge_used(x, u, v) for u, v in edges])
qubo_model.set_objective(path_cost)
# 添加约束条件
# 节点约束:每个节点必须占据一个位置
qubo_model.add_constraint(x.sum(axis=0) == 1, "node_cons", penalty=5)
# 位置约束:每个位置必须有一个节点
qubo_model.add_constraint(x.sum(axis=1) == 1, "pos_cons", penalty=5)
# 边约束:非连接边不得出现
qubo_model.add_constraint(
kw.qubo.quicksum([is_edge_used(x, u, v) for u, v in no_edges]),
"edge_cons", penalty=5
)
# 配置求解器, 需要替换 user_id 和 sdk_code
optimizer = kw.cim.CIMOptimizer(user_id="YOUR_USER_ID",sdk_code="YOUR_SDK_CODE", task_name="tsp_task")
optimizer = kw.cim.PrecisionReducer(optimizer, 8) # 8位精度
solver = kw.solver.SimpleSolver(optimizer)
# 求解问题
sol_dict, qubo_val = solver.solve_qubo(qubo_model)
# 验证结果
if sol_dict is not None:
# 验证结果
unsatisfied, res_dict = qubo_model.verify_constraint(sol_dict)
print(f"未满足约束数: {unsatisfied}")
print(f"约束项值: {res_dict}")
# 计算路径成本
path_cost = kw.qubo.get_val(qubo_model.objective, sol_dict)
print(f"实际路径成本: {path_cost}")
if __name__ == "__main__":
solve_tsp()