Exemplo n.º 1
0
        def DistancePriorityPickup(c, meetingCount):
            '''
            param c: Taxi id.
            if success, taxi will have non 0 passengerid, path, i=0
            '''

            InfVeh = AKIVehTrackedGetInf(c)
            currentpos = str(InfVeh.idSection)
            steps = []
            # a tuple list storing (no.of steps needed to get passenger, passenger id )

            for d in range(1, len(Passengerlist)):
                if Passengerlist[d] == None:
                    continue
                if Passengerlist[d].assigned == 0:
                    path = na.dijkstra_path_length(G, currentpos, Passengerlist[d].origin)
                    steps.append((path, d))

            steps = sorted(steps, key=lambda x: (x[0], x[1]))
            # sorted by : firstly, smallest steps to get,
            # secondly passenger id (if steps equal, first come first serve)
            if len(steps) > 0:
                d = steps[0][1]
                Taxilist[c].passengerid = d
                Passengerlist[d].assigned = 1

                Taxilist[
                    c].origin = currentpos  # since after drop off, taxi's place is actually its destination. Hence new origin = its currentplace.
                Taxilist[c].destination = Passengerlist[Taxilist[c].passengerid].origin

                if Taxilist[c].origin == Taxilist[
                    c].destination:  # if the taxi happen to be on the same section as the passenger
                    Passengerlist[Taxilist[c].passengerid].pickuptime = Taxilist[c].stoptime
                    Taxilist[c].destination = Passengerlist[Taxilist[c].passengerid].destination
                    Taxilist[c].occupy = 1
                    meetingCount += 1

                    Passengerlist[Taxilist[c].passengerid].take = 1
                    Taxilist[c].path = na.dijkstra_path(G, str(Taxilist[c].origin), str(
                        Taxilist[c].destination))  # go to passenger's destination
                    Taxilist[c].i = 0
                else:
                    Taxilist[c].path = na.dijkstra_path(G, str(Taxilist[c].origin), str(
                        Taxilist[c].destination))  # go to passenger's origin
                    Taxilist[c].i = 0

            else:
                Taxilist[c].passengerid = 0
                Taxilist[c].path = []
                Taxilist[c].origin = 0
                Taxilist[c].destination = 0
                print(
                    '................................Currently no waiting passenger to assign for taxi :',
                    c)
Exemplo n.º 2
0
 def shortest_path_and_len(self, src, dst):
     path = dijkstra_path(self.g, src, dst, 'weight')
     path_len = self.path_len(path)
     if path_len >= max_int:
         return None, None
     log.debug('path_len: %s, path: %s' % (path_len, path))
     return path, path_len
Exemplo n.º 3
0
    def generate_random_new_way(self):
        og = min_weighted_dominating_set(self.graph, "weight")
        start_node = og.pop()
        holder = set()
        while og:
            curr_node = og.pop()
            holder.update(dijkstra_path(self.graph, start_node, curr_node))

        if holder and is_valid_network(self.graph,
                                       self.graph.subgraph(holder)):
            self.network = nx.minimum_spanning_tree(
                self.graph.subgraph(holder))
        else:
            self.generate_random_old_way(high_degree=True)
Exemplo n.º 4
0
print ("Average Shortest Path")
print (algorithms.all_pairs_shortest_path(G))
print (algorithms.average_shortest_path_length(G))
print ()

# Graph Distance:
#    Unweighted distance - number of edges between two nodes
#    Weighted distance - sum of weights between two nodes. 
#        so shortest path is least combined weight, not necessarily the fewest nodes
#    Euclidean distance -  between the two nodes in the adjacency matrix: which is
#        proportional to the number of common neighbors shared between the nodes.
#

# Dijkstra's Algorithm:
#    for a given vertex it finds the lowest cost path to all other vertices, 
#    where “cost” is determined by summing edge weights. In graphs where edge 
#    weights correspond to distance (in unweighted graphs the weights are 
#    assumed to be one) the found path is the shortest. 
#    The algorithm can also determine the lowest cost path between two given 
#    vertices.
print (algorithms.dijkstra_path(G, 0, 3))
print (algorithms.dijkstra_predecessor_and_distance(G, 0, 3))

