Esempio n. 1
0
def assign():
    print('\nBaseline Assignments')

    N = env.traci.vehicle.getIDCount()
    M = len(env.target_nodes)
    for n in range(N):
        # Determine which target is the least far away
        cost = [float(env.dist.cost(n, m)) for m in range(M)]
        min_cost = min(cost)
        itar = None
        for i, c in enumerate(cost):
            if c == min_cost:
                itar = i
                break
            continue
        print("Veh=%d Tar=%d Cost=%.3f" % (n, itar, min_cost))

        # Then assign the route
        veh = env.vehicles_active[n]
        path = dict()

        # Path veh --> target
        path_veh2tar = dict()
        tar = env.target_nodes[itar]
        path_veh2tar['nids'] = nx.dijkstra_path(env.nx,
                                                veh['current edge']['to'],
                                                tar['id'])
        path_veh2tar['nids'].insert(0, veh['current edge']['from'])
        path_veh2tar['weight'], path_veh2tar['eids'] = nxops.path_info(
            env.nx, path_veh2tar['nids'])

        # path target --> dest
        path_tar2dest = dict()
        path_tar2dest['nids'] = nx.dijkstra_path(env.nx, tar['id'],
                                                 veh['destination node']['id'])
        path_tar2dest['weight'], path_tar2dest['eids'] = nxops.path_info(
            env.nx, path_tar2dest['nids'])

        # Combine together
        path['nids'] = purr.flattenlist(
            [path_veh2tar['nids'], path_tar2dest['nids']])
        path['weight'] = path_veh2tar['weight'] + path_tar2dest['weight']
        path['eids'] = purr.flattenlist(
            [path_veh2tar['eids'], path_tar2dest['eids']])

        # Update vehicle tracking data
        index = int(veh['id'][3:])
        env.vehicles[index]['target nid'] = tar['id']
        env.vehicles[index]['target eid'] = path['eids'][path['nids'].index(
            tar['id'])]
        env.vehicles[index]['diversion path length'] = path['weight']
        env.vehicles[index]['shortest path length'] = veh['veh2dest weight']

        # Route the vehicle with traci
        env.traci.vehicle.setRoute(veh['id'], path['eids'])

        continue

    print("Complete!")
    return
def main():
    map_dir = "../london-seg4/data/100"
    edges = purr.readXMLtag(purr.mrf(map_dir, r'*.edg.xml'), 'edge')
    connections = purr.readCSV(purr.mrf(map_dir, r'*.conn.csv'))
    stats = purr.readCSV('edges.stats.csv')
    purr.head(edges)
    purr.head(connections)
    purr.head(stats)

    # ~ return

    eids = [edge['id'] for edge in edges]
    connections = purr.flattenlist(
        purr.batchfilterdicts(connections,
                              'CONNECTION ID',
                              eids,
                              show_progress=True))
    print()

    total = len(connections) - 1
    for i, conn in enumerate(connections):
        try:
            speeds = purr.flattenlist(
                purr.batchfilterdicts(stats, 'ID', conn['EDGE IDS']))
        except TypeError:
            speeds = purr.flattenlist(
                purr.batchfilterdicts(stats, 'ID', [conn['EDGE IDS']]))
        mean = [float(speed['mean']) for speed in speeds]
        std = [float(speed['std']) for speed in speeds]
        p50 = [float(speed['p50']) for speed in speeds]
        p85 = [float(speed['p85']) for speed in speeds]
        edges[i]['mean'] = "%.3f" % (statistics.mean(mean))
        edges[i]['std'] = "%.3f" % (statistics.mean(std))
        edges[i]['p50'] = "%.3f" % (statistics.mean(p50))
        edges[i]['p85'] = "%.3f" % (statistics.mean(p85))
        purr.update(i, total, "Correlating speeds with edges ")
        continue

    with open("edg.xml", 'w') as f:
        f.write("<edges>")
        for edge in edges:
            f.write("\n\t<edge")
            for key, val in edge.items():
                f.write(' %s="%s"' % (key, val))
            f.write("/>")
            continue
        f.write("\n</edges>")

    print("COMPLETE!")

    return
