import streamlit as st import osmnx as ox import matplotlib.pyplot as plt import tempfile import os import folium from streamlit_folium import st_folium import random import networkx as nx from folium.plugins import PolyLineTextPath # Konfigurasi osmnx agar tidak menyimpan cache permanen ox.settings.use_cache = False ox.settings.cache_folder = tempfile.gettempdir() ox.settings.logs_folder = tempfile.gettempdir() @st.cache_resource def ambil_graf_keputih(): # Ambil graf awal dari OSM G = ox.graph_from_place("Keputih, Sukolilo, Surabaya, Indonesia", network_type="drive", simplify=True) # Ubah ke undirected agar bisa cari komponen terhubung G_undirected = G.to_undirected() # Ambil komponen terbesar largest_cc = max(nx.connected_components(G_undirected), key=len) G_connected = G.subgraph(largest_cc).copy() # Ambil data node dan edge gdf_nodes, gdf_edges = ox.graph_to_gdfs(G_connected) return G_connected, gdf_nodes, gdf_edges def buat_rute_polyline(G, rute_node_ids): garis_rute = [] for i in range(len(rute_node_ids) - 1): asal = rute_node_ids[i] tujuan = rute_node_ids[i + 1] try: # Ambil semua shortest path semua_path = list(nx.all_shortest_paths(G, asal, tujuan, weight="length")) # Pilih hanya satu (misalnya yang pertama) path = semua_path[0] titik = [(G.nodes[n]['y'], G.nodes[n]['x']) for n in path] garis_rute.extend(titik) except: continue # Lewati jika tidak ada path return garis_rute def buat_peta_folium(gdf_nodes, kantor_id=None, rumah_ids=None, garis_rute=None, tampilkan_hanya_yang_dipilih=False): pusat = gdf_nodes.geometry.unary_union.centroid m = folium.Map(location=[pusat.y, pusat.x], zoom_start=16) for i, (node_id, row) in enumerate(gdf_nodes.iterrows(), 1): if tampilkan_hanya_yang_dipilih: if kantor_id != node_id and (not rumah_ids or node_id not in rumah_ids): continue # Skip marker jika bukan kantor dan bukan rumah yang dipilih nama = f"Rumah ke-{i}" if kantor_id == node_id: warna = "red" ikon = "building" label = "Kantor" elif rumah_ids and node_id in rumah_ids: warna = "green" ikon = "home" label = nama else: warna = "blue" ikon = "home" label = nama folium.Marker( location=[row.y, row.x], popup=f"{label}
ID: {node_id}", icon=folium.Icon(color=warna, icon=ikon) ).add_to(m) if garis_rute: # Buat garis utama garis = folium.PolyLine(garis_rute, color="purple", weight=5, opacity=0.8) garis.add_to(m) # Tambahkan panah arah (text path dengan panah) panah = PolyLineTextPath( garis, ' ➤ ', # Simbol panah (spasi untuk jeda antar panah) repeat=True, offset=7, # posisi offset dari garis attributes={'fill': 'orange', 'font-weight': 'bold', 'font-size': '16'} ) panah.add_to(m) return m # Inisialisasi sesi if "halaman" not in st.session_state: st.session_state["halaman"] = "pilih_kantor" G, gdf_nodes, gdf_edges = ambil_graf_keputih() # Buat label node list_label = [f"Rumah ke-{i} (node {node_id})" for i, node_id in enumerate(gdf_nodes.index, 1)] id_mapping = dict(zip(list_label, gdf_nodes.index.to_list())) # SIDEBAR with st.sidebar: st.title("Input Lokasi") if st.session_state["halaman"] == "pilih_kantor": st.subheader("1. Pilih Kantor") kantor_label = st.selectbox("Node Kantor:", list_label) kantor_id = id_mapping[kantor_label] if st.button("Lanjut"): st.session_state["kantor_id"] = kantor_id st.session_state["halaman"] = "pilih_rumah" st.rerun() elif st.session_state["halaman"] == "pilih_rumah": st.subheader("2. Pilih Rumah Tujuan") # List rumah tidak boleh termasuk kantor list_label_rumah = [ label for label in list_label if id_mapping[label] != st.session_state["kantor_id"] ] rumah_labels = st.multiselect("Node Rumah:", list_label_rumah) rumah_ids = [id_mapping[label] for label in rumah_labels] if st.button("Mulai Pengantaran"): st.session_state["rumah_ids"] = rumah_ids st.session_state["halaman"] = "hasil" elif st.session_state["halaman"] == "hasil": if st.button("Kembali"): st.session_state["halaman"] = "pilih_kantor" st.rerun() st.markdown("---") if st.button("🔄 Restart Aplikasi"): for k in list(st.session_state.keys()): del st.session_state[k] st.rerun() ####################################################### # Fungsi: Membuat matriks jarak (TSP) dari graf dan daftar node def hitung_matriks_TSP(G, kantor_id, rumah_ids): semua_ids = [kantor_id] + rumah_ids reachable_ids = [kantor_id] # mulai dari kantor # Cek node mana saja yang reachable dari kantor for rumah_id in rumah_ids: try: nx.shortest_path_length(G, kantor_id, rumah_id, weight="length") reachable_ids.append(rumah_id) except nx.NetworkXNoPath: continue # Skip rumah yang tidak reachable dari kantor # Pastikan ada minimal 2 node (kantor + minimal 1 rumah) if len(reachable_ids) < 2: raise ValueError("Tidak cukup node yang saling terhubung. Harap pilih node yang lebih dekat atau tersambung.") TSP = [[0 for _ in reachable_ids] for _ in reachable_ids] indeks_ke_node = {i: node_id for i, node_id in enumerate(reachable_ids)} for i in range(len(reachable_ids)): for j in range(len(reachable_ids)): if i != j: try: TSP[i][j] = nx.shortest_path_length(G, indeks_ke_node[i], indeks_ke_node[j], weight="length") except nx.NetworkXNoPath: TSP[i][j] = float('inf') # opsional, atau bisa raise error return TSP, indeks_ke_node # Kelas individu untuk algoritma genetika class Individual: def __init__(self, chromosome, TSP): self.chromosome = chromosome self.TSP = TSP self.fitness = self.calc_fitness() def calc_fitness(self): distance = 0 for i in range(len(self.chromosome)): from_city = self.chromosome[i] to_city = self.chromosome[(i + 1) % len(self.chromosome)] distance += self.TSP[from_city][to_city] return distance def mutate(self): a = random.randint(1, len(self.chromosome) - 1) b = random.randint(1, len(self.chromosome) - 1) self.chromosome[a], self.chromosome[b] = self.chromosome[b], self.chromosome[a] @staticmethod def crossover(parent1, parent2): size = len(parent1.chromosome) p1 = parent1.chromosome[1:] p2 = parent2.chromosome[1:] start = random.randint(0, size - 2) end = random.randint(start + 1, size - 1) middle = p1[start:end] child = middle + [c for c in p2 if c not in middle] return Individual([0] + child, parent1.TSP) # Fungsi inisialisasi populasi awal def initial_population(TSP, size): population = [] for _ in range(size): chromosome = list(range(1, len(TSP))) random.shuffle(chromosome) chromosome = [0] + chromosome population.append(Individual(chromosome, TSP)) return population # Fungsi seleksi dan loop algoritma GA def select_parent(population): return min(random.sample(population, 5), key=lambda ind: ind.fitness) def jalankan_GA(TSP, generations=300, pop_size=100): population = initial_population(TSP, pop_size) for _ in range(generations): population.sort(key=lambda ind: ind.fitness) next_gen = population[:10] while len(next_gen) < pop_size: p1 = select_parent(population) p2 = select_parent(population) child = Individual.crossover(p1, p2) if random.random() < 0.2: child.mutate() next_gen.append(child) population = next_gen best = min(population, key=lambda ind: ind.fitness) return best.chromosome + [0], best.fitness ############################################################ # HALAMAN UTAMA if st.session_state["halaman"] == "pilih_kantor": st.header("Pilih Kantor pada Peta") st_folium(buat_peta_folium(gdf_nodes), width=700, height=500) elif st.session_state["halaman"] == "pilih_rumah": st.header("Pilih Rumah Tujuan pada Peta") st_folium(buat_peta_folium(gdf_nodes, kantor_id=st.session_state["kantor_id"]), width=700, height=500) elif st.session_state["halaman"] == "hasil": st.header("Hasil Pengantaran") rumah_ids = st.session_state.get("rumah_ids", []) kantor_id = st.session_state.get("kantor_id") # Jalankan GA TSP_matrix, indeks_ke_node = hitung_matriks_TSP(G, kantor_id, rumah_ids) best_path_indexed, best_fitness = jalankan_GA(TSP_matrix) path_nodes = [indeks_ke_node[i] for i in best_path_indexed] garis_rute = buat_rute_polyline(G, path_nodes) st_folium( buat_peta_folium( gdf_nodes, kantor_id=kantor_id, rumah_ids=set(path_nodes), # hanya node yang dilewati garis_rute=garis_rute, tampilkan_hanya_yang_dipilih=True # aktifkan filter ), width=700, height=500 ) st.success(f"Kurir berangkat dari kantor dengan node {kantor_id}") # Buat mapping dari node ke label rumah yang asli dari dropdown node_to_label = {} # Tambahkan label kantor node_to_label[kantor_id] = "Kantor" # Ambil semua label yang tersedia dari dropdown for label, node_id in id_mapping.items(): if node_id in rumah_ids: node_to_label[node_id] = label.split(" (")[0] # Ambil 'Rumah ke-498' saja # Konversi path_nodes ke label path_labels = [node_to_label.get(nid, str(nid)) for nid in path_nodes] rute_string = " → ".join(path_labels) st.success(f"Rute terbaik: {rute_string}") st.success(f"Total jarak: {best_fitness:.2f} meter") if st.button("Kembali"): st.session_state["halaman"] = "pilih_kantor" st.rerun()