Esempio n. 1
0
def explore_object(name, obj, where=st):
    """
    Explore methods of object.
    """

    fn = select_method(name, obj, where=where)
    args, kwargs = select_arguments(fn, where=where)

    t0 = time.time()
    msg = st.empty()
    result = fn(*args, **kwargs)
    msg.info(_("Method executed in {} seconds.").format(fmt(time.time() - t0)))

    st.line()
    st.subheader(_("Method help and signature"))
    st.help(fn)

    if result is not None:
        st.line()
        st.subheader(_("Function output"))

        if isinstance(result, plt.Axes):
            st.markdown(_("Function returned a matplotlib **ax** object. Showing it..."))
            st.pyplot(result.get_figure())
        else:
            st.write(result)
Esempio n. 2
0
def show_results(
    parent_region,
    regions,
    columns,
    targets,
    days,
    scenario,
    disease=covid19,
    transpose=False,
):
    """
    Show results from user input.
    """

    parent_region = mundi.region(parent_region)
    parent_region.ui.cases_and_deaths(disease=disease, grid=True, logy=True)

    if days and targets and columns:
        info = scenario["info"]
        info_cols = tuple(info)
        df = get_dataframe(
            regions, tuple(days), tuple(targets), tuple(columns), info_cols=info_cols
        )
        get = {**COL_NAMES, **info}.get
        df.columns = pd.MultiIndex.from_tuples(
            [tuple(_(get(x, x) for x in t)) for t in df.columns.to_list()]
        )
        if transpose:
            df = df.T

        st.subheader(_("Download results"))
        st.dataframe_download(df, name="report-brazil.{ext}")
Esempio n. 3
0
def options(where=st.sidebar):
    st = where

    opts = {
        None: _("Brazil"),
        "BR-1": _("North"),
        "BR-2": _("Northeast"),
        "BR-3": _("Southeast"),
        "BR-4": _("South"),
        "BR-5": _("Midwest"),
    }
    st.subheader(_("Region"))
    opt = st.radio(_("Select region"), [*opts], format_func=opts.get)
    if opt is None:
        regs = regions("BR", type="region", parent_id="BR")
    else:
        regs = regions(type="state", parent_id=opt)

    opts = {"cases": _("Cases"), "deaths": _("Deaths")}
    msg = _("Cases or deaths?")
    column = st.radio(msg, [*opts], format_func=opts.get)

    st.subheader(_("Plotting options"))
    lines = st.checkbox(_("Show Lines"))
    logy = False
    if lines:
        logy = st.checkbox(_("Logarithm scale"))

    return {"lines": lines, "logy": logy, "regions": regs, "column": column}
Esempio n. 4
0
def select_arguments(fn, where=st):
    """
    Select arguments from a callable object.

    This method only works if we are able to introspect the object signature.
    """

    st = where
    sig = inspect.Signature.from_callable(fn)
    args = []
    kwargs = {}
    show_title = True

    for k, v in sig.parameters.items():
        if k == "where":
            continue
        if show_title:
            st.subheader(_("Arguments"))
            show_title = False
        if v.annotation == str:
            kwargs[k] = st.text_input(k)
        elif v.annotation == bool:
            kwargs[k] = st.checkbox(k)
        elif v.annotation == float:
            kwargs[k] = st.number_input(k)
        elif v.annotation == int:
            kwargs[k] = st.number_input(k)
        else:
            st.text(k)

    return args, kwargs
Esempio n. 5
0
    def show(self):
        """
        Show results from user input.
        """
        parent_region = self.user_inputs["parent_region"]
        regions = self.user_inputs["regions"]
        columns = self.user_inputs["columns"]
        targets = self.user_inputs["targets"]
        days = self.user_inputs["days"]
        scenario = self.user_inputs["scenario"]
        transpose = self.user_inputs["transpose"]
        disease = self.user_inputs["disease"]

        parent_region = mundi.region(parent_region)
        parent_region.ui.cases_and_deaths(disease=disease, grid=True, logy=True)

        if days and targets and columns:
            info = scenario["info"]
            info_cols = tuple(info)
            df = self.get_dataframe(
                regions, tuple(days), tuple(targets), tuple(columns), info_cols=info_cols
            )
            get = {**COL_NAMES, **info}.get
            df.columns = pd.MultiIndex.from_tuples(
                [tuple(_(get(x, x) for x in t)) for t in df.columns.to_list()]
            )
            if transpose:
                df = df.T

            st.subheader(_("Download results"))
            st.dataframe_download(df, name="report-brazil.{ext}")
