forked from CokeStudios/mtr-pathfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmtr_pathfinder.py
More file actions
1771 lines (1487 loc) · 61.7 KB
/
mtr_pathfinder.py
File metadata and controls
1771 lines (1487 loc) · 61.7 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Find paths between two stations for Minecraft Transit Railway.
'''
from difflib import SequenceMatcher
from enum import Enum
from io import BytesIO
from itertools import chain
from math import gcd, sqrt
from operator import itemgetter
from statistics import median_low
from threading import Thread, BoundedSemaphore
from time import gmtime, strftime, time
from typing import Optional, Dict, Literal, Tuple, List, Union
from queue import Queue
import base64
import hashlib
import json
import os
import pickle
import re
from fontTools.ttLib import TTFont
from opencc import OpenCC
from PIL import Image, ImageDraw, ImageFont
import networkx as nx
import requests
__version__ = '130'
SERVER_TICK: int = 20
DEFAULT_AVERAGE_SPEED: dict = {
'train_normal': 14,
'train_light_rail': 11,
'train_high_speed': 40,
'boat_normal': 10,
'boat_light_rail': 10,
'boat_high_speed': 13,
'cable_car_normal': 8,
'airplane_normal': 70
} # 列车平均速度,单位 block/s
RUNNING_SPEED: int = 5.612 # 站内换乘速度,单位 block/s
TRANSFER_SPEED: int = 4.317 # 出站换乘速度,单位 block/s
WILD_WALKING_SPEED: int = 2.25 # 非出站换乘(越野)速度,单位 block/s
ROUTE_INTERVAL_DATA = Queue()
semaphore = BoundedSemaphore(25)
original = {}
tmp_names = {}
opencc1 = OpenCC('s2t')
opencc2 = OpenCC('t2jp')
opencc3 = OpenCC('t2s')
opencc4 = OpenCC('jp2t')
def get_close_matches(words, possibilities, cutoff=0.2):
result = [(-1, None)]
s = SequenceMatcher()
for word in words:
s.set_seq2(word)
for x, y in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() >= cutoff and \
s.quick_ratio() >= cutoff:
ratio = s.ratio()
if ratio >= cutoff:
result.append((ratio, y))
return max(result)[1]
# From https://github.com/TrueMyst/PillowFontFallback/blob/main/fontfallback/writing.py
def load_fonts(*font_paths: str) -> Dict[str, TTFont]:
"""
Loads font files specified by paths into memory and returns a dictionary of font objects.
"""
fonts = {}
for path in font_paths:
font = TTFont(path)
fonts[path] = font
return fonts
# From https://github.com/TrueMyst/PillowFontFallback/blob/main/fontfallback/writing.py
def has_glyph(font: TTFont, glyph: str) -> bool:
"""
Checks if the given font contains a glyph for the specified character.
"""
for table in font["cmap"].tables:
if table.cmap.get(ord(glyph)):
return True
return False
# From https://github.com/TrueMyst/PillowFontFallback/blob/main/fontfallback/writing.py
def merge_chunks(text: str, fonts: Dict[str, TTFont]) -> List[List[str]]:
"""
Merges consecutive characters with the same font into clusters, optimizing font lookup.
"""
chunks = []
for char in text:
for font_path, font in fonts.items():
if has_glyph(font, char):
chunks.append([char, font_path])
break
cluster = chunks[:1]
for char, font_path in chunks[1:]:
if cluster[-1][1] == font_path:
cluster[-1][0] += char
else:
cluster.append([char, font_path])
return cluster
# From https://github.com/TrueMyst/PillowFontFallback/blob/main/fontfallback/writing.py
def draw_text_v2(
draw: ImageDraw.ImageDraw,
xy: Tuple[int, int],
text: str,
color: Tuple[int, int, int],
fonts: Dict[str, TTFont],
size: int,
anchor: Optional[str] = None,
align: Literal["left", "center", "right"] = "left",
direction: Literal["rtl", "ltr", "ttb"] = "ltr",
) -> None:
"""
Draws text on an image at given coordinates, using specified size, color, and fonts.
"""
y_offset = 0
sentence = merge_chunks(text, fonts)
for words in sentence:
xy_ = (xy[0] + y_offset, xy[1] - 6)
font = ImageFont.truetype(words[1], size)
draw.text(
xy=xy_,
text=words[0],
fill=color,
font=font,
anchor=anchor,
align=align,
direction=direction,
embedded_color=True,
)
draw.text
box = font.getbbox(words[0])
y_offset += box[2] - box[0]
# From https://github.com/TrueMyst/PillowFontFallback/blob/main/fontfallback/writing.py
def draw_text(
draw: ImageDraw.ImageDraw,
xy: Tuple[int, int],
text: str,
color: Tuple[int, int, int],
fonts: Dict[str, TTFont],
size: int,
anchor: Optional[str] = None,
align: Literal["left", "center", "right"] = "left",
direction: Literal["rtl", "ltr", "ttb"] = "ltr",
) -> None:
"""
Draws multiple lines of text on an image, handling newline characters and adjusting spacing between lines.
"""
spacing = xy[1]
lines = text.split("\n")
for line in lines:
mod_cord = (xy[0], spacing)
draw_text_v2(
draw,
xy=mod_cord,
text=line,
color=color,
fonts=fonts,
size=size,
anchor=anchor,
align=align,
direction=direction,
)
spacing += size + 5
class RouteType(Enum):
'''
An Enum class to define the types of the route.
'''
IN_THEORY = 0
WAITING = 1
class ImagePattern(Enum):
'''
An Enum class to define the patterns of the image.
Number -> x offset
THUMB -> need to -20
'''
OR = 0
FAKE_STATION = 1
TEXT = 40.2
STATION = 40 # 圆圈 + 黑体字 -> 车站
THUMB_TEXT = 60 # 路线种类图标 + 灰字 -> 路线名
THUMB_INTEND_TEXT = 80
GREY_TEXT = 40.1
GREY_INTEND_TEXT = 60.1
def round_ten(n: float) -> int:
'''
Round the number in ten.
'''
ans = round(n / 10) * 10
return ans if ans > 0 else 10
def atoi(text: str) -> Union[str, int]:
'''
Convert a string to a digit.
'''
return int(text) if text.isdigit() else text
def natural_keys(text: str) -> list:
'''
A sorting key in number order.
'''
return [atoi(c) for c in re.split(r'(\d+)', text)]
def lcm(a: int, b: int) -> int:
'''
Calculate LCM of two integers.
'''
return a * b // gcd(a, b)
def fetch_interval_data(station_id: str, LINK) -> None:
'''
Fetch the interval data of a station.
'''
global ROUTE_INTERVAL_DATA
with semaphore:
link = LINK + f'/arrivals?worldIndex=0&stationId={station_id}'
try:
data = requests.get(link).json()
except Exception:
pass
else:
ROUTE_INTERVAL_DATA.put([station_id, [time(), data]])
def gen_route_interval(LOCAL_FILE_PATH, INTERVAL_PATH, LINK, MTR_VER) -> None:
'''
Generate all the interval data.
'''
with open(LOCAL_FILE_PATH, encoding='utf-8') as f:
data = json.load(f)
if MTR_VER == 3:
threads: list[Thread] = []
for station_id in data[0]['stations']:
t = Thread(target=fetch_interval_data, args=(station_id, LINK))
t.start()
threads.append(t)
for t in threads:
t.join()
interval_data_list = []
while not ROUTE_INTERVAL_DATA.empty():
interval_data_list.append(ROUTE_INTERVAL_DATA.get())
arrivals = dict(interval_data_list)
dep_dict_per_route: dict[str, list] = {}
dep_dict_per_route_: dict[str, list] = {}
for t, arrivals in arrivals.values():
dep_dict_per_station: dict[str, list] = {}
for arrival in arrivals[:-1]:
name = arrival['name']
if name in dep_dict_per_station:
dep_dict_per_station[name] += [arrival['arrival']]
else:
dep_dict_per_station[name] = [arrival['arrival']]
for x, item in dep_dict_per_station.items():
dep_s_list = []
if len(item) == 1:
if x not in dep_dict_per_route_:
dep_dict_per_route_[x] = [(item[0] / 1000 - t) * 1.25]
else:
for y in range(len(item) - 1):
dep_s_list.append((item[y + 1] - item[y]) / 1000)
if x in dep_dict_per_route:
dep_dict_per_route[x] += [sum(dep_s_list) /
len(dep_s_list)]
else:
dep_dict_per_route[x] = [sum(dep_s_list) /
len(dep_s_list)]
for x in dep_dict_per_route_:
if x not in dep_dict_per_route:
dep_dict_per_route[x] = dep_dict_per_route_[x]
freq_dict: dict[str, list] = {}
for route, arrivals in dep_dict_per_route.items():
if len(arrivals) == 1:
freq_dict[route] = round_ten(arrivals[0])
else:
freq_dict[route] = round_ten(sum(arrivals) / len(arrivals))
elif MTR_VER == 4:
link = LINK.rstrip('/') + '/mtr/api/map/departures?dimension=0'
departures = requests.get(link).json()['data']['departures']
dep_dict: dict[str, list[int]] = {}
for x in departures:
dep_list = set()
for y in x['departures']:
for z in y['departures']:
dep = round(z / 1000)
while dep < 0:
dep += 86400
dep_list.add(dep)
dep_list = list(sorted(dep_list))
dep_dict[x['id']] = dep_list
freq_dict: dict[str, list] = {}
for route_id, stats in dep_dict.items():
if len(stats) == 0:
continue
for route_stats in data[0]['routes']:
if route_stats['id'] == route_id:
break
else:
print(f'Route {route_id} not found')
continue
route_name = route_stats['name']
freq_list = []
for i1 in range(len(stats)):
i2 = i1 + 1
if i2 == len(stats):
i2 = 0
dep_2 = stats[i2] + 86400
else:
dep_2 = stats[i2]
dep_1 = stats[i1]
freq = dep_2 - dep_1
freq_list.append(freq)
median_freq = median_low(freq_list)
freq_dict[route_name] = round_ten(median_freq)
else:
return
y = input(f'是否替换{INTERVAL_PATH}文件? (Y/N) ').lower()
if y == 'y':
with open(INTERVAL_PATH, 'w', encoding='utf-8') as f:
json.dump(freq_dict, f)
def fetch_data(link: str, LOCAL_FILE_PATH, MTR_VER) -> str:
'''
Fetch all the route data and station data.
'''
if MTR_VER == 3:
link = link.rstrip('/') + '/data'
data = requests.get(link).json()
else:
link = link.rstrip('/') + \
'/mtr/api/map/stations-and-routes?dimension=0'
data = requests.get(link).json()['data']
data_new = {'routes': [], 'stations': {}}
i = 0
for d in data['stations']:
d['station'] = hex(i)[2:]
data_new['stations'][d['id']] = d
i += 1
x_dict = {x['id']: [] for x in data['stations']}
z_dict = {x['id']: [] for x in data['stations']}
for route in data['routes']:
# if route['hidden'] is True:
# continue
if route['circularState'] == 'CLOCKWISE':
route['circular'] = 'cw'
elif route['circularState'] == 'ANTICLOCKWISE':
route['circular'] = 'ccw'
else:
route['circular'] = ''
route['durations'] = [round(x / 1000) for x in route['durations']]
for station in route['stations']:
x_dict[station['id']] += [station['x']]
z_dict[station['id']] += [station['z']]
# route['stations'] = [f'{x}_{route["color"]}'
# for x in route['stations']]
data_new['routes'].append(route)
for station in data['stations']:
x_list = x_dict[station['id']]
z_list = z_dict[station['id']]
if len(x_list) == 0:
continue
data_new['stations'][station['id']]['x'] = \
sum(x_list) / len(x_list)
data_new['stations'][station['id']]['z'] = \
sum(z_list) / len(z_list)
data = [data_new]
y = input(f'是否替换{LOCAL_FILE_PATH}文件? (Y/N) ').lower()
if y == 'y':
with open(LOCAL_FILE_PATH, 'w', encoding='utf-8') as f:
json.dump(data, f)
return data
def get_distance(a_dict: dict, b_dict: dict, square: bool = False) -> float:
'''
Get the distance of two stations.
'''
dist_square = (a_dict['x'] - b_dict['x']) ** 2 + \
(a_dict['z'] - b_dict['z']) ** 2
if square is True:
return dist_square
return sqrt(dist_square)
def station_name_to_id(data: list, sta: str, STATION_TABLE,
fuzzy_compare=True) -> str:
'''
Convert a station's name to its ID.
'''
sta = sta.lower()
if sta in STATION_TABLE:
sta = STATION_TABLE[sta]
if sta in tmp_names:
return tmp_names[sta]
tra1 = opencc1.convert(sta)
sta_try = [sta, tra1, opencc2.convert(tra1)]
all_names = []
stations = data[0]['stations']
output = None
has_station = False
for station_id, station_dict in stations.items():
s_1 = station_dict['name']
if 'x' in station_dict and 'z' in station_dict:
all_names.append((s_1, station_id))
s_split = station_dict['name'].split('|')
s_2_2 = s_split[-1]
s_2 = s_2_2.split('/')[-1]
s_3 = s_split[0]
for st in sta_try:
if st in (s_1.lower(), s_2.lower(), s_2_2.lower(), s_3.lower()):
has_station = True
output = station_id
break
if has_station is False and fuzzy_compare is True:
output = get_close_matches(sta_try, all_names)
if output is not None:
tmp_names[sta] = output
return output
def get_route_station_index(route: dict, station_1_id: str, station_2_id: str,
MTR_VER=3) -> tuple:
'''
Get the index of the two stations in one route.
'''
if MTR_VER == 3:
st = [x.split('_')[0] for x in route['stations']]
else:
st = [x['id'] for x in route['stations']]
check_station_2 = False
for i, station in enumerate(st):
if station == station_1_id:
index1 = i
check_station_2 = True
if check_station_2 and station == station_2_id:
index2 = i
break
else:
index1 = index2 = None
return index1, index2
def get_approximated_time(route: dict, station_1_id: str, station_2_id: str,
data: list, tick: bool = False, MTR_VER=3) -> float:
'''
Get the approximated time of the two stations in one route.
'''
if MTR_VER == 4:
return get_app_time_v4(route, station_1_id, station_2_id)
index1, index2 = get_route_station_index(route,
station_1_id, station_2_id)
if index2 is None:
return None
station_1_position = {}
station_2_position = {}
t = 0
stations = route['stations'][index1:index2 + 1]
for i, station_1 in enumerate(stations):
try:
station_2 = stations[i + 1]
except IndexError:
break
station_1_check = False
station_2_check = False
for k, position_dict in data[0]['positions'].items():
if k == station_1:
station_1_position['x'] = position_dict['x']
station_1_position['z'] = position_dict['y']
station_1_check = True
elif k == station_2:
station_2_position['x'] = position_dict['x']
station_2_position['z'] = position_dict['y']
station_2_check = True
if station_1_check and station_2_check:
t += get_distance(station_1_position, station_2_position) \
/ DEFAULT_AVERAGE_SPEED[route['type']]
break
if tick is True:
t *= 20
return t
def get_app_time_v4(route: dict,
station_1_id: str, station_2_id: str) -> float:
'''
Get the approximated time of the two stations in one route.
'''
index1, index2 = get_route_station_index(route,
station_1_id, station_2_id, 4)
if index2 is None:
return None
t = 0
stations = route['stations'][index1:index2 + 1]
for i, station_1 in enumerate(stations):
try:
station_2 = stations[i + 1]
except IndexError:
break
t += get_distance(station_1, station_2) / \
DEFAULT_AVERAGE_SPEED[route['type']]
return t
def check_route_name(route_data, IGNORED_LINES: list[str],
ONLY_LINES: list[str] = None):
if ONLY_LINES is None:
ONLY_LINES = []
if ONLY_LINES:
IGNORED_LINES = []
lines_to_check = [x.lower().strip()
for x in IGNORED_LINES + ONLY_LINES if x != '']
n: str = route_data['name']
number: str = route_data['number']
route_names = [n, n.split('|')[0], n.split('||')[0]]
if ('||' in n and n.count('|') > 2) or \
('||' not in n and n.count('|') > 0):
eng_name = n.split('|')[1].split('|')[0]
if eng_name != '':
route_names.append(eng_name)
if number not in ['', ' ']:
for tmp_name in route_names[1:]:
route_names.append(tmp_name + ' ' + number)
cont = False
for x in route_names:
x = x.lower().strip()
if x in lines_to_check:
cont = True
break
if x.isascii():
continue
simp1 = opencc3.convert(x)
if simp1 in lines_to_check:
cont = True
break
simp2 = opencc3.convert(opencc4.convert(x))
if simp2 in lines_to_check:
cont = True
break
if ONLY_LINES:
cont = not cont
return cont
def create_graph(data: list, IGNORED_LINES: list[str], ONLY_LINES: list[str],
CALCULATE_HIGH_SPEED: bool, CALCULATE_BOAT: bool,
CALCULATE_WALKING_WILD: bool, ONLY_LRT: bool,
AVOID_STATIONS: list, route_type: RouteType,
original_ignored_lines: list[str],
INTERVAL_PATH: str,
version1: str, version2: str,
LOCAL_FILE_PATH, STATION_TABLE,
WILD_ADDITION, TRANSFER_ADDITION,
MAX_WILD_BLOCKS, MTR_VER, cache) -> nx.MultiDiGraph:
'''
Create the graph of all routes.
'''
global original, intervals
with open(INTERVAL_PATH, 'r', encoding='utf-8') as f:
intervals = json.load(f)
if not os.path.exists('mtr_pathfinder_temp'):
os.makedirs('mtr_pathfinder_temp')
filename = ''
m = hashlib.md5()
if cache is True and IGNORED_LINES == original_ignored_lines and \
CALCULATE_BOAT is True and ONLY_LRT is False and \
ONLY_LINES == [] and AVOID_STATIONS == [] and \
route_type == RouteType.WAITING:
for s in original_ignored_lines:
m.update(s.encode('utf-8'))
filename = f'mtr_pathfinder_temp{os.sep}' + \
f'3{int(CALCULATE_HIGH_SPEED)}{int(CALCULATE_WALKING_WILD)}' + \
f'-{version1}-{version2}-{m.hexdigest()}-{__version__}.dat'
if os.path.exists(filename):
with open(filename, 'rb') as f:
tup = pickle.load(f)
G = tup[0]
original = tup[1]
return G
routes = data[0]['routes']
new_durations = {}
for it0, route in enumerate(routes):
name_lower = route['name'].lower()
if 'placeholder' in name_lower or 'dummy' in name_lower:
continue
old_durations = route['durations']
if 0 in old_durations or old_durations == []:
stations = route['stations']
new_dur = []
for it1 in range(len(route['stations']) - 1):
if old_durations != [] and old_durations[it1] != 0:
new_dur.append(old_durations[it1])
continue
it2 = it1 + 1
if MTR_VER == 3:
station_1 = stations[it1].split('_')[0]
station_2 = stations[it2].split('_')[0]
else:
station_1 = stations[it1]['id']
station_2 = stations[it2]['id']
app_time = get_approximated_time(route, station_1, station_2,
data, True, MTR_VER)
if app_time == 0:
app_time = 0.01
new_dur.append(app_time)
if sum(new_dur) == 0:
continue
new_durations[str(it0)] = new_dur
if len(new_durations) > 0:
for route_id, new_duration in new_durations.items():
route_id = int(route_id)
old_route_data = data[0]['routes'][route_id]
old_route_data['durations'] = new_duration
data[0]['routes'][route_id] = old_route_data
with open(LOCAL_FILE_PATH, 'w', encoding='utf-8') as f:
json.dump(data, f)
avoid_ids = [station_name_to_id(data, x, STATION_TABLE)
for x in AVOID_STATIONS]
all_stations = data[0]['stations']
G = nx.MultiDiGraph()
edges_dict = {}
edges_attr_dict = {}
original = {}
waiting_walking_dict = {}
# 添加出站换乘
for station, station_dict in all_stations.items():
if 'x' not in station_dict or 'z' not in station_dict:
continue
if station in avoid_ids:
continue
for transfer in station_dict['connections']:
if transfer not in all_stations:
continue
if transfer in avoid_ids:
continue
transfer_dict = all_stations[transfer]
if 'x' not in transfer_dict or 'z' not in transfer_dict:
continue
dist = get_distance(station_dict, transfer_dict)
duration = dist / TRANSFER_SPEED
if (station, transfer) in edges_attr_dict:
edges_attr_dict[(station, transfer)].append(
(f'出站换乘步行 Walk {round(dist, 2)}m', duration, 0))
else:
edges_attr_dict[(station, transfer)] = [
(f'出站换乘步行 Walk {round(dist, 2)}m', duration, 0)]
waiting_walking_dict[(station, transfer)] = \
(duration, f'出站换乘步行 Walk {round(dist, 2)}m')
additions1 = set()
if station_dict['name'] in TRANSFER_ADDITION:
for x in TRANSFER_ADDITION[station_dict['name']]:
additions1.add(x)
for x in additions1:
for station2, station2_dict in all_stations.items():
if station2 in avoid_ids:
continue
if station2_dict['name'] == x:
if station2 not in station_dict['connections']:
try:
dist = get_distance(station_dict, station2_dict)
duration = dist / TRANSFER_SPEED
if (station, station2) not in edges_attr_dict:
edges_attr_dict[(station, station2)] = []
edges_attr_dict[(station, station2)].append(
(f'出站换乘步行 Walk {round(dist, 2)}m',
duration, 0))
waiting_walking_dict[(station, station2)] = \
(duration, f'出站换乘步行 Walk {round(dist, 2)}m')
except KeyError:
pass
break
additions2 = set()
if station_dict['name'] in WILD_ADDITION and \
CALCULATE_WALKING_WILD is True:
for x in WILD_ADDITION[station_dict['name']]:
additions2.add(x)
for x in additions2:
for station2, station2_dict in all_stations.items():
if station2 in avoid_ids:
continue
if station2_dict['name'] == x:
if station2 not in station_dict['connections']:
try:
dist = get_distance(station_dict, station2_dict)
duration = dist / WILD_WALKING_SPEED
if (station, station2) not in edges_attr_dict:
edges_attr_dict[(station, station2)] = []
edges_attr_dict[(station, station2)].append(
(f'步行 Walk {round(dist, 2)}m', duration, 0))
waiting_walking_dict[(station, station2)] = \
(duration, f'步行 Walk {round(dist, 2)}m')
except KeyError:
pass
break
# 添加普通路线
for route in data[0]['routes']:
n: str = route['name']
if check_route_name(route, IGNORED_LINES, ONLY_LINES) is True:
continue
if (not CALCULATE_HIGH_SPEED) and route['type'] == 'train_high_speed':
continue
if (not CALCULATE_BOAT) and 'boat' in route['type']:
continue
if ONLY_LRT and route['type'] != 'train_light_rail':
continue
if route_type == RouteType.WAITING:
if route['type'] == 'cable_car_normal':
intervals[n] = 2
if n not in intervals:
continue
stations = route['stations']
durations = route['durations']
if len(stations) < 2:
continue
if len(stations) - 1 < len(durations):
durations = durations[:len(stations) - 1]
if len(stations) - 1 > len(durations):
continue
# if route_type == RouteType.WAITING:
for i in range(len(durations)):
for i2 in range(len(durations[i:])):
i2 += i + 1
if MTR_VER == 3:
platform = None
station_1 = stations[i].split('_')[0]
station_2 = stations[i2].split('_')[0]
dur_list = durations[i:i2]
station_list = stations[i:i2 + 1]
c = False
for sta in station_list:
if sta.split('_')[0] in avoid_ids:
c = True
if c is True:
continue
if 0 in dur_list:
t = get_approximated_time(route, station_1, station_2,
data, MTR_VER)
if t is None:
continue
dur = t
else:
dur = sum(durations[i:i2]) / SERVER_TICK
else:
station_1 = stations[i]
station_2 = stations[i2]
dur_list = durations[i:i2]
station_list = stations[i:i2 + 1]
dwell = sum([x['dwellTime'] / 1000
for x in station_list][1:-1])
# if route_type == RouteType.IN_THEORY:
# dwell += (station_1['dwellTime'] +
# station_2['dwellTime']) / 2 / 1000
c = False
for sta in station_list:
if sta['id'] in avoid_ids:
c = True
if c is True:
continue
if 0 in dur_list:
t = get_app_time_v4(route, station_1, station_2,
data, MTR_VER)
if t is None:
continue
dur = round(t + dwell)
else:
dur = round(sum(durations[i:i2]) + dwell)
platform = station_1['name']
station_1 = station_1['id']
station_2 = station_2['id']
if route_type == RouteType.WAITING:
wait = float(intervals[n])
if (station_1, station_2) not in edges_dict:
edges_dict[(station_1, station_2)] = []
edges_dict[(station_1, station_2)].append(
(dur, wait, route['name'], platform))
original_tuple = (route['name'], station_1, station_2)
if original_tuple in original:
dur1 = original[original_tuple]
if dur < dur1:
original[original_tuple] = dur
else:
original[original_tuple] = dur
else:
if (station_1, station_2) not in edges_attr_dict:
edges_attr_dict[(station_1, station_2)] = []
edges_attr_dict[(station_1, station_2)].append(
((route['name'], platform), dur, 0))
# else:
# for i, duration in enumerate(durations):
# station_1 = stations[i].split('_')[0]
# station_2 = stations[i + 1].split('_')[0]
# station_list = stations[i:i + 2]
# c = False
# for sta in station_list:
# if sta.split('_')[0] in avoid_ids:
# c = True
# if c is True:
# continue
# add_edge = False
# if duration == 0:
# t = get_approximated_time(route, station_1, station_2,
# data, MTR_VER)
# if t is not None:
# add_edge = True
# else:
# add_edge = True
# t = duration / SERVER_TICK
# if add_edge is True:
# if (station_1, station_2) in edges_attr_dict:
# edges_attr_dict[(station_1, station_2)].append(
# (route['name'], t, 0))
# else:
# edges_attr_dict[(station_1, station_2)] = [
# (route['name'], t, 0)]
if route_type == RouteType.WAITING:
for tup, dur_tup in edges_dict.items():
dur = [x[0] for x in dur_tup]
wait = [x[1] for x in dur_tup]
routes = [x[2] for x in dur_tup]
platforms = [x[3] for x in dur_tup]
final_wait = []
final_routes = []
min_dur = min(dur)
for i, x in enumerate(dur):
if abs(x - min_dur) <= 60:
final_wait.append(wait[i])
final_routes.append((routes[i], platforms[i]))
s1 = tup[0]
s2 = tup[1]
lcm_sum = 1
sum_interval = 0
for x in final_wait:
if x != 0:
lcm_sum = lcm(lcm_sum, round(x))
for x in final_wait:
if x != 0:
sum_interval += (lcm_sum / round(x))
if sum_interval == 0:
sum_int = 0
else:
sum_int = lcm_sum / sum_interval / 2
if (s1, s2) in waiting_walking_dict:
t = waiting_walking_dict[(s1, s2)][0]
if abs(t - min_dur) <= 60:
route_name = waiting_walking_dict[(s1, s2)][1]
dur = waiting_walking_dict[(s1, s2)][0]
final_routes.append((route_name, None))
original[(route_name, s1, s2)] = dur
edges_attr_dict[(s1, s2)] = [(final_routes, min_dur, sum_int)]
for edge in edges_attr_dict.items():
u, v = edge[0]
min_time = min(e[1] + e[2] for e in edge[1])
for r in edge[1]:
if isinstance(r[0], str):
route_name = r[0]
platform = None