Пример #1
0
    def route(self, is_check_lanes=True):
        """
        Fastest path python router.
        """
        print 'route'
        # TODO: if too mant vtypes, better go through id_modes
        exectime_start = time.clock()

        net = self.get_scenario().net
        edges = net.edges
        vtypes = self.parent.vtypes

        ids_edges = []
        ids_trip = []
        costs = []
        for id_vtype in self.get_vtypes():
            id_mode = vtypes.ids_mode[id_vtype]

            # no routing for pedestrians
            if id_mode != net.modes.get_id_mode('pedestrian'):
                weights = edges.get_times(
                    id_mode=id_mode,
                    speed_max=vtypes.speeds_max[id_vtype],
                    is_check_lanes=is_check_lanes)

                ids_trip_vtype = self.get_trips_for_vtype(id_vtype)
                # print '  id_vtype,id_mode',id_vtype,id_mode#,ids_trip_vtype
                # print '  weights',weights
                ids_edge_depart = self.ids_edge_depart[ids_trip_vtype]
                ids_edge_arrival = self.ids_edge_arrival[ids_trip_vtype]

                for id_trip, id_edge_depart, id_edge_arrival in zip(
                        ids_trip_vtype, ids_edge_depart, ids_edge_arrival):
                    cost, route = routing.get_mincostroute_edge2edge(
                        id_edge_depart,
                        id_edge_arrival,
                        edges=edges,
                        weights=weights)
                    if len(route) > 0:
                        ids_edges.append(route)
                        ids_trip.append(id_trip)
                        costs.append(cost)

        ids_route = self.routes.get_value().add_rows(
            ids_trip=ids_trip,
            ids_edges=ids_edges,
            costs=costs,
        )
        self.add_routes(ids_trip, ids_route)
        print '  exectime', time.clock() - exectime_start
        return ids_trip, ids_route
Пример #2
0
    def get_route(self,  id_edge_from, id_edge_to, pos_from, pos_to, id_mode=-1):
        print 'get_route', id_edge_from, id_edge_to
        scenario = self.parent.get_scenario()
        edges = scenario.net.edges
        #lanes = scenario.net.lanes
        costs, tree = routing.edgedijkstra(
            id_edge_from, scenario.net.nodes, edges, set([id_edge_to, ]))
        dist, route = routing.get_mincostroute_edge2edge(
            id_edge_from, id_edge_to, costs, tree)
        dists = edges.lengths[route]

        # TODO: this should be a method of edges, icluding position and id_mode
        durations_approx = dists / edges.speeds_max[route]
        return route, dists, durations_approx
Пример #3
0
    def get_route(self,  id_edge_from, id_edge_to, pos_from, pos_to, id_mode=-1):
        print 'get_route', id_edge_from, id_edge_to
        scenario = self.parent.get_scenario()
        edges = scenario.net.edges
        #lanes = scenario.net.lanes
        costs, tree = routing.edgedijkstra(
            id_edge_from, scenario.net.nodes, edges, set([id_edge_to, ]))
        dist, route = routing.get_mincostroute_edge2edge(
            id_edge_from, id_edge_to, costs, tree)
        dists = edges.lengths[route]

        # TODO: this should be a method of edges, icluding position and id_mode
        durations_approx = dists / edges.speeds_max[route]
        return route, dists, durations_approx
Пример #4
0
    def route(self, is_check_lanes=True):
        """
        Fastest path python router.
        """
        print 'route'
        # TODO: if too mant vtypes, better go through id_modes
        exectime_start = time.clock()

        net = self.get_scenario().net
        edges = net.edges
        vtypes = self.parent.vtypes

        ids_edges = []
        ids_trip = []
        costs = []
        for id_vtype in self.get_vtypes():
            id_mode = vtypes.ids_mode[id_vtype]

            # no routing for pedestrians
            if id_mode != net.modes.get_id_mode('pedestrian'):
                weights = edges.get_times(id_mode=id_mode,
                                          speed_max=vtypes.speeds_max[id_vtype],
                                          is_check_lanes=is_check_lanes)

                ids_trip_vtype = self.get_trips_for_vtype(id_vtype)
                # print '  id_vtype,id_mode',id_vtype,id_mode#,ids_trip_vtype
                # print '  weights',weights
                ids_edge_depart = self.ids_edge_depart[ids_trip_vtype]
                ids_edge_arrival = self.ids_edge_arrival[ids_trip_vtype]

                for id_trip, id_edge_depart, id_edge_arrival in zip(ids_trip_vtype, ids_edge_depart,  ids_edge_arrival):
                    cost, route = routing.get_mincostroute_edge2edge(id_edge_depart,
                                                                     id_edge_arrival,
                                                                     edges=edges,
                                                                     weights=weights)
                    if len(route) > 0:
                        ids_edges.append(route)
                        ids_trip.append(id_trip)
                        costs.append(cost)

        ids_route = self.routes.get_value().add_rows(ids_trip=ids_trip,
                                                     ids_edges=ids_edges,
                                                     costs=costs,
                                                     )
        self.add_routes(ids_trip, ids_route)
        print '  exectime', time.clock()-exectime_start
        return ids_trip, ids_route
