正确配置了user_id和sdk_code
# Import distance matrix
w = np.array([[0, 13, 11, 16, 8],
[13, 0, 7, 14, 9],
[11, 7, 0, 10, 9],
[16, 14, 10, 0, 12],
[8, 9, 9, 12, 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]
# Node constraint: Each node must belong to exactly one position
sequence_cons = kw.qubo.quicksum([(1 - kw.qubo.quicksum([x[v, j] for j in range(n)])) ** 2 for v in range(n)])
# Position constraint: Each position can have only one node
node_cons = kw.qubo.quicksum([(1 - kw.qubo.quicksum([x[v, j] for v in range(n)])) ** 2 for j in range(n)])
# Edge constraint: Pairs without edges cannot appear in the path
connect_cons = kw.qubo.quicksum(
[kw.qubo.quicksum([x[u, j] * x[v, j + 1] for j in range(n - 1)]) + x[u, n - 1] * x[v, 0] for u, v in no_edges])
# Hamiltonian cycle constraint: Sum of the above three constraints
ham_cycle = sequence_cons + node_cons + connect_cons
# TSP path cost
path_cost = kw.qubo.quicksum(
[w[u, v] * (kw.qubo.quicksum([x[u, j] * x[v, j + 1] for j in range(n - 1)]) + x[u, n - 1] * x[v, 0]) for u, v in
edges])
# Final objective function with penalty factor 100 for the Hamiltonian constraint
obj = 100 * ham_cycle + path_cost
# Parse QUBO
obj = kw.qubo.make(obj)
# Convert to Ising model
obj_ising = kw.qubo.qubo_model_to_ising_model(obj)
# Extract the Ising matrix
matrix = obj_ising.get_ising()["ising"]
# Perform calculation using CIM simulator
worker = kw.cim.SimulatedCIMOptimizer(
pump=1.3,
noise=0.2,
laps=5000,
delta_time=0.05,
normalization=0.3,
iterations=50
)
output = worker.solve(matrix)
# Sort the results
opt = kw.sampler.optimal_sampler(matrix, output, bias=0, negtail_ff=False)
# Select the best solution
cim_best = opt[0][0]
# If the linear term variable is -1, perform a flip
cim_best = cim_best * cim_best[-1]
print(cim_best)
# Get the list of variable names
vars = obj_ising.get_variables()
# Substitute the spin vector and obtain the result dictionary
sol_dict = kw.qubo.get_sol_dict(cim_best, vars)
# Check the hard constraints for validity and path length
seq_val = kw.qubo.get_val(sequence_cons, sol_dict)
node_val = kw.qubo.get_val(node_cons, sol_dict)
ham_val = kw.qubo.get_val(ham_cycle, sol_dict)
print('position cons: {}'.format(seq_val))
print('node_cons cons: {}'.format(node_val))
print('ham_cycle: {}'.format(ham_val))
# Calculate the path length using path_cost
path_val = kw.qubo.get_val(path_cost, sol_dict)
print('path_cost: {}'.format(path_val))
报错:
