| 1 |
from SimPy.Simulation import * |
| 2 |
""" shortestPath_SimPy_OO.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, |
| 14 |
to_node,distance,goal_node,sim): |
| 15 |
Process.__init__(self,sim=sim) |
| 16 |
self.path=path[:] |
| 17 |
self.length=length |
| 18 |
self.from_node=from_node |
| 19 |
self.to_node=to_node |
| 20 |
self.distance=distance |
| 21 |
self.graph=graph |
| 22 |
self.goal_node=goal_node |
| 23 |
|
| 24 |
def run(self,to_node): |
| 25 |
if DEMO: print "Path so far: %s (length %d). Search from %s to %s"\ |
| 26 |
%(self.path,self.length,self.from_node,to_node) |
| 27 |
yield hold,self,self.distance |
| 28 |
if not self.sim.nodes[to_node].reached: |
| 29 |
self.path.append(to_node) |
| 30 |
self.length += self.distance |
| 31 |
self.sim.nodes[to_node].reached = 1 |
| 32 |
if to_node==self.goal_node: |
| 33 |
print "SHORTEST PATH",self.path,"Length:",self.length |
| 34 |
self.sim.stopSimulation() |
| 35 |
else: |
| 36 |
for i in self.graph[to_node]: |
| 37 |
s=searcher(graph=self.graph,path=self.path,length=self.length,from_node=i[0], |
| 38 |
to_node=i[1],distance=i[2],goal_node=self.goal_node,sim=self.sim) |
| 39 |
self.sim.activate(s,s.run(i[1])) |
| 40 |
|
| 41 |
|
| 42 |
class ShortestPathModel(Simulation): |
| 43 |
def search(self): |
| 44 |
print 'shortestPath_SimPy' |
| 45 |
self.initialize() |
| 46 |
self.nodes={} |
| 47 |
for i in ("Atown","Btown","Ccity","Dpueblo","Evillage","Fstadt"): |
| 48 |
self.nodes[i]=node() |
| 49 |
""" Format graph definition: a_graph={node_id:[(from,to,distance),(from,to,distance)],node_id:[ . . . ]) |
| 50 |
""" |
| 51 |
net={"Atown":(("Atown","Btown",3.5),("Atown","Ccity",1),("Atown","Atown",9),("Atown","Evillage",0.5)), |
| 52 |
"Btown":(("Btown","Ccity",5),), |
| 53 |
"Ccity":(("Ccity","Ccity",1),("Ccity","Fstadt",9),("Ccity","Dpueblo",3),("Ccity","Atown",3)), |
| 54 |
"Dpueblo":(("Dpueblo","Ccity",2),("Dpueblo","Fstadt",10)), |
| 55 |
"Evillage":(("Evillage","Btown",1),), |
| 56 |
"Fstadt":(("Fstadt","Ccity",3),)} |
| 57 |
if DEMO: print "Search for shortest path from %s to %s \nin graph %s" %("Atown","Fstadt",net) |
| 58 |
startup=searcher(graph=net,path=[],length=0,from_node="Atown", |
| 59 |
to_node="Atown",distance=0,goal_node="Fstadt",sim=self) |
| 60 |
self.activate(startup,startup.run("Atown")) |
| 61 |
self.simulate(until=10000) |
| 62 |
|
| 63 |
|
| 64 |
DEMO = 1 |
| 65 |
ShortestPathModel().search() |