Пример #5
0
    def get_route_between_parking(self,
                                  id_parking_from,
                                  id_parking_to,
                                  id_veh=-1):
        """
        Return route and distance of ride with vehicle type  vtype
        between id_parking_from and id_parking_to

        """
        # print 'get_route_between_parking',id_parking_from, id_parking_to
        scenario = self.parent.get_scenario()
        edges = scenario.net.edges
        lanes = scenario.net.lanes
        # print   self.get_demand().getVehicles().cols.maxSpeed
        #v_max = self.get_demand().getVehicles().maxSpeed.get(vtype)
        parking = scenario.landuse.parking

        ids_lanes = parking.ids_lane[[id_parking_from, id_parking_to]]
        id_edge_from, id_edge_to = lanes.ids_edge[ids_lanes]
        pos_from, pos_to = parking.positions[[id_parking_from, id_parking_to]]

        # print '  id_edge_from, id_edge_to=',id_edge_from, id_edge_to
        costs, tree = routing.edgedijkstra(id_edge_from, scenario.net.nodes,
                                           scenario.net.edges,
                                           set([
                                               id_edge_to,
                                           ]))
        dist, route = routing.get_mincostroute_edge2edge(
            id_edge_from, id_edge_to, costs, tree)

        # here is a big problem: starting with the successive node of edge_from
        # may result that the first edge of the route is not  connected with edge_from
        # And arriving at the preceding node of edge_to may result that from
        # the last edge in route the edge_to is not connected.

        #route = [edge_from]+route+[edge_to]
        dist = dist - pos_from - (edges.lengths[id_edge_to] - pos_to)
        # print 'get_route_between_parking',    dist,type(route),route#[-1].getLength()
        # print '  pos_from ,pos_to ', pos_from ,pos_to v=s/t

        # TODO: this should be a method of edges, icluding position and id_mode
        duration_approx = np.sum(edges.lengths[route] /
                                 edges.speeds_max[route])

        return route, dist, duration_approx
Пример #6
0
    def get_route_between_parking(self, id_parking_from, id_parking_to, id_veh=-1):
        """
        Return route and distance of ride with vehicle type  vtype
        between id_parking_from and id_parking_to

        """
        # print 'get_route_between_parking',id_parking_from, id_parking_to
        scenario = self.parent.get_scenario()
        edges = scenario.net.edges
        lanes = scenario.net.lanes
        # print   self.get_demand().getVehicles().cols.maxSpeed
        #v_max = self.get_demand().getVehicles().maxSpeed.get(vtype)
        parking = scenario.landuse.parking

        ids_lanes = parking.ids_lane[[id_parking_from, id_parking_to]]
        id_edge_from, id_edge_to = lanes.ids_edge[ids_lanes]
        pos_from, pos_to = parking.positions[[id_parking_from, id_parking_to]]

        # print '  id_edge_from, id_edge_to=',id_edge_from, id_edge_to
        costs, tree = routing.edgedijkstra(
            id_edge_from, scenario.net.nodes, scenario.net.edges, set([id_edge_to, ]))
        dist, route = routing.get_mincostroute_edge2edge(
            id_edge_from, id_edge_to, costs, tree)

        # here is a big problem: starting with the successive node of edge_from
        # may result that the first edge of the route is not  connected with edge_from
        # And arriving at the preceding node of edge_to may result that from
        # the last edge in route the edge_to is not connected.

        #route = [edge_from]+route+[edge_to]
        dist = dist - pos_from - (edges.lengths[id_edge_to] - pos_to)
        # print 'get_route_between_parking',    dist,type(route),route#[-1].getLength()
        # print '  pos_from ,pos_to ', pos_from ,pos_to v=s/t

        # TODO: this should be a method of edges, icluding position and id_mode
        duration_approx = np.sum(
            edges.lengths[route] / edges.speeds_max[route])

        return route, dist, duration_approx