pos=networkx.spring_layout(G)
networkx.draw_networkx_nodes(G,pos)
networkx.draw_networkx_edges(G,pos)
networkx.draw_networkx_labels(G,pos)
matplotlib.pyplot.axis('off')
matplotlib.pyplot.savefig("graphTraversals.png") 
matplotlib.pyplot.show() 
Exemplo n.º 5
0
def AAPIEnterVehicle(idveh, idsection):
    #print('Car enters with', idveh)
    import networkx.algorithms as na
    import traceback
    try:
        global CARS, waitingTimeSteps, vacantTimeSteps, clock
        #and str(idsection) in secIDs

        if len(
                Taxilist
        ) <= CARS or clock % 120 == 0:  # and not CARcondition : #only introduce tracked vehicle when it enters connected G.

            AKIVehSetAsTracked(idveh)
            InfVeh = AKIVehTrackedGetInf(idveh)

            if str(InfVeh.idSection) not in list(G.nodes):
                #print('Taxi coming from non SCP, have to throw it away')
                AKIVehSetAsNoTracked(idveh)
            else:

                Taxi_current_pos = str(InfVeh.idSection)

                steps = []
                # a tuple list storing (no.of steps needed to get passenger, passenger id )

                for d in range(1, len(Passengerlist)):
                    if Passengerlist[d] == None:
                        continue
                    if Passengerlist[d].assigned == 0:
                        steps.append(
                            (na.dijkstra_path_length(G, Taxi_current_pos,
                                                     Passengerlist[d].origin),
                             d))

                #print(steps)
                if len(steps) == 0:
                    Taxilist[idveh] = Taxi(0, 0, 0, 0, 0, 0, True, False, 0, 0,
                                           0)
                    Taxilist[idveh].path = []
                    print(
                        idveh,
                        "initialized, does not have unassigned waiting passenger"
                    )

                else:
                    steps = sorted(steps, key=lambda x:
                                   (x[0], x[1]))  #distance priority pick up
                    # sorted by : firstly, smallest steps to get,
                    # secondly passenger id (if steps equal, first come first serve)
                    if len(steps) > 0:
                        d = steps[0][1]
                        Taxilist[idveh] = Taxi(0, 0, 0, 0, 0, 0, True, False,
                                               0, 0, 0)
                        Taxilist[idveh].passengerid = d
                        Passengerlist[d].assigned = 1
                        Taxilist[idveh].origin = str(InfVeh.idSection)
                        Taxilist[idveh].destination = str(
                            Passengerlist[Taxilist[idveh].passengerid].origin)
                        Taxilist[idveh].path = na.dijkstra_path(
                            G, Taxilist[idveh].origin,
                            Taxilist[idveh].destination)
                        #print(idveh, "is assigned to passenger", d, 'at section', Passengerlist[d].origin, 'with path', Taxilist[idveh].path)

            if idveh not in Taxilist.keys():
                AKIVehSetAsNoTracked(idveh)

    except Exception:
        traceback.print_exc()

    return 0