Esempio n. 6
0
def options(where=st):
    st = where
    regs = regions("BR", type="state")

    # Regions to highlight
    st.subheader(_("Highlight"))
    opts = {
        "BR-1": _("North"),
        "BR-2": _("Northeast"),
        "BR-3": _("Southeast"),
        "BR-4": _("South"),
        "BR-5": _("Midwest"),
        "select": _("Select states"),
        # 'top5': _('Top 5'), NotImplemented
    }
    msg = _("Which states do you want to highlight?")
    opt = st.radio(msg, [*opts], format_func=opts.get)
    if opt == "select":
        fmt = {r.id: r.name for r in regs}.get
        ids = [r.id for r in regs]
        msg = _("Select states to highlight")
        select = set(
            st.multiselect(msg, ids, format_func=fmt, default=[regs[0].id]))
        highlight = [r for r in regs if r.id in select]
    elif opt == "top5":
        highlight = opt
    else:
        highlight = [r for r in regs if r.parent_id == opt]

    # Options
    st.subheader(_("Options"))
    logy = not st.checkbox(_("Linear scale"))

    column = "deaths" if st.checkbox(_("Plot deaths")) else "cases"

    diff = st.checkbox(_("Plot new daily cases"))

    population_adj = st.checkbox(_("Adjust for population"))

    default = (20 if diff else 100) // (1 if column == "cases" else 10)
    thresh = st.number_input(_("Minimum number of cases"),
                             min_value=0,
                             value=default)

    default = 7 if diff else 0
    smooth = st.number_input(_("Smooth over n days"),
                             min_value=0,
                             value=default)

    return {
        "regions": regs,
        "highlight": highlight,
        "diff": diff,
        "thresh": thresh,
        "smoothing": smooth,
        "column": column,
        "logy": logy,
        "population_adj": population_adj,
    }
Esempio n. 7
0
def sidebar(where=st.sidebar):
    st = where

    st.subheader(_("Section"))
    msg = _("Which section do you want to see?")
    key = st.radio(msg, list(APPS), format_func=lambda x: APPS[x].DISPLAY_NAME)
    app = APPS[key]
    opts = app.options(where=where)
    return app.show, opts
Esempio n. 8
0
def show_results(parent_region, regions, columns, targets, days, disease=covid19):
    """
    Show results from user input.
    """

    parent_region = mundi.region(parent_region)
    ax = parent_region.plot.cases_and_deaths(disease=disease, logy=True, grid=True)
    st.pyplot(ax.get_figure())
    if days and targets and columns:
        df = get_dataframe(regions, tuple(days), tuple(targets), tuple(columns), 61)

        st.subheader(_("Download results"))
        st.dataframe_download(df, name="report-brazil.{ext}")
    def show(self):

        parent_region = self.__datahandler.user_inputs["parent_region"]
        columns = self.__datahandler.user_inputs["columns"]
        targets = self.__datahandler.user_inputs["targets"]
        days = self.__datahandler.user_inputs["days"]
        disease = self.__datahandler.user_inputs["disease"]

        parent_region = mundi.region(parent_region)
        axes = parent_region.plot.cases_and_deaths(disease=disease, logy=True, grid=True)
        st.pyplot(axes.get_figure())
        if days and targets and columns:
            df = self.__datahandler.get_dataframe(tuple(days), tuple(targets), tuple(columns))

            st.subheader(_("Download results"))
            st.dataframe_download(df, name="report-brazil.{ext}")
Esempio n. 10
0
    def decorated(*args,
                  title=NOT_GIVEN,
                  header=NOT_GIVEN,
                  subheader=NOT_GIVEN,
                  **kwargs):

        st = kwargs.get("where", st_mod) if where is None else where

        if header is not NOT_GIVEN and not isinstance(header, bool):
            st.header(str(header))
        elif subheader is not NOT_GIVEN and not isinstance(subheader, bool):
            st.subheader(str(subheader))
        if title is not NOT_GIVEN or default:
            if subheader or level == "subheader":
                st.subheader(str(title))
            else:
                st.header(str(title))

        return fn(*args, **kwargs)
