-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphOperations.py
More file actions
53 lines (39 loc) · 1.3 KB
/
graphOperations.py
File metadata and controls
53 lines (39 loc) · 1.3 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
from networkx import DiGraph, NetworkXNoPath, multi_source_dijkstra as msDijkstra
def buildGraph(sub, edgeList):
graph = DiGraph()
intro = f"{sub}:Introduction"
for edge in edgeList:
src = edge["src"]
dst = edge["dst"]
travelWeight = edge["travelW"]
returnWeight = edge["returnW"]
graph.add_edge(src, dst, weight=travelWeight)
graph.add_edge(dst, src, weight=returnWeight)
if src != intro:
graph.add_edge(src, intro, weight=0)
if dst != intro:
graph.add_edge(dst, intro, weight=0)
return graph
def findPaths(graph, sources, targets):
paths = []
for target in targets:
try:
tmp = msDijkstra(graph, sources, target=target, weight="weight")
paths.append(tmp)
except NetworkXNoPath:
paths.append((float("inf"), target))
paths = sorted(paths, key=lambda i: i[0])
return paths
def mergePaths(paths):
uniqueNodes = set()
outputPath = []
for path in paths:
if not isinstance(path[1], list):
outputPath.append(path[1])
continue
for node in path[1]:
if node in uniqueNodes:
continue
uniqueNodes.add(node)
outputPath.append(node)
return outputPath