Exemplo n.º 6
0
def AAPIManage(time, timeSta, timeTrans, acycle):

    import traceback, random
    import networkx.algorithms as na
    global clock
    try:
        '''
        Taxi Pickup & Drop off management
        '''

        global Passengerlist, Taxilist, CARS, meeting, \
            meetingCount, vacant, waitAccumulation, vacantAccumulation, vacantTaxi, waitingTimeSteps, vacantTimeSteps, clock

        clock += 1  # this steps

        for p in range(1, len(Passengerlist)):
            if Passengerlist[p] == None:
                continue
            #print('Passenger', p, 'Has origin', Passengerlist[p].origin, 'destination', Passengerlist[p].destination, 'Is taken?', Passengerlist[p].take, 'Is assigned', Passengerlist[p].assigned)

        def DistancePriorityPickup(c, meetingCount):
            '''
            param c: Taxi id.
            if success, taxi will have non 0 passengerid, path, i=0
            '''

            InfVeh = AKIVehTrackedGetInf(c)
            currentpos = str(InfVeh.idSection)
            steps = []
            # a tuple list storing (no.of steps needed to get passenger, passenger id )

            for d in range(1, len(Passengerlist)):
                if Passengerlist[d] == None:
                    continue
                if Passengerlist[d].assigned == 0:
                    path = na.dijkstra_path_length(G, currentpos,
                                                   Passengerlist[d].origin)
                    steps.append((path, d))

            steps = sorted(steps, key=lambda x: (x[0], x[1]))
            # sorted by : firstly, smallest steps to get,
            # secondly passenger id (if steps equal, first come first serve)
            if len(steps) > 0:
                d = steps[0][1]
                Taxilist[c].passengerid = d
                Passengerlist[d].assigned = 1

                Taxilist[
                    c].origin = currentpos  # since after drop off, taxi's place is actually its destination. Hence new origin = its currentplace.
                Taxilist[c].destination = Passengerlist[
                    Taxilist[c].passengerid].origin

                if Taxilist[c].origin == Taxilist[
                        c].destination:  # if the taxi happen to be on the same section as the passenger
                    Passengerlist[Taxilist[
                        c].passengerid].pickuptime = Taxilist[c].stoptime
                    Taxilist[c].destination = Passengerlist[
                        Taxilist[c].passengerid].destination
                    Taxilist[c].occupy = 1
                    meetingCount += 1

                    Passengerlist[Taxilist[c].passengerid].take = 1
                    Taxilist[c].path = na.dijkstra_path(
                        G, str(Taxilist[c].origin),
                        str(Taxilist[c].destination
                            ))  # go to passenger's destination
                    Taxilist[c].i = 0
                else:
                    Taxilist[c].path = na.dijkstra_path(
                        G, str(Taxilist[c].origin),
                        str(Taxilist[c].destination
                            ))  # go to passenger's origin
                    Taxilist[c].i = 0

            else:
                Taxilist[c].passengerid = 0
                Taxilist[c].path = []
                Taxilist[c].origin = 0
                Taxilist[c].destination = 0
                print(
                    '................................Currently no waiting passenger to assign for taxi :',
                    c)

        def removeTaxi(c, meetingCount):
            '''
            Param: c is the taxi idveh
            return 0 if successful. return 1 if not successful
            '''
            if Taxilist[c] == None:
                print('Taxi', c, 'is already deleted!',
                      Taxilist[c].passengerid)
                return 1
            if Taxilist[c].passengerid != 0:
                #sometimes you really can't control it when it's taking a turn........This is logically incorrect, but rarely happens,  due to Aimsun
                if Passengerlist[Taxilist[c].passengerid].take == 1:
                    #But at least we know if the passenger is taken, meeting is successful.
                    Passengerlist[Taxilist[c].passengerid] = None
                else:
                    Passengerlist[Taxilist[c].passengerid].assigned = 0

                Taxilist.pop(c, None)
                AKIVehSetAsNoTracked(c)
                print(
                    'Decrease in Taxi Number!--------------------------------------------------------------------------'
                )
                print('Should not delete taxi', c,
                      '! Currently carrying passenger!',
                      Taxilist[c].passengerid)
                Taxilist[c] = None  # discard this taxi.
                return 1

            TaxiAveSpeed = '/Users/shirley/TaxiResults/TaxiAveSpeed_{}_{}.txt'.format(
                str(ANGConnGetReplicationId()), testID)
            file = open(TaxiAveSpeed, "a")
            file.write(str(c))
            file.write(',')
            file.write(
                str(format(Taxilist[c].speedAccumulation / clock, '.2f')))
            file.write(',')
            file.write(str(clock))
            file.write('\n')
            file.close()  # only discard one taxi at a time.

            Taxilist[c] = None  #discard this taxi.
            Taxilist.pop(c, None)
            AKIVehSetAsNoTracked(c)
            print(
                'Deleted Taxi', c,
                '-----------------------------------------------------------------------------------------------------------'
            )
            return 0

        for c in Taxilist.keys():

            if Taxilist[c] == None:
                continue
            InfVeh = AKIVehTrackedGetInf(c)
            print("Taxi", c, "position", InfVeh.idSection,
                  "is currently assigned with", Taxilist[c].passengerid,
                  " and Has completed the trip of",
                  Taxilist[c].completedPassenger)

            if len(Taxilist[c].path) != 0:

                #print('Taxi',c, 'has path', Taxilist[c].path,'i',Taxilist[c].i,'next section',Taxilist[c].path[Taxilist[c].i])
                #AKIVehTrackedModifyNextSection(c, int(Taxilist[c].path[Taxilist[c].i]))  # Track vehicle by using its (key) Vechicle id c

                # get the information of the vehicle again.
                # InfVeh = AKIVehTrackedGetInf(c)

                if InfVeh.idSection == -1:
                    pass
                    # if AKIVehTrackedModifyNextSection(c, int(Taxilist[c].path[Taxilist[c].i]))!=0:
                    #     print('Error   1 :   Taxi', c, 'currently on', InfVeh.idSection,'has error modifying turning into the correct next step',
                    #     Taxilist[c].path[Taxilist[c].i])
                #elif Taxilist[c].i != Taxilist[c].path.index(str(InfVeh.idSection))-1:
                #print('i should be ',Taxilist[c].i, 'and index should be',Taxilist[c].path.index(str(InfVeh.idSection)))
                #Taxilist[c].i == Taxilist[c].path.index(str(InfVeh.idSection))
                #print('Error__________________3 :   Taxi', c, 'Currently on', InfVeh.idSection,
                #' has error modifying to the correct next step',
                #Taxilist[c].path[Taxilist[c].i])

                elif InfVeh.idSection == int(
                        Taxilist[c].path[Taxilist[c].i]
                ) and Taxilist[c].i < len(Taxilist[c].path) - 1:
                    Taxilist[
                        c].i += 1  # move on to next step. This is incremented every for step.
                    if AKIVehTrackedModifyNextSection(
                            c, int(Taxilist[c].path[Taxilist[c].i])) != 0:
                        print('Error_____________2 :   Taxi', c,
                              'Currently on', InfVeh.idSection,
                              ' has error modifying to the correct next step',
                              Taxilist[c].path[Taxilist[c].i])

                    # move on to the next step

            #InfVeh = AKIVehTrackedGetInf(c)

            Taxilist[c].speedAccumulation += InfVeh.CurrentSpeed
            # Taxilist[c].path == 0 and

            if str(InfVeh.idSection) not in G.nodes(
            ) and InfVeh.idSection != -1:
                Passengerlist[Taxilist[c].passengerid].assigned = 0
                AKIVehSetAsNoTracked(c)
                print(
                    "^^^^^^^Taxi", c,
                    " is discarded for wondering out of the graph while not on a node^^^^^^^^^^^^^"
                )
                removeTaxi(c, meetingCount)
                continue

            if (Taxilist[c].passengerid == 0 or len(Taxilist[c].path)
                    == 0) and InfVeh.idSection != -1:  #case no customer.

                DistancePriorityPickup(c, meetingCount)

            InfVeh = AKIVehTrackedGetInf(c)
            '''
            Passenger pick up & droppoff management
            '''
            if len(Taxilist[c].path) != 0 and InfVeh.idSection == int(
                    Taxilist[c].path[-1]):
                #print('Car', c, 'is enterrring last step~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
                Taxilist[c].i = 0

                A2KSectionInf = AKIInfNetGetSectionANGInf(
                    int(Taxilist[c].path[-1]))
                Taxilist[c].sectionlength = A2KSectionInf.length
                Taxilist[c].midsection = Taxilist[c].sectionlength * 0.5

                if Taxilist[c].midsection - 40 < InfVeh.distance2End < Taxilist[
                        c].midsection + 40:
                    #print('Car', c, 'should be      stopped!!!!!!!!!!!!!!!---------------------------')
                    Taxilist[
                        c].stopping = True  # stop it on the midsection, as if the passenger emerges at midsection.

                if Taxilist[c].stopping == True:

                    if Taxilist[
                            c].firststop == True:  # only record the first stopping time-- otherwise this value could be re-write up to 5sec.

                        Taxilist[c].stoptime = AKIGetCurrentSimulationTime(
                        )  # current time.
                        Taxilist[c].firststop = False
                    AKIVehTrackedModifySpeed(c, 0)  # temporary stop
                    #print('Car', c, 'is stopped!!!!!!!!!!!!!!!---------------------------')

                if clock - Taxilist[c].stoptime > 3 and Taxilist[
                        c].stopping == True:  # if taxi restarts.
                    # current senario: taxi is stopped.
                    # Decide if it is a drop off or pick up senario.

                    Taxilist[c].stopping = False
                    #print('Car', c, 'should go back to movement!!!!!!!!!!!!!!!---------------------------')
                    Taxilist[
                        c].firststop = True  # change firststop back until next time the taxi stops.

                    # counter = counter + 1

                    # print('Taxi',c,'should Passenger that has origin ',Passengerlist[Taxilist[c].passengerid].origin, 'and destination',Passengerlist[Taxilist[c].passengerid].destination)
                    '''
                    A searching and pickup senario: taxi reaching for passenger: taxi's destination = current passenger's origin.
                    A taxi sending passenger reaching its destination : taxi's destinations = current passenger's destination.
                    '''
                    Pickup = (Taxilist[c].path[-1] == Passengerlist[
                        Taxilist[c].passengerid].origin)
                    Dropoff = (Taxilist[c].path[-1] == Passengerlist[
                        Taxilist[c].passengerid].destination)

                    if Pickup:
                        Passengerlist[Taxilist[c].passengerid].take = 1
                        Passengerlist[Taxilist[
                            c].passengerid].pickuptime = Taxilist[c].stoptime

                        # Taxilist[c].empty_distance=Taxilist[c].currentPathLength
                        '''
                        vacant_time, a list. 
                        =: the taxi's drop off time of the LAST passenger) - (the taxi's pick up time of the NEXT passenger)
                        '''
                        # Taxilist[c].vacant_time.append(Passengerlist[Taxilist[c].passengerid].pickuptime - Taxilist[c].droptime)
                        Taxilist[c].occupy = 1
                        Taxilist[c].origin = Passengerlist[
                            Taxilist[c].passengerid].origin
                        Taxilist[c].destination = Passengerlist[
                            Taxilist[c].passengerid].destination

                        Taxilist[c].path = na.dijkstra_path(
                            G, str(Taxilist[c].origin),
                            str(Taxilist[c].destination))

                        print(
                            'Taxi ', c, "has picked up",
                            Taxilist[c].passengerid, "on desination to",
                            Taxilist[c].destination
                        )  # have arrived the destination of the passenger and then go to take the next passenger
                        meetingCount += 1
                        Passengerlist[Taxilist[c].passengerid].take = 1

                    elif Dropoff:

                        Passengerlist[
                            Taxilist[c].passengerid].dropofftime = Taxilist[
                                c].stoptime  # current time

                        # Taxilist[c].droptime = Taxilist[c].stoptime #first stop time.
                        # Taxilist[c].occupied_distance=Taxilist[c].occupied_distance + Taxilist[c].currentPathLength
                        Passengerlist[Taxilist[
                            c].passengerid].distance_travelled = Taxilist[
                                c].currentPathLength
                        print('Taxi', c, 'dropped off passenger',
                              Taxilist[c].passengerid,
                              "________________________________")
                        Taxilist[c].completedPassenger.append(
                            Taxilist[c].passengerid)
                        Taxilist[c].occupy = 0  # becomes vacant
                        Taxilist[c].passengerid = 0
                        Taxilist[c].i = 0

                        # Taxilist[c].occupied_time=Taxilist[c].occupied_time + (Passengerlist[Taxilist[c].passengerid].dropofftime - Passengerlist[Taxilist[c].passengerid].pickuptime)
                        # accummulate occupied time.
                        '''
                        After dropping off, this part is our main concern: 
                        what pick up strategy is the best?
                        '''
                        # SequentialPickup()
                        DistancePriorityPickup(c, meetingCount)
        '''
        Define Vacant and Meeting.
        '''
        wait = 0
        for s in range(1, len(Passengerlist)):
            if Passengerlist[s] == None:
                continue
            if Passengerlist[s].take == 0:
                wait = wait + 1
        print('Number of passenger waiting: ', wait)

        waitingTimeSteps.append(wait)
        '''
        unassigned = 0
        for s in range(1, len(Passengerlist)):
            if Passengerlist[s]==None:
                continue
            if Passengerlist[s].assigned == 0:
                unassigned = unassigned + 1
        #print ('Number of passenger unassigned: ', unassigned)
        '''

        vacant = 0
        for c in Taxilist.keys():
            if Taxilist[c] == None:
                #Taxilist.pop(c,None)
                continue
            elif Taxilist[c].occupy == 0:
                vacant += 1
        print('Number of vacant taxi: ', vacant)
        vacantTimeSteps.append(vacant)

        waitAccumulation += wait
        vacantAccumulation += vacant
        print("Meeting happened in this interval:", meetingCount)
        '''
        In test small network, no complicated sin distribution is tested. 
        Manages the introducing of new passengers. and the reduction of existing vacant taxis
        '''

        def decision(time, sinscale):
            import random
            return random.random() < np.sin(time / sinscale)

        if clock % 60 == 0:  #and decision(clock+100, 200): #introduces new passenger every DI sec.

            start = random.choice(secIDs)
            while (True):
                end = random.choice(secIDs)
                if start != end and end in innerSec.keys():
                    break
            appeartime = AKIGetCurrentSimulationTime()  # get current time.
            Passengerlist.append(
                Passenger(start, end, 0, 0, appeartime, 0, 0, 0))

        global sinscale
        if (clock % 10 == 0) and decision(clock, sinscale):
            for c in Taxilist.keys():
                if Taxilist[c] == None or Taxilist[c].passengerid != 0:
                    continue
                if (removeTaxi(c, meetingCount) == 0):
                    break
        '''
        Manages the calculation of meeting function statistics.
        '''
        '''
                MFD generation
                '''
        global accumulation, flow, flows, accumulations, completion, completions, sectionid, junctionid, totallength, DiscreteInterval

        if clock % DiscreteInterval == 1:
            for id in sectionid:
                estad2 = AKIEstGetParcialStatisticsSection(id, timeSta, 0)

                A2KSectionInf = AKIInfNetGetSectionANGInf(id)

                sectionlength = A2KSectionInf.length

                if (estad2.report == 0):  # default, refer to manual.
                    flow += estad2.Flow * sectionlength
            if flow != 0:
                flows.append(flow / 3600)
                flow = 0
            print('flows:', flows)

        if clock % DiscreteInterval == 0:

            meeting.append([
                meetingCount, waitAccumulation / DiscreteInterval,
                vacantAccumulation / DiscreteInterval
            ])
            # flows: a list of normalised production/output over time.
            completions.append(completion)  #see exitvehicle
            print('Completionss:', completions)
            completion = 0
            for sectionnumbmer in sectionid:
                numbersinsection = AKIVehStateGetNbVehiclesSection(
                    sectionnumbmer,
                    True)  #total number of vehicle on the section
                accumulation = accumulation + numbersinsection  #sums all vehicles on all sections.

            for junctionnumber in junctionid:
                numbersinjunction = AKIVehStateGetNbVehiclesJunction(
                    junctionnumber)
                accumulation = accumulation + numbersinjunction  #similarly, sums all vehicles on all junctions.

            accumulations.append(accumulation)
            #print(accumulations)
            #print('Accumulations:', accumulations)
            accumulation = 0

            waitAccumulation = 0
            vacantAccumulation = 0
            meetingCount = 0

    except Exception:
        traceback.print_exc()

    return 0
