How to use the sumolib.net.readNet 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 / sumo / tools / net / netextract_subPart.py View on Github external
shape = edge.getShape()
        fd.write(" shape=\"")
        for i, c in enumerate(shape):
            if i != 0:
                fd.write(" ")
            fd.write(str(c[0]) + "," + str(c[1]))
        fd.write("\"")
        fd.write("/>\n")
    fd.write("\n")


if len(sys.argv) < 4:
    print("Usage: " + sys.argv[0] + "   ")
    sys.exit()
print("Reading net...")
net = sumolib.net.readNet(sys.argv[1])

edges = set()
nodes = set()
for n in sys.argv[3].split(","):
    n = net.getNode(n)
    nodes.add(n)
    for e in n._incoming:
        edges.add(e)
        nodes.add(e._from)
    for e in n._outgoing:
        edges.add(e)
        nodes.add(e._to)

net = sumolib.net.Net()
for e in edges:
    c = net.addEdge(e._id, e._from._id, e._to._id, e._priority, e._function)
github eclipse / sumo / tools / district / gridDistricts.py View on Github external
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


if __name__ == "__main__":
    options = getOptions()
    if options.verbose:
        print("Reading net")
    net = sumolib.net.readNet(options.netfile)
    xmin, ymin, xmax, ymax = net.getBoundary()
    odpairs = {}  # (x,y) -> TAZ
    centerCoords = {}  # edge -> center pos
    w = options.gridWidth
    w2 = w * 0.5 - 1
    for edge in net.getEdges():
        x, y = sumolib.geomhelper.positionAtShapeOffset(edge.getShape(True), edge.getLength() / 2)
        xIndex = int((x - xmin + w2) / w)
        yIndex = int((y - ymin + w2) / w)
        ii = (xIndex, yIndex)
        x2 = xIndex * w
        y2 = yIndex * w
        if ii not in odpairs:
            odpairs[ii] = TAZ("%s_%s" % (xIndex, yIndex),
                              [(x2 - w2, y2 - w2),
                               (x2 + w2, y2 - w2),
github eclipse / sumo / tools / route / tracegenerator.py View on Github external
optParser.add_option("-d", "--delta", default="1", type="float",
                         help="maximum distance between edge and trace points when matching to the second net")
    optParser.add_option("-x", "--x-offset", default=0.,
                         type="float", help="offset to add to traces")
    optParser.add_option("-y", "--y-offset", default=0.,
                         type="float", help="offset to add to traces")
    optParser.add_option("-o", "--output",
                         help="trace or route output (mandatory)", metavar="FILE")
    (options, args) = optParser.parse_args()

    if not options.output or not options.net or not options.routes:
        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, "route", ["id", "edges"]):
        edges = [net.getEdge(e) for e in route.edges.split()]
        trace = generateTrace(edges, options.step, options.x_offset, options.y_offset)
        if net2:
            path = sumolib.route.mapTrace(trace, net2, options.delta)
            if not path or path == ["*"]:
github eclipse / sumo / tools / projects / evacuation / generateTraffic.py View on Github external
def generate(netFile, mappedSiteFile, intersectionFile, tripFile):
    # EdgesInDistricts
    # evakuierungsbereich
    options = OptionParser()
    options.maxspeed = 1000.
    options.minspeed = 0.
    options.complete = False
    options.internal = False
    options.vclass = None
    options.assign_from = True
    options.verbose = False
    options.weighted = False
    options.shapeinfo = False
    options.output = "edgesInIntersections.taz.xml"
    net = sumolib.net.readNet(netFile)
    reader = EID.DistrictEdgeComputer(net)
    polyReader = sumolib.shapes.polygon.PolygonReader(True)
    parse(intersectionFile, polyReader)
    reader.computeWithin(polyReader.getPolygons(), options)
    reader.writeResults(options)

    # Evakuierungsziele
    options.output = "evacuationsiteEdges.taz.xml"
    reader = EID.DistrictEdgeComputer(net)
    polyReader = sumolib.shapes.polygon.PolygonReader(True)
    parse(mappedSiteFile, polyReader)
    reader.computeWithin(polyReader.getPolygons(), options)
    reader.writeResults(options)
    print("EdgesInDistricts - done")

    # O/D Matrix
github eclipse / sumo / sumo / tools / route / routeDiffStats.py View on Github external
def main():
    options = get_options()
    net = readNet(options.network)
    edges = set([e.getID() for e in net.getEdges()])

    lengths1 = {}
    lengths2 = {}
    lengthDiffStats = Statistics(
        "route length difference", histogram=True, scale=options.binwidth)
    for vehicle in parse(options.routeFile1, 'vehicle'):
        lengths1[vehicle.id] = getRouteLength(net, vehicle)
    for vehicle in parse(options.routeFile2, 'vehicle'):
        lengths2[vehicle.id] = getRouteLength(net, vehicle)
        lengthDiffStats.add(
            lengths2[vehicle.id] - lengths1[vehicle.id], vehicle.id)

    print(lengthDiffStats)

    if options.hist_output is not None:
github lcodeca / MoSTScenario / tools / mobility / intermodal.mobilitygen.py View on Github external
Initialize the synthetic population.
            :param conf: distionary with the configurations
            :param profiling=False: enable cProfile
        """

        self._conf = conf
        self._profiling = profiling

        self._random_generator = RandomState(seed=self._conf['seed'])

        logging.info('Starting TraCI with file %s.', conf['sumocfg'])
        sumocfg = '{}/{}'.format(BASE_DIR, conf['sumocfg'])
        traci.start(['sumo', '-c', sumocfg])

        logging.info('Loading SUMO net file %s%s', BASE_DIR, conf['SUMOnetFile'])
        self._sumo_network = sumolib.net.readNet(
            '{}/{}'.format(BASE_DIR, conf['SUMOnetFile']))

        logging.info('Loading SUMO parking lots from file %s%s',
                     BASE_DIR, conf['SUMOadditionals']['parkings'])
        self._load_parkings('{}/{}'.format(BASE_DIR, conf['SUMOadditionals']['parkings']))

        logging.info('Loading TAZ weights from %s%s',
                     BASE_DIR, conf['population']['tazWeights'])
        self._load_weights_from_csv(
            '{}/{}'.format(BASE_DIR, conf['population']['tazWeights']))

        logging.info('Loading buildings weights from %s%s',
                     BASE_DIR, conf['population']['buildingsWeight'])
        self._load_buildings_weight_from_csv_dir(
            '{}/{}'.format(BASE_DIR, conf['population']['buildingsWeight']))
github eclipse / sumo / sumo / tools / net / netcheck.py View on Github external
print("{} of {} edges are reachable from edge '{}':".format(
            len(found), len(net.getEdges()), source_id))

    ids = sorted([e.getID() for e in found])
    if options.selection_output:
        with open(options.selection_output, 'w') as f:
            for e in ids:
                f.write("edge:{}\n".format(e))
    else:
        print(ids)


if __name__ == "__main__":
    options = parse_args()

    net = sumolib.net.readNet(options.net)
    if options.source:
        getReachable(net, options.source, options)
    elif options.destination:
        getReachable(net, options.destination, options, True)
    else:
        components = getWeaklyConnected(
            net, options.vclass, options.ignore_connections)
        if len(components) != 1:
            print("Warning! Net is not connected.")

        total = 0
        max = 0
        max_idx = ""
        # Stores the distribution of components by edge counts - key: edge
        # counts - value: number found
        edge_count_dist = {}
github eclipse / sumo / tools / output / generateITetrisNetworkMetrics.py View on Github external
def getAvgNrLanesPerStreet(netfile):
    net = sumolib.net.readNet(netfile)
    nrLanes = 0
    for edge in net._edges:
        nrLanes += len(edge._lanes)

    return 1.0 * nrLanes / len(net._edges)