def set_route(tA):
    cDest = tA[0] 
    utilities = tA[1]
    
    # Use this info to route.
    for x in range(env.nash_assigner.N):
        print('Veh=%d Tar=%.0f Util=%.3f'%(x,cDest[x],utilities[x]))
        
        veh = env.vehicles_active[x]
        path = dict()
        
        # Not worth the effort. Go home
        if np.isnan(cDest[x]):
            path['nids'] = nx.dijkstra_path(env.nx,veh['current edge']['to'],veh['destination node']['id'])
            path['nids'].insert(0,veh['current edge']['from'])
            path['weight'] , path['eids'] = nxops.path_info(env.nx,path['nids'])
            
        # Otherwise, go to the target
        else:
            # Path veh --> target
            path_veh2tar = dict()
            tar = env.target_nodes[int(cDest[x])]
            path_veh2tar['nids'] = nx.dijkstra_path(env.nx,veh['current edge']['to'],tar['id'])
            path_veh2tar['nids'].insert(0,veh['current edge']['from'])
            path_veh2tar['weight'] , path_veh2tar['eids'] = nxops.path_info(env.nx,path_veh2tar['nids'])
            
            # path target --> dest
            path_tar2dest = dict()
            path_tar2dest['nids'] = nx.dijkstra_path(env.nx,tar['id'],veh['destination node']['id'])
            path_tar2dest['weight'], path_tar2dest['eids'] = nxops.path_info(env.nx,path_tar2dest['nids'])
            
            # Combine together
            path['nids'] = purr.flattenlist([path_veh2tar['nids'],path_tar2dest['nids']])
            path['weight'] = path_veh2tar['weight'] + path_tar2dest['weight']
            path['eids'] = purr.flattenlist([path_veh2tar['eids'],path_tar2dest['eids']])
            
            # Update vehicle tracking data
            index = int(veh['id'][3:])
            env.vehicles[index]['target nid'] = tar['id']
            env.vehicles[index]['target eid'] = path['eids'][path['nids'].index(tar['id'])]
            env.vehicles[index]['diversion path length'] = path['weight']
            env.vehicles[index]['shortest path length'] = veh['veh2dest weight']
        
        # Route the vehicle with traci
        try:
            env.traci.vehicle.setRoute(veh['id'],path['eids'])
        except env.traci.TraCIException:
            pass
        continue
    return
Esempio n. 4
0
def get_valid_edges_from_point(point,radius):
    print("Finding valid edges for point",point,"and radius",radius)
    x,y = point
    
    
    # Find the nodes that are within the radius
    nod_xml = purr.mrf(env.options.map_dir,r'*.nod.xml')
    nodes_all = purr.readXMLtag(nod_xml,'node')
    nodes_valid = []
    for node in nodes_all:        
        if abs(x - float(node['x'])) <= radius and abs(y - float(node['y'])) <= radius:
            nodes_valid.append(node)
        continue
        
    nodes_valid_ids = [node['id'] for node in nodes_valid]
    
    # Now that we know the nodes, we can pick out valid edges that the node begins at
    edg_xml = purr.mrf(env.options.map_dir,r'*.edg.xml')
    edges_all = purr.readXMLtag(edg_xml,'edge')
    edges_filtered = purr.batchfilterdicts(edges_all,'from',nodes_valid_ids,show_progress=True)
    edges_filtered = purr.flattenlist(edges_filtered)
    edges_valid = []
    for edge in edges_filtered:
        if not ':' in edge['id']:
            edges_valid.append(edge)
    
    print("Found %d edge candidates." % (len(edges_valid)))
    
    return edges_valid
def initialize(traci):
    print("Initializing targets...",end='')
    # load the node target IDs from file.
    target_node_ids = []
    try:
        with open(env.options.targets,'r') as f:
            for line in f:
                if '%' in line:
                    continue
                target_node_ids.append(line.strip())
                continue
    except FileNotFoundError:
        print('\nCould not open "%s"' % (env.options.targets))
        sys.exit(1)
    
    # Then retrieve the nodes
    env.target_nodes = purr.flattenlist(purr.batchfilterdicts(env.nodes,'id',target_node_ids))
    
    # Mark the targets on the map
    for node in env.target_nodes:
        xy = (float(node['x']),float(node['y']))
        preprocess.add_radius_polygon(traci,xy,30,(255,0,255))
    
    # Add target dictionaries to the env
    for node in env.target_nodes:
        target = {
            'id':node['id'],
            'sampling times':[],
            'sampling vids':[]
        }
        env.targets.append(target)
        continue
    
    print("Complete!")
    return
