예제 #1
0
def validate():
    if not env.method == "validate.pts":
        return
    vPs = []
    vPd = []
    n = 0
    total = env.veh_total
    for i in range(2 * env.veh_total):
        try:
            vehicle.shortest_path(i)
            n += 1
            purr.update(n, total, "Gathering valid points ")
            vPs.append(env.vPs[i])
            vPd.append(env.vPd[i])
            if len(vPs) == env.veh_total:
                print("\nValid points determined. Exiting...")
                purr.save(env.valid_points_file, (vPs, vPd, env.tP))
                purr.save(env.status_file, True)
                sys.exit(0)
        except nx.NetworkXNoPath:
            pass
        continue
    print("Not good points, need to reload.")
    purr.save(env.status_file, False)
    sys.exit(0)
    return
def main():
    global OPTIONS
    OPTIONS = get_options()
    edg_xml = purr.mrf(OPTIONS.map_dir, r'*.edg.xml')
    edges = purr.readXMLtag(edg_xml, 'edge')

    original_edges = speedhist.load_edges()
    connections = speedhist.load_connections()

    fn = 'hhh.edg.xml'

    with open(fn, 'w') as f:
        f.write('<edges>')

        n = 0
        total = len(edges)
        for edge in edges:
            conn = purr.filterdicts(connections, 'ID', edge['id'])[0]
            child_edges = speedhist.get_edges(conn, original_edges)
            _sum = 0
            for ce in child_edges:
                _sum += ce['mean']
            speed = _sum / len(child_edges)

            f.write(
                '\n\t<edge id="%s" from="%s" to="%s" priority="%s" numLanes="%s" speed="%.3f"/>'
                % (edge['id'], edge['from'], edge['to'], edge['priority'],
                   edge['numLanes'], speed))

            n += 1
            purr.update(n, total)
            continue

        f.write('\n</edges>')
    return
예제 #3
0
def load_complete_spm():
    complete_spm_pybin = "temp/complete-spm.pybin"
    try:
        env.spm_complete = purr.load(complete_spm_pybin)
    except FileNotFoundError:
        nodes = list(env.nx.nodes)
        weights = []
        n = 0
        total = len(nodes) * len(nodes)
        for irow, rn in enumerate(nodes):
            row = []
            for icol, cn in enumerate(nodes):
                weight = float('inf')
                if not cn == rn:
                    weight = None
                row.append(weight)
                n += 1
                purr.update(n, total, "Generating Complete SPM...")
                continue
            weights.append(row)
            continue
        spm = {'colnames': nodes, 'rownames': nodes, 'weights': weights}
        env.spm_complete = spm
        purr.save(complete_spm_pybin, env.spm_complete)
    print("Complete!")
    return
예제 #4
0
def initialize(traci):
    os.system("cls")
    print("Initializing...")

    preprocess.initialize_nx()
    preprocess.initialize_edges_for_spawns_and_sinks(traci)
    target.initialize(traci)
    env.traci = traci
    vehicle.initialize()
    spm.generate_tar2dest()
    env.dist = distance.distance()

    n = 0
    total = env.veh_exists_max
    for i in range(0, env.veh_exists_max):
        vehicle.add()
        n += 1
        purr.update(n,
                    total,
                    msg="Adding first %d vehicles " % (env.veh_exists_max))
        continue

    # ~ env.update_vehicle_info = True

    print("Initialization complete!")
    return
