Exemplo n.º 1
0
 def sim_init( self ) :
     """ simulation setup """
     # construct the simulation blocks
     sim = Simulation()
     self.sim = sim
     
     if False :
         script = sample_demands( self.horizon, self.rategraph, self.roadnet )
         source = ScriptSource( script )
         print 'obtained %d demands' % len( source.script )
         debug_input()
     else :
         source = RoadnetDemandSource( self.roadnet, self.rategraph )
         
     self.source = source
     source.join_sim( sim )
     
     
     # policy setup
     #import setiptah.roadgeometry.probability as roadprob
     #roadmap = roadprob.sampleroadnet()
     #U = roadprob.UniformDist( roadmap )
     #samplepoint = U.sample
     # instantiate the gate
     gate = GatedTaxiDispatch()
     gate.setScheduler( RoadmapFHKScheduler( self.roadnet ) )
     self.gate = gate
     
     # source -> gate
     
     # fleet setup
     vehicles = {}
     self.vehicles = vehicles
     
     # fleet parameters
     from setiptah.roadgeometry.roadmap_paths import RoadmapPlanner
     planner = RoadmapPlanner( self.roadnet ) 
     roads = [ road for _,__,road in self.roadnet.edges(data=True) ]
     road = random.choice( roads )
     ORIGIN = ROAD.RoadAddress(road,0.)      # just... somewhere
     
     for i in range( self.numveh ) :
         taxi = Taxi()
         
         taxi.setPlanner( planner )
         randpoint = roadprob.sampleaddress( self.roadnet, 'length' )
         taxi.setLocation( randpoint )
         taxi.setSpeed( 1. )
         
         taxi.join_sim( sim )
         
         gateIF = gate.newInterface()
         gate.add( gateIF )
         
         vehicles[taxi] = gateIF
         gateIF.output.connect( taxi.appendDemands )
         
         taxi.signalWakeup.connect( gateIF.input )
         taxi.signalIdle.connect( gateIF.input )
         
     gate.join_sim( sim )
     
     
     # record number of unassigned demands
     self.tape = []
     def record_unassigned() :
         # first, count the demands waiting in the gate
         unassg = len( self.gate._demandQ )  #+ len( self.dispatch.demands )
         # then, count the demands in vehicle queues (minus possibly 1 being worked on)
         for veh in self.vehicles :
             temp = len( veh._demandQ )
             temp = max( temp, 1 ) - 1
             unassg += temp
         # recorder the number
         self.tape.append( unassg )
         
     recorder = UniformClock( 1. )
     recorder.join_sim( sim )
     recorder.output.connect( record_unassigned )
     self.recorder = recorder
     
     # report demand arrivals to several places
     self.DEMANDS = []
     def record_arrival( dem ) :
         self.DEMANDS.append( dem )
     
     def give_to_dispatch( dem ) :
         #p, q = dem
         taxidem = Taxi.Demand( *dem )
         self.gate.queueDemand( taxidem )
         
     source_out = source.source()
     #source_out.connect( counting.increment )
     source_out.connect( record_arrival )
     source_out.connect( give_to_dispatch )
     #source.source().connect( give_to_dispatch )
     
     self.timer = data()
     self.timer.last_time = sim.time
     def say( dem ) :
         p, q = dem
         new_time = self.sim.time
         elapsed = new_time - self.timer.last_time
         print 'tick, %f: %s, %s' % ( elapsed, repr(p), repr(q) )
         self.timer.last_time = new_time
         
     source_out.connect( say )
     
     def gimme( *args, **kwargs ) :
         print "need a batch!!"
         
     # creates an interface from gate to interactive dispatcher
     #gate_if = gate.spawn_interface()
     #self.gate_if = gate_if
     #dispatch.request_batch.connect( gate.requestRelease )
     #dispatch.request_batch.connect( gimme )
     #gate.output.connect( dispatch.batch_arrived )
     #gate_if.batch_out.connect( dispatch.batch_arrived )
     
     def hello( *args, **kwargs ) :
         print 'vehicle is ready!'
