コード例 #1
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    optParser.add_option("-w", "--width", dest="width",
                         type="float", default=20, help="Defines the width of the dots")
    optParser.add_option("-c", "--color", dest="color",
                         default='r', help="Defines the dot color")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=1, help="Defines the edge width")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='k', help="Defines the edge color")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net is None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    tlsn = {}
    for tid in net._id2tls:
        t = net._id2tls[tid]
        tlsn[tid] = set()
        for c in t._connections:
            n = c[0].getEdge().getToNode()
            tlsn[tid].add(n)

    tlspX = []
    tlspY = []
    for tid in tlsn:
        x = 0
        y = 0
        n = 0
        for node in tlsn[tid]:
            x += node._coord[0]
            y += node._coord[1]
            n = n + 1
        x = x / n
        y = y / n
        tlspX.append(x)
        tlspY.append(y)

    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, {}, {}, options)
    plt.plot(tlspX, tlspY, options.color, linestyle='.',
             marker='o', markersize=options.width)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #2
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    optParser.add_option("-w", "--width", dest="width",
                         type="float", default=20, help="Defines the width of the dots")
    optParser.add_option("-c", "--color", dest="color",
                         default='r', help="Defines the dot color")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=1, help="Defines the edge width")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='k', help="Defines the edge color")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print "Error: a network to load must be given."
        return 1
    if options.verbose:
        print "Reading network from '%s'" % options.net
    net = sumolib.net.readNet(options.net)

    tlsn = {}
    for tid in net._id2tls:
        t = net._id2tls[tid]
        tlsn[tid] = set()
        for c in t._connections:
            n = c[0].getEdge().getToNode()
            tlsn[tid].add(n)

    tlspX = []
    tlspY = []
    for tid in tlsn:
        x = 0
        y = 0
        n = 0
        for node in tlsn[tid]:
            x += node._coord[0]
            y += node._coord[1]
            n = n + 1
        x = x / n
        y = y / n
        tlspX.append(x)
        tlspY.append(y)

    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, {}, {}, options)
    plt.plot(tlspX, tlspY, options.color, linestyle='.',
             marker='o', markersize=options.width)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #3
0
ファイル: plot_csv_pie.py プロジェクト: aarongolliver/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i", "--input", dest="input", metavar="FILE",
                         help="Defines the csv file to use as input")
    optParser.add_option("-p", "--percentage", dest="percentage", action="store_true",
                         default=False, help="Interprets read measures as percentages")
    optParser.add_option("-r", "--revert", dest="revert", action="store_true",
                         default=False, help="Reverts the order of read values")
    optParser.add_option("--no-labels", dest="nolabels", action="store_true",
                         default=False, help="Does not plot the labels")
    optParser.add_option("--shadow", dest="shadow", action="store_true",
                         default=False, help="Puts a shadow below the circle")
    optParser.add_option("--startangle", dest="startangle",
                         type="float", default=0, help="Sets the start angle")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.input == None:
        print("Error: at least one csv file must be given")
        sys.exit(1)

    fd = open(options.input)
    labels = []
    vals = []
    total = 0
    for line in fd:
        v = line.strip().split(";")
        if len(v) < 2:
            continue
        labels.append(v[0].replace("\\n", "\n"))
        vals.append(float(v[1]))
        total += float(v[1])

    if options.revert:
        labels.reverse()
        vals.reverse()
    colors = []
    for i, e in enumerate(labels):
        colors.append(helpers.getColor(options, i, len(labels)))

    fig, ax = helpers.openFigure(options)
    if options.nolabels:
        labels = None
    shadow = options.shadow
    if options.percentage:
        autopct = lambda p: '{:.1f}%'.format(p)
    else:
        autopct = lambda p: '{:.0f}'.format(p * total / 100)
    patches, texts, autotexts = plt.pie(
        vals, labels=labels, autopct=autopct, colors=colors, shadow=shadow, startangle=options.startangle)
    helpers.closeFigure(fig, ax, options)
コード例 #4
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i", "--input", dest="input", metavar="FILE",
                         help="Defines the csv file to use as input")
    optParser.add_option("-p", "--percentage", dest="percentage", action="store_true",
                         default=False, help="Interprets read measures as percentages")
    optParser.add_option("-r", "--revert", dest="revert", action="store_true",
                         default=False, help="Reverts the order of read values")
    optParser.add_option("--no-labels", dest="nolabels", action="store_true",
                         default=False, help="Does not plot the labels")
    optParser.add_option("--shadow", dest="shadow", action="store_true",
                         default=False, help="Puts a shadow below the circle")
    optParser.add_option("--startangle", dest="startangle",
                         type="float", default=0, help="Sets the start angle")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.input == None:
        print("Error: at least one csv file must be given")
        sys.exit(1)

    fd = open(options.input)
    labels = []
    vals = []
    total = 0
    for line in fd:
        v = line.strip().split(";")
        if len(v) < 2:
            continue
        labels.append(v[0].replace("\\n", "\n"))
        vals.append(float(v[1]))
        total += float(v[1])

    if options.revert:
        labels.reverse()
        vals.reverse()
    colors = []
    for i, e in enumerate(labels):
        colors.append(helpers.getColor(options, i, len(labels)))

    fig, ax = helpers.openFigure(options)
    if options.nolabels:
        labels = None
    shadow = options.shadow
    if options.percentage:
        autopct = lambda p: '{:.1f}%'.format(p)
    else:
        autopct = lambda p: '{:.0f}'.format(p * total / 100)
    patches, texts, autotexts = plt.pie(
        vals, labels=labels, autopct=autopct, colors=colors, shadow=shadow, startangle=options.startangle)
    helpers.closeFigure(fig, ax, options)
コード例 #5
0
ファイル: plt_single_summary.py プロジェクト: chunyulin/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input")
    helpers.addInteractionOptions(optParser)
    #helpers.addPlotOptions(optParser)
    options, _ = optParser.parse_args(args=args)

    #<step time="0.50" loaded="24" inserted="23" running="23" waiting="1" ended="0" arrived="0" collisions="0" teleports="0" halting="0" stopped="0" #meanWaitingTime="0.07" meanTravelTime="-1.00" meanSpeed="17.18" meanSpeedRelative="0.89" duration="368879895"/>

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    files = options.summary.split(",")

    cols = [
        "time", "loaded", "inserted", "running", "ended", "arrived",
        "collisions", "teleports", "halting", "stopped", "meanWaitingTime",
        "meanTravelTime", "meanSpeed", "meanSpeedRelative"
    ]

    d = []
    for data in sumolib.xml.parse_fast(files[0], "step", cols):
        d.append([float(x) for x in data])
    d = np.array(d)
    t = d[:, 0]

    plt.figure()

    plt.clf()
    plt.plot(t, d[:, 3], label=cols[3])
    plt.plot(t, d[:, 8], label=cols[8])
    plt.plot(t, d[:, 9], label=cols[9])
    plt.plot(t, d[:, 6], label=cols[6])
    plt.plot(t, d[:, 7], label=cols[7])
    plt.xlabel("Time/s")
    plt.legend()
    plt.savefig("summ_number.jpg")

    plt.clf()
    plt.plot(t, d[:, 10], label=cols[10])
    plt.plot(t, d[:, 11], label=cols[11])
    plt.plot(t, d[:, 12], label=cols[12])
    plt.xlabel("Time/s")
    plt.legend()
    plt.savefig("summ_time.jpg")
コード例 #6
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i",
                         "--input",
                         dest="input",
                         metavar="FILE",
                         help="Defines the input file to use")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    optParser.add_option("-c",
                         "--columns",
                         dest="columns",
                         default=None,
                         help="Defines which columns shall be plotted")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, _ = optParser.parse_args(args=args)

    if options.input is None:
        print("Error: an input file must be given")
        sys.exit(1)

    minV = 0
    maxV = 0
    if options.columns is not None:
        options.columns = [int(i) for i in options.columns.split(",")]
    nums = readValues(options.input, options.verbose, options.columns)
    for f in nums:
        maxV = max(maxV, len(nums[f]))
    ts = range(minV, maxV + 1)

    fig, ax = helpers.openFigure(options)
    for i in nums:
        v = nums[i]
        ci = i
        if options.columns is not None:
            ci = options.columns.index(i)
        c = helpers.getColor(options, ci, len(nums))
        plt.plot(ts[0:len(v)],
                 v,
                 label=helpers.getLabel(str(i), ci, options),
                 color=c)
    helpers.closeFigure(fig, ax, options)
