Beispiel #1
0
def plot_time_varying_multi_input(
    plotter: Plotter,
    tv_key: str,
    times: List[float],
    is_logscale: bool,
):
    """
    Plot single simple plot of a function over time
    """
    # Plot requested func names.
    fig, axes, max_dims, n_rows, n_cols, _ = plotter.get_figure()
    if is_logscale:
        axes.set_yscale("log")

    df = pd.DataFrame(tv_key)
    df.index = times

    axes.plot(df.index, df.values)
    change_xaxis_to_date(axes, REF_DATE)
    pyplot.legend(
        df.columns, loc="best", labels=[get_plot_text_dict(location) for location in df.columns]
    )
    if X_MIN is not None and X_MAX is not None:
        axes.set_xlim((X_MIN, X_MAX))
    axes.set_ylim(bottom=0.0)

    plotter.save_figure(
        fig, filename=f"time-variant-{'Google mobility'}", title_text="Google mobility"
    )
Beispiel #2
0
def plot_outputs_single(
    plotter: Plotter,
    scenario: Scenario,
    output_config: dict,
    is_logscale=False,
    axis=None,
    single_panel=True,
    xaxis_date=False,
):
    """
    Plot the model derived/generated outputs requested by the user for a single scenario.
    """
    if single_panel:
        fig, axis, _, _, _, _ = plotter.get_figure()

    if is_logscale:
        axis.set_yscale("log")

    output_name = output_config["output_key"]
    target_values = output_config["values"]
    target_times = output_config["times"]
    _plot_outputs_to_axis(axis, scenario, output_name)
    _plot_targets_to_axis(axis, target_values, target_times)

    if xaxis_date:
        change_xaxis_to_date(axis, REF_DATE)

    if X_MIN is not None and X_MAX is not None:
        axis.set_xlim((X_MIN, X_MAX))

    if single_panel:
        plotter.save_figure(fig, filename=output_name, subdir="outputs", title_text=output_name)
Beispiel #3
0
def tidy_cdr_axis(axis, rotation, start_date, end_date):
    """
    Tidy up a plot axis in the same way for both the two previous figures
    """
    change_xaxis_to_date(axis, ref_date=REF_DATE, rotation=rotation)
    axis.set_xlim([start_date, end_date])
    axis.set_ylim([0.0, 1.0])
    return axis
Beispiel #4
0
def plot_calibration(axis,
                     output,
                     outputs,
                     targets,
                     is_logscale,
                     ref_date=REF_DATE):
    # Track the maximum value being plotted
    label_font_size = 8

    max_value = 0.0
    for times, values in outputs:
        axis.plot(times, values)
        if len(values) > 0:
            max_value = max(values) if max(values) > max_value else max_value

    # Mark the MLE run with a dotted line
    axis.plot(outputs[-1][0],
              outputs[-1][1],
              linestyle=(0, (1, 3)),
              color="black",
              linewidth=3)

    # Add plot targets
    output_config = {"output_key": output, "values": [], "times": []}
    for t in targets.values():
        if t["output_key"] == output:
            output_config = t

    values = output_config["values"]
    times = output_config["times"]
    _plot_targets_to_axis(axis, values, times, on_uncertainty_plot=False)

    # Find upper limit for y-axis
    if values:
        upper_buffer = 2.0
        max_target = max(values)
        upper_ylim = (max_value if max_value < max_target * upper_buffer else
                      max_target * upper_buffer)
    else:
        upper_ylim = max_value

    if is_logscale:
        axis.set_yscale("log")
    else:
        axis.set_ylim([0.0, upper_ylim])

    # Sort out x-axis
    if output == "proportion_seropositive":
        axis.yaxis.set_major_formatter(
            mtick.PercentFormatter(1, symbol="", decimals=2))
        axis.set_ylabel("percentage", fontsize=label_font_size)
    axis.tick_params(axis="x", labelsize=label_font_size)
    axis.tick_params(axis="y", labelsize=label_font_size)
    change_xaxis_to_date(axis, ref_date, rotation=0)

    return axis
Beispiel #5
0
def plot_multicluster_mobility(
    plotter: StreamlitPlotter,
    calib_dir_path: str,
    mcmc_tables: List[pd.DataFrame],
    mcmc_params: List[pd.DataFrame],
    targets: dict,
    app_name: str,
    region: str,
):

    app = covid_19.app.get_region("victoria")
    params = app.params["default"]

    all_cluster_mobility_values = {}
    fig, axes, max_dims, n_rows, n_cols, _ = plotter.get_figure()

    for i_region in Region.VICTORIA_METRO + Region.VICTORIA_RURAL:
        google_mobility_values, google_mobility_days = get_mobility_data(
            params["country"]["iso3"],
            i_region.replace("-", "_").upper(), BASE_DATE,
            params["mobility"]["google_mobility_locations"])

        all_cluster_mobility_values[i_region] = google_mobility_values
    for i_region in Region.VICTORIA_METRO:
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["work"], 7),
                  color="k",
                  alpha=0.5)
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["other_locations"],
                      7),
                  color="g",
                  alpha=0.5)
    for i_region in Region.VICTORIA_RURAL:
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["work"], 7),
                  color="b",
                  alpha=0.5)
        axes.plot(google_mobility_days,
                  apply_moving_average(
                      all_cluster_mobility_values[i_region]["other_locations"],
                      7),
                  color="brown",
                  alpha=0.5)
    axes.set_xlim(left=STANDARD_X_LIMITS[0], right=STANDARD_X_LIMITS[1])
    axes.set_ylim(top=1.)
    change_xaxis_to_date(axes, REF_DATE, rotation=0)

    plotter.save_figure(fig,
                        filename=f"multi_cluster_mobility",
                        title_text="Google mobility")