Exemplo n.º 2
0
 def run(self, experiment ) :
     """ setup """
     sim = Simulation()
     self.sim = sim
     
     clock = PoissonClock( experiment.arrivalrate )
     clock.join_sim( sim )
     
     # prepare domain planning
     distr = distribs.distributions[ experiment.distrib_key ]
     
     # prepare domain Stacker Crane scheduling --- could be made dynamic
     # cuz i'm dumb...
     getTail = lambda dem : dem.origin
     getHead = lambda dem : dem.destination
     
     
     
     # instantiate planner
     if isinstance( distr, EuclideanDistribution ) :
         planner = EuclideanPlanner
         
     elif isinstance( distr, RoadmapDistribution ) :
         planner = RoadmapPlanner( distr.roadmap )
         
     else :
         raise NotImplementedError('unrecognized distribution')
     
     # instantiate scheduler
     if False or isinstance( distr, EuclideanDistribution ) :
         scheduler = kCraneScheduler( getTail, getHead, distr.distance )
         
     elif isinstance( distr, RoadmapDistribution ) :
         from setiptah.taxitheory.roadmap.simulation import RoadMap_kCraneScheduler
         scheduler = RoadMap_kCraneScheduler( getTail, getHead, distr.roadmap )
         
     else :
         raise NotImplementedError('unrecognized distribution')
             
     
     
     # instantiate the gate
     gate = GatedTaxiDispatch()
     gate.setScheduler( scheduler )
     
     # instantiate the fleet
     ORIGIN = distr.origin()
     
     TAXI = []
     for i in range( experiment.numveh ) :
         taxi = Taxi()
         TAXI.append( taxi )
         
         taxi.setPlanner( planner )
         taxi.setLocation( ORIGIN )
         taxi.setSpeed( experiment.vehspeed )
         
         taxi.join_sim( sim )
         
         gateIF = gate.newInterface()
         gate.add( gateIF )
         gateIF.output.connect( taxi.appendDemands )
         taxi.signalWakeup.connect( gateIF.input )
         taxi.signalIdle.connect( gateIF.input )
         
     gate.join_sim( sim )
     
     def tick() :
         print 'tick, %g' % sim.get_time()
         
         
     self.DEMANDS = []
     def myarrival() :
         demand = distr.sample()
         x = distr.getTail( demand )
         y = distr.getHead( demand )
         
         time = sim.get_time()
         demand = Taxi.Demand( x, y, time )
         print 'demand generated ', x, y, time
         
         self.DEMANDS.append( demand )
         # send the demand to the gate, not any one taxi
         gate.queueDemand( demand )
         
     clock.source().connect( myarrival )
     #clock.source().connect( EVER.increment )
     
     # should do post-hoc analysis... ignore this stuff
     # EDIT: do just for plotting
     self.ever_tape = []
     self.alive_tape = []
     
     def record() :
         self.ever_tape.append( len( self.DEMANDS ) )
         
         total = len( gate._demandQ )
         for taxi in TAXI :
             total += len( taxi._demandQ )
             
         self.alive_tape.append( total )
         
     probe = UniformClock(.1)        # why not
     probe.join_sim( sim )
     probe.source().connect( record )
     
     
     """ SIMULATE """
     if False :
         plt.close('all')
         self.fig = plt.figure()
         plt.show()
         
     self.batch_indices = []
     self.simUpdate()
     
     FIRSTBATCH = 50.
     MINBATCH = 20.
     CYCLESPERBATCH = 10.
     CEILINGRATIO = 1.01
     #
     ALPHA = .01
     QUOTA = 20
     # just *assume* we will not simulate above stability!!!
     # XTHRESH = 200       # this needs to be added!!!
     
     # phase I --- simulate base time
     # first, try to get approximately EN0 demands
     T0 = FIRSTBATCH / experiment.arrivalrate
     
     while sim.get_time() < T0 :
         callback = sim.get_next_action()
         callback()
     self.simUpdate()
     
     # phase II
     T = [ T0 ]
     
     quota = QUOTA
     batchmean = globalmean = np.mean( self.alive_tape )
     while quota > 0 :
         # try to get a "replacement", but never go for less that MINBATCH
         #target = max( batchmean, MINBATCH )
         target = max( CYCLESPERBATCH * globalmean, MINBATCH )
         Tk = target / experiment.arrivalrate
         
         epoch = sim.get_time()
         while sim.get_time() - epoch < Tk :
             callback = sim.get_next_action()
             callback()
             
         T.append( Tk )
         self.simUpdate()
         
         if False :
             # branch based on batchmean
             bstart = self.batch_indices[-2]
             batchmean = np.mean( self.alive_tape[bstart:] )
             if batchmean <= CEILINGRATIO * globalmean :
                 quota -= 1
             else :
                 pass
                 #quota = QUOTA
                 
         else :
             # branch based on globalmean, but quota in a row
             globalmean_next = np.mean( self.alive_tape )
             #if globalmean_next <= CEILINGRATIO * globalmean :
             if np.abs( globalmean_next - globalmean ) <= ALPHA * globalmean :
                 quota -= 1
             else :
                 quota = QUOTA
                 
             globalmean = globalmean_next
             
         
     # phase III
     # Tf = gamma * sum( T )
     Tf = 0.     # currently, no phase three
     epoch = sim.get_time()
     while sim.get_time() - epoch < Tf :
         callback = sim.get_next_action()
         callback()
         
     self.finalT = Tf
     self.simUpdate()
     
     
     print 'SIMULATION DONE'