コード例 #7
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    optParser.add_option("-m",
                         "--measure",
                         dest="measure",
                         default="running",
                         help="Define which measure to plot")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    minV = 0
    maxV = 0
    files = options.summary.split(",")
    nums = readValues(files, options.verbose, options.measure)
    times = readValues(files, options.verbose, "time")
    for f in files:
        maxV = max(maxV, len(nums[f]))
    ts = range(minV, maxV + 1)

    fig, ax = helpers.openFigure(options)
    for i, f in enumerate(files):
        v = sumolib.output.toList(nums[f], options.measure)
        t = sumolib.output.toList(times[f], "time")
        c = helpers.getColor(options, i, len(files))
        l = helpers.getLabel(f, i, options)
        plt.plot(t, v, label=l, color=c)
    helpers.closeFigure(fig, ax, options)
コード例 #8
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--selection", dest="selection", metavar="FILE",
                         help="Defines the selection to read")
    optParser.add_option("--selected-width", dest="selectedWidth",
                         type="float", default=1, help="Defines the width of selected edges")
    optParser.add_option("--color", "--selected-color", dest="selectedColor",
                         default='r', help="Defines the color of selected edges")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=.2, help="Defines the width of not selected edges")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='#606060', help="Defines the color of not selected edges")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.selection == None:
        print("Error: a selection to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)
    selection = sumolib.files.selection.read(options.selection)

    colors = {}
    widths = {}
    for e in selection["edge"]:
        colors[e] = options.selectedColor
        widths[e] = options.selectedWidth

    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, colors, widths, options)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #9
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--selection", dest="selection", metavar="FILE",
                         help="Defines the selection to read")
    optParser.add_option("--selected-width", dest="selectedWidth",
                         type="float", default=1, help="Defines the width of selected edges")
    optParser.add_option("--color", "--selected-color", dest="selectedColor",
                         default='r', help="Defines the color of selected edges")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=.2, help="Defines the width of not selected edges")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='#606060', help="Defines the color of not selected edges")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.selection == None:
        print("Error: a selection to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)
    selection = sumolib.files.selection.read(options.selection)

    colors = {}
    widths = {}
    for e in selection["edge"]:
        colors[e] = options.selectedColor
        widths[e] = options.selectedWidth

    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, colors, widths, options)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #10
0
ファイル: plot_summary.py プロジェクト: planetsumo/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser

    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input",
    )
    optParser.add_option(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="If set, the script says what it's doing",
    )
    optParser.add_option("-m", "--measure", dest="measure", default="running", help="Define which measure to plot")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.summary == None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    minV = 0
    maxV = 0
    files = options.summary.split(",")
    nums = readValues(files, options.verbose, options.measure)
    for f in files:
        maxV = max(maxV, len(nums[f]))
    ts = range(minV, maxV + 1)

    fig, ax = helpers.openFigure(options)
    for i, f in enumerate(files):
        v = sumolib.output.toList(nums[f], options.measure)
        c = helpers.getColor(options, i, len(files))
        l = helpers.getLabel(f, i, options)
        plt.plot(ts[0 : len(v)], v, label=l, color=c)
    helpers.closeFigure(fig, ax, options)
コード例 #11
0
ファイル: color_zones.py プロジェクト: vshekar/sumo_sim
def main():
    args = []
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--selection", dest="selection", metavar="FILE",
                         help="Defines the selection to read")
    optParser.add_option("--selected-width", dest="selectedWidth",
                         type="float", default=1, help="Defines the width of selected edges")
    optParser.add_option("--color", "--selected-color", dest="selectedColor",
                         default='r', help="Defines the color of selected edges")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=.2, help="Defines the width of not selected edges")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='#606060', help="Defines the color of not selected edges")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    
    options, remaining_args = optParser.parse_args(args=args)
    
    net = sumolib.net.readNet('../network/nyc.net.xml')
    selections = []
    color_list = ['r','g','b','c','m','y','b']
    
    colors = {}
    widths = {}

    zone_path = '../network'
    zone_files = [os.path.join(zone_path,f) for f in os.listdir(zone_path) if 'zone' in f]
    print(zone_files)

    for zone in zone_files:
        selections.append(sumolib.files.selection.read(zone))

    for i,selection in enumerate(selections):
        for e in selection["edge"]:
            colors[e] = color_list[i%7]
            widths[e] = 0.5
    
    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, colors, widths, options)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #12
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser

    optParser = OptionParser()
    optParser.add_option("-i", "--input", dest="input", metavar="FILE", help="Defines the input file to use")
    optParser.add_option(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="If set, the script says what it's doing",
    )
    optParser.add_option("-c", "--columns", dest="columns", default=None, help="Defines which columns shall be plotted")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.input == None:
        print("Error: an input file must be given")
        sys.exit(1)

    minV = 0
    maxV = 0
    if options.columns != None:
        options.columns = [int(i) for i in options.columns.split(",")]
    nums = readValues(options.input, options.verbose, options.columns)
    for f in nums:
        maxV = max(maxV, len(nums[f]))
    ts = range(minV, maxV + 1)

    fig, ax = helpers.openFigure(options)
    for i in nums:
        v = nums[i]
        ci = i
        if options.columns != None:
            ci = options.columns.index(i)
        c = helpers.getColor(options, ci, len(nums))
        l = helpers.getLabel(str(i), ci, options)
        plt.plot(ts[0 : len(v)], v, label=l, color=c)
    helpers.closeFigure(fig, ax, options)
コード例 #13
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    optParser.add_option("-m",
                         "--measure",
                         dest="measure",
                         default="running",
                         help="Define which measure to plot")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, _ = optParser.parse_args(args=args)

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    files = options.summary.split(",")
    fig, ax = helpers.openFigure(options)
    for i, f in enumerate(files):
        t = []
        v = []
        for time, val in sumolib.xml.parse_fast(f, "step",
                                                ("time", options.measure)):
            t.append(sumolib.miscutils.parseTime(time))
            v.append(float(val))
        c = helpers.getColor(options, i, len(files))
        plt.plot(t, v, label=helpers.getLabel(f, i, options), color=c)
    helpers.closeFigure(fig, ax, options)
コード例 #14
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    optParser.add_option("-w", "--width", dest="width",
                         type="float", default=20, help="Defines the width of the dots")
    optParser.add_option("-c", "--color", dest="color",
                         default='r', help="Defines the dot color")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=1, help="Defines the edge width")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='k', help="Defines the edge color")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net is None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)
 
    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, {}, {}, options)

    ax.set_xticklabels('')
    ax.set_yticklabels('')

    fig.patch.set_visible(False)
    ax.axis('off')

    #fig.set_size_inches(4.5, 3.5)  
    #fig.savefig('cenario.eps', bbox_inches = 'tight', pad_inches = 0.05, transparent=True)
    plt.show()
