File size: 9,066 Bytes
faea948
 
46bf7d3
 
faea948
0e240e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468bc02
0e240e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46bf7d3
b1621cd
0e240e7
 
 
 
5376ed0
 
0e240e7
babe0db
0e240e7
 
46bf7d3
0e240e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46bf7d3
b1621cd
0e240e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46bf7d3
0e240e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0dd6310
0e240e7
 
0dd6310
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
import streamlit as st
import folium
from geopy.geocoders import Nominatim
from itertools import combinations
import numpy as np
import requests
import polyline
import time
from functools import lru_cache
import json
from concurrent.futures import ThreadPoolExecutor

@st.cache_data
def get_route_osrm(start_coords: tuple, end_coords: tuple) -> tuple:
    """
    Get route using OSRM public API
    Returns: (distance in km, encoded polyline of the route)
    """
    try:
        # Format coordinates for OSRM (lon,lat format)
        coords = f"{start_coords[1]},{start_coords[0]};{end_coords[1]},{end_coords[0]}"
        
        # OSRM public API endpoint
        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  # Convert to km
                geometry = route["geometry"]  # Already encoded polyline
                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 using OSRM
    """
    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 = {}  # Store encoded polylines for routes
    
    def calculate_route(i, j):
        if i != j:
            # Add delay to avoid hitting rate limits
            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:  # Limit concurrent requests
        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) -> folium.Map:
    """
    Plot route using actual road paths from OSRM
    """
    route_group = folium.FeatureGroup(name="Route")
    
    # Plot road segments between consecutive points
    total_distance = 0
    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:
            # Decode and plot the polyline
            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)
    
    # Add markers with custom icons
    for i, point_idx in enumerate(route):
        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)
    
    # Add OpenStreetMap tile layer
    folium.TileLayer(
        tiles='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
        attr='&copy; <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 Solver with OSRM", layout="wide")
    
    st.title("🌍 TSP Route Optimizer")
    st.markdown("""
    Find the optimal driving route between multiple cities using OSRM.
    Enter city names below and click 'Optimize Route' to see the results.
    """)

    col1, col2 = st.columns([1, 2])

    with col1:
        st.subheader("πŸ“ Enter Cities")
        city_count = st.number_input("Number of cities", min_value=2, max_value=10, value=3, step=1,
                                   help="Maximum 10 cities recommended due to API limits")
        
        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):
            city_name = st.text_input(
                f"City {i+1}",
                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"⚠️ Could not find coordinates for '{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("❌ Please enter at least 2 valid cities")
            else:
                with st.spinner("Calculating optimal route..."):
                    start_time = time.time()
                    
                    # Get distance matrix and routes
                    dist_matrix, valid_coordinates, routes_dict = create_distance_matrix_with_routes(city_coords)
                    
                    # Calculate optimal route
                    from held_karp_tsp import held_karp_tsp  # Menggunakan fungsi yang sudah ada
                    min_cost, optimal_route = held_karp_tsp(dist_matrix)
                    
                    end_time = time.time()
                    
                    if min_cost == float('inf'):
                        st.error("❌ Could not find a valid route")
                    else:
                        # Display results
                        st.success(f"βœ… Route calculated in {end_time - start_time:.2f} seconds")
                        st.write(f"πŸ›£οΈ Total driving distance: {min_cost:.2f} km")
                        st.write("πŸ“ Optimal route:")
                        route_text = " β†’ ".join([city_names[i] for i in optimal_route])
                        st.code(route_text)
                        
                        # Update map with route
                        map_obj = plot_route_with_roads(map_obj, valid_coordinates, optimal_route, 
                                                      city_names, routes_dict)

        # Display map
        st.components.v1.html(folium.Map._repr_html_(map_obj), height=600)

if __name__ == "__main__":
    main()