Exemplo n.º 3
0
 def run(self) :
     """ setup """
     sim = Simulation()
     self.sim = sim
     
     clock = PoissonClock( self.rate )
     clock.join_sim( sim )
     
     # prepare geometry queries
     if True :
         ORIGIN = np.zeros(2)
         
         def samplepoint() :
             return np.random.rand(2)
             
         planner = EuclideanPlanner
         #scheduler = RoundRobinScheduler()
         
         # Euclidean instantiation
         getTail = lambda dem : dem.origin
         getHead = lambda dem : dem.destination
         distance = lambda x, y : np.linalg.norm( y - x )
         scheduler = kCraneScheduler( getTail, getHead, distance )
         
     else :
         import setiptah.roadgeometry.roadmap_basic as ROAD
         import setiptah.roadgeometry.probability as roadprob
         from setiptah.roadgeometry.roadmap_paths import RoadmapPlanner
         
         roadmap = roadprob.sampleroadnet()
         U = roadprob.UniformDist( roadmap )
         samplepoint = U.sample
         
         ORIGIN = samplepoint()
         
         distance = lambda x, y : ROAD.distance( roadmap, 
                                                 x, y, length='length' )
         planner = RoadmapPlanner( roadmap )
         
         if True :
             scheduler = RoundRobinScheduler()
         else :
             getTail = lambda dem : dem.origin
             getHead = lambda dem : dem.destination
             scheduler = kCraneScheduler( getTail, getHead, distance )
     
     # instantiate the gate
     gate = GatedTaxiDispatch()
     gate.setScheduler( scheduler )
     
     # instantiate the fleet
     TAXI = []
     for i in range( self.numveh ) :
         taxi = Taxi()
         TAXI.append( taxi )
         
         taxi.setPlanner( planner )
         taxi.setLocation( ORIGIN )
         taxi.setSpeed( self.vehspeed )
         
         taxi.join_sim( sim )
         
         gateIF = gate.newInterface()
         gate.add( gateIF )
         gateIF.output.connect( taxi.appendDemands )
         taxi.signalWakeup.connect( gateIF.input )
         taxi.signalIdle.connect( gateIF.input )
         
     gate.join_sim( sim )
     
     def tick() :
         print 'tick, %g' % sim.get_time()
         
         
     SIMULATION.DEMANDS = []
     def myarrival() :
         x = samplepoint()
         y = samplepoint()
         
         #print x, y
         time = sim.get_time()
         demand = Taxi.Demand( x, y, time )
         print 'demand generated ', x, y, time
         
         SIMULATION.DEMANDS.append( demand )
         # send the demand to the gate, not any one taxi
         gate.queueDemand( demand )
         
     EVER = dumbcounter()
     
     clock.source().connect( myarrival )
     clock.source().connect( EVER.increment )
         
     RESULTS.ever_tape = []
     RESULTS.alive_tape = []
     
     def record() :
         RESULTS.ever_tape.append( EVER.value() )
         
         total = len( gate._demandQ )
         for taxi in TAXI :
             total += len( taxi._demandQ )
             
         RESULTS.alive_tape.append( total )
         
     probe = UniformClock(.1)        # why not
     probe.join_sim( sim )
     probe.source().connect( record )
     
     
     """ run """
     if False :
         while sim.get_time() <= self.horizon :
             callback = sim.get_next_action()
             callback()
             
             frac = sim.get_time() / self.horizon
             perc = int( 100. * frac )
             #print perc
             
             self.timeElapsed.emit( perc )       # emit the custom signal?
             
         self.alarm()
             
     else :
         T0 = 100.
         alpha = 2.
         beta = 1.1
         gamma = 1.
         XTHRESH = 250
         
         # phase I --- simulate base time
         while sim.get_time() <= T0 :
             callback = sim.get_next_action()
             callback()
             
         self.alarm()
         
         
         # phase II
         T = [ T0 ]
         xmax = max( RESULTS.alive_tape )
         Tk = T0
         while True :
             Tk = alpha*Tk
             
             epoch = sim.get_time()
             while sim.get_time() - epoch <= Tk :
                 callback = sim.get_next_action()
                 callback()
                 
             T.append( Tk )
             self.alarm()
             
             newmax = max( RESULTS.alive_tape )
             if newmax > XTHRESH :
                 print 'TOO MUCH! BAILING!'
                 return
             if newmax <= beta * xmax : break
             
             xmax = newmax
             
             
         # phase III
         Tf = gamma * sum( T )
         epoch = sim.get_time()
         while sim.get_time() - epoch <= Tf :
             callback = sim.get_next_action()
             callback()
             
         RESULTS.finalT = Tf
         self.alarm()
         
         print 'SIMULATION DONE'