コード例 #15
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--tripinfos-inputs",
        dest="tripinfos",
        metavar="FILE",
        help="Defines the tripinfo-output files to use as input")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    optParser.add_option("-m",
                         "--measure",
                         dest="measure",
                         default="duration",
                         help="Define which measure to plot")
    optParser.add_option("--bins",
                         dest="bins",
                         type="int",
                         default=20,
                         help="Define the bin number")
    optParser.add_option("--norm",
                         dest="norm",
                         type="float",
                         default=1.,
                         help="Read values will be devided by this number")
    optParser.add_option("--minV",
                         dest="minV",
                         type="float",
                         default=None,
                         help="Define the minimum value boundary")
    optParser.add_option("--maxV",
                         dest="maxV",
                         type="float",
                         default=None,
                         help="Define the maximum value boundary")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.tripinfos == None:
        print "Error: at least one tripinfo file must be given"
        sys.exit(1)

    minV = options.minV
    maxV = options.maxV
    files = options.tripinfos.split(",")
    values = {}
    for f in files:
        if options.verbose:
            print "Reading '%s'..." % f
        nums = sumolib.output.parse_sax__asList(f, "tripinfo",
                                                [options.measure])
        fvp = sumolib.output.toList(nums, options.measure)
        fv = [x / options.norm for x in fvp]
        sumolib.output.prune(fv, options.minV, options.maxV)

        values[f] = fv
        if minV == None:
            minV = fv[0]
            maxV = fv[0]
        minV = min(minV, min(fv))
        maxV = max(maxV, max(fv))

    hists = {}
    binWidth = (maxV - minV) / float(options.bins)
    for f in files:
        h = [0] * options.bins
        for v in values[f]:
            i = min(int((v - minV) / binWidth), options.bins - 1)
            h[i] = h[i] + 1
        hists[f] = h

    width = binWidth / float(len(files)) * .8
    offset = binWidth * .1
    center = []
    for j in range(0, options.bins):
        center.append(binWidth * j + offset)

    fig, ax = helpers.openFigure(options)
    for i, f in enumerate(files):
        c = helpers.getColor(options, i, len(files))
        l = helpers.getLabel(f, i, options)
        plt.bar(center, hists[f], width=width, label=l, color=c)
        for j in range(0, options.bins):
            center[j] = center[j] + width
    helpers.closeFigure(fig, ax, options)
コード例 #16
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n",
                         "--net",
                         dest="net",
                         metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i",
                         "--dump-inputs",
                         dest="dumps",
                         metavar="FILE",
                         help="Defines the dump-output files to use as input")
    optParser.add_option("-m",
                         "--measures",
                         dest="measures",
                         default="speed,entered",
                         help="Define which measure to plot")
    optParser.add_option("--min-width",
                         dest="minWidth",
                         type="float",
                         default=.5,
                         help="Defines the minimum edge width")
    optParser.add_option("--max-width",
                         dest="maxWidth",
                         type="float",
                         default=3,
                         help="Defines the maximum edge width")
    optParser.add_option("--log-colors",
                         dest="logColors",
                         action="store_true",
                         default=False,
                         help="If set, colors are log-scaled")
    optParser.add_option("--log-widths",
                         dest="logWidths",
                         action="store_true",
                         default=False,
                         help="If set, widths are log-scaled")
    optParser.add_option("--min-color-value",
                         dest="colorMin",
                         type="float",
                         default=None,
                         help="If set, defines the minimum edge color value")
    optParser.add_option("--max-color-value",
                         dest="colorMax",
                         type="float",
                         default=None,
                         help="If set, defines the maximum edge color value")
    optParser.add_option("--min-width-value",
                         dest="widthMin",
                         type="float",
                         default=None,
                         help="If set, defines the minimum edge width value")
    optParser.add_option("--max-width-value",
                         dest="widthMax",
                         type="float",
                         default=None,
                         help="If set, defines the maximum edge width value")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    helpers.addNetOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    if options.measures == None:
        print("Error: a dump file must be given.")
        return 1

    times = []
    hc = None
    if options.dumps.split(",")[0] != "":
        if options.verbose:
            print("Reading colors from '%s'" % options.dumps.split(",")[0])
        hc = WeightsReader(options.measures.split(",")[0])
        sumolib.output.parse_sax(options.dumps.split(",")[0], hc)
        times = hc._edge2value

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

    for t in times:
        colors = {}
        maxColorValue = None
        minColorValue = None
        for e in net._id2edge:
            if hc and t in hc._edge2value and e in hc._edge2value[t]:
                if options.colorMax != None and hc._edge2value[t][
                        e] > options.colorMax:
                    hc._edge2value[t][e] = options.colorMax
                if options.colorMin != None and hc._edge2value[t][
                        e] < options.colorMin:
                    hc._edge2value[t][e] = options.colorMin
                if maxColorValue == None or maxColorValue < hc._edge2value[t][
                        e]:
                    maxColorValue = hc._edge2value[t][e]
                if minColorValue == None or minColorValue > hc._edge2value[t][
                        e]:
                    minColorValue = hc._edge2value[t][e]
                colors[e] = hc._edge2value[t][e]
        if options.colorMax != None:
            maxColorValue = options.colorMax
        if options.colorMin != None:
            minColorValue = options.colorMin
        if options.logColors:
            helpers.logNormalise(colors, maxColorValue)
        else:
            helpers.linNormalise(colors, minColorValue, maxColorValue)
        for e in colors:
            colors[e] = helpers.getColor(options, colors[e], 1.)
        if options.verbose:
            print("Color values are between %s and %s" %
                  (minColorValue, maxColorValue))

        widths = {}
        maxWidthValue = None
        minWidthValue = None
        for e in net._id2edge:
            if hw and t in hw._edge2value and e in hw._edge2value[t]:
                v = abs(hw._edge2value[t][e])
                if options.widthMax != None and v > options.widthMax:
                    v = options.widthMax
                if options.widthMin != None and v < options.widthMin:
                    v = options.widthMin
                if not maxWidthValue or maxWidthValue < v:
                    maxWidthValue = v
                if not minWidthValue or minWidthValue > v:
                    minWidthValue = v
                widths[e] = v
        if options.widthMax != None:
            maxWidthValue = options.widthMax
        if options.widthMin != None:
            minWidthValue = options.widthMin
        if options.logWidths:
            helpers.logNormalise(widths, options.colorMax)
        else:
            helpers.linNormalise(widths, minWidthValue, maxWidthValue)
        for e in widths:
            widths[e] = options.minWidth + widths[e] * \
                (options.maxWidth - options.minWidth)
        if options.verbose:
            print("Width values are between %s and %s" %
                  (minWidthValue, maxWidthValue))

        fig, ax = helpers.openFigure(options)
        ax.set_aspect("equal", None, 'C')
        helpers.plotNet(net, colors, widths, options)

        # drawing the legend, at least for the colors
        sm = plt.cm.ScalarMappable(
            cmap=matplotlib.cm.get_cmap(options.colormap),
            norm=matplotlib.colors.Normalize(vmin=minColorValue,
                                             vmax=maxColorValue))
        # "fake up the array of the scalar mappable. Urgh..." (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
        sm._A = []
        plt.colorbar(sm)

        options.nolegend = True
        optName = None
        if options.output and options.output.find("%s") >= 0:
            m, s = divmod(int(t), 60)
            h, m = divmod(m, 60)
            timeStr = "%02d:%02d:%02d" % (h, m, s)
            ax.text(7300,
                    15500,
                    timeStr,
                    bbox={
                        'facecolor': 'white',
                        'pad': 10
                    },
                    size=16)
            optName = options.output.replace("%s", str(t))
        helpers.closeFigure(fig, ax, options, False, optName)
        if optName == None:
            return 0
    return 0
