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}
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, }
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
def ask(self, parent_region="BR", where=st.sidebar): st = where scenario_kind = st.selectbox(_("Select scenario"), list(REGIONS_TYPES[parent_region])) scenario = REGIONS_TYPES[parent_region][scenario_kind] regions = self.__datahandler.get_regions(**scenario["query"]) if "filter" in scenario: filtering = scenario["filter"] format_func = filtering.pop("format_func", None) if format_func is not None: function = format_func def format_func(x): if x == "all": return _("All") return function(x) field, message = filtering.popitem() groups = sk.group_by(lambda x: getattr(x, field), regions) key = st.selectbox(message, ["all", *groups], format_func=format_func) if key != "all": regions = groups[key] message = _("Columns") columns = st.multiselect(message, COLUMNS, default=COLUMNS_DEFAULT) message = _("Isolation scores") kwargs = {"default": TARGETS_DEFAULT, "format_func": lambda x: f"{x}%"} targets = st.multiselect(message, TARGETS, **kwargs) message = _("Show values for the given days") days = st.multiselect(message, DAYS, default=DAYS_DEFAULT) if any(not isinstance(d, int) for d in days): day_max = sk.pipe( days, sk.remove(lambda d: isinstance(d, int)), sk.map(lambda d: int(NUMBER.search(d).groups()[0])), max, ) days = list(range(1, day_max + 1)) message = _("Transpose data") transpose = st.checkbox(message, value=False) self.__datahandler.user_inputs = { "parent_region": parent_region, "regions": regions, "columns": columns, "targets": targets, "days": days, "scenario": scenario, "transpose": transpose, "disease": "covid-19" }
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}
def sidebar(parent_region="BR", where=st.sidebar): """ Collect input parameters for the app to run. Returns: Dictionary with the following keys: parent_region, regions, columns, targets, days """ st = where kind = st.selectbox(_("Select scenario"), list(REGIONS_TYPES[parent_region])) scenario = REGIONS_TYPES[parent_region][kind] regions = get_regions(**scenario["query"]) if "filter" in scenario: filtering = scenario["filter"] format_func = filtering.pop("format_func", None) if format_func is not None: fn = format_func def format_func(x): if x == "all": return _("All") return fn(x) field, msg = filtering.popitem() groups = sk.group_by(lambda x: getattr(x, field), regions) key = st.selectbox(msg, ["all", *groups], format_func=format_func) if key != "all": regions = groups[key] msg = _("Columns") columns = st.multiselect(msg, COLUMNS, default=COLUMNS_DEFAULT) msg = _("Isolation scores") kwargs = {"default": TARGETS_DEFAULT, "format_func": lambda x: f"{x}%"} targets = st.multiselect(msg, TARGETS, **kwargs) msg = _("Show values for the given days") days = st.multiselect(msg, DAYS, default=DAYS_DEFAULT) if any(not isinstance(d, int) for d in days): day_max = sk.pipe( days, sk.remove(lambda d: isinstance(d, int)), sk.map(lambda d: int(NUMBER.search(d).groups()[0])), max, ) days = list(range(1, day_max + 1)) msg = _("Transpose data") transpose = st.checkbox(msg, value=False) return { "parent_region": parent_region, "regions": regions, "columns": columns, "targets": targets, "days": days, "scenario": scenario, "transpose": transpose, }
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)
def ask(title, **kwargs): if embed: return True return st.checkbox(title, **kwargs)
st.subheader(_("Dataset")) opts = { "show": _("Show in screen"), "csv": _("Comma separated values"), "xlsx": _("Excel"), } mime = {"csv": "text/csv", "xls": "application/vnd.ms-excel"} opt = st.radio(_("How do you want your data?"), list(opts), format_func=opts.get) df = pd.concat(data, axis=1) df.index = base.to_dates(df.index) df = df.astype(int) if not st.checkbox(_("Keep observed period")): df = df.iloc[data_size:] if opt == "show": st.write(df) else: df.index = [d.strftime("%Y-%m-%d") for d in df.index] if opt == "csv": fd = io.StringIO() df.to_csv(fd) data = fd.getvalue().encode("utf8") else: fd = io.BytesIO() df.to_excel(fd) data = fd.getvalue() data = base64.b64encode(data).decode("utf8")
mu, sigma = r_stats(data.values) T = data.index N = len(T) x0 = data.iloc[0] st.line_chart( pd.DataFrame( { "data": np.log(data.values), "mean": np.log(progression(mu, x0, N)), "high": np.log(progression(mu + sigma, x0, N)), "low": np.log(progression(mu - sigma, x0, N)), }, index=T, )) if st.checkbox("show?"): r_mean = mu r_sigma = sigma r_sigma_rel = r_sigma / r_mean st.experimental_show(r_mean) st.experimental_show(r_sigma) st.experimental_show(r_sigma_rel) st.line_chart( pd.DataFrame( { "approx": log_Zk(K, Y, approx=True), "no-approx": log_Zk(K, Y, approx=False) }, index=K,