コード例 #1
0
 def CYCLECOST( cycle, demands, roadnet, length_attr='length' ) :
     addr = lambda p : ROAD.RoadAddress( *p )
     
     carry = [ ROAD.distance( roadnet, addr(dem.pick), addr(dem.delv), length_attr ) for dem in demands ]
     
     edges = zip( cycle, cycle[1:] + cycle[:1] )
     #print edges
     
     edges = [ ( demands[i], demands[j] ) for i,j in edges ] 
     empty = [ ROAD.distance( roadnet, addr(dem1.delv), addr(dem2.pick), length_attr ) for dem1,dem2 in edges ]
     return sum( carry ) + sum( empty )
コード例 #2
0
def _options_roads_neq( roadnet, road1, road2, length_attr ) :
    edge1, data1 = ROAD.obtain_edge( roadnet, road1, data_flag=True )
    u1,v1,_ = edge1 ; roadlen1 = data1.get( length_attr, np.inf )
    edge2, data2 = ROAD.obtain_edge( roadnet, road2, data_flag=True )
    u2,v2,_ = edge2 ; roadlen2 = data2.get( length_attr, np.inf )
    
    x = GLOBAL.x ; y = GLOBAL.y    
    cost_dict = {
                 '<-s' : x,
                 's->' : roadlen1 - x,
                 '->t' : y,
                 't<-' : roadlen2 - y
                 }
    
    options = []
    # paths through endpoints
    WAYP1 = [ ( 's->', v1 ) ]
    if not data1.get( 'oneway', False ) : WAYP1.append( ( '<-s', u1 ) )
    WAYP2 = [ ( '->t', u2 ) ]
    if not data2.get( 'oneway', False ) : WAYP2.append( ( 't<-', v2 ) )
    
    for s,u in WAYP1 :
        p = ROAD.roadify( roadnet, u, length_attr )
        for t,v in WAYP2 :
            q = ROAD.roadify( roadnet, v, length_attr )
            
            dst = ROAD.distance( roadnet, p, q, length_attr )
            cost = cost_dict[s] + dst + cost_dict[t]
            options.append( cost )
            
    return options
コード例 #3
0
def MATCHCOSTS(match, P, Q, roadnet):
    costs = []
    for i, j in match:
        p = ROAD.RoadAddress(*P[i])
        q = ROAD.RoadAddress(*Q[j])
        d = ROAD.distance(roadnet, p, q, 'length')
        costs.append(d)
    return costs
コード例 #4
0
def MATCHCOSTS( match, P, Q, roadnet ) :
    costs = []
    for i, j in match :
        p = ROAD.RoadAddress( *P[i] )
        q = ROAD.RoadAddress( *Q[j] )
        d = ROAD.distance( roadnet, p, q, 'length' )
        costs.append( d )
    return costs
コード例 #5
0
def _options_roads_eq_yleqx( roadnet, road, length_attr ) :
    edge, data = ROAD.obtain_edge( roadnet, road, data_flag=True )
    u,v,_ = edge ; roadlen = data.get( length_attr, np.inf )
    p = ROAD.roadify( roadnet, u, length_attr )
    q = ROAD.roadify( roadnet, v, length_attr )
    
    x = GLOBAL.x ; y = GLOBAL.y
    sojourn_cost = roadlen - x + ROAD.distance( roadnet, q, p, length_attr ) + y    # a path using the rest of the network 
    options = [ sojourn_cost ]
    if not data.get( 'oneway', False ) :
        options.append( x - y )
    return options
コード例 #6
0
def balance_cost( pairs, roadmap ) :
    distfunc = lambda p, q : ROAD.distance( roadmap, p, q, 'length' )
    
    graph = nx.Graph()
    N = len( pairs )
    for i in xrange(N) :
        for j in xrange(N) :
            _, t = pairs[i]
            s, _ = pairs[j]
            dist = distfunc(t,s)
            graph.add_edge( (i,0), (j,1), weight = -dist )  # about to do MAX_weight_matching
            
    """ obvious TODO: use the N log N matching algorithm here, instead! """
    mate = nx.matching.max_weight_matching( graph, maxcardinality=True )
    
    def cost(i) :
        first = (i,0)
        second = mate[first]
        return -graph.get_edge_data( first, second ).get('weight') 
    balances = [ cost(i) for i in xrange(N) ]
    total_balance = sum( balances )
    return total_balance
コード例 #7
0
 def distance(self, p, q ) :
     return ROAD.distance( self.roadnet, p, q, 'length' )
コード例 #8
0
    if True and NUMPOINT <= 50:
        PR = [ROAD.RoadAddress(road, y) for road, y in PP]
        QR = [ROAD.RoadAddress(road, y) for road, y in QQ]

        class pointnode():
            def __init__(self, point, idx):
                self.point = point
                self.idx = idx

        RED = [pointnode(p, i) for i, p in enumerate(PR)]
        BLU = [pointnode(q, j) for j, q in enumerate(QR)]
        graph = nx.Graph()
        match_mat = np.zeros((NUMPOINT, NUMPOINT))
        for (i, r), (j, b) in itertools.product(enumerate(RED),
                                                enumerate(BLU)):
            w = ROAD.distance(roadnet, r.point, b.point, 'length')
            graph.add_edge(r, b, weight=-w)
            match_mat[i, j] = w
        match_dict = nx.max_weight_matching(graph, True)

        match_brute = [(r.idx, match_dict[r].idx)
                       for r in RED]  # match pruning
        #        matchstats = [ ( r.point, b.point, ROAD.distance( roadnet, r.point, b.point, 'length' ) )
        #                      for r,b in match ]
        costs_brute = MATCHCOSTS(match_brute, PP, QQ, roadnet)
        cost_brute = ROADMATCHCOST(match_brute, PP, QQ, roadnet)
        print match_brute
        print costs_brute
        print cost_brute
        #print 'optimal match has cost: %f' % matchcost