コード例 #17
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--dump-inputs", dest="dumps", metavar="FILE",
                         help="Defines the dump-output files to use as input")
    optParser.add_option("-m", "--measures", dest="measures",
                         default="speed,entered", help="Define which measure to plot")
    optParser.add_option("--min-width", dest="minWidth",
                         type="float", default=.5, help="Defines the minimum edge width")
    optParser.add_option("--max-width", dest="maxWidth",
                         type="float", default=3, help="Defines the maximum edge width")
    optParser.add_option("--log-colors", dest="logColors", action="store_true",
                         default=False, help="If set, colors are log-scaled")
    optParser.add_option("--log-widths", dest="logWidths", action="store_true",
                         default=False, help="If set, widths are log-scaled")
    optParser.add_option("--min-color-value", dest="colorMin",
                         type="float", default=None,
                         help="If set, defines the minimum edge color value")
    optParser.add_option("--max-color-value", dest="colorMax",
                         type="float", default=None,
                         help="If set, defines the maximum edge color value")
    optParser.add_option("--min-width-value", dest="widthMin",
                         type="float", default=None,
                         help="If set, defines the minimum edge width value")
    optParser.add_option("--max-width-value", dest="widthMax",
                         type="float", default=None,
                         help="If set, defines the maximum edge width value")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    optParser.add_option("--color-bar-label", dest="colorBarLabel", default="",
                         help="The label to put on the color bar")

    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    helpers.addNetOptions(optParser)

    # Override the help string for the output option
    outputOpt = optParser.get_option("--output")
    outputOpt.help = "Comma separated list of filename(s) the figure shall be written to; " +\
                     "for multiple time intervals use \'\%s\' in the filename as a " +\
                     "placeholder for the beginning of the time interval"

    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net is None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    if options.measures is None:
        print("Error: a dump file must be given.")
        return 1

    times = []
    hc = None
    colorDump = options.dumps.split(",")[0]
    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
            # extension
            filenames = optOutputNames.split(',')
            for i in range(0, len(filenames)):
                filename, extension = os.path.splitext(filenames[i])
                filenames[i] = filename + '-%s' + extension
            optOutputNames = ','.join(filenames)

    # Now go through each time interval and create the figures
    for t in times:
        if options.verbose:
            print("Processing interval with a beginning of %s" % t)
        colors = {}
        maxColorValue = None
        minColorValue = None
        for e in net._id2edge:
            if hc and t in hc._edge2value and e in hc._edge2value[t]:
                if options.colorMax is not None and hc._edge2value[t][e] > options.colorMax:
                    hc._edge2value[t][e] = options.colorMax
                if options.colorMin is not None and hc._edge2value[t][e] < options.colorMin:
                    hc._edge2value[t][e] = options.colorMin
                if maxColorValue is None or maxColorValue < hc._edge2value[t][e]:
                    maxColorValue = hc._edge2value[t][e]
                if minColorValue is None or minColorValue > hc._edge2value[t][e]:
                    minColorValue = hc._edge2value[t][e]
                colors[e] = hc._edge2value[t][e]
        if options.colorMax is not None:
            maxColorValue = options.colorMax
        if options.colorMin is not None:
            minColorValue = options.colorMin
        if options.logColors:
            helpers.logNormalise(colors, maxColorValue)
        else:
            helpers.linNormalise(colors, minColorValue, maxColorValue)
        for e in colors:
            colors[e] = helpers.getColor(options, colors[e], 1.)
        if options.verbose:
            print("Color values are between %s and %s" %
                  (minColorValue, maxColorValue))

        widths = {}
        maxWidthValue = None
        minWidthValue = None
        for e in net._id2edge:
            if hw and t in hw._edge2value and e in hw._edge2value[t]:
                v = abs(hw._edge2value[t][e])
                if options.widthMax is not None and v > options.widthMax:
                    v = options.widthMax
                if options.widthMin is not None and v < options.widthMin:
                    v = options.widthMin
                if maxWidthValue is None or maxWidthValue < v:
                    maxWidthValue = v
                if minWidthValue is None or minWidthValue > v:
                    minWidthValue = v
                widths[e] = v
        if options.widthMax is not None:
            maxWidthValue = options.widthMax
        if options.widthMin is not None:
            minWidthValue = options.widthMin
        if options.logWidths:
            helpers.logNormalise(widths, options.colorMax)
        else:
            helpers.linNormalise(widths, minWidthValue, maxWidthValue)
        for e in widths:
            widths[e] = options.minWidth + widths[e] * \
                (options.maxWidth - options.minWidth)
        if options.verbose:
            print("Width values are between %s and %s" %
                  (minWidthValue, maxWidthValue))

        fig, ax = helpers.openFigure(options)
        ax.set_aspect("equal", None, 'C')
        helpers.plotNet(net, colors, widths, options)

        # drawing the legend, at least for the colors
        norm = matplotlib.colors.LogNorm if options.logColors else matplotlib.colors.Normalize
        sm = plt.cm.ScalarMappable(cmap=matplotlib.cm.get_cmap(options.colormap),
                                   norm=norm(vmin=minColorValue, vmax=maxColorValue))

        # "fake up the array of the scalar mappable. Urgh..."
        # (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
        sm._A = []
        color_bar = plt.colorbar(sm)
        color_bar.set_label(options.colorBarLabel)

        # Should we also save the figure to a file / list of files (comma
        # separated)?
        if options.output:

            # If we have a "%s" in the name of the output then replace it with the
            # interval begin of the current interval
            expandedOutputNames = optOutputNames
            if expandedOutputNames.find('%s') >= 0:
                expandedOutputNames = expandedOutputNames.replace("%s", str(t))

            # Can be used to print additional text in the figure:
            #
            # m, s = divmod(int(t), 60)
            # h, m = divmod(m, 60)
            # timeStr = "%02d:%02d:%02d" % (h, m, s)
            # ax.text(0.2, 0.2, timeStr, bbox={
            #    'facecolor': 'white', 'pad': 10}, size=16)
            helpers.closeFigure(fig, ax, options, False, expandedOutputNames)

    return 0
コード例 #18
0
ファイル: plot_csv_bars.py プロジェクト: Kitem/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i",
                         "--input",
                         dest="input",
                         metavar="FILE",
                         help="Defines the csv file to use as input")
    optParser.add_option("-c",
                         "--column",
                         dest="column",
                         type="int",
                         default=1,
                         help="Selects the column to read values from")
    optParser.add_option("-r",
                         "--revert",
                         dest="revert",
                         action="store_true",
                         default=False,
                         help="Reverts the order of read values")
    optParser.add_option("-w",
                         "--width",
                         dest="width",
                         type="float",
                         default=.8,
                         help="Defines the width of the bars")
    optParser.add_option("--space",
                         dest="space",
                         type="float",
                         default=.2,
                         help="Defines the space between the bars")
    optParser.add_option(
        "--norm",
        dest="norm",
        type="float",
        default=1.,
        help="Divides the read numbers by this value before plotting them")
    optParser.add_option("--show-values",
                         dest="showValues",
                         action="store_true",
                         default=False,
                         help="Shows the values")
    optParser.add_option("--values-offset",
                         dest="valuesOffset",
                         type="float",
                         default=1.,
                         help="Position offset for values")
    optParser.add_option("--vertical",
                         dest="vertical",
                         action="store_true",
                         default=False,
                         help="vertical bars are used")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.input is None:
        print("Error: at least one csv file must be given")
        sys.exit(1)

    fd = open(options.input)
    labels = []
    vlabels = []
    vals = []
    total = 0
    xs = []
    ts = []
    s = options.width + options.space
    t = options.width / 2. + options.space / 2.
    x = options.space / 2.
    for line in fd:
        v = line.strip().split(";")
        if len(v) < 2:
            continue
        labels.append(v[0].replace("\\n", "\n"))
        value = float(v[options.column]) / options.norm
        vals.append(value)
        vlabels.append(str(value) + "%")
        total += value
        xs.append(x)
        ts.append(t)
        x = x + s
        t = t + s

    if options.revert:
        labels.reverse()
        vals.reverse()
        vlabels.reverse()
    colors = []
    for i, e in enumerate(labels):
        colors.append(helpers.getColor(options, i, len(labels)))

    fig, ax = helpers.openFigure(options)
    if not options.vertical:
        rects = plt.barh(xs, vals, height=options.width)
        for i, rect in enumerate(rects):
            if options.showValues:
                width = rect.get_width()
                ax.text(width + options.valuesOffset,
                        rect.get_y() + rect.get_height() / 2.,
                        vlabels[i],
                        va='center',
                        ha='left')
            rect.set_color(colors[i])
            rect.set_edgecolor('k')
        plt.ylim(0, x)
        plt.yticks(ts, labels)
    else:
        rects = plt.bar(xs, vals, width=options.width)
        for i, rect in enumerate(rects):
            if options.showValues:
                height = rect.get_height()
                ax.text(rect.get_x() + rect.get_width() / 2.,
                        height + options.valuesOffset,
                        vlabels[i],
                        ha='center',
                        va='bottom')
            rect.set_color(colors[i])
            rect.set_edgecolor('k')
        plt.xlim(0, x)
        plt.xticks(ts, labels)
    helpers.closeFigure(fig, ax, options, False)