Esempio n. 11
0
def sidebar(where=st.sidebar) -> dict:
    """
    Run sidebar that asks for user input.
    """

    st = where
    st.header(_("Brazilian Epidemiological indicators"))

    st.subheader(_("Sections"))
    opts = {k: v.title for k, v in SECTIONS.items()}
    opts["download"] = _("Download data")
    msg = _("Select a section")
    section = st.radio(msg, list(opts), format_func=opts.get)

    st.subheader(_("Filter results"))
    regions = select_regions(where=st)

    st.subheader(_("Options"))
    opts = {
        "static_table": st.checkbox(_("Static tables")),
        "cmap": st.selectbox(_("Colormap"), COLOR_MAPS, index=COLOR_MAPS.index("BuPu")),
    }

    return {"regions": regions, "section": section, **opts}
Esempio n. 12
0
def main(region="BR", disease=covid19):
    st.css()
    params = sidebar(
        region=region,
        disease=disease,
        secret_date=datetime.date(1904, 11, 10),
        secret_function=lambda: easter_egg(disease),
    )
    if params is None:  # Secret function was activated
        return

    debug = False

    if DEBUG and st.checkbox(_("Enable debug")):
        st.info(_("Running in debug mode!"))
        st.html(
            """
        <ul>
            <li><a href="#debug">{}</a></li>
        </ul>""".format(
                _("Debug section!")
            )
        )
        debug = True

    epidemiology = extract_keys(PARAMS, params)
    clinical = extract_keys(CLINICAL, params)

    # Run infections model
    m = cm = results = None
    try:
        m = model(disease=disease, **epidemiology)
        cm = m.clinical.overflow_model(icu_occupancy=0, hospital_occupancy=0, **clinical)
        cm.extra_info = params
        output(cm)

    finally:
        if debug:
            if results:
                st.html('<div style="height: 15rem"></div>')
            st.html('<h2 id="debug">{}</h2>'.format(_("Debug information")))

            st.subheader(_("Generic parameters"))
            st.write(params)

            st.subheader(_("Epidemiological parameters"))
            st.write(epidemiology)

            st.subheader(_("Clinical parameters"))
            st.write(clinical)

            st.subheader(_("Output"))
            st.write(results)

            if m:
                st.line_chart(m.data)

            if cm:
                st.line_chart(cm[["infectious", "severe", "critical"]])

                st.subheader(_("Distribution of deaths"))
                df = cm[DEATH_DISTRIBUTION_COLUMNS]
                df.columns = [DEATH_DISTRIBUTION_COL_NAMES[k] for k in df.columns]
                st.area_chart(df)
Esempio n. 13
0
def sidebar(title, where=st.sidebar, embed=False, disease="covid-19"):
    """
    Collect inputs in the sidebar or other location.
    """

    st = where
    region = st.region_input("BR", text=True)
    title(_("Covid risk factors ({name})").format(name=_(region.name)))

    # Scenarios
    model = start_model(region, disease)
    R0 = model.R0

    st.header(_("Forecast scenarios"))
    subs = {"R0": fmt(R0), "place": _(region.name)}
    st.markdown(
        _("""The computed value of R0 for {place} is **{R0}**. Let us
    consider 3 different scenarios: the first progress with this value of R0, the
    second increases social isolation to obtain a lower R0 and the third loosen
    social isolation and correspond to a higher R0.""").format(**subs))

    st.subheader("Scenario 1: more isolation")
    msg = _("What is the new R0?")
    R0_tight = st.slider(msg, 0.1, R0, R0 * 0.66)

    st.subheader("Scenario 2: less isolation")
    R0_loose = st.slider(msg, R0, max(2 * R0, 3.0), 1.33 * R0)
    R0_list = (R0, R0_tight, R0_loose)

    # Parameters
    st.header(_("Parameters"))
    st.subheader(_("Healthcare system"))
    if np.isnan(region.icu_capacity):
        population = region.population

        msg = _("Total ICU beds")
        icu = int(population / 10_000)
        icu = st.number_input(msg, min_value=0, value=icu)

        msg = _("Total hospital beds")
        hospital = int(population / 1_000)
        hospital = st.number_input(msg, min_value=0, value=hospital)

    else:
        icu = region.icu_capacity
        hospital = region.hospital_capacity

    msg = _("Fraction of ICU beds that is occupied?")
    rate = 1 - st.slider(msg, 0, 100, value=75) / 100

    # Options
    def ask(title, **kwargs):
        if embed:
            return True
        return st.checkbox(title, **kwargs)

    st.header(_("Options"))
    st.subheader(_("Plotting options"))
    options = {
        "logy": not ask(_("Linear scale")),
        "grid": not ask(_("Hide grid"))
    }
    st.subheader(_("Advanced information"))
    options = {
        "plot_opts": options,
        "show_weekday_rate": ask(_("Notification per weekday")),
    }

    return {
        "region": region,
        "icu_capacity": icu,
        "hospital_capacity": hospital,
        "icu_surge_capacity": rate * icu,
        "hospital_surge_capacity": rate * hospital,
        "R0_list": R0_list,
        **options,
    }