Esempio n. 6
0
def get_assignments():
    print("\nGetting Nash Assignments.")
    start = purr.now()

    # Get assigments
    index = env.traci.vehicle.getIDCount() - 1
    t = env.nash_assigners[index].getAssignments()
    cDest = t[0]
    utilities = t[1]

    # Use this info to route.
    for x in range(env.nash_assigners[index].N):
        print('Veh=%d Tar=%.0f Util=%.3f' % (x, cDest[x], utilities[x]))

        veh = env.vehicles_active[x]
        path = dict()

        # Not worth the effort. Go home
        if np.isnan(cDest[x]):
            path['nids'] = nx.dijkstra_path(env.nx, veh['current edge']['to'],
                                            veh['destination node']['id'])
            path['nids'].insert(0, veh['current edge']['from'])
            path['weight'], path['eids'] = nxops.path_info(
                env.nx, path['nids'])

        # Otherwise, go to the target
        else:
            # Path veh --> target
            path_veh2tar = dict()
            tar = env.target_nodes[int(cDest[x])]
            path_veh2tar['nids'] = nx.dijkstra_path(env.nx,
                                                    veh['current edge']['to'],
                                                    tar['id'])
            path_veh2tar['nids'].insert(0, veh['current edge']['from'])
            path_veh2tar['weight'], path_veh2tar['eids'] = nxops.path_info(
                env.nx, path_veh2tar['nids'])

            # path target --> dest
            path_tar2dest = dict()
            path_tar2dest['nids'] = nx.dijkstra_path(
                env.nx, tar['id'], veh['destination node']['id'])
            path_tar2dest['weight'], path_tar2dest['eids'] = nxops.path_info(
                env.nx, path_tar2dest['nids'])

            # Combine together
            path['nids'] = purr.flattenlist(
                [path_veh2tar['nids'], path_tar2dest['nids']])
            path['weight'] = path_veh2tar['weight'] + path_tar2dest['weight']
            path['eids'] = purr.flattenlist(
                [path_veh2tar['eids'], path_tar2dest['eids']])

            # Update vehicle tracking data
            index = int(veh['id'][3:])
            env.vehicles[index]['target nid'] = tar['id']
            env.vehicles[index]['target eid'] = path['eids'][
                path['nids'].index(tar['id'])]
            env.vehicles[index]['diversion path length'] = path['weight']
            env.vehicles[index]['shortest path length'] = veh[
                'veh2dest weight']

        # Route the vehicle with traci
        env.traci.vehicle.setRoute(veh['id'], path['eids'])
        continue

    print("Complete after %.3f" % (purr.elapsed(start)))
    return