Exemplo n.º 4
0
 def run(self) :
     """ setup """
     sim = Simulation()
     
     clock = PoissonClock( self.rate )
     clock.join_sim( sim )
     
     # prepare geometry queries
     if True :
         ORIGIN = np.zeros(2)
         
         def samplepoint() :
             return np.random.rand(2)
             
         planner = EuclideanPlanner
         #scheduler = RoundRobinScheduler()
         
         # Euclidean instantiation
         getTail = lambda dem : dem.origin
         getHead = lambda dem : dem.destination
         distance = lambda x, y : np.linalg.norm( y - x )
         scheduler = kCraneScheduler( getTail, getHead, distance )
         
     else :
         import setiptah.roadgeometry.roadmap_basic as ROAD
         import setiptah.roadgeometry.probability as roadprob
         from setiptah.roadgeometry.roadmap_paths import RoadmapPlanner
         
         roadmap = roadprob.sampleroadnet()
         U = roadprob.UniformDist( roadmap )
         samplepoint = U.sample
         
         ORIGIN = samplepoint()
         
         distance = lambda x, y : ROAD.distance( roadmap, 
                                                 x, y, length='length' )
         planner = RoadmapPlanner( roadmap )
         
         if True :
             scheduler = RoundRobinScheduler()
         else :
             getTail = lambda dem : dem.origin
             getHead = lambda dem : dem.destination
             scheduler = kCraneScheduler( getTail, getHead, distance )
     
     # instantiate the gate
     gate = GatedTaxiDispatch()
     gate.setScheduler( scheduler )
     
     # instantiate the fleet
     TAXI = []
     for i in range( self.numveh ) :
         taxi = Taxi()
         TAXI.append( taxi )
         
         taxi.setPlanner( planner )
         taxi.setLocation( ORIGIN )
         taxi.setSpeed( self.vehspeed )
         
         taxi.join_sim( sim )
         
         gateIF = gate.newInterface()
         gate.add( gateIF )
         gateIF.output.connect( taxi.appendDemands )
         taxi.signalWakeup.connect( gateIF.input )
         taxi.signalIdle.connect( gateIF.input )
         
     gate.join_sim( sim )
     
     def tick() :
         print 'tick, %g' % sim.get_time()
         
     def myarrival() :
         x = samplepoint()
         y = samplepoint()
         
         #print x, y
         time = sim.get_time()
         demand = Taxi.Demand( x, y, time )
         print 'demand generated ', x, y, time
         
         # send the demand to the gate, not any one taxi
         gate.queueDemand( demand )
         
     EVER = dumbcounter()
     
     clock.source().connect( myarrival )
     clock.source().connect( EVER.increment )
         
     RESULTS.ever_tape = []
     RESULTS.alive_tape = []
     
     def record() :
         RESULTS.ever_tape.append( EVER.value() )
         
         total = len( gate._demandQ )
         for taxi in TAXI :
             total += len( taxi._demandQ )
             
         RESULTS.alive_tape.append( total )
         
     probe = UniformClock(.1)        # why not
     probe.join_sim( sim )
     probe.source().connect( record )
     
     
     """ run """
     #T = 50.
     while sim.get_time() <= self.horizon :
         callback = sim.get_next_action()
         callback()
         
         frac = sim.get_time() / self.horizon
         perc = int( 100. * frac )
         #print perc
         
         self.timeElapsed.emit( perc )       # emit the custom signal?
         
     self.simulateDone.emit()