コード例 #19
0
ファイル: plot_net_speeds.py プロジェクト: aarongolliver/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("--edge-width", dest="defaultWidth",
                         type="float", default=1, help="Defines the edge width")
    optParser.add_option("--edge-color", dest="defaultColor",
                         default='k', help="Defines the edge color")
    optParser.add_option("--minV", dest="minV",
                         type="float", default=None, help="Define the minimum value boundary")
    optParser.add_option("--maxV", dest="maxV",
                         type="float", default=None, help="Define the maximum value boundary")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    speeds = {}
    minV = None
    maxV = None
    for e in net._id2edge:
        v = net._id2edge[e]._speed
        if minV == None or minV > v:
            minV = v
        if maxV == None or maxV < v:
            maxV = v
        speeds[e] = v
    if options.minV != None:
        minV = options.minV
    if options.maxV != None:
        maxV = options.maxV
    # if options.logColors:
#    helpers.logNormalise(colors, maxColorValue)
#  else:
#    helpers.linNormalise(colors, minColorValue, maxColorValue)

    helpers.linNormalise(speeds, minV, maxV)
    for e in speeds:
        speeds[e] = helpers.getColor(options, speeds[e], 1.)
    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, speeds, {}, options)

    # drawing the legend, at least for the colors
    print("%s -> %s" % (minV, maxV))
    sm = matplotlib.cm.ScalarMappable(
        cmap=get_cmap(options.colormap), norm=plt.normalize(vmin=minV, vmax=maxV))
    # "fake up the array of the scalar mappable. Urgh..." (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
    sm._A = []
    plt.colorbar(sm)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #20
0
ファイル: plot_net_dump.py プロジェクト: planetsumo/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--dump-inputs", dest="dumps", metavar="FILE",
                         help="Defines the dump-output files to use as input")
    optParser.add_option("-m", "--measures", dest="measures",
                         default="speed,entered", help="Define which measure to plot")
    optParser.add_option("--min-width", dest="minWidth",
                         type="float", default=.5, help="Defines the minimum edge width")
    optParser.add_option("--max-width", dest="maxWidth",
                         type="float", default=3, help="Defines the maximum edge width")
    optParser.add_option("--log-colors", dest="logColors", action="store_true",
                         default=False, help="If set, colors are log-scaled")
    optParser.add_option("--log-widths", dest="logWidths", action="store_true",
                         default=False, help="If set, widths are log-scaled")
    optParser.add_option("--min-color-value", dest="colorMin",
                         type="float", default=None,
                         help="If set, defines the minimum edge color value")
    optParser.add_option("--max-color-value", dest="colorMax",
                         type="float", default=None,
                         help="If set, defines the maximum edge color value")
    optParser.add_option("--min-width-value", dest="widthMin",
                         type="float", default=None,
                         help="If set, defines the minimum edge width value")
    optParser.add_option("--max-width-value", dest="widthMax",
                         type="float", default=None,
                         help="If set, defines the maximum edge width value")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")

    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    helpers.addNetOptions(optParser)

    # Override the help string for the output option
    outputOpt = optParser.get_option("--output")
    outputOpt.help = "Comma separated list of filename(s) the figure shall be written to; " +\
                     "for multiple time intervals use \'\%s\' in the filename as a " +\
                     "placeholder for the beginning of the time interval"

    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    if options.measures == None:
        print("Error: a dump file must be given.")
        return 1

    times = []
    hc = None
    colorDump = options.dumps.split(",")[0]
    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
            # extension
            filenames = optOutputNames.split(',')
            for i in range(0, len(filenames)):
                filename, extension = os.path.splitext(filenames[i])
                filenames[i] = filename + '-%s' + extension
            optOutputNames = ','.join(filenames)

    # Now go through each time interval and create the figures
    for t in times:
        if options.verbose:
            print("Processing interval with a beginning of %s" % t)
        colors = {}
        maxColorValue = None
        minColorValue = None
        for e in net._id2edge:
            if hc and t in hc._edge2value and e in hc._edge2value[t]:
                if options.colorMax != None and hc._edge2value[t][e] > options.colorMax:
                    hc._edge2value[t][e] = options.colorMax
                if options.colorMin != None and hc._edge2value[t][e] < options.colorMin:
                    hc._edge2value[t][e] = options.colorMin
                if maxColorValue == None or maxColorValue < hc._edge2value[t][e]:
                    maxColorValue = hc._edge2value[t][e]
                if minColorValue == None or minColorValue > hc._edge2value[t][e]:
                    minColorValue = hc._edge2value[t][e]
                colors[e] = hc._edge2value[t][e]
        if options.colorMax != None:
            maxColorValue = options.colorMax
        if options.colorMin != None:
            minColorValue = options.colorMin
        if options.logColors:
            helpers.logNormalise(colors, maxColorValue)
        else:
            helpers.linNormalise(colors, minColorValue, maxColorValue)
        for e in colors:
            colors[e] = helpers.getColor(options, colors[e], 1.)
        if options.verbose:
            print("Color values are between %s and %s" %
                  (minColorValue, maxColorValue))

        widths = {}
        maxWidthValue = None
        minWidthValue = None
        for e in net._id2edge:
            if hw and t in hw._edge2value and e in hw._edge2value[t]:
                v = abs(hw._edge2value[t][e])
                if options.widthMax != None and v > options.widthMax:
                    v = options.widthMax
                if options.widthMin != None and v < options.widthMin:
                    v = options.widthMin
                if not maxWidthValue or maxWidthValue < v:
                    maxWidthValue = v
                if not minWidthValue or minWidthValue > v:
                    minWidthValue = v
                widths[e] = v
        if options.widthMax != None:
            maxWidthValue = options.widthMax
        if options.widthMin != None:
            minWidthValue = options.widthMin
        if options.logWidths:
            helpers.logNormalise(widths, options.colorMax)
        else:
            helpers.linNormalise(widths, minWidthValue, maxWidthValue)
        for e in widths:
            widths[e] = options.minWidth + widths[e] * \
                (options.maxWidth - options.minWidth)
        if options.verbose:
            print("Width values are between %s and %s" %
                  (minWidthValue, maxWidthValue))

        fig, ax = helpers.openFigure(options)
        ax.set_aspect("equal", None, 'C')
        helpers.plotNet(net, colors, widths, options)

        # drawing the legend, at least for the colors
        sm = plt.cm.ScalarMappable(cmap=matplotlib.cm.get_cmap(options.colormap),
                                   norm=matplotlib.colors.Normalize(vmin=minColorValue,
                                                                    vmax=maxColorValue))

        # "fake up the array of the scalar mappable. Urgh..."
        # (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
        sm._A = []
        plt.colorbar(sm)

        # Should we also save the figure to a file / list of files (comma
        # separated)?
        if options.output:

            # If we have a "%s" in the name of the output then replace it with the
            # interval begin of the current interval
            expandedOutputNames = optOutputNames
            if expandedOutputNames.find('%s') >= 0:
                expandedOutputNames = expandedOutputNames.replace("%s", str(t))

            # Can be used to print additional text in the figure:
            #
            # m, s = divmod(int(t), 60)
            # h, m = divmod(m, 60)
            # timeStr = "%02d:%02d:%02d" % (h, m, s)
            # ax.text(0.2, 0.2, timeStr, bbox={
            #    'facecolor': 'white', 'pad': 10}, size=16)
            helpers.closeFigure(fig, ax, options, False, expandedOutputNames)

    return 0
