Spaces:
Sleeping
Sleeping
File size: 10,961 Bytes
faea948 46bf7d3 faea948 0e240e7 cc02ee9 e4ae25f cc02ee9 e4ae25f 3787471 cc02ee9 3787471 cc02ee9 3787471 cc02ee9 3787471 cc02ee9 3787471 cc02ee9 3787471 cc02ee9 3787471 cc02ee9 3787471 f2cb27e cc02ee9 f2cb27e cc02ee9 e4ae25f f2cb27e cc02ee9 3787471 cc02ee9 f2cb27e cc02ee9 3787471 f2cb27e 3787471 cc02ee9 0e240e7 cc02ee9 0e240e7 f2cb27e 0e240e7 468bc02 0e240e7 e4ae25f 0e240e7 46bf7d3 b1621cd 0e240e7 cc02ee9 5376ed0 0e240e7 babe0db 0e240e7 46bf7d3 f2cb27e 0e240e7 f2cb27e 0e240e7 f2cb27e 0e240e7 f2cb27e cc02ee9 0e240e7 f2cb27e 0e240e7 46bf7d3 b1621cd 0e240e7 3787471 0e240e7 1f0084d 0e240e7 1f0084d cc02ee9 0e240e7 1f0084d f2cb27e e4ae25f f2cb27e 1f0084d 0e240e7 46bf7d3 0e240e7 cc02ee9 0e240e7 cc02ee9 0e240e7 3787471 0e240e7 e4ae25f 0e240e7 0dd6310 0e240e7 0dd6310 0e240e7 1f0084d 0e240e7 3787471 0e240e7 cc02ee9 0e240e7 3787471 0e240e7 3787471 0e240e7 f2cb27e 0e240e7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
import streamlit as st
import folium
from geopy.geocoders import Nominatim
import numpy as np
import requests
import polyline
import time
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor
def held_karp_tsp_fixed_start(dist_matrix: np.ndarray, return_to_start: bool = True) -> tuple:
"""
Modified Held-Karp algorithm for solving TSP with fixed starting point (index 0)
Returns: (minimum cost, optimal route)
"""
if len(dist_matrix) < 2:
return 0, []
n = len(dist_matrix)
inf = float('inf')
# Only consider paths that start from index 0
dp = np.full((1 << n, n), inf)
parent = np.full((1 << n, n), -1, dtype=int)
# Initialize paths from start (index 0) to other cities
for i in range(1, n):
dp[1 << i | 1][i] = dist_matrix[0][i]
# Process all possible subsets of cities
for mask in range(1, 1 << n):
if not (mask & 1): # Skip if start city (0) is not in the subset
continue
for curr in range(n):
if not (mask & (1 << curr)):
continue
prev_mask = mask ^ (1 << curr)
if not prev_mask: # Skip if no previous cities
continue
for prev in range(n):
if not (prev_mask & (1 << prev)):
continue
candidate = dp[prev_mask][prev] + dist_matrix[prev][curr]
if candidate < dp[mask][curr]:
dp[mask][curr] = candidate
parent[mask][curr] = prev
# Find the optimal end point
mask = (1 << n) - 1
if return_to_start:
# For closed loop, find best path back to start
curr = min(range(1, n), key=lambda x: dp[mask][x] + dist_matrix[x][0])
final_cost = dp[mask][curr] + dist_matrix[curr][0]
else:
# For single trip, find best ending point
curr = min(range(1, n), key=lambda x: dp[mask][x])
final_cost = dp[mask][curr]
# Reconstruct the path
path = []
while curr != -1:
path.append(curr)
new_mask = mask ^ (1 << curr)
curr = parent[mask][curr]
mask = new_mask
path.append(0) # Add start city
if return_to_start:
path.append(0) # Add start city again for closed loop
path.reverse()
return final_cost, path
# Keep other helper functions unchanged
@st.cache_data
def get_route_osrm(start_coords: tuple, end_coords: tuple) -> tuple:
"""Get route using OSRM public API"""
try:
coords = f"{start_coords[1]},{start_coords[0]};{end_coords[1]},{end_coords[0]}"
url = f"http://router.project-osrm.org/route/v1/driving/{coords}"
params = {
"overview": "full",
"geometries": "polyline",
"annotations": "distance"
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
if data["code"] == "Ok" and len(data["routes"]) > 0:
route = data["routes"][0]
distance = route["distance"] / 1000
geometry = route["geometry"]
return distance, geometry
else:
st.warning("No route found")
return None, None
else:
st.warning(f"OSRM API error: {response.status_code}")
return None, None
except Exception as e:
st.error(f"Error getting route: {str(e)}")
return None, None
@st.cache_data
def cached_geocoding(city_name: str) -> tuple:
"""Cache geocoding results"""
try:
geolocator = Nominatim(user_agent="tsp_app")
location = geolocator.geocode(city_name, timeout=10)
if location:
return (location.latitude, location.longitude)
return None
except Exception as e:
st.error(f"Error geocoding {city_name}: {str(e)}")
return None
def create_distance_matrix_with_routes(coordinates: list) -> tuple:
"""Create distance matrix and store routes between all points"""
valid_coordinates = [c for c in coordinates if c is not None]
n = len(valid_coordinates)
if n < 2:
return np.array([]), valid_coordinates, {}
dist_matrix = np.zeros((n, n))
routes_dict = {}
def calculate_route(i, j):
if i != j:
time.sleep(0.1)
distance, route = get_route_osrm(valid_coordinates[i], valid_coordinates[j])
if distance is not None:
return i, j, distance, route
return i, j, 0, None
with ThreadPoolExecutor(max_workers=5) as executor:
futures = []
for i in range(n):
for j in range(i + 1, n):
futures.append(executor.submit(calculate_route, i, j))
with st.spinner("Calculating routes..."):
for future in futures:
i, j, distance, route = future.result()
if route is not None:
dist_matrix[i][j] = distance
dist_matrix[j][i] = distance
routes_dict[f"{i}-{j}"] = route
routes_dict[f"{j}-{i}"] = route
return dist_matrix, valid_coordinates, routes_dict
def plot_route_with_roads(map_obj: folium.Map, coordinates: list, route: list,
city_names: list, routes_dict: dict, return_to_start: bool) -> folium.Map:
"""Plot route using actual road paths from OSRM"""
route_group = folium.FeatureGroup(name="Route")
for i in range(len(route)-1):
start_idx = route[i]
end_idx = route[i+1]
route_key = f"{start_idx}-{end_idx}"
if route_key in routes_dict:
decoded_path = polyline.decode(routes_dict[route_key])
folium.PolyLine(
decoded_path,
color="blue",
weight=3,
opacity=0.8,
tooltip=f"Segment {i+1}: {city_names[start_idx]} β {city_names[end_idx]}"
).add_to(route_group)
for i, point_idx in enumerate(route):
if return_to_start:
icon_color = "green" if i == 0 or i == len(route)-1 else "blue"
else:
icon_color = "green" if i == 0 else "red" if i == len(route)-1 else "blue"
popup_text = f"""
<div style='font-size: 12px'>
<b>City:</b> {city_names[point_idx]}<br>
<b>Stop:</b> {i + 1} of {len(route)}
</div>
"""
folium.Marker(
location=coordinates[point_idx],
popup=folium.Popup(popup_text, max_width=200),
tooltip=f'Stop {i + 1}: {city_names[point_idx]}',
icon=folium.Icon(color=icon_color, icon='info-sign')
).add_to(route_group)
route_group.add_to(map_obj)
folium.TileLayer(
tiles='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
attr='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
).add_to(map_obj)
return map_obj
def main():
st.set_page_config(page_title="TSP Route Optimizer", layout="wide")
st.title("π Route Optimizer")
st.markdown("""
Temukan rute optimal berkendara antar lokasi.
Masukkan nama lokasi dibawah dan klik 'Optimize Route' untuk melihat hasilnya.
Kota 1 akan menjadi titik awal perjalanan.
""")
col1, col2 = st.columns([1, 2])
with col1:
st.subheader("π Masukkan Lokasi")
trip_type = st.radio(
"Tipe Perjalanan",
["Closed Loop (Kembali ke titik awal)", "Single Trip (Tidak kembali ke titik awal)"],
help="Pilih apakah Anda ingin kembali ke lokasi awal atau tidak"
)
return_to_start = trip_type.startswith("Closed Loop")
city_count = st.number_input("Jumlah lokasi", min_value=2, max_value=10, value=3, step=1,
help="Maksimum 10 lokasi direkomendasikan karena batasan API")
if 'city_inputs' not in st.session_state:
st.session_state.city_inputs = [''] * city_count
if len(st.session_state.city_inputs) != city_count:
st.session_state.city_inputs = st.session_state.city_inputs[:city_count] + [''] * max(0, city_count - len(st.session_state.city_inputs))
city_names = []
city_coords = []
for i in range(city_count):
label = "Kota 1 (Titik Awal)" if i == 0 else f"Kota {i+1}"
city_name = st.text_input(
label,
value=st.session_state.city_inputs[i],
key=f"city_{i}"
)
st.session_state.city_inputs[i] = city_name
if city_name:
coords = cached_geocoding(city_name)
if coords:
city_names.append(city_name)
city_coords.append(coords)
else:
st.warning(f"β οΈ Tidak dapat menemukan koordinat untuk '{city_name}'")
with col2:
if not city_coords:
map_center = [-2.548926, 118.014863] # Center of Indonesia
zoom_start = 5
else:
map_center = city_coords[0]
zoom_start = 5
map_obj = folium.Map(location=map_center, zoom_start=zoom_start)
if st.button("π Optimize Route", key="optimize"):
if len(city_coords) < 2:
st.error("β Masukkan minimal 2 lokasi yang valid")
else:
with st.spinner("Menghitung rute optimal..."):
start_time = time.time()
dist_matrix, valid_coordinates, routes_dict = create_distance_matrix_with_routes(city_coords)
min_cost, optimal_route = held_karp_tsp_fixed_start(dist_matrix, return_to_start)
end_time = time.time()
if min_cost == float('inf'):
st.error("β Tidak dapat menemukan rute yang valid")
else:
st.success(f"β
Rute dihitung dalam {end_time - start_time:.2f} detik")
st.write(f"π£οΈ Total jarak berkendara: {min_cost:.2f} km")
st.write("π Rute optimal:")
route_text = " β ".join([city_names[i] for i in optimal_route])
st.code(route_text)
map_obj = plot_route_with_roads(map_obj, valid_coordinates, optimal_route,
city_names, routes_dict, return_to_start)
st.components.v1.html(folium.Map._repr_html_(map_obj), height=600)
if __name__ == "__main__":
main() |