Пример #7
0
    def generate_trips(
        self,
        demand,
        time_start,
        time_end,
        id_mode,
        pos_depart_default=db.OPTIONMAP_POS_DEPARTURE['random_free'],
        #pos_arrival_default = db.OPTIONMAP_POS_ARRIVAL['max'],
        pos_arrival_default=db.OPTIONMAP_POS_ARRIVAL['random'],
        speed_depart_default=0.0,
        speed_arrival_default=0.0,
        # pedestrians always depart on lane 0
        ind_lane_depart_default=db.OPTIONMAP_LANE_DEPART['allowed'],
        # pedestrians always arrive on lane 0
        ind_lane_arrival_default=db.OPTIONMAP_LANE_ARRIVAL['current'],
        n_trials_connect=5,
        is_make_route=True,
    ):
        """
        Generates trips in demand.trip table.
        """
        print 'generate_trips', time_start, time_end, id_mode
        id_mode_ped = MODES['pedestrian']
        #OPTIONMAP_POS_DEPARTURE = { -1:"random",-2:"free",-3:"random_free",-4:"base"}
        #OPTIONMAP_POS_ARRIVAL = { -1:"random",-2:"max"}
        #OPTIONMAP_SPEED_DEPARTURE = { -1:"random",-2:"max"}
        #OPTIONMAP_SPEED_ARRIVAL = { -1:"current"}
        #OPTIONMAP_LANE_DEPART = {-1:"random",-2:"free",-3:"departlane"}
        #OPTIONMAP_LANE_ARRIVAL = { -1:"current"}

        trips = demand.trips
        #ids_vtype_mode = demand.vtypes.select_by_mode(id_mode)
        ids_vtype_mode, prob_vtype_mode = demand.vtypes.select_by_mode(
            id_mode, is_share=True)
        # print '  ids_vtype_mode', ids_vtype_mode
        n_vtypes = len(ids_vtype_mode)
        zones = self.zones.get_value()
        edges = zones.ids_edges_orig.get_linktab()
        edgelengths = edges.lengths

        if n_trials_connect > 0:
            # initialize routing to verify connection
            fstar = edges.get_fstar(is_ignor_connections=False)
            times = edges.get_times(id_mode=id_mode, is_check_lanes=True)

        n_trips_generated = 0
        n_trips_failed = 0

        is_nocon = False
        route = []
        for id_od in self.get_ids():
            id_orig = self.ids_orig[id_od]
            id_dest = self.ids_dest[id_od]
            tripnumber = self.tripnumbers[id_od]

            ids_edges_orig_raw = zones.ids_edges_orig[id_orig]
            ids_edges_dest_raw = zones.ids_edges_dest[id_dest]

            prob_edges_orig_raw = zones.probs_edges_orig[id_orig]
            prob_edges_dest_raw = zones.probs_edges_dest[id_dest]

            # check accessibility of origin edges
            ids_edges_orig = []
            prob_edges_orig = []
            inds_lane_orig = []
            for i in xrange(len(ids_edges_orig_raw)):
                id_edge = ids_edges_orig_raw[i]
                # if check accessibility...
                ind_lane_depart = edges.get_laneindex_allowed(id_edge, id_mode)
                # print '  get_laneindex_allowed',id_mode,id_edge,edges.ids_sumo[id_edge],ind_lane_depart
                if ind_lane_depart >= 0:
                    ids_edges_orig.append(id_edge)
                    prob_edges_orig.append(prob_edges_orig_raw[i])
                    inds_lane_orig.append(ind_lane_depart)

            # check accessibility of destination edges
            ids_edges_dest = []
            prob_edges_dest = []
            inds_lane_dest = []
            for i in xrange(len(ids_edges_dest_raw)):
                id_edge = ids_edges_dest_raw[i]
                # if check accessibility...
                ind_lane_arrival = edges.get_laneindex_allowed(
                    id_edge, id_mode)
                if ind_lane_arrival >= 0:
                    ids_edges_dest.append(id_edge)
                    prob_edges_dest.append(prob_edges_dest_raw[i])
                    inds_lane_dest.append(ind_lane_arrival)

            n_edges_orig = len(ids_edges_orig)
            n_edges_dest = len(ids_edges_dest)

            if (n_edges_orig > 0) & (n_edges_dest > 0) & (tripnumber > 0):
                # renormalize weights
                prob_edges_orig = np.array(prob_edges_orig, np.float)
                prob_edges_orig = prob_edges_orig / np.sum(prob_edges_orig)
                prob_edges_dest = np.array(prob_edges_dest, np.float)
                prob_edges_dest = prob_edges_dest / np.sum(prob_edges_dest)

                for d in xrange(int(tripnumber + 0.5)):
                    time_depart = random.uniform(time_start, time_end)

                    if (n_trials_connect > 0) & (id_mode != id_mode_ped):
                        # check if origin and destination edges are connected
                        n = n_trials_connect
                        is_nocon = True
                        while (n > 0) & is_nocon:
                            # this algorithm can be improved by calculating
                            # the minimum cost tree and chacking all destinations
                            i_orig = np.argmax(
                                random.rand(n_edges_orig) * prob_edges_orig)
                            id_edge_orig = ids_edges_orig[i_orig]
                            i_dest = np.argmax(
                                random.rand(n_edges_dest) * prob_edges_dest)
                            id_edge_dest = ids_edges_dest[i_dest]

                            cost, route = routing.get_mincostroute_edge2edge(
                                id_edge_orig,
                                id_edge_dest,
                                weights=times,
                                fstar=fstar)
                            is_nocon = len(route) == 0
                            n -= 1
                        # print '  found route',len(route),n_trials_connect-n
                        if not is_make_route:
                            route = []
                    else:
                        # no check if origin and destination edges are connected
                        i_orig = np.argmax(
                            random.rand(n_edges_orig) * prob_edges_orig)
                        id_edge_orig = ids_edges_orig[i_orig]

                        i_dest = np.argmax(
                            random.rand(n_edges_dest) * prob_edges_dest)
                        id_edge_dest = ids_edges_dest[i_dest]

                    if not is_nocon:
                        ind_lane_orig = inds_lane_orig[i_orig]
                        ind_lane_dest = inds_lane_dest[i_dest]

                        pos_depart = pos_depart_default
                        pos_arrival = pos_arrival_default
                        # print '  bef:pos_depart,pos_arrival,id_mode,id_mode_ped',  pos_depart,pos_arrival,id_mode,id_mode_ped
                        if id_mode_ped == id_mode:
                            # persons do not understand "random", "max" etc
                            # so produce a random number here

                            #{ -1:"random",-2:"free",-3:"random_free",-4:"base"}
                            edgelength = edgelengths[id_edge_orig]
                            if pos_depart in (-1, -2, -3):
                                pos_depart = random.uniform(
                                    0.1 * edgelength, 0.9 * edgelength, 1)[0]
                            else:
                                pos_depart = 0.1 * edgelength

                            # { -1:"random",-2:"max"}
                            edgelength = edgelengths[id_edge_dest]
                            if pos_arrival == -1:
                                pos_arrival = random.uniform(
                                    0.1 * edgelength, 0.9 * edgelength, 1)[0]
                            else:
                                pos_arrival = 0.9 * edgelength
                        # print '  af:pos_depart,pos_arrival,id_mode,id_mode_ped',  pos_depart,pos_arrival,id_mode,id_mode_ped
                        # print '  n_vtypes',n_vtypes
                        # print '  random.randint(n_vtypes)',random.randint(n_vtypes)
                        #id_vtype = ids_vtype_mode[random.randint(n_vtypes)]
                        id_vtype = ids_vtype_mode[np.argmax(
                            random.rand(n_vtypes) * prob_vtype_mode)]
                        id_trip = trips.make_trip(
                            id_vtype=id_vtype,
                            time_depart=time_depart,
                            id_edge_depart=id_edge_orig,
                            id_edge_arrival=id_edge_dest,
                            ind_lane_depart=ind_lane_orig,
                            ind_lane_arrival=ind_lane_dest,
                            position_depart=pos_depart,
                            position_arrival=pos_arrival,
                            speed_depart=speed_depart_default,
                            speed_arrival=speed_arrival_default,
                            route=route,
                        )
                        # print '  ',id_trip,id_edge_orig,edges.ids_sumo[id_edge_orig],ind_lane_depart
                        # print '  ',id_trip,self.position_depart[id_trip],
                        n_trips_generated += 1
                    else:
                        n_trips_failed += tripnumber
            else:
                n_trips_failed += tripnumber

        print '  n_trips_generated', n_trips_generated
        print '  n_trips_failed', n_trips_failed