コード例 #21
0
		optParser = OptionParser()
		optParser.add_option("-n", "--net", dest="net", metavar="FILE", help="Defines the network to read")
		optParser.add_option("--edge-width", dest="defaultWidth", type="float", default=2.5, help="Defines the edge width")
		optParser.add_option("--edge-color", dest="defaultColor", default="r", help="Defines the edge color")

		optParser.add_option(
			"-v",
			"--verbose",
			dest="verbose",
			action="store_true",
			default=False,
			help="If set, the script says what it's doing",
		)
		# standard plot options
		helpers.addInteractionOptions(optParser)
		helpers.addPlotOptions(optParser)
		options, remaining_args = optParser.parse_args(args=args)
		options.colormap = "jet"
		#Net file

		net = sumolib.net.readNet(path)
		#count = 0

		key_max = max(edge_traversal_list.keys(), key=(lambda k: edge_traversal_list[k]))
		key_min = min(edge_traversal_list.keys(), key=(lambda k: edge_traversal_list[k]))
		minCount = edge_traversal_list[key_min]
		maxCount = edge_traversal_list[key_max]

		helpers.linNormalise(edge_traversal_list, minCount, maxCount)
コード例 #22
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i", "--tripinfos-inputs", dest="tripinfos", metavar="FILE",
                         help="Defines the tripinfo-output files to use as input")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    optParser.add_option("-m", "--measure", dest="measure",
                         default="duration", help="Define which measure to plot")
    optParser.add_option("--bins", dest="bins",
                         type="int", default=20, help="Define the bin number")
    optParser.add_option("--norm", dest="norm",
                         type="float", default=1., help="Read values will be devided by this number")
    optParser.add_option("--minV", dest="minV",
                         type="float", default=None, help="Define the minimum value boundary")
    optParser.add_option("--maxV", dest="maxV",
                         type="float", default=None, help="Define the maximum value boundary")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.tripinfos == None:
        print "Error: at least one tripinfo file must be given"
        sys.exit(1)

    minV = options.minV
    maxV = options.maxV
    files = options.tripinfos.split(",")
    values = {}
    for f in files:
        if options.verbose:
            print "Reading '%s'..." % f
        nums = sumolib.output.parse_sax__asList(
            f, "tripinfo", [options.measure])
        fvp = sumolib.output.toList(nums, options.measure)
        fv = [x / options.norm for x in fvp]
        sumolib.output.prune(fv, options.minV, options.maxV)

        values[f] = fv
        if minV == None:
            minV = fv[0]
            maxV = fv[0]
        minV = min(minV, min(fv))
        maxV = max(maxV, max(fv))

    hists = {}
    binWidth = (maxV - minV) / float(options.bins)
    for f in files:
        h = [0] * options.bins
        for v in values[f]:
            i = min(int((v - minV) / binWidth), options.bins - 1)
            h[i] = h[i] + 1
        hists[f] = h

    width = binWidth / float(len(files)) * .8
    offset = binWidth * .1
    center = []
    for j in range(0, options.bins):
        center.append(binWidth * j + offset)

    fig, ax = helpers.openFigure(options)
    for i, f in enumerate(files):
        c = helpers.getColor(options, i, len(files))
        l = helpers.getLabel(f, i, options)
        plt.bar(center, hists[f], width=width, label=l, color=c)
        for j in range(0, options.bins):
            center[j] = center[j] + width
    helpers.closeFigure(fig, ax, options)
コード例 #23
0
def plot(densities, md, net, filename=None):
    args = []
    optParser = OptionParser()
    optParser.add_option("-n",
                         "--net",
                         dest="net",
                         metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("--edge-width",
                         dest="defaultWidth",
                         type="float",
                         default=0.5,
                         help="Defines the width of not selected edges")
    optParser.add_option("--edge-color",
                         dest="defaultColor",
                         default='#000000',
                         help="Defines the color of not selected edges")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")

    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    options, remaining_args = optParser.parse_args(args=args)

    for i, interval in enumerate(densities):
        colors = {}
        widths = {}
        max_density = 0
        min_density = 10000
        for e in interval.keys():
            if max_density < interval[e]:
                max_density = interval[e]
            if min_density > interval[e]:
                min_density = interval[e]

        for e in interval.keys():

            colors[e] = get_color(interval[e], md)
            #widths[e] = normalize(interval[e], max_density, min_density) + 2.0
            widths[e] = 4

        fig, ax = helpers.openFigure(options)
        ax.set_aspect("equal", None, 'C')
        helpers.plotNet(net, colors, widths, options)
        lines = ax.get_lines()
        for line in lines:
            line.set_linestyle('--')
        ax.set_title('{num1:02d}:00:00 to {num2:02d}:00:00 hrs'.format(
            num1=(i + 6) % 24, num2=(i + 7) % 24))
        if filename:
            fig.savefig(f'../output/{filename}.pdf',
                        bbox_inches='tight',
                        pad_inches=0)
        else:
            fig.savefig('../output/hour' + str(i) + '.pdf',
                        bbox_inches='tight',
                        pad_inches=0)
        options.nolegend = True

        helpers.closeFigure(fig, ax, options)
コード例 #24
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input")
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    options, _ = optParser.parse_args(args=args)

    #<interval begin="90.00" end="120.00" id="e1det_886398487#2.123_3" nVehContrib="0" flow="0.00" occupancy="0.00" speed="-1.00" harmonicMeanSpeed="-1.00" #length="-1.00" nVehEntered="0"/>

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    files = options.summary.split(",")

    tid = 2
    cols = [
        "begin", "end", "id", "nVehContrib", "flow", "occupancy", "speed",
        "harmonicMeanSpeed", "length", "nVehEntered"
    ]
    label = cols[0:tid] + cols[tid + 1:]

    data = {}
    for raw in sumolib.xml.parse_fast(files[0], "interval", cols):
        id = raw[tid]

        if id not in data:
            print("Adding ..", id)
            data[id] = []
        data[id].append([float(x) for x in raw[0:tid] + raw[tid + 1:]])

    fig = plt.figure()
    for i, k in enumerate(data):
        tag = "e1{:02d}".format(i)
        d = np.array(data[k])
        t = d[:, 0]

        plt.plot(t, d[:, 4], label=label[4])
        plt.savefig("{}_occ.jpg".format(tag))
        plt.xlabel("Time/s")
        plt.legend()
        plt.clf()

        plt.plot(t, d[:, 5], label=label[5])
        plt.plot(t, d[:, 6], label=label[6])
        plt.savefig("{}_vel.jpg".format(tag))
        plt.xlabel("Time/s")
        plt.legend()
        plt.clf()

        plt.plot(t, d[:, 2], label=label[2])
        plt.plot(t, d[:, 3], label=label[3])
        plt.plot(t, d[:, 8], label=label[8])
        plt.savefig("{}_flow.jpg".format(tag))
        plt.xlabel("Time/s")
        plt.legend()
        plt.clf()
コード例 #25
0
ファイル: plt_e2.py プロジェクト: chunyulin/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i", "--summary-inputs", dest="summary", metavar="FILE",
                         help="Defines the summary-output files to use as input")
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    options, _ = optParser.parse_args(args=args)

    #"begin",end="150.00" id="e2det_109505014#6.100_0" sampledSeconds="33.11" nVehEntered="3" nVehLeft="2" nVehSeen="3" meanSpeed="12.46" meanTimeLoss="2.76" meanOccupancy="0.34" maxOccupancy="3.08" meanMaxJamLengthInVehicles="0.02" meanMaxJamLengthInMeters="0.05" maxJamLengthInVehicles="1" maxJamLengthInMeters="2.10" jamLengthInVehiclesSum="7" jamLengthInMetersSum="14.70" meanHaltingDuration="4.50" maxHaltingDuration="4.50" haltingDurationSum="4.50" meanIntervalHaltingDuration="4.50" maxIntervalHaltingDuration="4.50" intervalHaltingDurationSum="4.50" startedHalts="1.00" meanVehicleNumber="0.23" maxVehicleNumber="2" />

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    files = options.summary.split(",")
    
    tid=2
    cols = ["begin","end","id",     
             "sampledSeconds","nVehEntered","nVehLeft","nVehSeen",                                   
             "meanSpeed","meanTimeLoss","meanOccupancy","maxOccupancy","meanMaxJamLengthInVehicles",
             "meanMaxJamLengthInMeters","maxJamLengthInVehicles","maxJamLengthInMeters","jamLengthInVehiclesSum","jamLengthInMetersSum",
             "meanHaltingDuration","maxHaltingDuration","haltingDurationSum","meanIntervalHaltingDuration","maxIntervalHaltingDuration", "intervalHaltingDurationSum","startedHalts","meanVehicleNumber","maxVehicleNumber" ]
    
    print(cols)
    label = cols[0:tid]+cols[tid+1:]
    
    data = {}
    for raw in sumolib.xml.parse_fast(files[0], "interval", cols ):
        id = raw[tid]
        if id not in data:
            data[id] = []
        data[id].append( [ float(x) for x in raw[0:tid]+raw[tid+1:] ] )
    
    fig = plt.figure()
    for i, k in enumerate(data):
        tag="e2{:02d}".format(i)
        d = np.array(data[k])
        t = d[:,0]

        plt.plot(t, d[:,7], label=label[7])
        plt.plot(t, d[:,8], label=label[8])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_occ.jpg".format(tag))
        plt.clf()
        
        plt.plot(t, d[:,6], label=label[6])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_vel.jpg".format(tag))
        plt.clf()
   
        plt.plot(t, d[:,15], label=label[15])
        plt.plot(t, d[:,16], label=label[16])
        plt.plot(t, d[:,17], label=label[17])
        plt.plot(t, d[:,18], label=label[18])
        plt.plot(t, d[:,19], label=label[19])
        plt.plot(t, d[:,20], label=label[20])
        plt.plot(t, d[:,21], label=label[21])
        plt.plot(t, d[:,22], label=label[22])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_flow.jpg".format(tag))
        plt.clf()
