-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
271 lines (224 loc) · 8.41 KB
/
index.js
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
const graphlib = require('graphlib');
exports.ksp = function (g, source, target, K, weightFunc, edgeFunc) {
// clone graph to avoid changes to the original
let _g = graphlib.json.read(graphlib.json.write(g));
// Initialize containers for candidate paths and k shortest paths
let ksp = [];
let candidates = [];
// Compute and add the shortest path */
let kthPath = getDijkstra(_g, source, target, weightFunc, edgeFunc);
if (!kthPath) {
return ksp;
}
ksp.push(kthPath);
// Iteratively compute each of the k shortest paths */
for (let k = 1; k < K; k++) {
// Get the (k-1)st shortest path
let previousPath = cloneObject(ksp[k - 1]); // clone path to new var
if (!previousPath) {
break;
}
/* Iterate over all of the nodes in the (k-1)st shortest path except for the target node; for each node,
(up to) one new candidate path is generated by temporarily modifying the graph and then running
Dijkstra's algorithm to find the shortest path between the node and the target in the modified
graph */
for (let i = 0; i < previousPath.edges.length; i++) {
// Initialize a container to store the modified (removed) edges for this node/iteration
let removedEdges = [];
// Spur node = currently visited node in the (k-1)st shortest path
let spurNode = previousPath.edges[i].fromNode;
// Root path = prefix portion of the (k-1)st path up to the spur node
let rootPath = clonePathTo(previousPath, i);
// Iterate over all of the (k-1) shortest paths */
ksp.forEach(p => {
p = cloneObject(p); // clone p
let stub = clonePathTo(p, i);
// Check to see if this path has the same prefix/root as the (k-1)st shortest path
if (isPathEqual(rootPath, stub)) {
// If so, eliminate the next edge in the path from the graph (later on, this forces the spur
// node to connect the root path with an un-found suffix path) */
let re = p.edges[i];
_g.removeEdge(re.fromNode, re.toNode);
removedEdges.push(re);
}
})
// Temporarily remove all of the nodes in the root path, other than the spur node, from the graph */
rootPath.edges.forEach(rootPathEdge => {
let rn = rootPathEdge.fromNode;
if (rn !== spurNode) {
// remove node and return removed edges
let removedEdgeFromNode = removeNode(_g, rn, weightFunc);
removedEdges.push(...removedEdgeFromNode);
}
})
// Spur path = shortest path from spur node to target node in the reduced graph
let spurPath = getDijkstra(_g, spurNode, target, weightFunc, edgeFunc);
// If a new spur path was identified...
if (spurPath != null) {
// Concatenate the root and spur paths to form the new candidate path
let totalPath = cloneObject(rootPath);
let edgesToAdd = cloneObject(spurPath.edges);
totalPath.edges.push(...edgesToAdd);
totalPath.totalCost += spurPath.totalCost;
// If candidate path has not been generated previously, add it
if (!isPathExistInArray(candidates, totalPath)) {
candidates.push(totalPath);
}
}
addEdges(_g, removedEdges);
}
// Identify the candidate path with the shortest cost */
let isNewPath;
do {
kthPath = removeBestCandidate(candidates);
isNewPath = true;
if (kthPath != null) {
for (let p of ksp) {
// Check to see if this candidate path duplicates a previously found path
if (isPathEqual(p, kthPath)) {
isNewPath = false;
break;
}
}
}
} while (!isNewPath);
// If there were not any more candidates, stop
if (kthPath == null) {
break;
}
// Add the best, non-duplicate candidate identified as the k shortest path
ksp.push(kthPath);
}
return ksp;
}
// Dijkstra algorithm to find the shortest path
function getDijkstra(g, source, target, weightFunc, edgeFunc) {
if (!weightFunc) {
weightFunc = (e) => g.edge(e);
}
let dijkstra = graphlib.alg.dijkstra(g, source, weightFunc, edgeFunc);
return extractPathFromDijkstra(g, dijkstra, source, target, weightFunc, edgeFunc);
}
function extractPathFromDijkstra(g, dijkstra, source, target, weightFunc, edgeFunc) {
// check if there is a valid path
if (dijkstra[target].distance === Number.POSITIVE_INFINITY) {
return null;
}
let edges = [];
let currentNode = target;
while (currentNode !== source) {
let previousNode = dijkstra[currentNode].predecessor;
// extract weight from edge, using weightFunc if supplied, or the default way
let weightValue;
if (weightFunc) {
weightValue = weightFunc({ v: previousNode, w: currentNode });
} else {
weightValue = g.edge(previousNode, currentNode)
}
let edge = getNewEdge(previousNode, currentNode, weightValue);
edges.push(edge);
currentNode = previousNode;
}
let result = {
totalCost: dijkstra[target].distance,
edges: edges.reverse()
};
return result;
}
function addEdges(g, edges) {
edges.forEach(e => {
g.setEdge(e.fromNode, e.toNode, e.edgeObj);
})
}
// input: a graph and a node to remove
// return value: array of removed edges
function removeNode(g, rn, weightFunc) {
let remEdges = [];
let edges = cloneObject(g.edges());
// save all the edges we are going to remove
edges.forEach(edge => {
if (edge.v == rn || edge.w == rn) {
// extract weight
let weightValue;
if (weightFunc) {
weightValue = weightFunc(edge);
} else {
weightValue = g.edge(edge);
}
let e = getNewEdge(edge.v, edge.w, weightValue);
remEdges.push(e);
}
})
g.removeNode(rn); // removing the node from the graph
return remEdges;
}
// return a new path object from source path to a given index
function clonePathTo(path, i) {
let newPath = cloneObject(path);
let edges = [];
let l = path.edges.length;
if (i > l) {
i = 1;
}
// copy i edges from the source path
for (let j = 0; j < i; j++) {
edges.push(path.edges[j]);
}
// calc the cost of the new path
newPath.totalCost = 0;
edges.forEach(edge => {
newPath.totalCost += edge.weight;
})
newPath.edges = edges;
return newPath;
}
// compare between two path objects, return true if equals
function isPathEqual(path1, path2) {
if (path2 == null) {
return false;
}
let numEdges1 = path1.edges.length;
let numEdges2 = path2.edges.length;
// compare number of edges
if (numEdges1 != numEdges2) {
return false;
}
// compare each edge
for (let i = 0; i < numEdges1; i++) {
let edge1 = path1.edges[i];
let edge2 = path2.edges[i];
if (edge1.fromNode != edge2.fromNode) {
return false;
}
if (edge1.toNode != edge2.toNode) {
return false;
}
}
return true;
}
// build a new edge object
function getNewEdge(fromNode, toNode, weight) {
return {
fromNode: fromNode,
toNode: toNode,
weight: weight
}
}
// since javascript sends object by ref, we sometimes want to clone objects and its childs to avoid it
// this is a workaround for clone objects
function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj));
}
// return true if a given path is found on array of path
function isPathExistInArray(candidates, path) {
candidates.forEach(candi => {
if (isPathEqual(candi, path)) {
return true;
}
})
return false;
}
// sort the candidates array by total cose, then remove and return the best candidate.
function removeBestCandidate(candidates) {
return candidates.sort((a, b) => a.totalCost - b.totalCost).shift();
}