import os
import time
import json
import requests
import numpy as np
API_KEY = os.environ["QCOS_API_KEY"]
BASE_URL = "https://api.softquantus.com"
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
# 5-city distance matrix (symmetric)
cities = ["Paris", "Berlin", "Madrid", "Rome", "Warsaw"]
distances = np.array([
[0, 878, 1270, 1110, 1365],
[878, 0, 1870, 1185, 520],
[1270, 1870, 0, 1360, 2570],
[1110, 1185, 1360, 0, 1320],
[1365, 520, 2570, 1320, 0]
])
# Submit QAOA TSP job
resp = requests.post(
f"{BASE_URL}/api/v1/algorithms/qaoa",
headers=HEADERS,
json={
"problem_type": "tsp",
"problem_data": {
"distance_matrix": distances.tolist(),
"city_names": cities
},
"backend": "statevector_simulator",
"shots": 10000,
"options": {
"depth": 4,
"optimizer": "COBYLA",
"constraint_penalty": 8.0
}
}
)
resp.raise_for_status()
job_id = resp.json()["job_id"]
print(f"TSP QAOA job: {job_id}")
# Poll
while True:
r = requests.get(f"{BASE_URL}/api/v1/jobs/{job_id}", headers=HEADERS).json()
if r["status"] in ("completed", "failed"):
break
time.sleep(5)
result = r["result"]
route = result["optimal_route"]
total_km = result["total_distance"]
print(f"\nOptimal Route:")
for i, city in enumerate(route):
if i < len(route) - 1:
d = distances[cities.index(city)][cities.index(route[i+1])]
print(f" {city} → {route[i+1]}: {d} km")
print(f"\nTotal distance: {total_km} km")
print(f"Approximation ratio: {result.get('approximation_ratio', 'N/A')}")