Пример #8
0
    def route(self,
              id_fromstop,
              id_tostop,
              stops_to_enter=None,
              stops_to_exit=None,
              times=None,
              fstar=None):
        """
        Routes public transit from fromstop to tostop.
        Reurned are the following arrays, one entry per stage:
            ids_line        : line IDs , with negative id for walking
            linktypes       : type of link
            ids_fromstop    : IDs of stops where each stage  starts
            ids_tostop      : IDs of stops where each stage  engs
            durations       : Duration of each stage in secs
        """
        # print 'route id_fromstop, id_tostop',id_fromstop,id_tostop
        if times is None:
            times = self.get_times()

        if fstar is None:
            fstar = self.get_fstar()

        if stops_to_enter is None:
            stops_to_enter, stops_to_exit = self.get_stops_to_enter_exit()

        ptlinktypes = self.types.choices
        #type_enter = ptlinktypes['enter']
        type_transit = ptlinktypes['transit']
        #type_board = ptlinktypes['board']
        #type_alight = ptlinktypes['alight']
        #type_transfer = ptlinktypes['transfer']
        type_walk = ptlinktypes['walk']
        #type_exit = ptlinktypes['exit']

        # trick: pick a link that points to the fromstop
        # and one that starts with tostop
        # later remove first an last link and respective duration

        id_fromlink = stops_to_enter[id_fromstop]
        id_tolink = stops_to_exit[id_tostop]

        print '  route id_fromstop, id_tostop', id_fromstop, id_tostop
        print '  route id_fromlink, id_tolink', id_fromlink, id_tolink

        routeduration, route = get_mincostroute_edge2edge(id_fromlink,
                                                          id_tolink,
                                                          weights=times,
                                                          fstar=fstar)

        # self.print_route(route)

        # print '  len(route)',len(route)
        if len(route) == 0:
            return [], [], [], [], []

        # unite links on the same line and determine durations
        # for each stage
        ids_line = []
        ids_fromstop = []
        ids_tostop = []
        durations = []
        linktypes = []
        id_line_last = -1
        duration_accum = 0.0
        # print '  self.types[route]',self.types[route],len(self.types[route])
        # print '  self.types[route]',self.types[route],len(self.types[route])
        # for linktype,id_line,duration in zip(self.types[route],self.ids_line[route],):
        #    print '    linktype',linktype,linktype == type_transit,linktype == type_walk
        #    print '    id_line',id_line
        #    #print '    ',

        for linktype, id_line, duration, id_fromstop, id_tostop in\
            zip(self.types[route],
                self.ids_line[route],
                self.durations[route],
                self.ids_fromstop[route], self.ids_tostop[route]):

            # print '    linktype',linktype,'id_line',id_line,'duration',duration
            if linktype == type_transit:
                # check if this link is yet another stop of te same line
                if id_line_last == -1:
                    # no previous line, so it is
                    # the first transit link in a transit
                    # init first stage
                    ids_line.append(id_line)
                    ids_fromstop.append(id_fromstop)
                    ids_tostop.append(id_tostop)  # will be updated
                    linktypes.append(linktype)
                    durations.append(duration +
                                     duration_accum)  # will be updated
                    id_line_last = id_line
                    duration_accum = 0.0

                else:  # successive stop(s) in a transit
                    durations[-1] += duration
                    ids_tostop[-1] = id_tostop

            elif linktype == type_walk:
                ids_line.append(id_line)
                ids_fromstop.append(id_fromstop)
                ids_tostop.append(id_tostop)
                linktypes.append(linktype)
                durations.append(duration + duration_accum)
                id_line_last = -1
                duration_accum = 0.0
            else:
                # for all other link types simply accumulate duration
                # which will be added to a successive walk or transit stage
                duration_accum += duration

            # print '      ids_line',ids_line
            # print '      linktypes',linktypes
            # print '      durations',durations
            # print '      ids_fromstop',ids_fromstop
            # print '      ids_tostop',ids_tostop

        return durations, linktypes, ids_line, ids_fromstop, ids_tostop
