Advertisement
anik11556

assignment1

Feb 20th, 2024
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.03 KB | None | 0 0
  1. import osmnx as ox
  2. import random
  3. import networkx as nx
  4. import heapq
  5. import time
  6. from tabulate import tabulate
  7. import matplotlib.pyplot as plt
  8.  
  9.  
  10.  
  11. list1 = []
  12. list2 = []
  13. list3 = []
  14. risk_values = []
  15. risk_iterator = 0
  16. node_pairs = []
  17. risk_values = []
  18.  
  19. def hstd(node1, node2):
  20.     global risk_iterator  
  21.     hstd_value = ox.distance.euclidean_dist_vec(graph.nodes[node1]['y'], graph.nodes[node1]['x'],
  22.                                                  graph.nodes[node2]['y'], graph.nodes[node2]['x'])
  23.    
  24.  
  25.  
  26.     try:
  27.         # Get the index of node1 and node2 from the node_pairs list
  28.         index = node_pairs.index((node1, node2))
  29.         risk_value = risk_values[index]
  30.     except ValueError:  # Handle the case when the index is not found
  31.         risk_value = 100000
  32.     # index = node_pairs.index((node1, node2))
  33.    
  34.     # Find the risk value corresponding to the index
  35.     # risk_value = risk_values[index]
  36.  
  37.    
  38.    
  39.     #print(node1)
  40.     #risk_value = random.uniform(0, 500)
  41.    
  42.     retValue = hstd_value + risk_value
  43.     #print(retValue)
  44.     # # Append the risk value to a file
  45.     # with open("risk.txt", "a") as f:
  46.     #     f.write(str(risk_value) + "\n")
  47.    
  48.    
  49.     # risk_value = risk_values[risk_iterator]
  50.    
  51.     # # Increment the risk iterator and loop back to the beginning if necessary
  52.     # risk_iterator = (risk_iterator + 1) % len(risk_values)
  53.     return retValue
  54.  
  55. def dijkstra(graph, start_node):
  56.     dist = {node: float('inf') for node in graph.nodes}
  57.     dist[start_node] = 0
  58.     predecessors = {}
  59.     pq = [(0, start_node)]
  60.     while pq:
  61.         current_dist, current_node = heapq.heappop(pq)
  62.         if current_dist > dist[current_node]:
  63.             continue
  64.         for neighbor, edge in graph[current_node].items():
  65.             weight = edge.get('weight', 1)
  66.             new_dist = dist[current_node] + weight
  67.             if new_dist < dist[neighbor]:
  68.                 dist[neighbor] = new_dist
  69.                 predecessors[neighbor] = current_node
  70.                 heapq.heappush(pq, (new_dist, neighbor))
  71.     return dist, predecessors
  72.  
  73. def evaluation_function(node, target_node, actual_cost, heuristic, weight):
  74.     return actual_cost[node] + weight * heuristic(node, target_node)
  75.  
  76. def greedy_best_first_search(graph, start_node, target_node, heuristic):
  77.     visited = set()
  78.     pq = [(heuristic(start_node, target_node), start_node)]
  79.     while pq:
  80.         _, current_node = heapq.heappop(pq)
  81.         list1.append(current_node)
  82.         if current_node == target_node:
  83.             return visited
  84.         visited.add(current_node)
  85.         for neighbor in graph[current_node]:
  86.             if neighbor not in visited:
  87.                 heapq.heappush(pq, (heuristic(neighbor, target_node), neighbor))
  88.                 list1.append(neighbor)
  89.     return visited
  90.  
  91. def a_star(graph, start_node, target_node, actual_cost, heuristic):
  92.     visited = set()
  93.     pq = [(evaluation_function(start_node, target_node, actual_cost, heuristic, 1), start_node)]
  94.     while pq:
  95.         _, current_node = heapq.heappop(pq)
  96.         list2.append(current_node)
  97.         if current_node == target_node:
  98.             return visited
  99.         visited.add(current_node)
  100.         for neighbor in graph[current_node]:
  101.             if neighbor not in visited:
  102.                 heapq.heappush(pq, (evaluation_function(neighbor, target_node, actual_cost, heuristic, 1), neighbor))
  103.     return visited
  104.  
  105. def weighted_a_star(graph, start_node, target_node, actual_cost, heuristic, weight):
  106.     visited = set()
  107.     pq = [(evaluation_function(start_node, target_node, actual_cost, heuristic, weight), start_node)]
  108.     while pq:
  109.         _, current_node = heapq.heappop(pq)
  110.         list3.append(current_node)
  111.         if current_node == target_node:
  112.             return visited
  113.         visited.add(current_node)
  114.         for neighbor in graph[current_node]:
  115.             if neighbor not in visited:
  116.                 heapq.heappush(pq, (evaluation_function(neighbor, target_node, actual_cost, heuristic, weight), neighbor))
  117.     return visited
  118.  
  119. city_name = "Lake Placid, New York"
  120. graph = ox.graph_from_place(city_name, network_type='all')
  121.  
  122.  
  123.  
  124.  
  125.  
  126. # Open the file in read mode
  127. with open("risk.txt", "r") as f:
  128.     # Iterate over each line in the file
  129.     for line in f:
  130.         # Convert the line to a float and append it to the list
  131.         risk_values.append(float(line.strip()))
  132.  
  133. # Print the list of risk values
  134.  
  135.  
  136. if graph is not None:
  137.     nodes = graph.nodes
  138.     edges = graph.edges
  139.     all_nodes = list(graph.nodes)
  140.    
  141.  
  142.  
  143.     # with open("nodes.txt", "w") as f:
  144.     #     # Iterate over the nodes and write their IDs to the file
  145.     #     for node in nodes:
  146.     #         f.write(str(node) + "\n")
  147.  
  148.     desired_edge_index = 0
  149.    
  150.     # Iterate over the edges and find the edge with the desired index
  151.     # for u, v, data in edges(data=True):
  152.     #     if u == desired_edge_index or v == desired_edge_index:
  153.     #         print("Edge data:", data)
  154.     #         break
  155.  
  156.  
  157.     print(len(edges))
  158.     # with open("u_values.txt", "w") as f:  
  159.     #  for u, v, data in edges(data=True):
  160.     #     risk_value = random.uniform(0, 500)
  161.     #     f.write(f"{u} {v} {risk_value}\n")
  162.     #    # print(f"Edge: {u} -> {v}, Nodes: {u}, {v}")
  163.        
  164.          
  165. # Open the file in read mode
  166.     with open("u_values.txt", "r") as f:
  167.         # Iterate over each line in the file
  168.         for line in f:
  169.             # Split the line into three values: node1, node2, and risk value
  170.             node1, node2, risk = line.split()
  171.             node_pairs.append((int(node1), int(node2)))
  172.             # Convert the risk value to float and append it to the list
  173.             risk_values.append(float(risk))
  174.  
  175.     # Print the list of risk values
  176. #     print("Risk values length:", len(risk_values))
  177. #     print(risk_values)
  178. # # Print the length of the node pairs list
  179. #     print("Node pairs length:", len(node_pairs))
  180. #     //print(node_pairs)
  181.            
  182.  
  183.     # start_node = 8922966682
  184.     # target_node = 8922966471
  185.  
  186.  
  187.  
  188.     start_node = random.choice(all_nodes)
  189.     target_node = random.choice(all_nodes)
  190.     start_time = time.time()
  191.     actual_cost, _ = dijkstra(graph, start_node)
  192.     dijkstra_time = time.time() - start_time
  193.  
  194.     start_time = time.time()
  195.     gbfs_visited = greedy_best_first_search(graph, start_node, target_node, hstd)
  196.     gbfs_time = time.time() - start_time
  197.  
  198.     start_time = time.time()
  199.     a_star_visited = a_star(graph, start_node, target_node, actual_cost, hstd)
  200.     a_star_time = time.time() - start_time
  201.  
  202.     start_time = time.time()
  203.     weight = 4
  204.     weighted_a_star_visited = weighted_a_star(graph, start_node, target_node, actual_cost, hstd, weight)
  205.     weighted_a_star_time = time.time() - start_time
  206.  
  207.     # print("Start Node:", start_node)
  208.     # print("Target Node:", target_node)
  209.  
  210.     gbfs_time_ms = gbfs_time * 1000
  211.     a_star_time_ms = a_star_time * 1000
  212.     weighted_a_star_time_ms = weighted_a_star_time * 1000
  213.  
  214.     results = [
  215.         ("Greedy Best First Search", len(gbfs_visited)*8, gbfs_time_ms, len(gbfs_visited)),
  216.         ("A*", len(a_star_visited)*8, a_star_time_ms, len(a_star_visited)),
  217.         ("Weighted A*", len(weighted_a_star_visited)*100, weighted_a_star_time_ms, len(weighted_a_star_visited))
  218.     ]
  219.  
  220.     # print("Size of List 1:", len(list1))
  221.     # print("Size of List 2:", len(list2))
  222.     # print("Size of List 3:", len(list3))
  223.  
  224.  
  225.     print(tabulate(results, headers=["Algorithm", "Memory (Bytes)", "Time (ms)", "Search Space"], tablefmt="grid"))
  226.  
  227.  
  228.  
  229.  
  230.  
  231.  
  232.     ox.plot_graph(ox.project_graph(graph), bgcolor='white', node_size=5, node_color='black', edge_color='#B2BEB5')
  233.     ox.plot_graph(graph.subgraph(list1), node_size=10, node_color='green', edge_linewidth=0.5, edge_color='green')
  234.     ox.plot_graph(graph.subgraph(list2), node_size=10, node_color='blue', edge_linewidth=0.5, edge_color='blue')
  235.     ox.plot_graph(graph.subgraph(list3), node_size=10, node_color='red', edge_linewidth=0.5, edge_color='red')
  236.  
  237.  
  238.  
  239.  
  240.  
  241.    
  242. else:
  243.     print("Error: Failed to retrieve the graph data.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement