def epidemic_curves_plot(regions: Sequence[RegionT], smooth_windows=(7, 2), column="cases", where=st, lines=False, logy=False, **kwargs): st = where data = epidemic_curves_data(regions, column, **kwargs) names = {r.id: r.name for r in regions} window_lines, window_bar = smooth_windows if lines: (data.rename(columns=names).rolling(window_lines, center=True, min_periods=1).mean().plot( logy=logy, grid=True)) else: (data.rename(columns=names).rolling( window_bar, center=True).mean().plot(kind="bar", grid=True, stacked=True, width=1)) xticks = plt.xticks()[0][::7] dates = pd.to_datetime(xticks, unit="D", origin=data.index[0]) dates = [d.strftime("%d/%m") for d in dates] plt.xticks(xticks, dates, rotation=45) plt.ylim((0, None)) plt.tight_layout() st.pyplot()
def show( regions, highlight, column="cases", logy=True, thresh=100, diff=False, smoothing=0, population_adj=False, where=st, ): st = where regions = set(regions) highlight = set(highlight) regions.difference_update(highlight) for opt, regs in [ ({"color": "0.7", "legend": False}, regions), ({"legend": True, "lw": 2}, highlight), ]: for reg in regs: data = reg.pydemic.epidemic_curve(diff=diff)[column] if population_adj: data *= 1e6 / reg.population if smoothing: data = data.rolling(smoothing, center=True, min_periods=1).mean() data = data[data >= thresh].reset_index(drop=True) data.plot(logy=logy, grid=True, label=reg.name, **opt) plt.tight_layout() st.pyplot()
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)
def plot_cases_and_projection(model, cases): cases = cases.reset_index(drop=True) cases.index = cases.index - len(cases) corrected = cases["cases"] / notification cases["cases"].plot() cases["deaths"].plot() corrected.plot() m_cases = model["cases"] m_cases.index = m_cases.index - len(cases) m_cases.plot() m_deaths = model["deaths"] m_deaths.index = m_deaths.index - len(cases) m_deaths.plot() plt.ylim(10, None) plt.mark_x(0, "k--") plt.tight_layout("x") plt.legend() if grid: plt.grid() if logy: plt.yscale("log") st.pyplot()
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}")
def hospitalization_chart(model, shift=0): df = model[["severe", "critical"]] df.index = df.index - shift df.plot(grid=grid) plt.mark_y(model.hospital_surge_capacity, "--", color=plt.color(2), label=_("Hospital beds")) plt.mark_y(model.icu_surge_capacity, "--", color=plt.color(2), label=_("ICU")) if shift: plt.mark_x(0, "k--") plt.legend() plt.tight_layout("x") st.pyplot()
cases *= col[-1] / cases.sum() return cases def seir_curves(cases, params, **kwargs): for param in ["gamma", "sigma", "prob_symptoms", "rho", "R0"]: kwargs.setdefault(param, getattr(params, param)) return fit.seair_curves(cases, **kwargs) notification = st.slider("Sub-notificação", 0.01, 0.30, value=0.13) R0 = st.slider("R0", 0.1, 3.0, value=2.0) m = models.SEAIR(region=region, disease=covid19, R0=R0) data = seir_curves(cases["cases"] / notification, params, population=region.population) m.set_data(data) m.run(60) cm = m.clinical.overflow_model() ax = cases.plot() ax = (cases["cases"] / notification).plot(ax=ax) cm.plot(["cases:dates", "deaths:dates"], ax=ax, logy=True) st.pyplot() df = pd.concat([cases.diff(), fit_infectious(cases)], axis=1) df = np.maximum(df, 1).dropna() st.line_chart(np.log(df))
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 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()