How to use the sumolib.output function in sumolib

To help you get started, we’ve selected a few sumolib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eclipse / sumo / tests / complex / sumo / max_depart / runner.py View on Github external
fdo = open("results.csv", "w")
for departPos in "random free random_free base pwagSimple pwagGeneric maxSpeedGap".split():
    print(">>> Building the routes (for departPos %s)" % departPos)
    fd = open("input_routes.rou.xml", "w")
    print("""
    
    
    
""" % (3 * (departPos, DEPARTSPEED, PERIOD)), file=fd)
    fd.close()

    print(">>> Simulating ((for departPos %s)" % departPos)
    call([sumoBinary, "-c", "sumo.sumocfg", "-v"])

    dump = sumolib.output.dump.readDump("aggregated.xml", ["entered"])
    print("%s;%s" % (departPos, dump.get("entered")[-1]["1si"]), file=fdo)

    if os.path.exists(departPos + "_aggregated.xml"):
        os.remove(departPos + "_aggregated.xml")
    os.rename("aggregated.xml", departPos + "_aggregated.xml")
fdo.close()
github eclipse / sumo / tests / complex / traffic_lights / loop_flow / evaluator.py View on Github external
rf2range = range(int(flow2def[0]), int(flow2def[1]), int(flow2def[2]))
rf2range.reverse()
for t in types:
    print("Processing outputs for %s" % t)
    durationM[t] = []
    waitStepsM[t] = []
    for f1 in rf1range:
        print(" f1 at %s" % f1)
        durationM[t].append([])
        waitStepsM[t].append([])
        for f2 in f2range:
            duration = 0
            waitSteps = 0
            vehNum = 0
            # summary
            pd = sumolib.output.parse(
                "results/tripinfos_%s_%s_%s.xml" % (t, f1, f2), "tripinfo")
            for v in pd:
                if float(v.depart) < 3600:
                    continue
                duration = duration + float(v.duration)
                waitSteps = waitSteps + float(v.waitSteps)
                vehNum = vehNum + 1
            if vehNum != 0:
                duration = duration / float(vehNum)
                waitSteps = waitSteps / float(vehNum)
            durationM[t][-1].append(duration)
            waitStepsM[t][-1].append(waitSteps)
            if duration > durationMinMax[1]:
                durationMinMax[1] = duration
            if waitSteps > waitStepsMinMax[1]:
                waitStepsMinMax[1] = waitSteps
github eclipse / sumo / tests / complex / sumo / extended / rerouter / runner.py View on Github external
t[0], t[1], t[2]))
            for multi in [True, False]:
                print("    Checking with multi-referenced routes: %s" % multi)
                for emb in [True, False]:
                    print(
                        "     Checking with embedded rerouter definition: %s" % emb)
                    writeRoutes(edge[1], multi)
                    writeRerouter(edge[0], t, r, emb)

                    sys.stdout.flush()
                    retcode = subprocess.call(
                        [sumoBinary, "-c", "sumo.sumocfg", "-b", str(t[0])], stdout=nd, stderr=sys.stderr)
                    sys.stdout.flush()
                    v = {}

                    vehroutes = list(sumolib.output.parse(
                        "vehroutes.xml", ["vehicle"], {'route': ['exitTimes', 'edges']}))

                    wvn = 10 - int((t[0] + 10) / 20)
                    if len(vehroutes) != wvn:
                        print(
                            "Mismatching number of vehicles (%s instead of %s)" % (len(vehroutes), wvn))

                    verify(vehroutes, edge[0])
                    try:
                        os.remove("vehroutes.xml")
                    except OSError:
                        pass
    nd.close()
github eclipse / sumo / tools / addStops2Routes.py View on Github external
def main(options):
    # with io.open(options.outfile, 'w', encoding="utf8") as outf:
    # with open(options.outfile, 'w', encoding="utf8") as outf:
    with open(options.outfile, 'w') as outf:
        net = sumolib.net.readNet(options.netfile)
        vtypes = readTypes(options)
        sumolib.writeXMLHeader(outf, "$Id: addStops2Routes.py v1_3_1+0411-36956f96df michael.behrisch@dlr.de 2019-09-21 21:10:12 +0200 $", "routes")  # noqa
        for file in options.routefiles.split(','):
            for veh in sumolib.output.parse(file, 'vehicle'):
                edgesList = veh.route[0].edges.split()
                lastEdge = net.getEdge(edgesList[-1])
                lanes = lastEdge.getLanes()
                for lane in lanes:
                    if lane.allows(vtypes[veh.type]):
                        stopAttrs = {"lane": lane.getID()}
                        if options.parking:
                            stopAttrs["parking"] = "true"
                        if options.duration:
                            stopAttrs["duration"] = options.duration
                        if options.until:
                            stopAttrs["until"] = options.until
                        veh.addChild("stop", attrs=stopAttrs)
                        break

                outf.write(veh.toXML(' '*4))
