Example #1
0
def run_tests(locals):
    outcomes = dict()

    def add_outcome(name, successful):
        if name in outcomes:
            raise RuntimeError("Duplicate test name: " + name)
        outcomes[name] = successful

    loc = list(locals.keys())
    for l in loc:
        if l.startswith("test_"):
            print("---- running: " + l + " ----")
            f = locals[l]
            try:
                o = f()
            except Exception as e:
                print("EXCEPTION: " + str(e))
                o = False
            passed = (
                o is None
            ) or o  # "void" methods are successful if they don't raise an Exception
            print("PASS" if passed else "FAIL")
            add_outcome(l, passed)

    plot.set_property("Graph.Title", "See console for test results.")

    failed_names = [n for n, s in outcomes.items() if not s]
    faileds = ", ".join(failed_names)
    import sys
    print("FAILED TESTS: " + (faileds or "NONE"), file=sys.stderr)

    if faileds:
        raise Exception(str(len(failed_names)) + " tests failed")
Example #2
0
def plot_histograms(df, props):
    p = plot if chart.is_native_chart() else plt

    def get_prop(k):
        return props[k] if k in props else None

    title_col, legend_cols = extract_label_columns(df)

    for i, t in enumerate(df.itertuples(index=False)):
        style = _make_histline_args(props, t, df)

        # We are branching here, and call the two .hist implementations
        # differently, because the MPL API does not have support for
        # underflows/overflows, so we have to "fake" them into the real
        # data as additional cells. Drawing them separately wouldn't
        # work, because that would change the histogram when the
        # "normalized" or "cumulative" transforms are done (by MPL).
        if chart.is_native_chart():
            p.hist(t.binedges[:-1],
                   t.binedges,
                   weights=t.binvalues,
                   label=make_legend_label(legend_cols, t),
                   minvalue=t.min,
                   maxvalue=t.max,
                   underflows=t.underflows,
                   overflows=t.overflows,
                   **style)
        else:
            edges = list(t.binedges)
            values = list(t.binvalues)
            has_underflow_bin = not np.isnan(t.min) and not np.isnan(
                t.underflows) and t.min < edges[0]
            has_overflow_bin = not np.isnan(t.max) and not np.isnan(
                t.overflows) and t.max >= edges[-1]
            if has_underflow_bin:
                edges = [t.min] + edges
                values = [t.underflows] + values
            if has_overflow_bin:
                edges = edges + [t.max]
                values = values + [t.overflows]

            p.hist(edges[:-1],
                   edges,
                   weights=values,
                   label=make_legend_label(legend_cols, t),
                   **style)

    show_overflows = get_prop("show_overflows")
    if show_overflows and chart.is_native_chart():
        plot.set_property("Hist.ShowOverflowCell",
                          str(_parse_optional_bool(show_overflows)).lower())

    title = get_prop("title") or make_chart_title(df, title_col, legend_cols)
    set_plot_title(title)
Example #3
0
def plot_bars(df, props, names=None, errors_df=None):
    p = plot if chart.is_native_chart() else plt

    def get_prop(k):
        return props[k] if k in props else None

    group_fill_ratio = 0.8
    aligned_bar_fill_ratio = 0.9
    overlap_visible_fraction = 1 / 3

    # used only by the mpl charts
    xs = np.arange(len(df.index),
                   dtype=np.float64)  # the x locations for the groups
    width = group_fill_ratio / len(df.columns)  # the width of the bars
    bottoms = np.zeros_like(xs)
    group_increment = 0.0

    baseline = get_prop("baseline")
    if baseline:
        if chart.is_native_chart():  # is this how this should be done?
            plot.set_property("Bars.Baseline", baseline)
        else:
            bottoms += float(baseline)

    extra_args = dict()

    placement = get_prop("bar_placement")
    if placement:
        if chart.is_native_chart():  # is this how this should be done?
            plot.set_property("Bar.Placement", placement)
        else:
            extra_args["bottom"] = bottoms
            if placement == "InFront":
                width = group_fill_ratio
            elif placement == "Stacked":
                width = group_fill_ratio
            elif placement == "Aligned":
                width = group_fill_ratio / len(df.columns)
                group_increment = width
                xs -= width * (len(df.columns) - 1) / 2
                width *= aligned_bar_fill_ratio
            elif placement == "Overlap":
                width = group_fill_ratio / (
                    1 + len(df.columns) * overlap_visible_fraction)
                group_increment = width * overlap_visible_fraction
                extra_parts = (1.0 / overlap_visible_fraction - 1)
                xs += width / extra_parts - (
                    len(df.columns) +
                    extra_parts) * width * overlap_visible_fraction / 2

    for i, column in enumerate(df):
        style = _make_bar_args(props, df)

        if not chart.is_native_chart():  # FIXME: noot pretty...
            extra_args['zorder'] = 1 - (i / len(df.columns) / 10)

        label = df.columns.name + "=" + _to_label(
            column) if df.columns.name else _to_label(column)
        ys = df[column].values
        p.bar(xs, ys, width, label=label, **extra_args, **style)

        if not chart.is_native_chart() and errors_df is not None:
            plt.errorbar(xs,
                         ys,
                         yerr=errors_df[column],
                         capsize=float(get_prop("cap_size") or 4),
                         **style,
                         linestyle="none",
                         ecolor=mpl.rcParams["axes.edgecolor"])

        xs += group_increment
        if placement == "Stacked":
            bottoms += df[column].values

    rotation = get_prop("xlabel_rotation")
    if rotation:
        rotation = float(rotation)
    else:
        rotation = 0
    p.xticks(list(range(len(df.index))),
             list([_to_label(i) for i in df.index.values]),
             rotation=rotation)

    # Add some text for labels, title and custom x-axis tick labels, etc.
    groups = (get_prop("groups") or "").split(",")
    series = (get_prop("series") or "").split(",")

    p.xlabel(_to_label(df.index.names[0]))

    title = ""
    if len(names):
        names_str = [str(n) for n in names]
        groups_series_str = [str(gs) for gs in groups + series]
        p.ylabel(", ".join(names_str))
        title = ", ".join(names_str)
        if groups_series_str and groups_series_str[0]:
            title += " by " + ", ".join(groups_series_str)

    set_plot_title(get_prop("title") or title)
Example #4
0
try:
    df = xa.join(ya, how='outer').join(iso, how='outer')
except:
    import traceback
    traceback.print_exc()

values = df["value"]
titles = df["title"] if "title" in df else None
units = df["unit"] if "unit" in df else None

values[yaxis_column] = pd.to_numeric(values[yaxis_column], errors="ignore")

df = pd.pivot_table(values,
                    columns=iso_column,
                    index=xaxis_column,
                    values=yaxis_column,
                    dropna=False)

df.reset_index(inplace=True)
df.rename({xaxis_column: "time"}, axis="columns", inplace=True)

plot.plot_vectors(df)

title = props["title"] or ', '.join(titles[yaxis_column].unique())
utils.set_plot_title(title)

if units is not None:
    plot.set_property("Y.Axis.Title",
                      "[" + ', '.join(units[yaxis_column].unique()) + "]")