コード例 #9
0
 
 import setiptah.roadgeometry.probability as roadprob
 
 if True :
     roadmap = roadprob.sampleroadnet()
     p = roadprob.sampleaddress( roadmap )
     q = roadprob.sampleaddress( roadmap )
 
 # give me a summary of the road network
 for u,v,road, data in roadmap.edges_iter( keys=True, data=True ) :
     print '%s: %s -> %s ; length=%f' % ( road, repr(u), repr(v), data.get('length',1) )
     
 print '...going from %s to %s' % ( repr(p), repr(q) )
 frwd = minpath( p, q, roadmap )
 frwdL = pathLength( frwd )
 frwdLRef = distance( roadmap, p, q, 'length' )
 print frwd
 print 'FRWD LENGTH: %f; survey says: %f' % ( frwdL, frwdLRef )
 
 
 bkwd = minpath( q, p, roadmap )
 bkwdL = pathLength( bkwd )
 bkwdLRef = distance( roadmap, q, p, 'length' )
 
 print 'BKWD LENGTH: %f; survey says: %f' % ( bkwdL, bkwdLRef )
 
 if np.abs( frwdL - frwdLRef ) > 10**-10 or np.abs( bkwdL - bkwdLRef ) > 10**-10 :
     print 'ALERT!!! NOT AGREE WITH REF'
 else :
     print 'cool as a cucumber'
     
コード例 #10
0
    # compare to optimal matching
    if True and NUMPOINT <= 50 :
        PR = [ ROAD.RoadAddress( road, y ) for road, y in PP ]
        QR = [ ROAD.RoadAddress( road, y ) for road, y in QQ ]
        
        class pointnode() :
            def __init__(self, point, idx ) :
                self.point = point
                self.idx = idx
                
        RED = [ pointnode(p,i) for i,p in enumerate(PR) ]
        BLU = [ pointnode(q,j) for j,q in enumerate(QR) ]
        graph = nx.Graph()
        match_mat = np.zeros((NUMPOINT,NUMPOINT))
        for (i,r), (j,b) in itertools.product( enumerate(RED), enumerate(BLU) ) :
            w = ROAD.distance( roadnet, r.point, b.point, 'length' )
            graph.add_edge( r, b, weight=-w )
            match_mat[i,j] = w
        match_dict = nx.max_weight_matching( graph, True )
        
        match_brute = [ (r.idx,match_dict[r].idx) for r in RED ]      # match pruning
#        matchstats = [ ( r.point, b.point, ROAD.distance( roadnet, r.point, b.point, 'length' ) )
#                      for r,b in match ]
        costs_brute = MATCHCOSTS( match_brute, PP, QQ, roadnet )
        cost_brute = ROADMATCHCOST( match_brute, PP, QQ, roadnet )
        print match_brute
        print costs_brute
        print cost_brute
        #print 'optimal match has cost: %f' % matchcost

        
コード例 #11
0
         label, length = road_iter.next()
         roadnet.add_edge( u, v, label, length=length, oneway=True )
         
         
 
 if True :
     distr = {}
     distr[('W','E')] = 1./5
     distr[('N','E')] = 1./5
     distr[('W','S')] = 3./5
     
     Ed = roadEd( roadnet, distr, length_attr='length' )
     print 'Ed computed %f' % Ed
     
     pairs = [ roadprob.samplepair( roadnet, distr ) for i in range(20000) ]
     dst = [ ROAD.distance( roadnet, p, q, 'length' ) for p,q in pairs ]
     Ed_emp = np.mean( dst )
     print 'Ed empirical %f' % Ed_emp
     
     
 else :
     ROADS = ['N', 'S', 'E', 'W' ]
     #PAIRS = itertools.product( ROADS, ROADS )
     #PAIRS = [ ('E','E') ]
     edges = [ name for _,__,name in roadnet.edges( keys=True ) ]
     #PAIRS = [ ( random.choice(edges), random.choice(edges) ) for i in range(5) ]
     for road1, road2 in PAIRS :
         Ed_cond = roadEd_conditional( roadnet, road1, road2 )
         #
         pairs = [ sample( roadnet, { (road1, road2) : 1.} ) for i in range(20000) ]
         dst = [ ROAD.distance( roadnet, p, q, 'length' ) for p,q in pairs ]
コード例 #12
0
 def distance(self, x, y ) :
     return ROAD.distance( self.roadmap, x, y, weight=self.length_attr )
コード例 #13
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'
コード例 #14
0
def enroute_cost( pairs, roadmap ) :
    distfunc = lambda p, q : ROAD.distance( roadmap, p, q, 'length' )
    
    enroutes = [ distfunc(s,t) for s,t in pairs ]
    total_enroute = sum( enroutes )
    return total_enroute
コード例 #15
0
 def cost( demidx ) :
     x.init( *demands[demidx].pick )
     return ROAD.distance( roadmap, agentLoc, x, 'length' )
コード例 #16
0
 def distance(self, p, q ) :
     return ROAD.distance( self.roadmap, p, q, weight='length' )
コード例 #17
0
ファイル: taxisim.py プロジェクト: kyletreleaven/taxitheory
 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()