Пример #9
0
    def guess_routes(self, is_keep_existing=False):
        """
        Guess sequence of edges between stops if not previously specified 
        using shortest path routing.
        """
        # print 'guess_routes'
        ids_line = self.get_ids()
        vtypes = self.ids_vtype.get_linktab()
        ptstops = self.get_ptstops()
        net = self.get_net()
        #edges = net.edges
        lanes = net.lanes
        #'ids_lane', net.lanes,
        #ids_stopedge = ptstops.ids_lane
        ids_laneedge = net.lanes.ids_edge
        ids_stoplane = ptstops.ids_lane

        # make forward star for transport net
        fstar = net.edges.get_fstar()

        # get edge travel times for each PT mode
        get_times = net.edges.get_times
        map_mode_to_times = {}
        ids_mode = vtypes.ids_mode[self.ids_vtype[ids_line]]
        for id_mode in set(ids_mode):
            map_mode_to_times[id_mode] = get_times(id_mode=id_mode,
                                                   is_check_lanes=True)

        # complete routes between all pairs of stops of all lines
        for id_line, ids_stop, id_mode in zip(ids_line,
                                              self.ids_stops[ids_line],
                                              ids_mode):
            # print '  id_line, ids_stop',id_line, ids_stop
            ids_stopedge = ids_laneedge[ids_stoplane[ids_stop]]
            # print '  ids_stopedge',ids_stopedge
            ids_edge = self.ids_edges[id_line]
            # print '  ids_edge',ids_edge
            if (ids_edge in [None, []]) | (not is_keep_existing):
                # complete route between stops
                ids_edge = []
                duration = 0
                for i in xrange(1, len(ids_stop)):
                    # print '    route',ids_stopedge[i-1],ids_stopedge[i]
                    time, ids_edges_current = get_mincostroute_edge2edge(
                        ids_stopedge[i - 1],
                        ids_stopedge[i],
                        weights=map_mode_to_times[id_mode],
                        fstar=fstar)

                    # print '    ids_edges_current',ids_edges_current
                    if len(ids_edges_current) == 0:
                        # no connections found between stops
                        ids_edges = []
                        break
                    else:
                        duration += time
                        if i == 1:
                            ids_edge += ids_edges_current
                        else:
                            # avoid edge overlaps
                            ids_edge += ids_edges_current[1:]

                # print '  ids_edge',ids_edge
                self.ids_edges[id_line] = ids_edge
