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)
def main(embed=False, disease=None): """ Run application. """ if not embed: st.css(keep_menu=True) st.sidebar.logo() title = st.empty().title title(_("Covid risk factors")) else: title = lambda *args: None opts = sidebar(title, where=st if embed else st.sidebar, embed=embed, disease=disease) show_opts = extract_keys(SHOW_OPTS, opts) clinical_opts = extract_keys(CLINICAL_OPTS, opts) run_opts = extract_keys(RUN_OPTS, opts) # Start model with known R0 region = opts["region"] plot_opts = show_opts["plot_opts"] st.header(_("Cases and deaths")) region.ui.epidemic_summary() region.ui.cases_and_deaths(title=None, download=f"cases-{region.id}.csv", **plot_opts) model = start_model(**opts) group = start_group(model, **run_opts) show_outputs(model, group, clinical_opts=clinical_opts, **opts, **show_opts)
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 show(self): curves = self.get_epidemic_curves(self.user_inputs['states'].index).fillna(0) # Acc cases ax = curves.iloc[-30:, self.user_inputs['idx']::2].plot(legend=False, grid=True) curves[self.user_inputs['loc'], self.user_inputs['which']].iloc[-30:].plot(ax=ax, legend=False, grid=True) st.pyplot() # Daily cases # ax = curves.iloc[-30:, self.user_inputs['idx']::2] # curves[self.user_inputs['loc'], self.user_inputs['which']] \ # .iloc[-30:] \ # .diff() \ # .plot(ax=ax, legend=False, grid=True) # st.pyplot() # # Growth factors growths = self.get_growths(self.user_inputs['states'].index, self.user_inputs['which']) ci = pd.DataFrame({"low": growths["value"] - growths["std"], "std": growths["std"]}) st.header("Growth factor +/- error") ci.plot.bar(width=0.9, ylim=(0.8, 2), stacked=True, grid=True) plt.plot(self.user_inputs['states'].index, [1] * len(self.user_inputs['states']), "k--") st.pyplot() # # Duplication times st.header("Duplication time") (np.log(2) / np.log(growths["value"])).plot.bar(grid=True, ylim=(0, 30)) st.pyplot() # R0 st.header("R0") params = covid19.params(region=self.user_inputs['loc']) ( np.log(growths["value"]) .apply(lambda K: formulas.R0_from_K("SEAIR", params, K=K)) .plot.bar(width=0.9, grid=True, ylim=(0, 4)) ) st.pyplot() ms_good, ms_keep, ms_bad = self.run_models(self.user_inputs['states'].index, self.user_inputs['which']) # ICU overflow for ms, msg in [ (ms_keep, "keep trends"), (ms_bad, "no distancing"), (ms_good, "more distancing"), ]: st.header(f"Deaths and ICU overflow ({msg})") deaths = pd.DataFrame({m.region.id: m["deaths:dates"] for m in ms}) deaths.plot(legend=False, color="0.5") deaths.sum(1).plot(grid=True) deaths[self.user_inputs['loc']].plot(legend=True, grid=True) st.cards({"Total de mortes": fmt(deaths.iloc[-1].sum())}) st.pyplot() data = {} for m in ms: overflow = m.results["dates.icu_overflow"] if overflow: data[m.region.id] = (overflow - pd.to_datetime(today())).days if data: data = pd.Series(data) data.plot.bar(width=0.9, grid=True) st.pyplot()
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, }
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()
values. """) # 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")
from pydemic.utils import trim_zeros import pandas as pd from fbprophet import Prophet from matplotlib import pyplot as plt from mundi import region from pydemic.models import SEAIR from pydemic.region import RegionT from pydemic_ui import st plt.gcf() for r in [ "US", "DE", "IT", "CN", "ES", "BR", "BR-SP", "BR-MG", "BR-PA", "BR-MS" ]: br: RegionT = region(r) st.header(br.name) cases = br.pydemic.epidemic_curve() new = cases.diff().iloc[15:] new.plot(grid=True, logy=True) st.pyplot() col: pd.Series = new["cases"] # col = trim_zeros(col.where(col < 10, 0)) Y = col.reset_index().rename(columns={"date": "ds", "cases": "y"}) Y["cap"] = cap = 100 * Y["y"].max() m = Prophet( changepoint_range=0.9, weekly_seasonality=True,