def main():
    global OPTIONS
    OPTIONS = get_options()

    # Nodes
    nod_xml = purr.mrf(OPTIONS.map_dir, r'*.nod.xml')
    nodes = purr.readXMLtag(nod_xml, 'node')
    print("nodes: ", len(nodes))

    # Edges
    edg_xml = purr.mrf(OPTIONS.map_dir, r'*.edg.xml')
    edges = purr.readXMLtag(edg_xml, 'edge')
    print("edges: ", len(edges))

    # Load in Uber speed data
    original_edges = speedhist.load_edges()
    connections = speedhist.load_connections()

    with open(OPTIONS.output, 'w') as f:
        f.write("% from to weight id\n")

        # Each each is a connection
        n = 0
        total = len(edges)
        for edge in edges:
            # Edges with shape
            try:
                length = length_from_shape(edge['shape'])

            # Edges w/o shape
            except KeyError:
                node_from = purr.filterdicts(nodes, 'id', edge['from'])[0]
                node_to = purr.filterdicts(nodes, 'id', edge['to'])[0]
                length = length_from_nodes(node_from, node_to)

            # Determine Speed
            # ~ speed = float(edge['speed'])
            conn = purr.filterdicts(connections, 'ID', edge['id'])[0]
            child_edges = speedhist.get_edges(conn, original_edges)
            _sum = 0
            for ce in child_edges:
                _sum += ce['mean']
            speed = _sum / len(child_edges)

            f.write("%s %s %.3f %s\n" %
                    (edge['from'], edge['to'], length / speed, edge['id']))

            n += 1
            purr.update(n, total, msg="Calculating edge lengths ")
            continue
        pass
    print()

    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
예제 #7
0
def initialize():
    env.vehicles = [None for iveh in range(env.veh_total)]
    total = len(env.vehicles)
    for i, x in enumerate(env.vehicles):
        veh = vehdict()
        veh['id'] = 'veh%d' % (i)
        veh['shortest path'] = random_shortest_path()
        veh['source'] = veh['shortest path']['nids'][0]
        veh['destination'] = veh['shortest path']['nids'][-1]
        veh['shortest path length'] = veh['shortest path']['weight']
        env.vehicles[i] = veh
        purr.update(i+1,total,"Initializing Vehicles ")
    print()
    return
예제 #8
0
def main():
    global OPTIONS
    OPTIONS = get_options()

    # Nodes
    nod_xml = purr.mrf(OPTIONS.map_dir, r'*.nod.xml')
    nodes = purr.readXMLtag(nod_xml, 'node')
    print("nodes: ", len(nodes))

    # Edges
    edg_xml = purr.mrf(OPTIONS.map_dir, r'*.edg.xml')
    edges = purr.readXMLtag(edg_xml, 'edge')
    print("edges: ", len(edges))

    with open(OPTIONS.output, 'w') as f:
        f.write("% from to weight id\n")

        # Each each is a connection
        n = 0
        total = len(edges)
        for edge in edges:
            if edge['from'] == edge['to']:
                n += 1
                continue

            # Edges with shape
            try:
                length = length_from_shape(edge['shape'])

            # Edges w/o shape
            except KeyError:
                node_from = purr.filterdicts(nodes, 'id', edge['from'])[0]
                node_to = purr.filterdicts(nodes, 'id', edge['to'])[0]
                length = length_from_nodes(node_from, node_to)

            speed = float(edge['speed'])

            f.write("%s %s %.3f %s\n" %
                    (edge['from'], edge['to'], length / speed, edge['id']))

            n += 1
            purr.update(n, total, msg="Calculating edge lengths ")
            continue
        pass
    print()

    return
예제 #9
0
def initialize(traci):
    os.system("cls")
    print("Initializing...")
    
    trips = purr.readXMLtag(purr.mrf(env.map_dir,r"*.trips.xml"),"trip")
    
    total = len(trips) - 1
    print('Number of trips:',len(trips))
    for i,trip in enumerate(trips):
        veh = vehicle.Vehicle("veh%d" % (i))
        try:
            veh.add(traci,trip['from'],trip['to'],trip['depart'])
        except:
            pass
        env.vehicles.append(veh)
        purr.update(i,total)

    print("Initialization complete!")
    return
예제 #10
0
def generate(colnames, rownames):
    weights = []
    n = 0
    total = len(colnames) * len(rownames)
    for irow, rn in enumerate(rownames):
        row = []
        for icol, cn in enumerate(colnames):
            weight = float('inf')
            if not cn == rn:
                weight = nxops.path_info(env.nx,
                                         nx.dijkstra_path(env.nx, cn, rn))[0]
            row.append(weight)
            n += 1
            purr.update(n, total, "Generating SPM ")
            continue
        weights.append(row)
        continue
    spm = {'colnames': colnames, 'rownames': rownames, 'weights': weights}
    print()
    return spm
