Update src/streamlit_app.py
Browse files- src/streamlit_app.py +300 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,302 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import osmnx as ox
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import tempfile
|
| 5 |
+
import os
|
| 6 |
+
import folium
|
| 7 |
+
from streamlit_folium import st_folium
|
| 8 |
+
import random
|
| 9 |
+
import networkx as nx
|
| 10 |
+
from folium.plugins import PolyLineTextPath
|
| 11 |
|
| 12 |
+
|
| 13 |
+
# Konfigurasi osmnx agar tidak menyimpan cache permanen
|
| 14 |
+
ox.settings.use_cache = False
|
| 15 |
+
ox.settings.cache_folder = tempfile.gettempdir()
|
| 16 |
+
ox.settings.logs_folder = tempfile.gettempdir()
|
| 17 |
+
|
| 18 |
+
@st.cache_resource
|
| 19 |
+
def ambil_graf_keputih():
|
| 20 |
+
# Ambil graf awal dari OSM
|
| 21 |
+
G = ox.graph_from_place("Keputih, Sukolilo, Surabaya, Indonesia", network_type="drive", simplify=True)
|
| 22 |
+
|
| 23 |
+
# Ubah ke undirected agar bisa cari komponen terhubung
|
| 24 |
+
G_undirected = G.to_undirected()
|
| 25 |
+
|
| 26 |
+
# Ambil komponen terbesar
|
| 27 |
+
largest_cc = max(nx.connected_components(G_undirected), key=len)
|
| 28 |
+
G_connected = G.subgraph(largest_cc).copy()
|
| 29 |
+
|
| 30 |
+
# Ambil data node dan edge
|
| 31 |
+
gdf_nodes, gdf_edges = ox.graph_to_gdfs(G_connected)
|
| 32 |
+
return G_connected, gdf_nodes, gdf_edges
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def buat_rute_polyline(G, rute_node_ids):
|
| 36 |
+
garis_rute = []
|
| 37 |
+
for i in range(len(rute_node_ids) - 1):
|
| 38 |
+
asal = rute_node_ids[i]
|
| 39 |
+
tujuan = rute_node_ids[i + 1]
|
| 40 |
+
try:
|
| 41 |
+
path = nx.shortest_path(G, asal, tujuan, weight="length")
|
| 42 |
+
titik = [(G.nodes[n]['y'], G.nodes[n]['x']) for n in path]
|
| 43 |
+
garis_rute.extend(titik)
|
| 44 |
+
except:
|
| 45 |
+
continue # Lewati jika tidak ada path
|
| 46 |
+
return garis_rute
|
| 47 |
+
|
| 48 |
+
def buat_peta_folium(gdf_nodes, kantor_id=None, rumah_ids=None, garis_rute=None, tampilkan_hanya_yang_dipilih=False):
|
| 49 |
+
pusat = gdf_nodes.geometry.unary_union.centroid
|
| 50 |
+
m = folium.Map(location=[pusat.y, pusat.x], zoom_start=16)
|
| 51 |
+
|
| 52 |
+
for i, (node_id, row) in enumerate(gdf_nodes.iterrows(), 1):
|
| 53 |
+
if tampilkan_hanya_yang_dipilih:
|
| 54 |
+
if kantor_id != node_id and (not rumah_ids or node_id not in rumah_ids):
|
| 55 |
+
continue # Skip marker jika bukan kantor dan bukan rumah yang dipilih
|
| 56 |
+
|
| 57 |
+
nama = f"Rumah ke-{i}"
|
| 58 |
+
if kantor_id == node_id:
|
| 59 |
+
warna = "red"
|
| 60 |
+
ikon = "building"
|
| 61 |
+
label = "Kantor"
|
| 62 |
+
elif rumah_ids and node_id in rumah_ids:
|
| 63 |
+
warna = "green"
|
| 64 |
+
ikon = "home"
|
| 65 |
+
label = nama
|
| 66 |
+
else:
|
| 67 |
+
warna = "blue"
|
| 68 |
+
ikon = "home"
|
| 69 |
+
label = nama
|
| 70 |
+
|
| 71 |
+
folium.Marker(
|
| 72 |
+
location=[row.y, row.x],
|
| 73 |
+
popup=f"{label}<br>ID: {node_id}",
|
| 74 |
+
icon=folium.Icon(color=warna, icon=ikon)
|
| 75 |
+
).add_to(m)
|
| 76 |
+
|
| 77 |
+
if garis_rute:
|
| 78 |
+
# Buat garis utama
|
| 79 |
+
garis = folium.PolyLine(garis_rute, color="purple", weight=5, opacity=0.8)
|
| 80 |
+
garis.add_to(m)
|
| 81 |
+
|
| 82 |
+
# Tambahkan panah arah (text path dengan panah)
|
| 83 |
+
panah = PolyLineTextPath(
|
| 84 |
+
garis,
|
| 85 |
+
' ➤ ', # Simbol panah (spasi untuk jeda antar panah)
|
| 86 |
+
repeat=True,
|
| 87 |
+
offset=7, # posisi offset dari garis
|
| 88 |
+
attributes={'fill': 'orange', 'font-weight': 'bold', 'font-size': '16'}
|
| 89 |
+
)
|
| 90 |
+
panah.add_to(m)
|
| 91 |
+
|
| 92 |
+
return m
|
| 93 |
+
|
| 94 |
+
# Inisialisasi sesi
|
| 95 |
+
if "halaman" not in st.session_state:
|
| 96 |
+
st.session_state["halaman"] = "pilih_kantor"
|
| 97 |
+
|
| 98 |
+
G, gdf_nodes, gdf_edges = ambil_graf_keputih()
|
| 99 |
+
|
| 100 |
+
# Buat label node
|
| 101 |
+
list_label = [f"Rumah ke-{i} (node {node_id})" for i, node_id in enumerate(gdf_nodes.index, 1)]
|
| 102 |
+
id_mapping = dict(zip(list_label, gdf_nodes.index.to_list()))
|
| 103 |
+
|
| 104 |
+
# SIDEBAR
|
| 105 |
+
with st.sidebar:
|
| 106 |
+
st.title("Input Lokasi")
|
| 107 |
+
|
| 108 |
+
if st.session_state["halaman"] == "pilih_kantor":
|
| 109 |
+
st.subheader("1. Pilih Kantor")
|
| 110 |
+
kantor_label = st.selectbox("Node Kantor:", list_label)
|
| 111 |
+
kantor_id = id_mapping[kantor_label]
|
| 112 |
+
|
| 113 |
+
if st.button("Lanjut"):
|
| 114 |
+
st.session_state["kantor_id"] = kantor_id
|
| 115 |
+
st.session_state["halaman"] = "pilih_rumah"
|
| 116 |
+
st.rerun()
|
| 117 |
+
|
| 118 |
+
elif st.session_state["halaman"] == "pilih_rumah":
|
| 119 |
+
st.subheader("2. Pilih Rumah Tujuan")
|
| 120 |
+
|
| 121 |
+
# List rumah tidak boleh termasuk kantor
|
| 122 |
+
list_label_rumah = [
|
| 123 |
+
label for label in list_label
|
| 124 |
+
if id_mapping[label] != st.session_state["kantor_id"]
|
| 125 |
+
]
|
| 126 |
+
rumah_labels = st.multiselect("Node Rumah:", list_label_rumah)
|
| 127 |
+
rumah_ids = [id_mapping[label] for label in rumah_labels]
|
| 128 |
+
|
| 129 |
+
if st.button("Mulai Pengantaran"):
|
| 130 |
+
st.session_state["rumah_ids"] = rumah_ids
|
| 131 |
+
st.session_state["halaman"] = "hasil"
|
| 132 |
+
|
| 133 |
+
elif st.session_state["halaman"] == "hasil":
|
| 134 |
+
if st.button("Kembali"):
|
| 135 |
+
st.session_state["halaman"] = "pilih_kantor"
|
| 136 |
+
st.rerun()
|
| 137 |
+
|
| 138 |
+
st.markdown("---")
|
| 139 |
+
if st.button("🔄 Restart Aplikasi"):
|
| 140 |
+
for k in list(st.session_state.keys()):
|
| 141 |
+
del st.session_state[k]
|
| 142 |
+
st.rerun()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
#######################################################
|
| 146 |
+
|
| 147 |
+
# Fungsi: Membuat matriks jarak (TSP) dari graf dan daftar node
|
| 148 |
+
def hitung_matriks_TSP(G, kantor_id, rumah_ids):
|
| 149 |
+
semua_ids = [kantor_id] + rumah_ids
|
| 150 |
+
reachable_ids = [kantor_id] # mulai dari kantor
|
| 151 |
+
|
| 152 |
+
# Cek node mana saja yang reachable dari kantor
|
| 153 |
+
for rumah_id in rumah_ids:
|
| 154 |
+
try:
|
| 155 |
+
nx.shortest_path_length(G, kantor_id, rumah_id, weight="length")
|
| 156 |
+
reachable_ids.append(rumah_id)
|
| 157 |
+
except nx.NetworkXNoPath:
|
| 158 |
+
continue # Skip rumah yang tidak reachable dari kantor
|
| 159 |
+
|
| 160 |
+
# Pastikan ada minimal 2 node (kantor + minimal 1 rumah)
|
| 161 |
+
if len(reachable_ids) < 2:
|
| 162 |
+
raise ValueError("Tidak cukup node yang saling terhubung. Harap pilih node yang lebih dekat atau tersambung.")
|
| 163 |
+
|
| 164 |
+
TSP = [[0 for _ in reachable_ids] for _ in reachable_ids]
|
| 165 |
+
indeks_ke_node = {i: node_id for i, node_id in enumerate(reachable_ids)}
|
| 166 |
+
|
| 167 |
+
for i in range(len(reachable_ids)):
|
| 168 |
+
for j in range(len(reachable_ids)):
|
| 169 |
+
if i != j:
|
| 170 |
+
try:
|
| 171 |
+
TSP[i][j] = nx.shortest_path_length(G, indeks_ke_node[i], indeks_ke_node[j], weight="length")
|
| 172 |
+
except nx.NetworkXNoPath:
|
| 173 |
+
TSP[i][j] = float('inf') # opsional, atau bisa raise error
|
| 174 |
+
|
| 175 |
+
return TSP, indeks_ke_node
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# Kelas individu untuk algoritma genetika
|
| 179 |
+
class Individual:
|
| 180 |
+
def __init__(self, chromosome, TSP):
|
| 181 |
+
self.chromosome = chromosome
|
| 182 |
+
self.TSP = TSP
|
| 183 |
+
self.fitness = self.calc_fitness()
|
| 184 |
+
|
| 185 |
+
def calc_fitness(self):
|
| 186 |
+
distance = 0
|
| 187 |
+
for i in range(len(self.chromosome)):
|
| 188 |
+
from_city = self.chromosome[i]
|
| 189 |
+
to_city = self.chromosome[(i + 1) % len(self.chromosome)]
|
| 190 |
+
distance += self.TSP[from_city][to_city]
|
| 191 |
+
return distance
|
| 192 |
+
|
| 193 |
+
def mutate(self):
|
| 194 |
+
a = random.randint(1, len(self.chromosome) - 1)
|
| 195 |
+
b = random.randint(1, len(self.chromosome) - 1)
|
| 196 |
+
self.chromosome[a], self.chromosome[b] = self.chromosome[b], self.chromosome[a]
|
| 197 |
+
|
| 198 |
+
@staticmethod
|
| 199 |
+
def crossover(parent1, parent2):
|
| 200 |
+
size = len(parent1.chromosome)
|
| 201 |
+
p1 = parent1.chromosome[1:]
|
| 202 |
+
p2 = parent2.chromosome[1:]
|
| 203 |
+
start = random.randint(0, size - 2)
|
| 204 |
+
end = random.randint(start + 1, size - 1)
|
| 205 |
+
|
| 206 |
+
middle = p1[start:end]
|
| 207 |
+
child = middle + [c for c in p2 if c not in middle]
|
| 208 |
+
|
| 209 |
+
return Individual([0] + child, parent1.TSP)
|
| 210 |
+
|
| 211 |
+
# Fungsi inisialisasi populasi awal
|
| 212 |
+
def initial_population(TSP, size):
|
| 213 |
+
population = []
|
| 214 |
+
for _ in range(size):
|
| 215 |
+
chromosome = list(range(1, len(TSP)))
|
| 216 |
+
random.shuffle(chromosome)
|
| 217 |
+
chromosome = [0] + chromosome
|
| 218 |
+
population.append(Individual(chromosome, TSP))
|
| 219 |
+
return population
|
| 220 |
+
|
| 221 |
+
# Fungsi seleksi dan loop algoritma GA
|
| 222 |
+
def select_parent(population):
|
| 223 |
+
return min(random.sample(population, 5), key=lambda ind: ind.fitness)
|
| 224 |
+
|
| 225 |
+
def jalankan_GA(TSP, generations=300, pop_size=100):
|
| 226 |
+
population = initial_population(TSP, pop_size)
|
| 227 |
+
for _ in range(generations):
|
| 228 |
+
population.sort(key=lambda ind: ind.fitness)
|
| 229 |
+
next_gen = population[:10]
|
| 230 |
+
|
| 231 |
+
while len(next_gen) < pop_size:
|
| 232 |
+
p1 = select_parent(population)
|
| 233 |
+
p2 = select_parent(population)
|
| 234 |
+
child = Individual.crossover(p1, p2)
|
| 235 |
+
if random.random() < 0.2:
|
| 236 |
+
child.mutate()
|
| 237 |
+
next_gen.append(child)
|
| 238 |
+
|
| 239 |
+
population = next_gen
|
| 240 |
+
|
| 241 |
+
best = min(population, key=lambda ind: ind.fitness)
|
| 242 |
+
return best.chromosome + [0], best.fitness
|
| 243 |
+
############################################################
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# HALAMAN UTAMA
|
| 247 |
+
if st.session_state["halaman"] == "pilih_kantor":
|
| 248 |
+
st.header("Pilih Kantor pada Peta")
|
| 249 |
+
st_folium(buat_peta_folium(gdf_nodes), width=700, height=500)
|
| 250 |
+
|
| 251 |
+
elif st.session_state["halaman"] == "pilih_rumah":
|
| 252 |
+
st.header("Pilih Rumah Tujuan pada Peta")
|
| 253 |
+
st_folium(buat_peta_folium(gdf_nodes, kantor_id=st.session_state["kantor_id"]), width=700, height=500)
|
| 254 |
+
|
| 255 |
+
elif st.session_state["halaman"] == "hasil":
|
| 256 |
+
st.header("Hasil Pengantaran")
|
| 257 |
+
rumah_ids = st.session_state.get("rumah_ids", [])
|
| 258 |
+
kantor_id = st.session_state.get("kantor_id")
|
| 259 |
+
|
| 260 |
+
# Jalankan GA
|
| 261 |
+
TSP_matrix, indeks_ke_node = hitung_matriks_TSP(G, kantor_id, rumah_ids)
|
| 262 |
+
best_path_indexed, best_fitness = jalankan_GA(TSP_matrix)
|
| 263 |
+
path_nodes = [indeks_ke_node[i] for i in best_path_indexed]
|
| 264 |
+
|
| 265 |
+
garis_rute = buat_rute_polyline(G, path_nodes)
|
| 266 |
+
|
| 267 |
+
st_folium(
|
| 268 |
+
buat_peta_folium(
|
| 269 |
+
gdf_nodes,
|
| 270 |
+
kantor_id=kantor_id,
|
| 271 |
+
rumah_ids=set(path_nodes), # hanya node yang dilewati
|
| 272 |
+
garis_rute=garis_rute,
|
| 273 |
+
tampilkan_hanya_yang_dipilih=True # aktifkan filter
|
| 274 |
+
),
|
| 275 |
+
width=700,
|
| 276 |
+
height=500
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
st.success(f"Kurir berangkat dari kantor dengan node {kantor_id}")
|
| 281 |
+
|
| 282 |
+
# Buat mapping dari node ke label rumah yang asli dari dropdown
|
| 283 |
+
node_to_label = {}
|
| 284 |
+
|
| 285 |
+
# Tambahkan label kantor
|
| 286 |
+
node_to_label[kantor_id] = "Kantor"
|
| 287 |
+
|
| 288 |
+
# Ambil semua label yang tersedia dari dropdown
|
| 289 |
+
for label, node_id in id_mapping.items():
|
| 290 |
+
if node_id in rumah_ids:
|
| 291 |
+
node_to_label[node_id] = label.split(" (")[0] # Ambil 'Rumah ke-498' saja
|
| 292 |
+
|
| 293 |
+
# Konversi path_nodes ke label
|
| 294 |
+
path_labels = [node_to_label.get(nid, str(nid)) for nid in path_nodes]
|
| 295 |
+
rute_string = " → ".join(path_labels)
|
| 296 |
+
st.success(f"Rute terbaik: {rute_string}")
|
| 297 |
+
|
| 298 |
+
st.success(f"Total jarak: {best_fitness:.2f} meter")
|
| 299 |
+
|
| 300 |
+
if st.button("Kembali"):
|
| 301 |
+
st.session_state["halaman"] = "pilih_kantor"
|
| 302 |
+
st.rerun()
|