Exemplo n.º 7
0
def short_distance():
    from networkx import algorithms
    g=generate_graph()
    print algorithms.shortest_path(g,0,5)

    print algorithms.dijkstra_path(g,0,5)
Exemplo n.º 8
0
print("Average Shortest Path")
print(algorithms.all_pairs_shortest_path(G))
print(algorithms.average_shortest_path_length(G))
print()

# Graph Distance:
#    Unweighted distance - number of edges between two nodes
#    Weighted distance - sum of weights between two nodes.
#        so shortest path is least combined weight, not necessarily the fewest nodes
#    Euclidean distance -  between the two nodes in the adjacency matrix: which is
#        proportional to the number of common neighbors shared between the nodes.
#

# Dijkstra's Algorithm:
#    for a given vertex it finds the lowest cost path to all other vertices,
#    where “cost” is determined by summing edge weights. In graphs where edge
#    weights correspond to distance (in unweighted graphs the weights are
#    assumed to be one) the found path is the shortest.
#    The algorithm can also determine the lowest cost path between two given
#    vertices.
print(algorithms.dijkstra_path(G, 0, 3))
print(algorithms.dijkstra_predecessor_and_distance(G, 0, 3))

pos = networkx.spring_layout(G)
networkx.draw_networkx_nodes(G, pos)
networkx.draw_networkx_edges(G, pos)
networkx.draw_networkx_labels(G, pos)
matplotlib.pyplot.axis('off')
matplotlib.pyplot.savefig("graphTraversals.png")
matplotlib.pyplot.show()
Exemplo n.º 9
0
 def shortest_path_and_len(self, src, dst):
     path = dijkstra_path(self.g, src, dst, 'weight')
     path_len = self.path_len(path)
     if path_len >= max_int:
         return None, None
     return path, path_len
