-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetro_simulator.py
More file actions
392 lines (306 loc) · 12.6 KB
/
Copy pathmetro_simulator.py
File metadata and controls
392 lines (306 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import math
freq_peak = 4
freq_offpeak = 8
fares = [
(2, 11),
(5, 21),
(12, 32),
(21, 43),
(32, 54),
(float('inf'), 64)
]
METRO_LINES = {}
TRAVEL_TIMES = {}
INTERCHANGES = {}
# Time functions
def to_minutes(time_str):
h, m = map(int, time_str.split(":"))
return h * 60 + m
def minutes_to_str(mins):
h = mins // 60
m = mins % 60
return f"{h:02d}:{m:02d}"
op_start_min = to_minutes("06:00")
op_end_min = to_minutes("23:00")
peak1_start = to_minutes("08:00")
peak1_end = to_minutes("11:00")
peak2_start = to_minutes("17:00")
peak2_end = to_minutes("20:00")
def is_working_time(minute):
return op_start_min <= minute <= op_end_min
def get_frequency(minute):
if (peak1_start < minute < peak1_end) or (peak2_start < minute < peak2_end):
return freq_peak
return freq_offpeak
# Load data from file
def load_data(file):
global METRO_LINES, TRAVEL_TIMES, INTERCHANGES
try:
with open(file, 'r') as f:
for row in f:
row = row.strip()
if not row or row.startswith('#'):
continue
parts = [p.strip() for p in row.split(',')]
# skip header
if parts[0].lower() == 'line':
continue
if len(parts) != 5:
continue
line_name, station, next_station, time_str, _flag = parts
# Create line entry
if line_name not in METRO_LINES:
METRO_LINES[line_name] = []
# Add station
if station not in METRO_LINES[line_name]:
METRO_LINES[line_name].append(station)
# Add next station
if next_station and next_station not in METRO_LINES[line_name]:
METRO_LINES[line_name].append(next_station)
# Add travel times both ways
try:
t = int(time_str)
TRAVEL_TIMES[(station, next_station)] = t
TRAVEL_TIMES[(next_station, station)] = t
except:
pass
except FileNotFoundError:
print("File not found.")
return False
station_lines = {}
for line, stations in METRO_LINES.items():
for s in stations:
station_lines.setdefault(s, set()).add(line)
# A station is an interchange if it appears in 2+ lines
INTERCHANGES = {s: lines for s, lines in station_lines.items() if len(lines) >= 2}
globals()['INTERCHANGES'] = INTERCHANGES
return True
load_data("metro_data.txt")
# getting start and end time offset
def get_offset(line, terminal, station):
stations = METRO_LINES[line]
if not stations:
return None
#getting offset from first station
if terminal == stations[0]:
offset = 0
i_station = 0
while i_station < len(stations):
if stations[i_station] == station:
return offset
if i_station + 1 < len(stations):
offset += TRAVEL_TIMES.get((stations[i_station], stations[i_station + 1]), 0)
i_station += 1
return offset
#getting offset if its the last station
elif terminal == stations[-1]:
offset = 0
i_station = len(stations) - 1
while i_station >= 0:
if stations[i_station] == station:
return offset
if i_station - 1 >= 0:
offset += TRAVEL_TIMES.get((stations[i_station], stations[i_station - 1]), 0)
i_station -= 1
return offset
else:
return None
#getting arrival time of next metro from both directions
def get_next_metro(line, check_time, station):
for s in METRO_LINES[line]:
if station == s:
offset_start = get_offset(line, METRO_LINES[line][0], station)
offset_end = get_offset(line, METRO_LINES[line][-1], station)
first_arival_start = op_start_min + offset_start
first_arival_end = op_start_min + offset_end
last_arival_start = op_end_min + offset_start
last_arival_end = op_end_min + offset_end
check_time = to_minutes(check_time)
next_time_start, next_time_end = None, None
if check_time <= first_arival_start:
next_time_start = first_arival_start
elif check_time <= last_arival_start:
k = math.ceil((check_time - first_arival_start) / get_frequency(check_time))
next_time = first_arival_start + k * get_frequency(check_time)
next_time_start = next_time
elif check_time > last_arival_start:
next_time_start = "No service."
if check_time <= first_arival_end:
next_time_end = first_arival_end
elif check_time <= last_arival_end:
k = math.ceil((check_time - first_arival_end) / get_frequency(check_time))
next_time = first_arival_end + k * get_frequency(check_time)
next_time_end = next_time
elif check_time > last_arival_end:
next_time_end = "No service."
return (line, next_time_start, next_time_end)
return None
# print(get_next_metro("Yellow", "10:13", "Rajiv Chowk"))
# print(get_next_metro("Blue", "10:13", "Rajiv Chowk"))
# print(get_next_metro("Blue", "23:50", "Dwarka Sector 21"))
#get route on same line
def get_route_same_line(stations, source, destination):
source_index = stations.index(source)
destination_index = stations.index(destination)
if source_index < destination_index:
return stations[source_index:destination_index + 1]
else:
return stations[destination_index:source_index + 1][::-1]
# print(get_route_same_line(METRO_LINES["Blue"], "Rajiv Chowk", "Noida Sector 62"))
def get_route(source, destination, transfers=0, visited=set()):
all_routes = []
if transfers > 2:
return None
visited.add(source)
for line in METRO_LINES:
stations = METRO_LINES[line]
if source in stations and destination in stations:
path = get_route_same_line(stations, source, destination)
t=0
for i in range(len(path)-1):
t+= TRAVEL_TIMES.get((path[i], path[i+1]), 0)
all_routes.append([(line, path, t)])
for line in METRO_LINES:
stations = METRO_LINES[line]
if source not in stations:
continue
for interchange in INTERCHANGES.keys():
if interchange not in stations:
continue
if interchange in visited:
continue
base_path = get_route_same_line(stations, source, interchange)
interchange_path = get_route(interchange, destination, transfers+1, visited.copy())
t=0
for i in range(len(base_path)-1):
t+= TRAVEL_TIMES.get((base_path[i], base_path[i+1]), 0)
if interchange_path != None:
route = [(line, base_path, t)] + interchange_path
all_routes.append(route)
if all_routes:
fastest_time = sum([t for line, stations, t in all_routes[0]])
fastest_route = all_routes[0]
for route in all_routes:
if sum([t for line, stations, t in route]) < fastest_time:
fastest_time = sum([t for line, stations, t in route])
fastest_route = route
return fastest_route
else:
return None
# print(get_route("Kashmere Gate", "Botanical Garden"))
#finding direction to manage which side time to take
def get_direction(line, source, destination, time):
stations = METRO_LINES[line]
source_id = stations.index(source)
destination_id = stations.index(destination)
metro_times = get_next_metro(line, time, source)
if not metro_times:
return None
if source_id < destination_id:
direction = METRO_LINES[line][-1]
else:
direction = METRO_LINES[line][0]
return direction
def next_metro(line, station, current_time):
result = get_next_metro(line, current_time, station)
if result:
line, next_time_start, next_time_end = result
ts1 = next_time_start
ts2 = ts1+get_frequency(ts1)
ts3 = ts2+get_frequency(ts2)
print(f"Next metro towards {METRO_LINES[line][-1]} at {minutes_to_str(ts1)}")
print(f"Subsequent metro towards {METRO_LINES[line][-1]} at {minutes_to_str(ts2)}, {minutes_to_str(ts3)}...")
te1 = next_time_end
te2 = te1+get_frequency(te1)
te3 = te2+get_frequency(te2)
print(f"Next metro towards {METRO_LINES[line][0]} at {minutes_to_str(te1)}")
print(f"Subsequent metro towards {METRO_LINES[line][0]} at {minutes_to_str(te2)}, {minutes_to_str(te3)}...")
# next_metro("Yellow", "Rajiv Chowk", "10:13")
# print(get_route("Kashmere Gate", "Botanical Garden"))
def journey(source, destination, tot):
interchange_delay = 3
print("Journey Plan:")
route = get_route(source, destination)
print(f"Start at {source} ({route[0][0]} line)")
if not route:
print("No route found.")
return
line, arival_time_start, arival_time_end = get_next_metro(route[0][0], tot, source)
towards = get_direction(route[0][0], source, route[0][1][-1], tot)
if towards == METRO_LINES[route[0][0]][-1]:
print(f"Next metro at {minutes_to_str(arival_time_start)} towards {towards}")
waiting_time = arival_time_start - to_minutes(tot)
else:
print(f"Next metro at {minutes_to_str(arival_time_end)} towards {towards}")
waiting_time = arival_time_end - to_minutes(tot)
t = to_minutes(tot) + route[0][2]+waiting_time
print(f"Arrive at {route[0][1][-1]} at {minutes_to_str(t)} minutes.")
i = 1
while i < len(route):
line, stations, travel_time = route[i]
print(f"Transfer to {line} line.")
t += interchange_delay
arival_time_start, arival_time_end = get_next_metro(line, minutes_to_str(t), stations[0])[1:]
towards = get_direction(line, stations[0], stations[-1], minutes_to_str(t))
if towards == METRO_LINES[line][-1]:
print(f"Next metro at {minutes_to_str(arival_time_start)} towards {towards}")
waiting_time = arival_time_start - t
else:
print(f"Next metro at {minutes_to_str(arival_time_end)} towards {towards}")
waiting_time = arival_time_end - t
t += travel_time + waiting_time
print(f"Arrive at {stations[-1]} at {minutes_to_str(t)} minutes.")
i += 1
travel_time_total = t - to_minutes(tot)
print(f"Total travel time: {minutes_to_str(travel_time_total)} minutes.")
station_order = set()
for i in range(len(route)):
line, stations, travel_time = route[i]
station_order.update(stations)
num_stations = len(station_order)-1
fare = 0
for n_station, f in fares:
if num_stations <= n_station:
fare = f
break
print(f"Total stations traveled: {num_stations}")
print(f"Total fare: ₹{fare}")
# journey("Dwarka", "Botanical Garden", "10:12")
def check_station_exists(station_name):
for stations in METRO_LINES.values():
if station_name in stations:
return True
return False
def main():
while True:
print("1. Get next metro timings")
print("2. Plan a journey")
choice = input("Enter your choice (1/2): ")
#checking valid names here only so that we don't get None ValueError in the defined functions
if choice == '1':
line = input("Enter metro line: ")
if line not in METRO_LINES:
print("Invalid line name, please try again.")
continue
station = input("Enter station name: ")
if not check_station_exists(station):
print("invalid station, please try again.")
continue
current_time = input("Enter current time (HH:MM): ")
next_metro(line, station, current_time)
break
elif choice == '2':
source = input("Enter source station: ")
if not check_station_exists(source):
print("invalid station, please try again.")
continue
destination = input("Enter destination station: ")
if not check_station_exists(destination):
print("Invalid station, please try again.")
continue
start_time = input("Enter start time (HH:MM): ")
journey(source, destination, start_time)
break
else:
print("Invalid choice. Please try again.")
main()