Advertisement
Guest User

tsp_train_solver.py

a guest
Sep 1st, 2024
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.87 KB | None | 0 0
  1. import csv
  2. import random
  3. from typing import List, Tuple
  4. import numpy as np
  5.  
  6. class Station:
  7. def __init__(self, name: str, departures: List[float], arrivals: List[float]):
  8. self.name = name
  9. self.departures = departures
  10. self.arrivals = arrivals
  11.  
  12. def read_csv(filename: str) -> List[Station]:
  13. stations = []
  14. with open(filename, 'r') as file:
  15. reader = csv.reader(file)
  16. next(reader) # Skip header
  17. for row in reader:
  18. name = row[0]
  19. departures = [float(x) for x in row[1::2]]
  20. arrivals = [float(x) for x in row[2::2]]
  21. stations.append(Station(name, departures, arrivals))
  22. return stations
  23.  
  24. def calculate_transfer_time(from_station: Station, to_station: Station) -> float:
  25. # Simplified transfer time calculation
  26. # In a real scenario, this would be more complex, considering schedules and probabilities
  27. return min(abs(d - a) for d in from_station.departures for a in to_station.arrivals)
  28.  
  29. def nearest_neighbor(stations: List[Station]) -> List[int]:
  30. n = len(stations)
  31. unvisited = set(range(1, n))
  32. tour = [0]
  33.  
  34. while unvisited:
  35. last = tour[-1]
  36. next_station = min(unvisited, key=lambda x: calculate_transfer_time(stations[last], stations[x]))
  37. tour.append(next_station)
  38. unvisited.remove(next_station)
  39.  
  40. return tour
  41.  
  42. def two_opt(tour: List[int], stations: List[Station]) -> List[int]:
  43. improvement = True
  44. best_tour = tour
  45. while improvement:
  46. improvement = False
  47. for i in range(1, len(tour) - 2):
  48. for j in range(i + 1, len(tour)):
  49. new_tour = tour[:i] + tour[i:j][::-1] + tour[j:]
  50. if calculate_total_time(new_tour, stations) < calculate_total_time(best_tour, stations):
  51. best_tour = new_tour
  52. improvement = True
  53. tour = best_tour
  54. return tour
  55.  
  56. def calculate_total_time(tour: List[int], stations: List[Station]) -> float:
  57. total_time = 0
  58. for i in range(len(tour) - 1):
  59. total_time += calculate_transfer_time(stations[tour[i]], stations[tour[i + 1]])
  60. return total_time
  61.  
  62. def solve_tsp(stations: List[Station]) -> List[int]:
  63. # Start with Nearest Neighbor heuristic
  64. initial_tour = nearest_neighbor(stations)
  65.  
  66. # Improve the tour using 2-opt (a simplified version of Lin-Kernighan)
  67. improved_tour = two_opt(initial_tour, stations)
  68.  
  69. return improved_tour
  70.  
  71. def main(filename: str):
  72. stations = read_csv(filename)
  73. optimal_tour = solve_tsp(stations)
  74.  
  75. print("Optimal Itinerary:")
  76. for i in optimal_tour:
  77. print(f"Station: {stations[i].name}")
  78.  
  79. total_time = calculate_total_time(optimal_tour, stations)
  80. print(f"\nExpected total time: {total_time:.2f} hours")
  81.  
  82. if __name__ == "__main__":
  83. main("foo.csv")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement