Beispiel #1
0
def write_ped(f, index, options, depart):
    if options.color is None:
        color = ''
    elif options.color == "random":
        color = ' color="%s"' % Colorgen(("random", 1, 1))()
    else:
        color = ' color="%s"' % options.color

    if options.trip is not None:
        edges = 'from="%s" to="%s"' % options.trip
    else:
        edges = 'edges="%s"' % ' '.join(options.route)

    f.write(('    <vType id="%s%s" vClass="pedestrian" width="%s" length="%s" minGap="%s" maxSpeed="%s" ' +
             'guiShape="pedestrian"%s/>\n') % (
        options.name, index,
        randomOrFixed(options.width),
        randomOrFixed(options.length),
        randomOrFixed(options.minGap),
        randomOrFixed(options.maxSpeed, 0.4), color))
    f.write('    <person id="%s%s" type="%s%s" depart="%s" departPos="%s">\n' %
            (options.name, index, options.name, index, depart, options.departPos))
    f.write('        <walk %s arrivalPos="%s"/>\n' %
            (edges, options.arrivalPos))
    f.write('    </person>\n')
Beispiel #2
0
def parse_args():
    USAGE = "Usage: " + sys.argv[0] + " <netfile> <routefile> [options]"
    optParser = OptionParser()
    optParser.add_option("-o", "--outfile", help="name of output file")
    optParser.add_option(
        "-u",
        "--hue",
        default="random",
        help="hue for polygons (float from [0,1] or 'random')")
    optParser.add_option(
        "-s",
        "--saturation",
        default=1,
        help="saturation for polygons (float from [0,1] or 'random')")
    optParser.add_option(
        "-b",
        "--brightness",
        default=1,
        help="brightness for polygons (float from [0,1] or 'random')")
    optParser.add_option("-l",
                         "--layer",
                         default=100,
                         help="layer for generated polygons")
    options, args = optParser.parse_args()
    try:
        options.net, options.routefile = args
        options.colorgen = Colorgen(
            (options.hue, options.saturation, options.brightness))
    except Exception:
        sys.exit(USAGE)
    if options.outfile is None:
        options.outfile = options.routefile + ".poly.xml"
    return options
Beispiel #3
0
def parse_args(args):
    USAGE = "Usage: " + sys.argv[0] + " <netfile> <routefile> [options]"
    optParser = OptionParser()
    optParser.add_option("-o", "--outfile", help="name of output file")
    optParser.add_option("-u", "--hue", default="random",
                         help="hue for polygons (float from [0,1] or 'random')")
    optParser.add_option("-s", "--saturation", default=1,
                         help="saturation for polygons (float from [0,1] or 'random')")
    optParser.add_option("-b", "--brightness", default=1,
                         help="brightness for polygons (float from [0,1] or 'random')")
    optParser.add_option(
        "-l", "--layer", default=100, help="layer for generated polygons")
    optParser.add_option("--geo", action="store_true",
                         default=False, help="write polgyons with geo-coordinates")
    optParser.add_option("--blur", type="float",
                         default=0, help="maximum random disturbance to route geometry")
    optParser.add_option("--standalone", action="store_true",
                         default=False, help="Parse stand-alone routes that are not define as child-element of a vehicle")
    options, args = optParser.parse_args(args=args)
    if len(args) < 2:
        sys.exit(USAGE)
    try:
        options.net = args[0]
        options.routefiles = args[1:]
        options.colorgen = Colorgen(
            (options.hue, options.saturation, options.brightness))
    except:
        sys.exit(USAGE)
    if options.outfile is None:
        options.outfile = options.routefiles[0] + ".poly.xml"
    return options
Beispiel #4
0
def fcd2poi(inpFCD, outSTRM, ignored):
    colors = defaultdict(
        lambda: RGBAColor(*Colorgen(("random", 1, 1)).byteTuple()))
    outSTRM.write("<pois>\n")
    for timestep in inpFCD:
        for v in timestep.vehicle:
            outSTRM.write("    %s\n" % PoI("%s_%s" % (
                v.id, timestep.time), v.id, LAYER, colors[v.id], v.x, v.y, lonLat=True).toXML())
    outSTRM.write("</pois>\n")
Beispiel #5
0
def write_ped(f, index, options, depart, edges):
    if options.color is None:
        color = ''
    elif options.color == "random":
        color = ' color="%s"' % Colorgen(("random", 1, 1))()
    else:
        color = ' color="%s"' % options.color

    f.write(
        '    <vType id="%s%s" vClass="pedestrian" width="%s" length="%s" minGap="%s" maxSpeed="%s" guiShape="pedestrian"%s/>\n'
        % (options.name, index, randomOrFixed(options.width),
           randomOrFixed(options.length), randomOrFixed(
               options.minGap), randomOrFixed(options.maxSpeed, 0.4), color))
    f.write('    <person id="%s%s" type="%s%s" depart="%s">\n' %
            (options.name, index, options.name, index, depart))
    f.write('        <walk edges="%s" departPos="%s" arrivalPos="%s"/>\n' %
            (edges, options.departPos, options.arrivalPos))
    f.write('    </person>\n')
Beispiel #6
0
def parse_args(args):
    USAGE = "Usage: " + sys.argv[0] + " <netfile> <routefile> [options]"
    optParser = OptionParser()
    optParser.add_option("-o", "--outfile", help="name of output file")
    optParser.add_option("-u", "--hue", default="random",
                         help="hue for polygons (float from [0,1] or 'random')")
    optParser.add_option("-s", "--saturation", default=1,
                         help="saturation for polygons (float from [0,1] or 'random')")
    optParser.add_option("-b", "--brightness", default=1,
                         help="brightness for polygons (float from [0,1] or 'random')")
    optParser.add_option("-l", "--layer", default=100, help="layer for generated polygons")
    optParser.add_option("--geo", action="store_true",
                         default=False, help="write polgyons with geo-coordinates")
    optParser.add_option("--internal", action="store_true",
                         default=False, help="include internal edges in generated shapes")
    optParser.add_option("--spread", type="float", help="spread polygons laterally to avoid overlap")
    optParser.add_option("--blur", type="float",
                         default=0, help="maximum random disturbance to route geometry")
    optParser.add_option("--scale-width", type="float", dest="scaleWidth",
                         help="group similar routes and scale width by " +
                              "group size multiplied with the given factor (in m)")
    optParser.add_option("--standalone", action="store_true", default=False,
                         help="Parse stand-alone routes that are not define as child-element of a vehicle")
    optParser.add_option("--filter-output.file", dest="filterOutputFile",
                         help="only write output for edges in the given selection file")
    optParser.add_option("--seed", type="int", help="random seed")
    options, args = optParser.parse_args(args=args)
    if options.seed:
        random.seed(options.seed)
    if len(args) < 2:
        sys.exit(USAGE)
    try:
        options.net = args[0]
        options.routefiles = args[1:]
        options.colorgen = Colorgen(
            (options.hue, options.saturation, options.brightness))
    except Exception:
        sys.exit(USAGE)
    if options.outfile is None:
        options.outfile = options.routefiles[0] + ".poly.xml"

    return options
def getOptions():
    optParser = OptionParser()
    optParser.add_option("-v", "--verbose", action="store_true", default=False,
                         help="tell me what you are doing")
    optParser.add_option("-n", "--net-file", dest="netfile", help="the network to read lane and edge permissions")
    optParser.add_option("-o", "--output", help="output taz file")
    optParser.add_option("-w", "--grid-width", dest="gridWidth", type="float", default=100.0,
                         help="width of gride cells in m")
    optParser.add_option("-u", "--hue", default="random",
                         help="hue for taz (float from [0,1] or 'random')")
    optParser.add_option("-s", "--saturation", default=1,
                         help="saturation for taz (float from [0,1] or 'random')")
    optParser.add_option("-b", "--brightness", default=1,
                         help="brightness for taz (float from [0,1] or 'random')")
    (options, args) = optParser.parse_args()
    if not options.netfile or not options.output:
        optParser.print_help()
        optParser.exit("Error! net-file and output file")
    options.colorgen = Colorgen((options.hue, options.saturation, options.brightness))
    return options
Beispiel #8
0
def main():
    DUAROUTER = sumolib.checkBinary('duarouter')
    options = get_options()
    net = readNet(options.network)

    routeInfos = {}  # id-> RouteInfo
    if options.standalone:
        for route in parse(options.routeFile, 'route'):
            ri = RouteInfo()
            ri.edges = route.edges.split()
            routeInfos[route.id] = ri
    else:
        for vehicle in parse(options.routeFile, 'vehicle'):
            ri = RouteInfo()
            ri.edges = vehicle.route[0].edges.split()
            routeInfos[vehicle.id] = ri

    for rInfo in routeInfos.values():
        rInfo.airDist = euclidean(
            net.getEdge(rInfo.edges[0]).getShape()[0],
            net.getEdge(rInfo.edges[-1]).getShape()[-1])
        rInfo.length = getRouteLength(net, rInfo.edges)
        rInfo.airDistRatio = rInfo.length / rInfo.airDist

    duarouterInput = options.routeFile
    if options.standalone:
        # generate suitable input file for duarouter
        duarouterInput += ".vehRoutes.xml"
        with open(duarouterInput, 'w') as outf:
            outf.write('<routes>\n')
            for rID, rInfo in routeInfos.items():
                outf.write('    <vehicle id="%s" depart="0">\n' % rID)
                outf.write('        <route edges="%s"/>\n' %
                           ' '.join(rInfo.edges))
                outf.write('    </vehicle>\n')
            outf.write('</routes>\n')

    duarouterOutput = options.routeFile + '.rerouted.rou.xml'
    duarouterAltOutput = options.routeFile + '.rerouted.rou.alt.xml'

    subprocess.call([
        DUAROUTER, '-n', options.network, '-r', duarouterInput, '-o',
        duarouterOutput, '--no-step-log'
    ])

    for vehicle in parse(duarouterAltOutput, 'vehicle'):
        routeAlts = vehicle.routeDistribution[0].route
        if len(routeAlts) == 1:
            routeInfos[vehicle.id].detour = 0
            routeInfos[vehicle.id].detourRatio = 1
            routeInfos[vehicle.id].shortest_path_distance = routeInfos[
                vehicle.id].length
        else:
            oldCosts = float(routeAlts[0].cost)
            newCosts = float(routeAlts[1].cost)
            assert (routeAlts[0].edges.split() == routeInfos[vehicle.id].edges)
            routeInfos[vehicle.id].shortest_path_distance = getRouteLength(
                net, routeAlts[1].edges.split())
            if oldCosts <= newCosts:
                routeInfos[vehicle.id].detour = 0
                routeInfos[vehicle.id].detourRatio = 1
                if oldCosts < newCosts:
                    sys.stderr.write((
                        "Warning: fastest route for '%s' is slower than original route "
                        + "(old=%s, new=%s). Check vehicle types\n") %
                                     (vehicle.id, oldCosts, newCosts))
            else:
                routeInfos[vehicle.id].detour = oldCosts - newCosts
                routeInfos[vehicle.id].detourRatio = oldCosts / newCosts

    implausible = []
    allRoutesStats = Statistics("overal implausiblity")
    implausibleRoutesStats = Statistics("implausiblity above threshold")
    for rID in sorted(routeInfos.keys()):
        ri = routeInfos[rID]
        ri.implausibility = (
            options.airdist_ratio_factor * ri.airDistRatio +
            options.detour_factor * ri.detour +
            options.detour_ratio_factor * ri.detourRatio +
            max(0, options.min_dist / ri.shortest_path_distance - 1) +
            max(0, options.min_air_dist / ri.airDist - 1))
        allRoutesStats.add(ri.implausibility, rID)
        if ri.implausibility > options.threshold:
            implausible.append((ri.implausibility, rID, ri))
            implausibleRoutesStats.add(ri.implausibility, rID)

    # generate restrictions
    if options.restrictions_output is not None:
        with open(options.restrictions_output, 'w') as outf:
            for score, rID, ri in sorted(implausible):
                edges = ri.edges
                if options.odrestrictions and len(edges) > 2:
                    edges = [edges[0], edges[-1]]
                outf.write("0 %s\n" % " ".join(edges))

    if options.ignore_routes is not None:
        numImplausible = len(implausible)
        ignored = set([r.strip() for r in open(options.ignore_routes)])
        implausible = [r for r in implausible if r not in ignored]
        print(
            "Loaded %s routes to ignore. Reducing implausible from %s to %s" %
            (len(ignored), numImplausible, len(implausible)))

    # generate polygons
    polyOutput = options.routeFile + '.implausible.add.xml'
    colorgen = Colorgen(("random", 1, 1))
    with open(polyOutput, 'w') as outf:
        outf.write('<additional>\n')
        for score, rID, ri in sorted(implausible):
            generate_poly(options, net, rID, colorgen(), ri.edges, outf, score)
        outf.write('</additional>\n')

    sys.stdout.write(
        'score\troute\t(airDistRatio, detourRatio, detour, shortestDist, airDist)\n'
    )
    for score, rID, ri in sorted(implausible):
        # , ' '.join(ri.edges)))
        sys.stdout.write('%.7f\t%s\t%s\n' %
                         (score, rID,
                          (ri.airDistRatio, ri.detourRatio, ri.detour,
                           ri.shortest_path_distance, ri.airDist)))

    print(allRoutesStats)
    print(implausibleRoutesStats)
Beispiel #9
0
def main():
    options = get_options()
    if options.verbose:
        print("parsing network from", options.network)
    net = readNet(options.network, withInternal=True)
    read = 0
    routeInfos = {}  # id-> RouteInfo
    skipped = set()
    for routeFile in options.routeFiles:
        if options.verbose:
            print("parsing routes from", routeFile)
        idx = 0
        if options.standalone:
            for idx, route in enumerate(parse(routeFile, 'route')):
                if options.verbose and idx > 0 and idx % 100000 == 0:
                    print(idx, "routes read")
                addOrSkip(routeInfos, skipped, route.id, route, options.min_edges)
        else:
            if options.heterogeneous:
                for idx, vehicle in enumerate(parse(routeFile, 'vehicle')):
                    if options.verbose and idx > 0 and idx % 100000 == 0:
                        print(idx, "vehicles read")
                    addOrSkip(routeInfos, skipped, vehicle.id, vehicle.route[0], options.min_edges)
            else:
                prev = (None, None)
                for vehicle, route in parse_fast_nested(routeFile, 'vehicle', 'id', 'route', 'edges'):
                    if prev[0] != vehicle.id:
                        if options.verbose and idx > 0 and idx % 500000 == 0:
                            print(idx, "vehicles read")
                        if prev[0] is not None:
                            addOrSkip(routeInfos, skipped, prev[0], prev[1], options.min_edges)
                        prev = (vehicle.id, route)
                        idx += 1
                if prev[0] is not None:
                    addOrSkip(routeInfos, skipped, prev[0], prev[1], options.min_edges)
        read += idx
    if options.verbose:
        print(read, "routes read", len(skipped), "short routes skipped")

    if options.verbose:
        print("calculating air distance and checking loops")
    for idx, ri in enumerate(routeInfos.values()):
        if options.verbose and idx > 0 and idx % 100000 == 0:
            print(idx, "routes checked")
        calcDistAndLoops(ri, net, options)

    prefix = os.path.commonprefix(options.routeFiles)
    duarouterOutput = prefix + '.rerouted.rou.xml'
    duarouterAltOutput = prefix + '.rerouted.rou.alt.xml'
    if os.path.exists(duarouterAltOutput) and options.reuse_routing:
        if options.verbose:
            print("reusing old duarouter file", duarouterAltOutput)
    else:
        if options.standalone:
            duarouterInput = prefix
            # generate suitable input file for duarouter
            duarouterInput += ".vehRoutes.xml"
            with open(duarouterInput, 'w') as outf:
                outf.write('<routes>\n')
                for rID, rInfo in routeInfos.items():
                    outf.write('    <vehicle id="%s" depart="0">\n' % rID)
                    outf.write('        <route edges="%s"/>\n' % ' '.join(rInfo.edges))
                    outf.write('    </vehicle>\n')
                outf.write('</routes>\n')
        else:
            duarouterInput = ",".join(options.routeFiles)

        command = [sumolib.checkBinary('duarouter'), '-n', options.network,
                   '-r', duarouterInput, '-o', duarouterOutput,
                   '--no-step-log', '--routing-threads', str(options.threads),
                   '--routing-algorithm', 'astar', '--aggregate-warnings',  '1']
        if options.verbose:
            command += ["-v"]
        if options.verbose:
            print("calling duarouter:", " ".join(command))
        subprocess.call(command)

    for vehicle in parse(duarouterAltOutput, 'vehicle'):
        if vehicle.id in skipped:
            continue
        routeAlts = vehicle.routeDistribution[0].route
        if len(routeAlts) == 1:
            routeInfos[vehicle.id].detour = 0
            routeInfos[vehicle.id].detourRatio = 1
            routeInfos[vehicle.id].shortest_path_distance = routeInfos[vehicle.id].length
        else:
            oldCosts = float(routeAlts[0].cost)
            newCosts = float(routeAlts[1].cost)
            assert(routeAlts[0].edges.split() == routeInfos[vehicle.id].edges)
            routeInfos[vehicle.id].shortest_path_distance = sumolib.route.getLength(net, routeAlts[1].edges.split())
            if oldCosts <= newCosts:
                routeInfos[vehicle.id].detour = 0
                routeInfos[vehicle.id].detourRatio = 1
                if oldCosts < newCosts:
                    sys.stderr.write(("Warning: fastest route for '%s' is slower than original route " +
                                      "(old=%s, new=%s). Check vehicle types\n") % (
                        vehicle.id, oldCosts, newCosts))
            else:
                routeInfos[vehicle.id].detour = oldCosts - newCosts
                routeInfos[vehicle.id].detourRatio = oldCosts / newCosts

    implausible = []
    allRoutesStats = Statistics("overall implausiblity")
    implausibleRoutesStats = Statistics("implausiblity above threshold")
    for rID in sorted(routeInfos.keys()):
        ri = routeInfos[rID]
        ri.implausibility = (options.airdist_ratio_factor * ri.airDistRatio +
                             options.detour_factor * ri.detour +
                             options.detour_ratio_factor * ri.detourRatio +
                             max(0, options.min_dist / ri.shortest_path_distance - 1) +
                             max(0, options.min_air_dist / ri.airDist - 1))
        allRoutesStats.add(ri.implausibility, rID)
        if ri.implausibility > options.threshold or ri.edgeLoop or ri.nodeLoop:
            implausible.append((ri.implausibility, rID, ri))
            implausibleRoutesStats.add(ri.implausibility, rID)

    # generate restrictions
    if options.restrictions_output is not None:
        with open(options.restrictions_output, 'w') as outf:
            for score, rID, ri in sorted(implausible):
                edges = ri.edges
                if options.odrestrictions and len(edges) > 2:
                    edges = [edges[0], edges[-1]]
                outf.write("0 %s\n" % " ".join(edges))

    # write xml output
    if options.xmlOutput is not None:
        with open(options.xmlOutput, 'w') as outf:
            sumolib.writeXMLHeader(outf, "$Id$", options=options)  # noqa
            outf.write('<implausibleRoutes>\n')
            for score, rID, ri in sorted(implausible):
                edges = " ".join(ri.edges)
                outf.write('    <route id="%s" edges="%s" score="%s"/>\n' % (
                    rID, edges, score))
            outf.write('</implausibleRoutes>\n')

    if options.ignore_routes is not None:
        numImplausible = len(implausible)
        ignored = set([r.strip() for r in open(options.ignore_routes)])
        implausible = [r for r in implausible if r not in ignored]
        print("Loaded %s routes to ignore. Reducing implausible from %s to %s" % (
            len(ignored), numImplausible, len(implausible)))

    # generate polygons
    polyOutput = prefix + '.implausible.add.xml'
    colorgen = Colorgen(("random", 1, 1))
    with open(polyOutput, 'w') as outf:
        outf.write('<additional>\n')
        for score, rID, ri in sorted(implausible):
            generate_poly(options, net, rID, colorgen(), ri.edges, outf, score)
        outf.write('</additional>\n')

    sys.stdout.write('score\troute\t(airDistRatio, detourRatio, detour, shortestDist, airDist, edgeLoop, nodeLoop)\n')
    for score, rID, ri in sorted(implausible):
        # , ' '.join(ri.edges)))
        sys.stdout.write('%.7f\t%s\t%s\n' % (score, rID, (ri.airDistRatio, ri.detourRatio,
                                                          ri.detour, ri.shortest_path_distance,
                                                          ri.airDist, ri.edgeLoop, ri.nodeLoop)))

    print(allRoutesStats)
    print(implausibleRoutesStats)