rishiilluri

Untitled

Oct 11th, 2022
923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.69 KB | None | 0 0
  1. #!/usr/local/bin/python3
  2. # route.py : Find routes through maps
  3. #
  4. # Code by: name IU ID
  5. #
  6. # Based on skeleton code by V. Mathur and D. Crandall, Fall 2022
  7. #
  8.  
  9.  
  10. # !/usr/bin/env python3
  11. import sys
  12. from queue import PriorityQueue
  13. import math
  14.  
  15. def distance(origin, destination):
  16.     lat1, lon1 = origin
  17.     lat2, lon2 = destination
  18.     radius = 6371
  19.  
  20.     dlat = math.radians(lat2-lat1)
  21.     dlon = math.radians(lon2-lon1)
  22.     a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
  23.         * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
  24.     c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
  25.     d = radius * c
  26.     return d
  27.  
  28. # def avg_lat_lon(city_gps):
  29. #     lat = 0
  30. #     lon = 0
  31. #     for city in city_gps:
  32. #         lat+=city_gps[city][0]
  33. #         lon+=city_gps[city][1]
  34. #     size = len(city_gps)
  35. #     return (lat/size, lon/size)
  36.  
  37. def avg_speed(road_segments):
  38.     speed = 0
  39.     for segment in road_segments:
  40.         speed += float(segment[3])
  41.     return speed/len(road_segments)
  42.  
  43. def max_speed(road_segments):
  44.     speed = 0
  45.     for segment in road_segments:
  46.         speed = max(speed, float(segment[3]))
  47.     return speed
  48.  
  49. def avg_segment_distance(road_segments):
  50.     distance = 0
  51.     for segment in road_segments:
  52.         distance += float(segment[2])
  53.     return distance/len(road_segments)
  54.  
  55.  
  56. def g(distance, delivery, time, path, cost):
  57.     if cost == "distance":
  58.         return distance
  59.     if cost == "segments":
  60.         return len(path)
  61.     if cost == "time":
  62.         return time
  63.     if cost == "delivery":
  64.         return delivery
  65.  
  66. def h(current_city, end_city, city_gps, road_segments, cost):
  67.     if cost == "distance":
  68.         if current_city not in city_gps:
  69.             # current_city_lat_lon = avg_lat_lon(city_gps)
  70.             return 0
  71.         else:
  72.             current_city_lat_lon = city_gps[current_city]
  73.         if end_city not in city_gps:
  74.             # end_city_lat_lon = avg_lat_lon(city_gps)
  75.             return 0
  76.         else:
  77.             end_city_lat_lon = city_gps[end_city]
  78.         return distance(current_city_lat_lon, end_city_lat_lon)
  79.  
  80.     if cost == "time" or cost == "delivery":
  81.         if current_city not in city_gps:
  82.             # current_city_lat_lon = avg_lat_lon(city_gps)
  83.             return 0
  84.         else:
  85.             current_city_lat_lon = city_gps[current_city]
  86.         if end_city not in city_gps:
  87.             # end_city_lat_lon = avg_lat_lon(city_gps)
  88.             return 0
  89.         else:
  90.             end_city_lat_lon = city_gps[end_city]
  91.         return distance(current_city_lat_lon, end_city_lat_lon)/max_speed(road_segments)
  92.     if cost == "segments":
  93.         if current_city not in city_gps:
  94.             # current_city_lat_lon = avg_lat_lon(city_gps)
  95.             return 0
  96.         else:
  97.             current_city_lat_lon = city_gps[current_city]
  98.         if end_city not in city_gps:
  99.             # end_city_lat_lon = avg_lat_lon(city_gps)
  100.             return 0
  101.         else:
  102.             end_city_lat_lon = city_gps[end_city]
  103.         return distance(current_city_lat_lon, end_city_lat_lon)/avg_segment_distance(road_segments)
  104.  
  105.  
  106.  
  107. def get_route(start, end, cost):
  108.    
  109.     """
  110.    Find shortest driving route between start city and end city
  111.    based on a cost function.
  112.  
  113.    1. Your function should return a dictionary having the following keys:
  114.        -"route-taken" : a list of pairs of the form (next-stop, segment-info), where
  115.           next-stop is a string giving the next stop in the route, and segment-info is a free-form
  116.           string containing information about the segment that will be displayed to the user.
  117.           (segment-info is not inspected by the automatic testing program).
  118.        -"total-segments": an integer indicating number of segments in the route-taken
  119.        -"total-miles": a float indicating total number of miles in the route-taken
  120.        -"total-hours": a float indicating total amount of time in the route-taken
  121.        -"total-delivery-hours": a float indicating the expected (average) time
  122.                                   it will take a delivery driver who may need to return to get a new package
  123.    2. Do not add any extra parameters to the get_route() function, or it will break our grading and testing code.
  124.    3. Please do not use any global variables, as it may cause the testing code to fail.
  125.    4. You can assume that all test cases will be solvable.
  126.    5. The current code just returns a dummy solution.
  127.    """
  128.  
  129.     city_gps = {}
  130.     with open("city-gps.txt", "r") as file:
  131.         for line in file:
  132.             # print(line[:-1].split(" "))
  133.             x = line[:-1].split(" ")
  134.             city_gps[x[0]] = (float(x[1]), float(x[2]))
  135.     # print(city_gps)
  136.    
  137.    
  138.     road_segments = []
  139.     with open("road-segments.txt", "r") as file:
  140.         for line in file:
  141.             road_segments.append(line[:-1].split(" "))
  142.    
  143.  
  144.     graph = {}
  145.     for segment in road_segments:
  146.         city1 = segment[0]
  147.         city2 = segment[1]
  148.         distance = float(segment[2])
  149.         speed = float(segment[3])
  150.         name = segment[4]
  151.         if city1 not in graph:
  152.             graph[city1] = []
  153.         if city2 not in graph:
  154.             graph[city2] = []
  155.        
  156.         graph[city1].append((city2, distance, speed, name))
  157.         graph[city2].append((city1, distance, speed, name))
  158.  
  159.  
  160.     fringe = PriorityQueue()
  161.     fringe.put((0, start, 0, 0, 0, 0, []))
  162.     visit = {}
  163.     while not fringe.empty():
  164.         (priority, city, distance, delivery_distance, delivery_time, time, path) = fringe.get()
  165.         visit[city] = 1
  166.         if city == end:
  167.             return {"total-segments" : len(path),
  168.                     "total-miles" : distance,
  169.                     "total-hours" : time,
  170.                     "total-delivery-hours" : delivery_time,
  171.                     "route-taken" : path}
  172.        
  173.         for next_city in graph[city]:
  174.             if visit.get(next_city[0]):
  175.                 continue
  176.             f = g(distance, delivery_time, time, path, cost) + h(next_city[0], end, city_gps, road_segments, cost)
  177.             next_segment = (next_city[0], f"{next_city[3]} for {next_city[1]} miles")
  178.             segment_time = next_city[1]/next_city[2]
  179.             if next_city[2] >= 50:
  180.                 p = math.tanh((next_city[1])/1000)
  181.                 new_delivery_time = delivery_time + p*(2*(time+segment_time)) + segment_time
  182.                 new_delivery_distance = delivery_distance + p*(2*(distance+next_city[1])) + next_city[1]
  183.                
  184.             else:
  185.                 new_delivery_time = delivery_time + segment_time
  186.                 new_delivery_distance = delivery_distance + next_city[1]
  187.            
  188.             fringe.put((f, next_city[0], distance+next_city[1], new_delivery_distance, new_delivery_time, time+segment_time, path+[(next_segment),]))
  189.  
  190.  
  191.  
  192. # Please don't modify anything below this line
  193. #
  194. if __name__ == "__main__":
  195.     if len(sys.argv) != 4:
  196.         raise(Exception("Error: expected 3 arguments"))
  197.  
  198.     (_, start_city, end_city, cost_function) = sys.argv
  199.     if cost_function not in ("segments", "distance", "time", "delivery"):
  200.         raise(Exception("Error: invalid cost function"))
  201.  
  202.     result = get_route(start_city, end_city, cost_function)
  203.  
  204.     # Pretty print the route
  205.     print("Start in %s" % start_city)
  206.     for step in result["route-taken"]:
  207.         print("   Then go to %s via %s" % step)
  208.  
  209.     print("\n          Total segments: %4d" % result["total-segments"])
  210.     print("             Total miles: %8.3f" % result["total-miles"])
  211.     print("             Total hours: %8.3f" % result["total-hours"])
  212.     print("Total hours for delivery: %8.3f" % result["total-delivery-hours"])
  213.  
  214.  
  215.  
Advertisement
Add Comment
Please, Sign In to add comment