Пример #10
0
    def generate_trips(self, demand, time_start, time_end, id_mode,
                       pos_depart_default=db.OPTIONMAP_POS_DEPARTURE['random_free'],
                       #pos_arrival_default = db.OPTIONMAP_POS_ARRIVAL['max'],
                       pos_arrival_default=db.OPTIONMAP_POS_ARRIVAL['random'],
                       speed_depart_default=0.0,
                       speed_arrival_default=0.0,
                       # pedestrians always depart on lane 0
                       ind_lane_depart_default=db.OPTIONMAP_LANE_DEPART['allowed'],
                       # pedestrians always arrive on lane 0
                       ind_lane_arrival_default=db.OPTIONMAP_LANE_ARRIVAL['current'],
                       n_trials_connect=5,
                       is_make_route=True,
                       ):
        """
        Generates trips in demand.trip table.
        """
        print 'generate_trips', time_start, time_end, id_mode
        id_mode_ped = MODES['pedestrian']
        #OPTIONMAP_POS_DEPARTURE = { -1:"random",-2:"free",-3:"random_free",-4:"base"}
        #OPTIONMAP_POS_ARRIVAL = { -1:"random",-2:"max"}
        #OPTIONMAP_SPEED_DEPARTURE = { -1:"random",-2:"max"}
        #OPTIONMAP_SPEED_ARRIVAL = { -1:"current"}
        #OPTIONMAP_LANE_DEPART = {-1:"random",-2:"free",-3:"departlane"}
        #OPTIONMAP_LANE_ARRIVAL = { -1:"current"}

        trips = demand.trips
        #ids_vtype_mode = demand.vtypes.select_by_mode(id_mode)
        ids_vtype_mode, prob_vtype_mode = demand.vtypes.select_by_mode(
            id_mode, is_share=True)
        # print '  ids_vtype_mode', ids_vtype_mode
        n_vtypes = len(ids_vtype_mode)
        zones = self.zones.get_value()
        edges = zones.ids_edges_orig.get_linktab()
        edgelengths = edges.lengths

        if n_trials_connect > 0:
            # initialize routing to verify connection
            fstar = edges.get_fstar(is_ignor_connections=False)
            times = edges.get_times(id_mode=id_mode, is_check_lanes=True)

        n_trips_generated = 0
        n_trips_failed = 0

        is_nocon = False
        route = []
        for id_od in self.get_ids():
            id_orig = self.ids_orig[id_od]
            id_dest = self.ids_dest[id_od]
            tripnumber = self.tripnumbers[id_od]

            ids_edges_orig_raw = zones.ids_edges_orig[id_orig]
            ids_edges_dest_raw = zones.ids_edges_dest[id_dest]

            prob_edges_orig_raw = zones.probs_edges_orig[id_orig]
            prob_edges_dest_raw = zones.probs_edges_dest[id_dest]

            # check accessibility of origin edges
            ids_edges_orig = []
            prob_edges_orig = []
            inds_lane_orig = []
            for i in xrange(len(ids_edges_orig_raw)):
                id_edge = ids_edges_orig_raw[i]
                # if check accessibility...
                ind_lane_depart = edges.get_laneindex_allowed(id_edge, id_mode)
                # print '  get_laneindex_allowed',id_mode,id_edge,edges.ids_sumo[id_edge],ind_lane_depart
                if ind_lane_depart >= 0:
                    ids_edges_orig.append(id_edge)
                    prob_edges_orig.append(prob_edges_orig_raw[i])
                    inds_lane_orig.append(ind_lane_depart)

            # check accessibility of destination edges
            ids_edges_dest = []
            prob_edges_dest = []
            inds_lane_dest = []
            for i in xrange(len(ids_edges_dest_raw)):
                id_edge = ids_edges_dest_raw[i]
                # if check accessibility...
                ind_lane_arrival = edges.get_laneindex_allowed(
                    id_edge, id_mode)
                if ind_lane_arrival >= 0:
                    ids_edges_dest.append(id_edge)
                    prob_edges_dest.append(prob_edges_dest_raw[i])
                    inds_lane_dest.append(ind_lane_arrival)

            n_edges_orig = len(ids_edges_orig)
            n_edges_dest = len(ids_edges_dest)

            if (n_edges_orig > 0) & (n_edges_dest > 0) & (tripnumber > 0):
                # renormalize weights
                prob_edges_orig = np.array(prob_edges_orig, np.float)
                prob_edges_orig = prob_edges_orig/np.sum(prob_edges_orig)
                prob_edges_dest = np.array(prob_edges_dest, np.float)
                prob_edges_dest = prob_edges_dest/np.sum(prob_edges_dest)

                for d in xrange(int(tripnumber+0.5)):
                    time_depart = random.uniform(time_start, time_end)

                    if (n_trials_connect > 0) & (id_mode != id_mode_ped):
                        # check if origin and destination edges are connected
                        n = n_trials_connect
                        is_nocon = True
                        while (n > 0) & is_nocon:
                            # this algorithm can be improved by calculating
                            # the minimum cost tree and chacking all destinations
                            i_orig = np.argmax(random.rand(
                                n_edges_orig)*prob_edges_orig)
                            id_edge_orig = ids_edges_orig[i_orig]
                            i_dest = np.argmax(random.rand(
                                n_edges_dest)*prob_edges_dest)
                            id_edge_dest = ids_edges_dest[i_dest]

                            cost, route = routing.get_mincostroute_edge2edge(id_edge_orig,
                                                                             id_edge_dest,
                                                                             weights=times,
                                                                             fstar=fstar
                                                                             )
                            is_nocon = len(route) == 0
                            n -= 1
                        # print '  found route',len(route),n_trials_connect-n
                        if not is_make_route:
                            route = []
                    else:
                        # no check if origin and destination edges are connected
                        i_orig = np.argmax(random.rand(
                            n_edges_orig)*prob_edges_orig)
                        id_edge_orig = ids_edges_orig[i_orig]

                        i_dest = np.argmax(random.rand(
                            n_edges_dest)*prob_edges_dest)
                        id_edge_dest = ids_edges_dest[i_dest]

                    if not is_nocon:
                        ind_lane_orig = inds_lane_orig[i_orig]
                        ind_lane_dest = inds_lane_dest[i_dest]

                        pos_depart = pos_depart_default
                        pos_arrival = pos_arrival_default
                        # print '  bef:pos_depart,pos_arrival,id_mode,id_mode_ped',  pos_depart,pos_arrival,id_mode,id_mode_ped
                        if id_mode_ped == id_mode:
                            # persons do not understand "random", "max" etc
                            # so produce a random number here

                            #{ -1:"random",-2:"free",-3:"random_free",-4:"base"}
                            edgelength = edgelengths[id_edge_orig]
                            if pos_depart in (-1, -2, -3):
                                pos_depart = random.uniform(
                                    0.1*edgelength, 0.9*edgelength, 1)[0]
                            else:
                                pos_depart = 0.1*edgelength

                            # { -1:"random",-2:"max"}
                            edgelength = edgelengths[id_edge_dest]
                            if pos_arrival == -1:
                                pos_arrival = random.uniform(
                                    0.1*edgelength, 0.9*edgelength, 1)[0]
                            else:
                                pos_arrival = 0.9*edgelength
                        # print '  af:pos_depart,pos_arrival,id_mode,id_mode_ped',  pos_depart,pos_arrival,id_mode,id_mode_ped
                        # print '  n_vtypes',n_vtypes
                        # print '  random.randint(n_vtypes)',random.randint(n_vtypes)
                        #id_vtype = ids_vtype_mode[random.randint(n_vtypes)]
                        id_vtype = ids_vtype_mode[np.argmax(
                            random.rand(n_vtypes)*prob_vtype_mode)]
                        id_trip = trips.make_trip(id_vtype=id_vtype,
                                                  time_depart=time_depart,
                                                  id_edge_depart=id_edge_orig,
                                                  id_edge_arrival=id_edge_dest,
                                                  ind_lane_depart=ind_lane_orig,
                                                  ind_lane_arrival=ind_lane_dest,
                                                  position_depart=pos_depart,
                                                  position_arrival=pos_arrival,
                                                  speed_depart=speed_depart_default,
                                                  speed_arrival=speed_arrival_default,
                                                  route=route,
                                                  )
                        # print '  ',id_trip,id_edge_orig,edges.ids_sumo[id_edge_orig],ind_lane_depart
                        # print '  ',id_trip,self.position_depart[id_trip],
                        n_trips_generated += 1
                    else:
                        n_trips_failed += tripnumber
            else:
                n_trips_failed += tripnumber

        print '  n_trips_generated', n_trips_generated
        print '  n_trips_failed', n_trips_failed