예제 #11
0
 def correlateNormalPoints2SumoNodes(self, P, msg=''):
     closestNode = [None for p in P]
     total = len(self.nodes) - 1
     for n, node in enumerate(self.nodes):
         nx = node['normX']
         ny = node['normY']
         for i, p in enumerate(P):
             px, py = p
             px = float(px)
             py = float(py)
             dist = math.sqrt(math.pow(nx - px, 2) + math.pow(ny - py, 2))
             if closestNode[i] == None or closestNode[i]['err'] > dist:
                 node['err'] = dist
                 closestNode[i] = node
             continue
         purr.update(n, total, msg)
         continue
     print()
     err = [node['err'] for node in closestNode]
     print("Mean err %.5f" % (statistics.mean(err)))
     return closestNode
예제 #12
0
def initialize():
    env.vehicles = [None for iveh in range(env.veh_total)]
    for i, item in enumerate(env.vehicles):
        veh = vehdict()
        veh['id'] = 'veh%d' % (i)
        try:
            veh['shortest path'] = shortest_path(i)
            
            # Starting points
            xy = (float(env.vPs[i]['x']),float(env.vPs[i]['y']))
            preprocess.add_radius_polygon(xy,50,(0,0,255),3)
            preprocess.add_radius_polygon(xy,10,(0,255,255),4)
            
             # Ending points
            xy = (float(env.vPd[i]['x']),float(env.vPd[i]['y']))
            preprocess.add_radius_polygon(xy,50,(255,0,0),3)
            preprocess.add_radius_polygon(xy,10,(255,255,0),4)        
        except nx.NetworkXNoPath:
            # Starting points
            xy0 = (float(env.vPs[i]['x']),float(env.vPs[i]['y']))
            preprocess.add_radius_polygon(xy0,50,(0,0,150),i+3)
            preprocess.add_radius_polygon(xy0,10,(0,150,150),i+4)
            
             # Ending points
            xy1 = (float(env.vPd[i]['x']),float(env.vPd[i]['y']))
            preprocess.add_radius_polygon(xy1,50,(150,0,0),i+3)
            preprocess.add_radius_polygon(xy1,10,(150,150,0),i+4)
            
            purr.save(env.status_file,False)
            print("\nPoints improperly placed.")
            sys.exit(0)
            pass
        veh['source'] = veh['shortest path']['nids'][0]
        veh['destination'] = veh['shortest path']['nids'][-1]
        veh['shortest path length'] = veh['shortest path']['weight']
        env.vehicles[i] = veh
        purr.update(i+1,env.veh_total,"Initializing vehicles ")
        continue

    return
예제 #13
0
def initialize(traci):
    os.system("cls")
    print("Initializing...")

    env.traci = traci
    preprocess.initialize_nx()
    preprocess.initialize_edges_and_nodes()
    point.validate()
    vehicle.initialize()
    target.initialize(traci)
    spm.generate_tar2dest()
    env.dist = distance.distance()

    n = 0
    total = env.veh_exists_max
    for i in range(0, env.veh_exists_max):
        vehicle.add()
        n += 1
        purr.update(n,
                    total,
                    msg="Adding first %d vehicles " % (env.veh_exists_max))
        continue
    print()

    vehicle.update()
    spm.update_veh2tar()
    env.nash_assigner = ss2.nashAssigner(N=len(env.vPd),
                                         M=len(env.tP),
                                         R=env.R,
                                         tau=env.tau,
                                         dist=env.dist)
    if env.method == "greedy":
        vehicle.set_route(env.nash_assigner.greedyAssignments())
    else:
        vehicle.set_route(env.nash_assigner.getAssignments())

    # ~ env.update_vehicle_info = True

    print("Initialization complete!")
    return