Esempio n. 7
0
def recalculate():
    env.recalculate_nash = False
    print()

    print("Retrieving spatial vehicle data...", end='')
    st = purr.now()
    vehicle.update_nash()
    print("Complete after %.3fs" % (purr.elapsed(st)))

    print("Recalculating target assignments...", end='')
    st = purr.now()
    N = len(env.vids_active) - 1
    # ~ N = 10
    env.nash_assigner = sysSim.nashAssigner(N=N,
                                            M=len(env.targets),
                                            R=200,
                                            tau=1,
                                            dist=env.dist)
    t = env.nash_assigner.getAssignments()
    print("Complete after %.3fs" % (purr.elapsed(st)))

    cDest = t[0]
    utilities = t[1]

    # ~ print('Assigining vehicles to new targets.')
    for x in range(env.nash_assigner.N):
        # ~ print('vehicle,target,utililty: (%d,%.0f,%.3f)'%(x,cDest[x],utilities[x]))

        veh = env.vehicles_active[x]
        path = dict()

        # Not worth the effort. Go home
        if np.isnan(cDest[x]):
            path['nids'] = nxops.dijkstra(env.nx, veh['current edge']['to'],
                                          veh['destination node']['id'])
            path['nids'].insert(0, veh['current edge']['from'])
            path['weight'], path['eids'] = nxops.path_info(
                env.nx, path['nids'])

        # Otherwise, go to the target
        else:
            # Path veh --> target
            path_veh2tar = dict()
            tar = env.target_nodes[int(cDest[x])]
            path_veh2tar['nids'] = nxops.dijkstra(env.nx,
                                                  veh['current edge']['to'],
                                                  tar['id'])
            path_veh2tar['nids'].insert(0, veh['current edge']['from'])
            path_veh2tar['weight'], path_veh2tar['eids'] = nxops.path_info(
                env.nx, path_veh2tar['nids'])

            # path target --> dest
            path_tar2dest = dict()
            path_tar2dest['nids'] = nxops.dijkstra(
                env.nx, tar['id'], veh['destination node']['id'])
            path_tar2dest['weight'], path_tar2dest['eids'] = nxops.path_info(
                env.nx, path_tar2dest['nids'])

            # Combine together
            path['nids'] = purr.flattenlist(
                [path_veh2tar['nids'], path_tar2dest['nids']])
            path['weight'] = path_veh2tar['weight'] + path_tar2dest['weight']
            path['eids'] = purr.flattenlist(
                [path_veh2tar['eids'], path_tar2dest['eids']])

            # Update vehicle tracking data
            index = int(veh['id'][3:])
            env.vehicles[index]['target nid'] = tar['id']
            env.vehicles[index]['target eid'] = path['eids'][
                path['nids'].index(tar['id'])]
            env.vehicles[index]['diversion path length'] = path['weight']

        # Route the vehicle with traci
        env.traci.vehicle.setRoute(veh['id'], path['eids'])
        continue

    # ~ print('Dijkstra: Calls=%d Time=%.3fs Avg=%.3fs' % (env.fs_dijkstra['calls'],env.fs_dijkstra['time'],env.fs_dijkstra['time']/env.fs_dijkstra['calls']))

    return
def main():
    map_dir = "../orlando-seg1/"

    # Load Nodes
    nod_xml = purr.mrf(map_dir, r'*.nod.xml')
    nodes = purr.readXMLtag(nod_xml, 'node')

    # Load Edges
    edg_xml = purr.mrf(map_dir, r'*edg.xml')
    edges = purr.readXMLtag(edg_xml, 'edge')

    # Correlate From/To Nodes with edges
    print('Finding Nodes From')
    nids_from = [edge['from'] for edge in edges]
    nodes_from = purr.flattenlist(
        purr.batchfilterdicts(nodes, 'id', nids_from, show_progress=True))

    print('\nFinding Nodes To')
    nids_to = [edge['to'] for edge in edges]
    nodes_to = purr.flattenlist(
        purr.batchfilterdicts(nodes, 'id', nids_to, show_progress=True))
    print()

    # Create the CSV for Nodes
    node_attr = [
        'id', 'x', 'y', 'z', 'type', 'tlType', 'tl', 'radius', 'keepClear',
        'rightOfWay'
    ]
    node_csv = 'node.csv'
    with open(node_csv, 'w') as csv:
        # Column Names
        csv.write(node_attr[0])
        for attr in node_attr[1:]:
            csv.write(',%s' % (attr))
        csv.write('\n')

        # Fill in rows
        n = 0
        total = len(nodes)
        for node in nodes:
            csv.write(node[node_attr[0]])
            for attr in node_attr[1:]:
                csv.write(',')
                try:
                    csv.write(node[attr])
                except KeyError:
                    pass
                continue
            csv.write('\n')
            n += 1
            purr.update(n, total, msg="Writing node.csv ")
            continue
        pass

    print()

    # Create the CSV for Edges
    edge_attr = [
        'id', 'from', 'to', 'type', 'numLanes', 'speed', 'priority',
        'spreadType', 'width', 'name', 'endOffset', 'sidewalkWidth'
    ]
    edge_allow = [
        'emergency', 'authority', 'passenger', 'hov', 'taxi', 'bus',
        'delivery', 'truck', 'trailer', 'motorcyle', 'moped'
    ]
    edge_csv = 'edge.csv'
    with open(edge_csv, 'w') as csv:
        # Column Names
        csv.write(edge_attr[0])
        for attr in edge_attr[1:]:
            csv.write(',%s' % (attr))
        csv.write(',length')
        for attr in edge_allow:
            csv.write(',%s' % (attr))
        csv.write('\n')

        # Fill in Rows
        n = 0
        total = len(edges)
        for i, edge in enumerate(edges):
            # id
            csv.write(edge[edge_attr[0]])

            # Attributes
            for attr in edge_attr[1:]:
                csv.write(',')
                try:
                    csv.write(edge[attr])
                except KeyError:
                    pass
                continue

            # Length
            try:
                csv.write(',%.3f' % (shape_len(edge['shape'])))
            except KeyError:
                x0 = float(nodes_from[i]['x'])
                y0 = float(nodes_from[i]['y'])
                x1 = float(nodes_to[i]['x'])
                y1 = float(nodes_to[i]['y'])
                csv.write(',%.3f' % (dist(x0, y0, x1, y1)))

            # Vehicle Types
            vtype_allowed = [0 for item in edge_allow]

            # Has neither tag. It is assumed that all vehicles are allowed.
            if (not purr.xml_has_atrribute(edge, 'allow')) and (
                    not purr.xml_has_atrribute(edge, 'disallow')):
                vtype_allowed = [1 for item in edge_allow]

            # Has the allow tag. Those specified are allowed
            elif (purr.xml_has_atrribute(edge, 'allow')):
                vtypes = edge['allow'].split(' ')
                for j, vt in enumerate(edge_allow):
                    if vt in vtypes:
                        edge_allow[j] = 1
                    continue

            # Lastly it has the dissalow tag, and what is not speficied is allowed
            elif (purr.xml_has_atrribute(edge, 'disallow')):
                vtype_allowed = [1 for item in edge_allow]
                vtypes = edge['allow'].split(' ')
                for j, vt in enumerate(edge_allow):
                    if vt in vtypes:
                        edge_allow[j] = 0
                    continue

            # ~ for j,vt in enumerate(edge_allow):
            # ~ print(edge_allow[j],vtype_allowed[j])

            for vt in vtype_allowed:
                csv.write(',%d' % (vt))
            csv.write('\n')

            n += 1
            purr.update(n, total, 'Writing edges.csv ')
            continue
        pass
        print('\nComplete.')
    return