Esempio n. 14
0
def show_outputs(base, group, region: RegionT, plot_opts, clinical_opts,
                 **kwargs):
    """
    Show results from user input.
    """
    cmodels = group.clinical.overflow_model(**clinical_opts)
    cforecast = cmodels[0]
    start = base.info["event.simulation_start"]

    #
    # Introduction
    #
    st.header(_("Introduction"))
    st.markdown(report_intro(region))
    st.cards(
        {
            _("Basic reproduction number"): fmt(base.R0),
            _("Ascertainment rate"): pc(
                base.info["observed.notification_rate"]),
        },
        color="st-gray-900",
    )

    #
    # Forecast
    #
    st.header(_("Forecasts"))
    st.markdown(forecast_intro(region))

    # Infectious curve
    group["infectious:dates"].plot(**plot_opts)
    mark_x(start.date, "k--")
    plt.legend()
    plt.title(_("Active cases"))
    plt.tight_layout()
    st.pyplot()

    st.markdown("#### " + _("Download data"))
    opts = ["critical", "severe", "infectious", "cases", "deaths"]
    default_columns = ["critical", "severe", "cases", "deaths"]
    columns = st.multiselect(_("Select columns"),
                             opts,
                             default=default_columns)

    rename = dict(zip(range(len(columns)), columns))
    columns = [c + ":dates" for c in columns]
    data = pd.concat([cm[columns].rename(rename, axis=1) for cm in cmodels],
                     axis=1,
                     keys=cmodels.names)
    st.data_anchor(data.astype(int), f"data-{region.id}.csv")

    #
    # Reopening
    #
    st.header(_("When can we reopen?"))
    st.markdown(reopening_intro(region))

    st.subheader(_("Step 1: Controlling the curve"))
    st.markdown(rt_intro(region))

    st.subheader(_("Step 2: Testing"))
    st.markdown(rt_intro(region))
    if kwargs.get("show_weekday_rate"):
        region.ui.weekday_rate()

    st.subheader(_("Step 3: Hospital capacity"))
    st.markdown(rt_intro(region))

    # Hospitalization
    cmodels["critical:dates"].plot(**plot_opts)
    mark_x(start.date, "k--")
    mark_y(cforecast.icu_surge_capacity, "k:")
    plt.legend()
    plt.title(_("Critical cases"))
    plt.tight_layout()
    st.pyplot()
Esempio n. 15
0
""")

# Show cases
cases = info.get_cases_for_region(region)
data = info.get_seair_curves_for_region(region, notification_rate=notification)

n_cases = len(cases)
ui.cases_and_deaths_plot(cases, logy=logy, grid=grid)

# Run model
cm = run_model(region, duration, R0, notification)
data_size = cm.iter - duration

# Show results
st.header("Simulation results")
st.subheader("Cases and deaths")
plot_cases_and_projection(cm, cases)

#
# Cards
#
st.subheader(_("New deaths"))
progression_cards(cm["deaths"], color="st-red")

st.subheader(_("New cases"))
opts = [_("Estimated"), _("Reported")]
is_reported = st.radio(_("Reporting"), [0, 1], format_func=opts.__getitem__)
mul = notification if is_reported else 1.0
progression_cards(cm["cases"] * mul, color="st-gray-900")

st.subheader(_("Hospitalizations"))