Beispiel #6
0
def plot_multi_fit(
    plotter: Plotter,
    output_names: list,
    outputs: dict,
    targets,
    is_logscale=False,
    title_font_size=8,
    label_font_size=8,
    dpi_request=300,
    capitalise_first_letter=False,
):

    fig, axes, _, n_rows, n_cols, indices = plotter.get_figure(
        len(output_names), share_xaxis=True)

    for i_output in range(n_rows * n_cols):
        if i_output < len(output_names):
            output = output_names[i_output]
            axis = plot_calibration(
                axes[indices[i_output][0], indices[i_output][1]],
                output,
                outputs[output],
                targets,
                is_logscale,
            )
            change_xaxis_to_date(axis, REF_DATE, rotation=0)
            axis.set_title(
                get_plot_text_dict(
                    output, capitalise_first_letter=capitalise_first_letter),
                fontsize=title_font_size,
            )
            filename = f"calibration-fit-{output}"
        else:
            axes[indices[i_output][0], indices[i_output][1]].axis("off")

    fig.tight_layout()
    plotter.save_figure(fig, filename=filename, dpi_request=dpi_request)
Beispiel #7
0
def plot_timeseries_with_uncertainty(plotter: Plotter,
                                     uncertainty_df: pd.DataFrame,
                                     output_name: str,
                                     scenario_idxs: List[int],
                                     targets: dict,
                                     is_logscale=False,
                                     x_low=0.0,
                                     x_up=1e6,
                                     axis=None,
                                     n_xticks=None,
                                     ref_date=REF_DATE,
                                     add_targets=True,
                                     overlay_uncertainty=True,
                                     title_font_size=12,
                                     label_font_size=10,
                                     dpi_request=300,
                                     capitalise_first_letter=False,
                                     legend=False,
                                     requested_x_ticks=None,
                                     show_title=True,
                                     ylab=None,
                                     x_axis_to_date=True,
                                     start_quantile=0,
                                     sc_colors=None,
                                     custom_title=None,
                                     vlines={},
                                     hlines={}):
    """
    Plots the uncertainty timeseries for one or more scenarios.
    Also plots any calibration targets that are provided.
    """

    single_panel = axis is None
    if single_panel:
        fig, axis, _, _, _, _ = plotter.get_figure()

    n_scenarios_to_plot = len(scenario_idxs)
    if sc_colors is None:
        n_scenarios_to_plot = min([len(scenario_idxs), len(COLORS)])
        colors = _apply_transparency(COLORS[:n_scenarios_to_plot],
                                     ALPHAS[:n_scenarios_to_plot])

    # Plot each scenario on a single axis
    data_to_return = {}
    for i, scenario_idx in enumerate(scenario_idxs[:n_scenarios_to_plot]):
        if sc_colors is None:
            if scenario_idx < len(colors):
                scenario_colors = colors[scenario_idx]
            else:
                scenario_colors = colors[-1]
        else:
            scenario_colors = sc_colors[i]

        times, quantiles = _plot_uncertainty(
            axis,
            uncertainty_df,
            output_name,
            scenario_idx,
            x_up,
            x_low,
            scenario_colors,
            overlay_uncertainty=overlay_uncertainty,
            start_quantile=start_quantile,
            zorder=i + 1,
        )

        data_to_return[scenario_idx] = pd.DataFrame.from_dict(quantiles)
        data_to_return[scenario_idx].insert(0, "days from 31/12/2019", times)

    # Add plot targets
    if add_targets:
        values, times = _get_target_values(targets, output_name)
        trunc_values = [
            v for (v, t) in zip(values, times) if x_low <= t <= x_up
        ]
        trunc_times = [
            t for (v, t) in zip(values, times) if x_low <= t <= x_up
        ]
        _plot_targets_to_axis(axis,
                              trunc_values,
                              trunc_times,
                              on_uncertainty_plot=True)

    # Sort out x-axis
    if x_axis_to_date:
        change_xaxis_to_date(axis, ref_date, rotation=0)
    axis.tick_params(axis="x", labelsize=label_font_size)
    axis.tick_params(axis="y", labelsize=label_font_size)

    # Add lines with marking text to plots
    add_vertical_lines_to_plot(axis, vlines)
    add_horizontal_lines_to_plot(axis, hlines)

    if output_name == "proportion_seropositive":
        axis.yaxis.set_major_formatter(mtick.PercentFormatter(1, symbol=""))
    if show_title:
        title = custom_title if custom_title else get_plot_text_dict(
            output_name)
        axis.set_title(title, fontsize=title_font_size)

    if requested_x_ticks is not None:
        pyplot.xticks(requested_x_ticks)
    elif n_xticks is not None:
        pyplot.locator_params(axis="x", nbins=n_xticks)

    if is_logscale:
        axis.set_yscale("log")
    elif not (output_name.startswith("rel_diff")
              or output_name.startswith("abs_diff")):
        axis.set_ylim(ymin=0)

    if ylab is not None:
        axis.set_ylabel(ylab, fontsize=label_font_size)

    if legend:
        pyplot.legend(labels=scenario_idxs)

    if single_panel:
        idx_str = "-".join(map(str, scenario_idxs))
        filename = f"uncertainty-{output_name}-{idx_str}"
        plotter.save_figure(fig, filename=filename, dpi_request=dpi_request)

    return data_to_return