Beispiel #1
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
Beispiel #2
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,
    }
Beispiel #3
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,
    }
Beispiel #4
0
from collections import namedtuple

import numpy as np
import pandas as pd
from scipy import special as sfn, optimize

from pydemic_ui import st

MeanStd = namedtuple("MeanStd", ("mean", "std"))

r = st.number_input("Growth factor", value=1.2)
N = st.number_input("N", value=50)
alpha = st.number_input("alpha", value=2.0, format="%0.4g")
rng = np.random.default_rng()


# @st.cache
def test_data(r, N, alpha):
    X = np.linspace(0, 10, N)
    R = rng.gamma(alpha, r / alpha, size=N)
    Y = np.multiply.accumulate(R)
    return pd.Series(Y, index=X)


def log_Zk(alpha, Y, approx=False):
    alpha = np.asarray(alpha)
    if not alpha.shape:
        return np.sum(log_Zk(np.array([alpha]), Y, approx))

    eta = (Y[1:] / Y[:-1])[None, :]
    delta = np.log(eta.mean()) - np.log(eta).mean()