Пример #11
0
    def route(self, id_fromstop, id_tostop,
              stops_to_enter=None, stops_to_exit=None,
              times=None, fstar=None):
        """
        Routes public transit from fromstop to tostop.
        Reurned are the following arrays, one entry per stage:
            ids_line        : line IDs , with negative id for walking
            linktypes       : type of link
            ids_fromstop    : IDs of stops where each stage  starts
            ids_tostop      : IDs of stops where each stage  engs
            durations       : Duration of each stage in secs
        """
        # print 'route id_fromstop, id_tostop',id_fromstop,id_tostop
        if times is None:
            times = self.get_times()

        if fstar is None:
            fstar = self.get_fstar()

        if stops_to_enter is None:
            stops_to_enter, stops_to_exit = self.get_stops_to_enter_exit()

        ptlinktypes = self.types.choices
        #type_enter = ptlinktypes['enter']
        type_transit = ptlinktypes['transit']
        #type_board = ptlinktypes['board']
        #type_alight = ptlinktypes['alight']
        #type_transfer = ptlinktypes['transfer']
        type_walk = ptlinktypes['walk']
        #type_exit = ptlinktypes['exit']

        # trick: pick a link that points to the fromstop
        # and one that starts with tostop
        # later remove first an last link and respective duration

        id_fromlink = stops_to_enter[id_fromstop]
        id_tolink = stops_to_exit[id_tostop]

        print '  route id_fromstop, id_tostop', id_fromstop, id_tostop
        print '  route id_fromlink, id_tolink', id_fromlink, id_tolink

        routeduration, route = get_mincostroute_edge2edge(
            id_fromlink, id_tolink,
            weights=times, fstar=fstar
        )

        # self.print_route(route)

        # print '  len(route)',len(route)
        if len(route) == 0:
            return [], [], [], [], []

        # unite links on the same line and determine durations
        # for each stage
        ids_line = []
        ids_fromstop = []
        ids_tostop = []
        durations = []
        linktypes = []
        id_line_last = -1
        duration_accum = 0.0
        # print '  self.types[route]',self.types[route],len(self.types[route])
        # print '  self.types[route]',self.types[route],len(self.types[route])
        # for linktype,id_line,duration in zip(self.types[route],self.ids_line[route],):
        #    print '    linktype',linktype,linktype == type_transit,linktype == type_walk
        #    print '    id_line',id_line
        #    #print '    ',

        for linktype, id_line, duration, id_fromstop, id_tostop in\
            zip(self.types[route],
                self.ids_line[route],
                self.durations[route],
                self.ids_fromstop[route], self.ids_tostop[route]):

            # print '    linktype',linktype,'id_line',id_line,'duration',duration
            if linktype == type_transit:
                # check if this link is yet another stop of te same line
                if id_line_last == -1:
                    # no previous line, so it is
                    # the first transit link in a transit
                    # init first stage
                    ids_line.append(id_line)
                    ids_fromstop.append(id_fromstop)
                    ids_tostop.append(id_tostop)  # will be updated
                    linktypes.append(linktype)
                    durations.append(duration+duration_accum)  # will be updated
                    id_line_last = id_line
                    duration_accum = 0.0

                else:  # successive stop(s) in a transit
                    durations[-1] += duration
                    ids_tostop[-1] = id_tostop

            elif linktype == type_walk:
                ids_line.append(id_line)
                ids_fromstop.append(id_fromstop)
                ids_tostop.append(id_tostop)
                linktypes.append(linktype)
                durations.append(duration+duration_accum)
                id_line_last = -1
                duration_accum = 0.0
            else:
                # for all other link types simply accumulate duration
                # which will be added to a successive walk or transit stage
                duration_accum += duration

            # print '      ids_line',ids_line
            # print '      linktypes',linktypes
            # print '      durations',durations
            # print '      ids_fromstop',ids_fromstop
            # print '      ids_tostop',ids_tostop

        return durations, linktypes, ids_line, ids_fromstop, ids_tostop
