Debian Codegraph @

docs/examples/shortestPath_SimPy.py

raw symbols SCIP
1 from SimPy.Simulation import *
2 """ shortestPath_SimPy.py
3
4 Finds the shortest path in a network.
5 Author: Klaus Muller
6 """
7
8 class node:
9 def __init__(self):
10 self.reached=0
11
12 class searcher(Process):
13 def __init__(self,graph,path,length,from_node,to_node,distance,goal_node):
14 Process.__init__(self)
15 self.path=path[:]
16 self.length=length
17 self.from_node=from_node
18 self.to_node=to_node
19 self.distance=distance
20 self.graph=graph
21 self.goal_node=goal_node
22
23 def run(self,to_node):
24 if DEMO: print "Path so far: %s (length %d). Search from %s to %s" %(self.path,self.length,self.from_node,to_node)
25 yield hold,self,self.distance
26 if not nodes[to_node].reached:
27 self.path.append(to_node)
28 self.length += self.distance
29 nodes[to_node].reached = 1
30 if to_node==self.goal_node:
31 print "SHORTEST PATH",self.path,"Length:",self.length
32 stopSimulation()
33 else:
34 for i in self.graph[to_node]:
35 s=searcher(graph=self.graph,path=self.path,length=self.length,from_node=i[0],
36 to_node=i[1],distance=i[2],goal_node=self.goal_node)
37 activate(s,s.run(i[1]))
38
39 print 'shortestPath_SimPy'
40 initialize()
41 nodes={}
42 DEMO=1
43 for i in ("Atown","Btown","Ccity","Dpueblo","Evillage","Fstadt"):
44 nodes[i]=node()
45 """ Format graph definition: a_graph={node_id:[(from,to,distance),(from,to,distance)],node_id:[ . . . ])
46 """
47 net={"Atown":(("Atown","Btown",3.5),("Atown","Ccity",1),("Atown","Atown",9),("Atown","Evillage",0.5)),
48 "Btown":(("Btown","Ccity",5),),
49 "Ccity":(("Ccity","Ccity",1),("Ccity","Fstadt",9),("Ccity","Dpueblo",3),("Ccity","Atown",3)),
50 "Dpueblo":(("Dpueblo","Ccity",2),("Dpueblo","Fstadt",10)),
51 "Evillage":(("Evillage","Btown",1),),
52 "Fstadt":(("Fstadt","Ccity",3),)}
53 if DEMO: print "Search for shortest path from %s to %s \nin graph %s" %("Atown","Fstadt",net)
54 startup=searcher(graph=net,path=[],length=0,from_node="Atown",to_node="Atown",distance=0,goal_node="Fstadt")
55 activate(startup,startup.run("Atown"))
56 simulate(until=10000)