Exemplo n.º 10
0
def AAPIManage(time, timeSta, timeTrans, acycle):
    #print('Current Manage step -------------------------------------------------------------------')
    import traceback, random
    import networkx.algorithms as na
    try:
        global clock, numberofpassenger, Passengerlist, Taxilist, CARS, clock2, accumulation, numbersinsection, numbersinjunction, astring, meeting, \
            meetingCount, waitNumber, vacant, waitAccumulation, vacantAccumulation
        global counter

        numberofpassenger = len(Passengerlist)

        wait = 0
        for s in range(0, numberofpassenger):
            if Passengerlist[s].take == 0:
                wait = wait + 1
        print('Number of passenger waiting: ', wait)

        vacant = 0
        for c in Taxilist:

            if Taxilist[c].occupy == 0:
                vacant += 1
        print('Number of vacant taxi: ', vacant)
        waitAccumulation += wait
        vacantAccumulation += vacant

        if clock == 10:  #introduces new passenger every 90 sec.

            start = random.choice(secIDs)
            while (True):
                end = random.choice(secIDs)
                if start != end:
                    break
            appeartime = AKIGetCurrentSimulationTime()  # get current time.
            Passengerlist.append(Passenger(start, end, 0, appeartime, 0, 0, 0))
            clock = 0

        else:
            clock = clock + 1
        #print clock

        if clock2 == 90:
            print('In this 900sec, there were ', waitAccumulation,
                  'passengers were waiting and there were ',
                  vacantAccumulation, 'Became vacant')
            meeting.append([
                meetingCount, wait, vacant, waitAccumulation,
                vacantAccumulation
            ])
            waitAccumulation = 0
            vacantAccumulation = 0
            meetingCount = 0
            clock2 = 0
        else:
            clock2 = clock2 + 1

        #print('We have ----------------------- Taxi.taxiCount:',Taxi.taxiCount)
        for c in Taxilist:

            if Taxilist[c].path == 0:
                '''
                Make this vacant taxi go to the passenger.
                '''
                InfVeh = AKIVehTrackedGetInf(c)
                '''
                AKIVehTrackedGetInf: Read the informaiton of a tracked vehicle.
                '''
                Taxilist[c].origin = str(InfVeh.idSection)
                Taxilist[c].destination = str(
                    Passengerlist[Taxilist[c].passengerid].origin)
                #print('Taxi origin:', Taxilist[c].origin)
                #print('Taxi destination:', Taxilist[c].destination)
                Taxilist[c].path = na.dijkstra_path(G, Taxilist[c].origin,
                                                    Taxilist[c].destination)

                Taxilist[c].currentPathLength = na.dijkstra_path_length(
                    G, Taxilist[c].origin, Taxilist[c].destination)

                Taxilist[c].vacant_distance.append(
                    Taxilist[c].currentPathLength)
            '''
            idSection = 32766 because it exceeded visible network. 
            '''

            #print('Taxi',c,' has Current Section ID', InfVeh.idSection, 'its next step is', weirdValue)

            AKIVehTrackedModifyNextSection(
                c, int(Taxilist[c].path[
                    Taxilist[c].i]))  #Vechicle id starting from 1 instead of 0

            #get the information of the vehicle again.
            InfVeh = AKIVehTrackedGetInf(c)

            if InfVeh.idSection == int(Taxilist[c].path[Taxilist[c].i]):

                #Taxilist[c].noofpath=len(Taxilist[c].path)  #length of all steps

                if Taxilist[c].i < len(
                        Taxilist[c].path) - 1:  #if number of steps < all steps

                    Taxilist[c].i = Taxilist[
                        c].i + 1  #move on to next step. This is incremented every for step.
                    AKIVehTrackedModifyNextSection(
                        c, int(Taxilist[c].path[
                            Taxilist[c].i]))  #move on to next step

            InfVeh = AKIVehTrackedGetInf(c)
            '''
            Passenger pick up.
            '''
            if InfVeh.idSection == int(Taxilist[c].destination):

                Taxilist[c].i = 0

                A2KSectionInf = AKIInfNetGetSectionANGInf(
                    int(Taxilist[c].destination))
                Taxilist[c].sectionlength = A2KSectionInf.length
                Taxilist[c].midsection = Taxilist[c].sectionlength * 0.5

                if Taxilist[c].midsection - 10 < InfVeh.distance2End < Taxilist[
                        c].midsection + 10:

                    Taxilist[
                        c].stopping = True  #stop it on the midsection, as if the passenger emerges at midsection.

                if Taxilist[c].stopping == True:

                    if Taxilist[
                            c].firststop == True:  #only record the first stopping time-- otherwise this value could be re-write up to 5sec.

                        Taxilist[c].stoptime = AKIGetCurrentSimulationTime(
                        )  #current time.
                        Taxilist[c].firststop = False
                    AKIVehTrackedModifySpeed(c, 0)  #temporary stop

                print(
                    'Taxi ', c, "has its passenger ", Taxilist[c].passengerid,
                    " now on trip to ",
                    Passengerlist[Taxilist[c].passengerid].destination
                )  # have taken the passenger, then send the passenger to his destination

                if time - Taxilist[c].stoptime > 5 and Taxilist[
                        c].stopping == True:  #if taxi restarts.
                    #current senario: taxi is stopped.
                    #Decide if it is a drop off or pick up senario.

                    Taxilist[c].stopping = False
                    Taxilist[
                        c].firststop = True  #change firststop back until next time the taxi stops.
                    counter = counter + 1

                    print('Taxi', c, 'should Passenger that has origin ',
                          Passengerlist[Taxilist[c].passengerid].origin,
                          'and destination',
                          Passengerlist[Taxilist[c].passengerid].destination)
                    '''
                    A searching and pickup senario: taxi reaching for passenger: taxi's destination = current passenger's origin.
                    A taxi sending passenger reaching its destination : taxi's destinations = current passenger's destination.
                    '''
                    Pickup = Taxilist[c].destination == Passengerlist[
                        Taxilist[c].passengerid].origin
                    Dropoff = Taxilist[c].destination == Passengerlist[
                        Taxilist[c].passengerid].destination

                    if Pickup:

                        Passengerlist[Taxilist[
                            c].passengerid].pickuptime = Taxilist[c].stoptime
                        #Taxilist[c].noofpath=len(Taxilist[c].path)

                        Taxilist[c].empty_distance = Taxilist[
                            c].currentPathLength
                        '''
                        vacant_time, a list. 
                        =: the taxi's drop off time of the LAST passenger) - (the taxi's pick up time of the NEXT passenger)
                        '''
                        Taxilist[c].vacant_time.append(
                            Passengerlist[Taxilist[c].passengerid].pickuptime -
                            Taxilist[c].droptime)
                        Taxilist[c].occupy = 1
                        Taxilist[c].origin = Passengerlist[
                            Taxilist[c].passengerid].origin
                        Taxilist[c].destination = Passengerlist[
                            Taxilist[c].passengerid].destination

                        Taxilist[c].path = na.dijkstra_path(
                            G, str(Taxilist[c].origin),
                            str(Taxilist[c].destination))

                        print(
                            'Taxi ', c, "has picked up",
                            Taxilist[c].passengerid, "on desination to",
                            Taxilist[c].destination
                        )  # have arrived the destination of the passenger and then go to take the next passenger
                        meetingCount += 1

                    elif Dropoff:

                        Passengerlist[
                            Taxilist[c].passengerid].dropofftime = Taxilist[
                                c].stoptime  #current time
                        Taxilist[c].droptime = Taxilist[c].stoptime  #
                        #Taxilist[c].noofpath=len(Taxilist[c].path)
                        Taxilist[c].occupied_distance = Taxilist[
                            c].occupied_distance + Taxilist[c].currentPathLength
                        Passengerlist[Taxilist[
                            c].passengerid].distance_travelled = Taxilist[
                                c].currentPathLength
                        Taxilist[c].occupy = 0  #becomes vacant

                        Taxilist[c].occupied_time = Taxilist[c].occupied_time + (
                            Passengerlist[Taxilist[c].passengerid].dropofftime
                            -
                            Passengerlist[Taxilist[c].passengerid].pickuptime)

                        #accummulate occupied time.

                        def SequentialPickup():
                            for d in range(0, numberofpassenger):
                                if Passengerlist[
                                        d].take == 0:  # subsequently take on the next waiting passenger on the given list.
                                    Taxilist[c].passengerid = d
                                    Passengerlist[d].take = 1
                                    break

                        def DistancePriorityPickup():

                            steps = []
                            # a tuple list storing (no.of steps needed to get passenger, passenger id )

                            for d in range(0, numberofpassenger):
                                if Passengerlist[d].take == 0:
                                    steps.append((na.dijkstra_path_length(
                                        G, Taxilist[c].destination,
                                        Passengerlist[d].origin), d))

                            steps = sorted(steps, key=lambda x: (x[0], x[1]))
                            # sorted by : firstly, smallest steps to get,
                            # secondly passenger id (if steps equal, first come first serve)
                            if len(steps) > 0:
                                d = steps[0][1]
                                Taxilist[c].passengerid = d
                                Passengerlist[d].take = 1

                        #SequentialPickup()
                        DistancePriorityPickup()
                        Taxilist[c].origin = Taxilist[
                            c].destination  #since after drop off, taxi's place is actually its destination. Hence new origin = its currentplace.
                        Taxilist[c].destination = Passengerlist[
                            Taxilist[c].passengerid].origin

                        if Taxilist[c].origin == Taxilist[
                                c].destination:  #if the taxi happen to be on the same section as the passenger
                            Passengerlist[
                                Taxilist[c].
                                passengerid].pickuptime = Taxilist[c].stoptime
                            Taxilist[c].vacant_time.append(0)
                            Taxilist[c].vacant_distance.append(0)
                            Taxilist[c].destination = Passengerlist[
                                Taxilist[c].passengerid].destination
                            Taxilist[c].path = na.dijkstra_path(
                                G, str(Taxilist[c].origin),
                                str(Taxilist[c].destination)
                            )  #go to passenger's destination
                        else:
                            Taxilist[c].path = na.dijkstra_path(
                                G, str(Taxilist[c].origin),
                                str(Taxilist[c].destination)
                            )  #go to passenger's origin
                            Taxilist[c].vacant_distance.append(
                                Taxilist[c].currentPathLength)

    except Exception:
        traceback.print_exc()

    return 0
Exemplo n.º 11
0
from networkx import algorithms
import networkx
from networkx import *
import itertools
g = networkx.generators.krackhardt_kite_graph()
print(algorithms.shortest_path(g, 5, 1))
print(algorithms.dijkstra_path(g, 5, 1))
#print(dict(algorithms.all_pairs_shortest_path(g)))
#print(dict(algorithms.all_pairs_shortest_path(g))[5])
#并排显示
#lst1=[1,2]
#lst2=[5,6]
#print(lst1,lst2)
#print(*lst1)
nodes = list(g.nodes())[:8]
node_pairs = list(itertools.combinations(nodes, 2))
#print(node_pairs)
for pair in node_pairs:
    print(algorithms.shortest_path(g, *pair),
          algorithms.dijkstra_path(g, *pair))
print(node_pairs)
Exemplo n.º 12
0
 def addItem(self, dst_url):
     try:
         path = dijkstra_path(self._graph, self.url, dst_url)
         self._table[dst_url] = path[1] if len(path) > 1 else path[0]
     except Exception as e:
         print(e)