github eclipse / sumo / sumo / tools / visualization / plot_net_dump.py View on Github external
colorMeasure = options.measures.split(",")[0]
    if colorDump:
        if options.verbose:
            print("Reading colors from '%s'" % colorDump)
        hc = WeightsReader(colorMeasure)
        sumolib.output.parse_sax(colorDump, hc)
        times = hc._edge2value

    hw = None
    widthDump = options.dumps.split(",")[1]
    widthMeasure = options.measures.split(",")[1]
    if widthDump != "":
        if options.verbose:
            print("Reading widths from '%s'" % widthDump)
        hw = WeightsReader(widthMeasure)
        sumolib.output.parse_sax(widthDump, hw)
        times = hw._edge2value

    # Should we also save the figure to a file / list of files (comma
    # separated)? Then we need to check the output filename(s)
    if options.output:
        options.nolegend = True
        optOutputNames = options.output

        # If we have multiple intervals to be plotted, make sure we have
        # proper output filenames (with a %s as a placeholder in it)
        if len(times) > 1 and optOutputNames.find('%s') < 0:
            print('Warning: multiple time intervals detected, but ' +
                  'the output filename(s) do not contain a \'%s\' placeholder. ' +
                  'Continuing by using a default placeholder.')

            # Modify each filename by putting a '-%s' right before the
github eclipse / sumo / sumo / tools / output / vehroute2amitranOD.py View on Github external
def convert(vehRoutes, routeOut, odOut, interval):
    routeDict = {}
    actorConfig = defaultdict(list)  # map type -> list of time slices
    with open(routeOut, 'w') as routes:
        routes.write("\n")
        for v in sumolib.output.parse(vehRoutes, 'vehicle'):
            depart = float(v.depart)
            travelTime = float(v.arrival) - depart
            if hasattr(v, "routeDistribution"):
                edges = v.routeDistribution[0].route[-1].edges
            else:
                edges = v.route[0].edges
            ac = getattr(v, "type", "DEFAULT_VEHTYPE")
            if edges not in routeDict:
                idx = len(routeDict)
                routeDict[edges] = idx
                routes.write('    \n' % idx)
                for e in edges.split():
                    routes.write('        \n' % e)
                routes.write('    \n')
            else:
                idx = routeDict[edges]
github eclipse / sumo / sumo / tools / tlsCycleAdaptation.py View on Github external
def getFlows(net, routeFiles, tlsList, begin, verbose):
    tlsFlowsMap = {}
    end = begin + 3600
    for tls in tlsList:
        tlsFlowsMap[tls._id] = collections.defaultdict(lambda: collections.defaultdict(int))
    for file in routeFiles.split(','):
        if verbose:
            print ("route file:%s" % file)
        for veh in sumolib.output.parse(file, 'vehicle'):
            if float(veh.depart) >= end:
                break
            if float(veh.depart) >= begin:
                edgeList = veh.route[0].edges.split()
                for tls in tlsList:
                    # c: [[inLane, outLane, linkNo],[],..]
                    for c in tls.getConnections():
                        inEdge = c[0].getEdge().getID()
                        outEdge = c[1].getEdge().getID()
                        if inEdge in edgeList:
                            beginIndex = edgeList.index(inEdge)
                            if beginIndex < len(edgeList) - 1 and edgeList[beginIndex + 1] == outEdge:
                                pce = 1.
                                if veh.type == "bicycle":
                                    pce = 0.2
                                elif veh.type in ["moped", "motorcycle"]:
github eclipse / sumo / sumo / tools / route / tracegenerator.py View on Github external
optParser.exit("missing input or output")

    if options.verbose:
        print("Reading net ...")
    net = sumolib.net.readNet(options.net)
    net2 = None
    if options.net2:
        net.move(-net.getLocationOffset()[0], -net.getLocationOffset()[1])
        net2 = sumolib.net.readNet(options.net2)
        net2.move(-net2.getLocationOffset()[0], -net2.getLocationOffset()[1])

    if options.verbose:
        print("Reading routes ...")

    f = open(options.output, "w")
    for route in sumolib.output.parse_fast(options.routes, "vehicle", ["id", "edges"]):
        edges = [net.getEdge(e) for e in route.edges.split()]
        trace = generateTrace(edges, options.step)
        if net2:
            path = sumolib.route.mapTrace(trace, net2, options.delta)
            if not path or path == ["*"]:
                print("No match for", route.id)
            print(route.id, path, file=f)
        else:
            print("%s:%s" %
                  (route.id, " ".join(["%s,%s" % p for p in trace])), file=f)
    f.close()
github eclipse / sumo / sumo / tools / detector / validate.py View on Github external
totals[detId] += total
        if detId in sources:
            countIn += total
        if detId in sinks:
            countOut += total
print("detIn: %s detOut: %s" % (countIn, countOut))
totalSim = collections.defaultdict(int)
if options.validation:
    c.clear()
    v.clear()
    countIn = 0
    countOut = 0
    start = 0
    end = options.interval
#   
    for interval in sumolib.output.parse_fast(options.validation, "interval", ["begin", "id", "speed", "nVehEntered"]):
        detId = interval.id[11:]
        time = int(float(interval.begin) / 60)
        if time >= end:
            start = end
            end += options.interval
            for det, vals in sims.iteritems():
                if c[det] > 0:
                    vals.append((time, c[det], v[det] / c[det]))
            c.clear()
            v.clear()
        c[detId] += int(interval.nVehEntered)
        totalSim[detId] += int(interval.nVehEntered)
        v[detId] += 3.6 * int(interval.nVehEntered) * float(interval.speed)
        if detId in sources:
            countIn += int(interval.nVehEntered)
        if detId in sinks:
github eclipse / sumo / tools / visualization / plot_summary.py View on Github external
def readValues(files, verbose, measure):
    ret = {}
    for f in files:
        if verbose:
            print("Reading '%s'..." % f)
        ret[f] = sumolib.output.parse_sax__asList(f, "step", [measure])
    return ret