-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabeling_v2.py
94 lines (83 loc) · 2.93 KB
/
labeling_v2.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/5/6 14:21
# @Author : Xavier Ma
# @Email : [email protected]
# @File : labeling_v2.py
# @Statement : The hybrid link-node-based labeling method for the shortest path problem with turn restrictions (SPPTR)
# @Reference : Li Qingquan, et al. A hybrid link-node approach for finding shortest paths in road networks with turn restrictions[J]. Transactions in GIS, 2015.
from numpy import inf
from pqdict import PQDict
def find_neighbors(network):
# find the neighbors of each node
neighbor = []
for i in network.keys():
neighbor.append(list(network[i].keys()))
return neighbor
def main(network, source, destination, tr):
"""
The main function
:param network: {node1: {node2: length, node3: length, ...}, ...}
:param source: the source node
:param destination: the destination node
:param tr: turn restrictions
:return:
"""
# Step 1. Initialize parameters
neighbor = find_neighbors(network)
omega = [] # the list of explored labels
queue = PQDict({}) # priority queue
p_list = {} # path label
label_in = 0 # the number of labels added to the priority queue
label_out = 0 # the number of labels popped from the priority queue
rn = set() # restricted nodes
for turn in tr:
if turn[1] != source and turn[1] != destination:
rn.add(turn[1])
# Step 2. Add the first labels
for node in neighbor[source]:
ind = str([source, node]) if node in rn else node
queue[ind] = network[source][node]
p_list[ind] = [source, node]
label_in += 1
# Step 3. The main loop
while queue:
# Step 3.1. Select the label with the minimum length
(label, length) = queue.popitem()
label_out += 1
path = p_list[label]
omega.append(label)
i = path[-2]
j = path[-1]
if j == destination:
return {
'path': path,
'length': length,
'label in': label_in,
'label out': label_out,
}
# Step 3.2. Extend labels
for k in neighbor[j]:
ind = str([j, k]) if k in rn else k
if [i, j, k] not in tr and ind not in omega:
temp_length = length + network[j][k]
if temp_length < queue.get(ind, inf):
temp_path = path.copy()
temp_path.append(k)
queue[ind] = temp_length
p_list[ind] = temp_path
label_in += 1
return {}
if __name__ == '__main__':
test_network = {
0: {2: 1},
1: {2: 1},
2: {0: 1, 1: 1, 3: 2, 5: 1},
3: {4: 1},
4: {5: 2},
5: {2: 1},
}
s = 0
d = 5
tr = [[0, 2, 5]]
print(main(test_network, s, d, tr))