コード例 #26
0
ファイル: plot_csv_bars.py プロジェクト: cbrafter/sumo
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-i", "--input", dest="input", metavar="FILE",
                         help="Defines the csv file to use as input")
    optParser.add_option("-c", "--column", dest="column",
                         type="int", default=1, help="Selects the column to read values from")
    optParser.add_option("-r", "--revert", dest="revert", action="store_true",
                         default=False, help="Reverts the order of read values")
    optParser.add_option("-w", "--width", dest="width",
                         type="float", default=.8, help="Defines the width of the bars")
    optParser.add_option("--space", dest="space",
                         type="float", default=.2, help="Defines the space between the bars")
    optParser.add_option("--norm", dest="norm",
                         type="float", default=1., help="Divides the read numbers by this value before plotting them")
    optParser.add_option("--show-values", dest="showValues", action="store_true",
                         default=False, help="Shows the values")
    optParser.add_option("--values-offset", dest="valuesOffset",
                         type="float", default=1., help="Position offset for values")
    optParser.add_option("--vertical", dest="vertical", action="store_true",
                         default=False, help="vertical bars are used")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.input == None:
        print("Error: at least one csv file must be given")
        sys.exit(1)

    fd = open(options.input)
    labels = []
    vlabels = []
    vals = []
    total = 0
    xs = []
    ts = []
    s = options.width + options.space
    t = options.width / 2. + options.space / 2.
    x = options.space / 2.
    for line in fd:
        v = line.strip().split(";")
        if len(v) < 2:
            continue
        labels.append(v[0].replace("\\n", "\n"))
        value = float(v[options.column]) / options.norm
        vals.append(value)
        vlabels.append(str(value) + "%")
        total += value
        xs.append(x)
        ts.append(t)
        x = x + s
        t = t + s

    if options.revert:
        labels.reverse()
        vals.reverse()
        vlabels.reverse()
    colors = []
    for i, e in enumerate(labels):
        colors.append(helpers.getColor(options, i, len(labels)))

    fig, ax = helpers.openFigure(options)
    if not options.vertical:
        rects = plt.barh(xs, vals, height=options.width)
        for i, rect in enumerate(rects):
            if options.showValues:
                width = rect.get_width()
                ax.text(width + options.valuesOffset, rect.get_y() +
                        rect.get_height() / 2., vlabels[i], va='center', ha='left')
            rect.set_color(colors[i])
            rect.set_edgecolor('k')
        plt.ylim(0, x)
        plt.yticks(ts, labels)
    else:
        rects = plt.bar(xs, vals, width=options.width)
        for i, rect in enumerate(rects):
            if options.showValues:
                height = rect.get_height()
                ax.text(rect.get_x() + rect.get_width() / 2., height +
                        options.valuesOffset, vlabels[i], ha='center', va='bottom')
            rect.set_color(colors[i])
            rect.set_edgecolor('k')
        plt.xlim(0, x)
        plt.xticks(ts, labels)
    helpers.closeFigure(fig, ax, options, False)
コード例 #27
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n",
                         "--net",
                         dest="net",
                         metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("--edge-width",
                         dest="defaultWidth",
                         type="float",
                         default=1,
                         help="Defines the edge width")
    optParser.add_option("--edge-color",
                         dest="defaultColor",
                         default='k',
                         help="Defines the edge color")
    optParser.add_option("--minV",
                         dest="minV",
                         type="float",
                         default=None,
                         help="Define the minimum value boundary")
    optParser.add_option("--maxV",
                         dest="maxV",
                         type="float",
                         default=None,
                         help="Define the maximum value boundary")
    optParser.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action="store_true",
                         default=False,
                         help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net is None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    speeds = {}
    minV = None
    maxV = None
    for e in net._id2edge:
        v = net._id2edge[e]._speed
        if minV is None or minV > v:
            minV = v
        if maxV is None or maxV < v:
            maxV = v
        speeds[e] = v
    if options.minV is not None:
        minV = options.minV
    if options.maxV is not None:
        maxV = options.maxV
    # if options.logColors:


#    helpers.logNormalise(colors, maxColorValue)
#  else:
#    helpers.linNormalise(colors, minColorValue, maxColorValue)

    helpers.linNormalise(speeds, minV, maxV)
    for e in speeds:
        speeds[e] = helpers.getColor(options, speeds[e], 1.)
    fig, ax = helpers.openFigure(options)
    ax.set_aspect("equal", None, 'C')
    helpers.plotNet(net, speeds, {}, options)

    # drawing the legend, at least for the colors
    print("%s -> %s" % (minV, maxV))
    sm = matplotlib.cm.ScalarMappable(
        cmap=matplotlib.cm.get_cmap(options.colormap),
        norm=matplotlib.colors.normalize(vmin=minV, vmax=maxV))
    # "fake up the array of the scalar mappable. Urgh..." (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
    sm._A = []
    plt.colorbar(sm)
    options.nolegend = True
    helpers.closeFigure(fig, ax, options)