Esempio n. 9
0
def add_baseline(traci):
    # Vehicle ID
    vid = "veh%d" % (env.veh_id_counter)
    env.veh_id_counter += 1

    # Selected a path. It must be have a conenction between spawn and sink
    ntrys = 0
    shortest_path = {
        'weight': None,
        'nids': None,
        'eids': None
    }
    while True:
        # Pick a random spawn and sink edge
        spawn_edge = random.choice(env.spawn_edge)
        sink_edge = random.choice(env.sink_edge)

        # Determine the shortest path
        try:
            shortest_path['nids'] = nx.dijkstra_path(env.nx,
                                                     spawn_edge['from'],
                                                     sink_edge['to'])
            break
        except nx.NetworkXNoPath:
            ntrys += 1
            print(
                "%s: Cannont create a path between %s and %s... Trying again (%d)."
                % (vid, spawn_edge['from'], sink_edge['to'], ntrys))
        continue

    # At this point, it is assumed that the path is connected
    # Now the weight of the path and the edge eids of the path is determined
    shortest_path['weight'], shortest_path['eids'] = nxops.path_info(
        env.nx, shortest_path['nids'])

    # display the spawn and sink destions
    spawn_node, sink_node = purr.flattenlist(
        purr.batchfilterdicts(
            env.nodes, 'id',
            [shortest_path['nids'][0], shortest_path['nids'][-1]]))
    spawn_point = (float(spawn_node['x']), float(spawn_node['y']))
    sink_point = (float(sink_node['x']), float(sink_node['y']))

    # Find the optimal target point to visit
    path = nxops.naive_target_selection(env.nx, shortest_path['nids'],
                                        env.target_nodes)

    # Create a route with the path eids
    rid = "route%d" % (env.route_id_counter)
    env.route_id_counter += 1
    traci.route.add(rid, path['path_eids'])

    # Add a vehicle
    traci.vehicle.add(vid, rid)

    # Determine the edge immediately after the node
    target_node_index = path['path_nids'].index(path['target_node']['id'])
    target_eid = path['path_eids'][target_node_index]

    # Create the vehicle dictionary
    veh = {
        "id": vid,
        "source": spawn_node['id'],
        "destination": sink_node['id'],
        "shortest path length": shortest_path['weight'],
        "diversion path length": path['weight'],
        "sample time": None,
        "target nid": path['target_node']['id'],
        "target eid": target_eid,
        "path": path
    }
    env.vehicles.append(veh)
    return