Skip to content

Commit

Permalink
[ADD] haversine
Browse files Browse the repository at this point in the history
  • Loading branch information
lavi02 committed Jan 15, 2024
1 parent 048c5a8 commit dcecd36
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
41 changes: 41 additions & 0 deletions src/service/tsp/hvsine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import math
import networkx as nx
import numpy as np

def haversine(coord1, coord2):
# 지구 반지름 (km 단위)
R = 6371.0

lat1, lon1 = coord1
lat2, lon2 = coord2

dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)

a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

distance = R * c
return distance

def create_haversine_matrix(coords):
num_coords = len(coords)
matrix = np.zeros((num_coords, num_coords))
for i in range(num_coords):
for j in range(num_coords):
if i != j:
matrix[i][j] = haversine(coords[i], coords[j])
return matrix


def create_graph(nodes, edges):
G = nx.Graph()
for node in nodes:
G.add_node(node)

for edge in edges:
node1, node2 = edge
distance = haversine(nodes[node1], nodes[node2])
G.add_edge(node1, node2, weight=distance)

return G
8 changes: 8 additions & 0 deletions src/service/tsp/q.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ def choose_action(self, state):
Returns:
The action to be taken
'''
neighbors = list(self.env.graph.neighbors(state))
num_available_actions = len(neighbors)
if num_available_actions == 0:
return -1

available_actions = len(list(self.env.graph.neighbors(state)))
if random.uniform(0, 1) < self.epsilon:
action = random.choice(range(available_actions))
Expand All @@ -65,6 +70,9 @@ def update(self, state, action, reward, next_state):
reward: The reward for the action
next_state: The next state
'''
if action == -1: # 더 이상 이동할 수 없는 경우
return

available_actions = len(list(self.env.graph.neighbors(state)))
if next_state == self.env.destination_node:
self.q_table[state, action] = reward
Expand Down
19 changes: 17 additions & 2 deletions src/service/tsp/tsp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from src.service.tsp.q import nx, ox, np
from src.service.tsp.hvsine import create_graph, create_haversine_matrix
from src.service.tsp.solver import RouteOptimizer, OrToolsRouteOptimizer, QLearningRouteOptimizer, AStarRouteOptimizer
from typing import List

Expand All @@ -7,9 +8,9 @@

def download_korea_road_network() -> nx.Graph:
try:
korea_gdf = ox.geocode_to_gdf("South Korea")
korea_gdf = ox.geocode_to_gdf("Seoul, South Korea")
korea_graph = ox.graph_from_polygon(
korea_gdf.unary_union, network_type='drive')
korea_gdf.unary_union, network_type='drive', simplify=True)
return korea_graph
except Exception as e:
handler.log.error("Error downloading Korea road network: %s" % e)
Expand Down Expand Up @@ -76,6 +77,20 @@ def run(waypoints: dict, start_fixed: bool = False, end_fixed: bool = False) ->
objective_value, path = runner.run(matrix, start_fixed, end_fixed)
handler.log.info("Objective value: %s, Path: %s" % (objective_value, path))

if objective_value == 0 or path is None:
coords = list(waypoints.values())
matrix = create_haversine_matrix(coords)

data = create_graph(waypoints, matrix)
path = nx.shortest_path(data, 0, len(waypoints) - 1, weight='weight')
handler.log.info("Objective value: %s, Path: %s" % (objective_value, path))

optimized_waypoints = {}
for i, index in enumerate(path):
optimized_waypoints[list(waypoints.keys())[i]] = coords[index]

return optimized_waypoints

optimized_waypoints = {}
for i, index in enumerate(path):
optimized_waypoints[list(waypoints.keys())[i]] = coords[index]
Expand Down

0 comments on commit dcecd36

Please sign in to comment.