コード例 #28
0
ファイル: plot_net_dump.py プロジェクト: kbleeck/customSumo26
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option("-n", "--net", dest="net", metavar="FILE",
                         help="Defines the network to read")
    optParser.add_option("-i", "--dump-inputs", dest="dumps", metavar="FILE",
                         help="Defines the dump-output files to use as input")
    optParser.add_option("-m", "--measures", dest="measures",
                         default="speed,entered", help="Define which measure to plot")
    optParser.add_option("--min-width", dest="minWidth",
                         type="float", default=.5, help="Defines the minimum edge width")
    optParser.add_option("--max-width", dest="maxWidth",
                         type="float", default=3, help="Defines the maximum edge width")
    optParser.add_option("--log-colors", dest="logColors", action="store_true",
                         default=False, help="If set, colors are log-scaled")
    optParser.add_option("--log-widths", dest="logWidths", action="store_true",
                         default=False, help="If set, widths are log-scaled")
    optParser.add_option("--min-color-value", dest="colorMin",
                         type="float", default=None, help="If set, defines the minimum edge color value")
    optParser.add_option("--max-color-value", dest="colorMax",
                         type="float", default=None, help="If set, defines the maximum edge color value")
    optParser.add_option("--min-width-value", dest="widthMin",
                         type="float", default=None, help="If set, defines the minimum edge width value")
    optParser.add_option("--max-width-value", dest="widthMax",
                         type="float", default=None, help="If set, defines the maximum edge width value")
    optParser.add_option("-v", "--verbose", dest="verbose", action="store_true",
                         default=False, help="If set, the script says what it's doing")
    # standard plot options
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    helpers.addNetOptions(optParser)
    # parse
    options, remaining_args = optParser.parse_args(args=args)

    if options.net == None:
        print("Error: a network to load must be given.")
        return 1
    if options.verbose:
        print("Reading network from '%s'" % options.net)
    net = sumolib.net.readNet(options.net)

    if options.measures == None:
        print("Error: a dump file must be given.")
        return 1

    times = []
    hc = None
    if options.dumps.split(",")[0] != "":
        if options.verbose:
            print("Reading colors from '%s'" % options.dumps.split(",")[0])
        hc = WeightsReader(options.measures.split(",")[0])
        sumolib.output.parse_sax(options.dumps.split(",")[0], hc)
        times = hc._edge2value

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

    for t in times:
        colors = {}
        maxColorValue = None
        minColorValue = None
        for e in net._id2edge:
            if hc and t in hc._edge2value and e in hc._edge2value[t]:
                if options.colorMax != None and hc._edge2value[t][e] > options.colorMax:
                    hc._edge2value[t][e] = options.colorMax
                if options.colorMin != None and hc._edge2value[t][e] < options.colorMin:
                    hc._edge2value[t][e] = options.colorMin
                if maxColorValue == None or maxColorValue < hc._edge2value[t][e]:
                    maxColorValue = hc._edge2value[t][e]
                if minColorValue == None or minColorValue > hc._edge2value[t][e]:
                    minColorValue = hc._edge2value[t][e]
                colors[e] = hc._edge2value[t][e]
        if options.colorMax != None:
            maxColorValue = options.colorMax
        if options.colorMin != None:
            minColorValue = options.colorMin
        if options.logColors:
            helpers.logNormalise(colors, maxColorValue)
        else:
            helpers.linNormalise(colors, minColorValue, maxColorValue)
        for e in colors:
            colors[e] = helpers.getColor(options, colors[e], 1.)
        if options.verbose:
            print("Color values are between %s and %s" %
                  (minColorValue, maxColorValue))

        widths = {}
        maxWidthValue = None
        minWidthValue = None
        for e in net._id2edge:
            if hw and t in hw._edge2value and e in hw._edge2value[t]:
                v = abs(hw._edge2value[t][e])
                if options.widthMax != None and v > options.widthMax:
                    v = options.widthMax
                if options.widthMin != None and v < options.widthMin:
                    v = options.widthMin
                if not maxWidthValue or maxWidthValue < v:
                    maxWidthValue = v
                if not minWidthValue or minWidthValue > v:
                    minWidthValue = v
                widths[e] = v
        if options.widthMax != None:
            maxWidthValue = options.widthMax
        if options.widthMin != None:
            minWidthValue = options.widthMin
        if options.logWidths:
            helpers.logNormalise(widths, options.colorMax)
        else:
            helpers.linNormalise(widths, minWidthValue, maxWidthValue)
        for e in widths:
            widths[e] = options.minWidth + widths[e] * \
                (options.maxWidth - options.minWidth)
        if options.verbose:
            print("Width values are between %s and %s" %
                  (minWidthValue, maxWidthValue))

        fig, ax = helpers.openFigure(options)
        ax.set_aspect("equal", None, 'C')
        helpers.plotNet(net, colors, widths, options)

        # drawing the legend, at least for the colors
        sm = plt.cm.ScalarMappable(cmap=matplotlib.cm.get_cmap(
            options.colormap), norm=matplotlib.colors.Normalize(vmin=minColorValue, vmax=maxColorValue))
        # "fake up the array of the scalar mappable. Urgh..." (pelson, http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots)
        sm._A = []
        plt.colorbar(sm)

        options.nolegend = True
        optName = None
        if options.output and options.output.find("%s") >= 0:
            m, s = divmod(int(t), 60)
            h, m = divmod(m, 60)
            timeStr = "%02d:%02d:%02d" % (h, m, s)
            ax.text(7300, 15500, timeStr, bbox={
                    'facecolor': 'white', 'pad': 10}, size=16)
            optName = options.output.replace("%s", str(t))
        helpers.closeFigure(fig, ax, options, False, optName)
        if optName == None:
            return 0
    return 0
コード例 #29
0
def main(args=None):
    """The main function; parses options and plots"""
    # ---------- build and read options ----------
    from optparse import OptionParser
    optParser = OptionParser()
    optParser.add_option(
        "-i",
        "--summary-inputs",
        dest="summary",
        metavar="FILE",
        help="Defines the summary-output files to use as input")
    helpers.addInteractionOptions(optParser)
    helpers.addPlotOptions(optParser)
    options, _ = optParser.parse_args(args=args)

    #<interval begin="0.00" end="150.00" id="e3_A0" meanTravelTime="27.93" meanOverlapTravelTime="28.57" meanSpeed="12.58" meanHaltsPerVehicle="0.39" meanTimeLoss="14.21" vehicleSum="36" meanSpeedWithin="7.42" meanHaltsPerVehicleWithin="0.84" meanDurationWithin="49.01" vehicleSumWithin="63" meanIntervalSpeedWithin="7.42" meanIntervalHaltsPerVehicleWithin="0.84" meanIntervalDurationWithin="49.01" meanTimeLossWithin="36.65"/>

    if options.summary is None:
        print("Error: at least one summary file must be given")
        sys.exit(1)

    files = options.summary.split(",")

    tid = 2
    cols = [
        "begin", "end", "id", "meanTravelTime", "meanOverlapTravelTime",
        "meanSpeed", "meanHaltsPerVehicle", "meanTimeLoss", "vehicleSum",
        "meanSpeedWithin", "meanHaltsPerVehicleWithin", "meanDurationWithin",
        "vehicleSumWithin", "meanIntervalSpeedWithin",
        "meanIntervalHaltsPerVehicleWithin", "meanIntervalDurationWithin",
        "meanTimeLossWithin"
    ]

    print(cols)
    label = cols[0:tid] + cols[tid + 1:]

    data = {}
    for raw in sumolib.xml.parse_fast(files[0], "interval", cols):
        id = raw[tid]
        if id not in data:
            print("Adding ..", id)
            data[id] = []
        data[id].append([float(x) for x in raw[0:tid] + raw[tid + 1:]])

    fig = plt.figure()
    for k in data:
        #tag="e3{:02d}".format(i)
        tag = k
        d = np.array(data[k])
        t = d[:, 0]

        plt.plot(t, d[:, 2], label=label[2])
        plt.plot(t, d[:, 3], label=label[3])
        plt.plot(t, d[:, 6], label=label[6])
        plt.plot(t, d[:, 10], label=label[10])
        plt.plot(t, d[:, 11], label=label[11])
        plt.plot(t, d[:, 14], label=label[14])
        plt.plot(t, d[:, 15], label=label[15])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_time.jpg".format(tag))
        plt.clf()

        plt.plot(t, d[:, 4], label=label[4])
        plt.plot(t, d[:, 8], label=label[8])
        plt.plot(t, d[:, 9], label=label[9])
        plt.plot(t, d[:, 12], label=label[12])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_vel.jpg".format(tag))
        plt.clf()

        plt.plot(t, d[:, 5], label=label[5])
        plt.plot(t, d[:, 7], label=label[7])
        plt.plot(t, d[:, 13], label=label[13])
        plt.xlabel("Time/s")
        plt.legend()
        plt.savefig("{}_flow.jpg".format(tag))
        plt.clf()