예제 #14
0
def cone_spread():
    cones = cone_target_region()
    target_node_candidates = []
    total = len(env.nodes) - 1
    for n, node in enumerate(env.nodes):
        x = float(node['x'])
        y = float(node['y'])
        for shape in cones:
            if purr.point_inside_polygon(x, y, shape):
                target_node_candidates.append(node)
                break
            continue
        purr.update(n, total, "Finding target node candidates ")
        continue
    print()
    print('Found %d target node candidates.' % (len(target_node_candidates)))
    if env.target_n > len(target_node_candidates):
        print(
            "Not enough nodes for requested target amount. Increase target.node.angle."
        )
        sys.exit(1)
    random.seed(env.seed)
    return random.sample(target_node_candidates, env.target_n)
예제 #15
0
def initialize(traci):
    os.system("cls")
    print("Initializing...")

    preprocess.initialize_nx()
    preprocess.initialize_shortest_path_weights()
    preprocess.initialize_edges_for_spawns_and_sinks(traci)
    target.initialize(traci)

    n = 0
    total = env.veh_exists_max
    for i in range(0, env.veh_exists_max):
        vehicle.add(traci)
        n += 1
        purr.update(n,
                    total,
                    msg="Adding first %d vehicles " % (env.veh_exists_max))
        continue

    if env.method == 'nash':
        env.dist = distance()

    print("Initialization complete!")
    return
예제 #16
0
def update():
    env.update_vehicle_info = False
    
    # Clean out the old object 
    env.vehicles_active = []
    
    # Refill 
    total = len(env.vehicles)
    for i,v in enumerate(env.vehicles):
        veh = dict()
            
        # Who am I?
        veh['id'] = v['id']
        
        # Where am I?
        veh['route index'] = env.traci.vehicle.getRouteIndex(veh['id'])
        
        # What is my route?
        veh['route id'] = env.traci.vehicle.getRouteID(veh['id'])
        
        # What is my sink node?
        veh['destination node'] = env.vehicles_dest[int(veh['id'][3:])]
        
        if veh['route index'] < 0:
            veh['route index'] = 0
            veh['position on edge (m)'] = 0.000001
            eid = env.traci.route.getEdges(veh['route id'])[0]
        else:
        
            # How far along the edge am I (m)?
            veh['position on edge (m)'] = env.traci.vehicle.getLanePosition(veh['id'])
            
            # What edge am I on?
            eid = env.traci.vehicle.getRoadID(veh['id'])
        
        # Obtain the edge object. Here we can have two cases:
        #  1. veh is at an intersection
        #  2. veh is on an edg
        
        # Veh is within an intersection. Assume the start of the next edge with a position on edge (m) of zero.
        if ':' in eid:
            veh['route'] = env.traci.route.getEdges(veh['route id'])
            eid = veh['route'][veh['route index']+1]
            veh['current edge'] = purr.filterdicts(env.edges,'id',eid)[0]
            veh['position on edge (m)'] = 0.000001
        else:
            veh['current edge'] = purr.filterdicts(env.edges,'id',eid)[0]
            
        # How far am I along the edge (weight)
        veh['position on edge (s)'] = veh['position on edge (m)'] / float(veh['current edge']['speed'])
            
        # How much weight to the end of the edge?
        edge_candidates = env.nx.get_edge_data(veh['current edge']['from'],veh['current edge']['to'])
        for j in range(len(edge_candidates)):
            if veh['current edge']['id'] == edge_candidates[j]['id']:
                veh['weight remaining'] = edge_candidates[j]['weight'] - veh['position on edge (s)']
                break
            continue
            
        # What is the weight of Veh --> Dest
        veh['veh2dest weight'] = veh['weight remaining'] + nxops.path_info(env.nx,nx.dijkstra_path(env.nx,veh['current edge']['to'],veh['destination node']['id']))[0]

        env.vehicles_active.append(veh)
        
        purr.update(i+1,total,"Updating vehicle location data ")
        # ~ env.recalculate_nash = True
        continue
    print()
    return
예제 #17
0
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