optimal-route / app.py
fudii0921's picture
Update app.py
3b533eb verified
import networkx as nx
import gradio as gr
def find_shortest_path(graph, start, end):
"""
Find the shortest path in a graph using Dijkstra's algorithm.
Parameters:
graph (dict): A dictionary representing the graph where keys are node names and values are dictionaries of neighboring nodes and their distances.
start (str): The starting node.
end (str): The destination node.
Returns:
list: The shortest path from start to end.
float: The total distance of the shortest path.
"""
G = nx.DiGraph()
# Add edges to the graph
for node, neighbors in graph.items():
for neighbor, distance in neighbors.items():
G.add_edge(node, neighbor, weight=distance)
# Find the shortest path using Dijkstra's algorithm
shortest_path = nx.dijkstra_path(G, start, end)
total_distance = nx.dijkstra_path_length(G, start, end)
return shortest_path, total_distance
def combine_maps(city_map, jam_map):
"""
Combine city map and jam map by adding their weights.
Parameters:
city_map (dict): A dictionary representing the city map where keys are node names and values are dictionaries of neighboring nodes and their distances.
jam_map (dict): A dictionary representing the jam map where keys are node names and values are dictionaries of neighboring nodes and their jam factors.
Returns:
dict: A combined map with summed weights.
"""
combined_map = {}
for node in city_map:
combined_map[node] = {}
for neighbor in city_map[node]:
combined_map[node][neighbor] = city_map[node][neighbor] + jam_map[node][neighbor]
return combined_map
# Example graph representing the city map
city_map = {
'重症外傷センター': {'池袋': 2, '中目黒': 5},
'池袋': {'重症外傷センター': 2, '中目黒': 3, '六本木': 4},
'中目黒': {'重症外傷センター': 5, '池袋': 3, '六本木': 2, '銀座': 6},
'六本木': {'池袋': 4, '中目黒': 2, '銀座': 1},
'銀座': {'中目黒': 6, '六本木': 1}
}
# Example graph representing the jam map
jam_map = {
'重症外傷センター': {'池袋': 5, '中目黒': 2},
'池袋': {'重症外傷センター': 5, '中目黒': 4, '六本木': 3},
'中目黒': {'重症外傷センター': 5, '池袋': 6, '六本木': 3, '銀座': 2},
'六本木': {'池袋': 1, '中目黒': 3, '銀座': 5},
'銀座': {'中目黒': 3, '六本木': 4}
}
# Combine city map and jam map
combined_map = combine_maps(city_map, jam_map)
def shortest_path_interface(start_point, destination):
shortest_path, total_distance = find_shortest_path(combined_map, start_point, destination)
return f"一番短い{start_point}から{destination}までの経路は: {shortest_path}\nトータルの距離は{total_distance}ユニットです。"
# Create Gradio interface
iface = gr.Interface(
fn=shortest_path_interface,
inputs=[gr.Textbox(label="出発地",value="銀座"),gr.Textbox(label="到着地",value="重症外傷センター")],
outputs="text",
title="救急搬送ルートの最適化",
description="出発地点と目的地を入力して、最短経路を計算します。"
)
# Launch the interface
iface.launch()