Пример #12
0
    def guess_routes(self, is_keep_existing=False):
        """
        Guess sequence of edges between stops if not previously specified 
        using shortest path routing.
        """
        # print 'guess_routes'
        ids_line = self.get_ids()
        vtypes = self.ids_vtype.get_linktab()
        ptstops = self.get_ptstops()
        net = self.get_net()
        #edges = net.edges
        lanes = net.lanes
        #'ids_lane', net.lanes,
        #ids_stopedge = ptstops.ids_lane
        ids_laneedge = net.lanes.ids_edge
        ids_stoplane = ptstops.ids_lane

        # make forward star for transport net
        fstar = net.edges.get_fstar()

        # get edge travel times for each PT mode
        get_times = net.edges.get_times
        map_mode_to_times = {}
        ids_mode = vtypes.ids_mode[self.ids_vtype[ids_line]]
        for id_mode in set(ids_mode):
            map_mode_to_times[id_mode] = get_times(id_mode=id_mode,
                                                   is_check_lanes=True)

        # complete routes between all pairs of stops of all lines
        for id_line, ids_stop, id_mode in zip(ids_line,
                                              self.ids_stops[ids_line],
                                              ids_mode
                                              ):
            # print '  id_line, ids_stop',id_line, ids_stop
            ids_stopedge = ids_laneedge[ids_stoplane[ids_stop]]
            # print '  ids_stopedge',ids_stopedge
            ids_edge = self.ids_edges[id_line]
            # print '  ids_edge',ids_edge
            if (ids_edge in [None, []]) | (not is_keep_existing):
                # complete route between stops
                ids_edge = []
                duration = 0
                for i in xrange(1, len(ids_stop)):
                    # print '    route',ids_stopedge[i-1],ids_stopedge[i]
                    time, ids_edges_current = get_mincostroute_edge2edge(
                        ids_stopedge[i-1],
                        ids_stopedge[i],
                        weights=map_mode_to_times[id_mode],
                        fstar=fstar)

                    # print '    ids_edges_current',ids_edges_current
                    if len(ids_edges_current) == 0:
                        # no connections found between stops
                        ids_edges = []
                        break
                    else:
                        duration += time
                        if i == 1:
                            ids_edge += ids_edges_current
                        else:
                            # avoid edge overlaps
                            ids_edge += ids_edges_current[1:]

                # print '  ids_edge',ids_edge
                self.ids_edges[id_line] = ids_edge