Beispiel #1
0
def run_seir(w_date,
             w_location,
             cases_df,
             population_df,
             w_location_granulariy,
             r0_dist,
             w_params=DEFAULT_PARAMS,
             sample_size=SAMPLE_SIZE,
             reported_rate=None,
             NEIR0=None):

    if reported_rate is None:
        calc_reported_rate, cCFR = estimate_subnotification(
            w_location, w_date, w_location_granulariy)
        new_reported_rate = calc_reported_rate * 100
    else:
        new_reported_rate = reported_rate

    if NEIR0 is None:
        new_NEIR0 = make_NEIR0(cases_df, population_df, w_location, w_date,
                               reported_rate)
    else:
        new_NEIR0 = NEIR0

    w_params['r0_dist'] = r0_dist
    model = SEIRBayes(new_NEIR0, w_params['r0_dist'],
                      w_params['gamma_inv_dist'], w_params['alpha_inv_dist'],
                      new_reported_rate, w_params['t_max'])

    model_output = model.sample(sample_size)

    return (model, model_output, sample_size,
            w_params['t_max']), new_reported_rate, new_NEIR0
Beispiel #2
0
        st.altair_chart(
            plot_r0(r0_samples, w_date, _place, MIN_DAYS_r0_ESTIMATE))
        r0_dist = r0_samples[:, -1]
        st.markdown(
            f'**O $R_{{0}}$ estimado está entre '
            f'${np.quantile(r0_dist, 0.01):.03}$ e ${np.quantile(r0_dist, 0.99):.03}$**'
        )
        st.markdown(texts.r0_CITATION)
    else:
        r0_dist = make_r0_widgets()
        st.markdown(texts.r0_ESTIMATION_DONT)

    w_params = make_param_widgets(NEIR0)
    model = SEIRBayes(**w_params, r0_dist=r0_dist)
    model_output = model.sample(sample_size)
    ei_df = make_EI_df(model_output, sample_size)
    st.markdown(texts.MODEL_INTRO)
    st.write(texts.SEIRBAYES_DESC)
    w_scale = st.selectbox('Escala do eixo Y', ['log', 'linear'], index=1)
    fig = plot_EI(model_output, w_scale)
    st.altair_chart(fig)
    download_placeholder = st.empty()
    if download_placeholder.button('Preparar dados para download em CSV'):
        href = make_download_href(ei_df, w_params, should_estimate_r0)
        st.markdown(href, unsafe_allow_html=True)
        download_placeholder.empty()

    dists = [w_params['alpha_inv_dist'], w_params['gamma_inv_dist'], r0_dist]
    SEIR0 = model._params['init_conditions']
    st.markdown(texts.make_SIMULATION_PARAMS(SEIR0, dists, should_estimate_r0))
Beispiel #3
0
def write():

    st.markdown("## Modelo Epidemiológico (SEIR-Bayes)")
    st.markdown(texts.INTRO_MODELO)
    st.sidebar.markdown("---")
    st.sidebar.markdown(texts.PARAMETER_SELECTION)
    w_granularity = st.sidebar.selectbox('Unidade',
                                         options=['country', 'state'],
                                         index=1,
                                         format_func=global_format_func)

    cases_df = data.load_cases(w_granularity, 'fiocruz')
    population_df = data.load_population(w_granularity)
    srag_death_subnotification = data.load_srag_death_subnotification()
    vulnerable_population = data.load_vulnerable_population()

    DEFAULT_PLACE = (DEFAULT_STATE
                     if w_granularity == 'state' else DEFAULT_COUNTRY)

    options_place = make_place_options(cases_df, population_df, w_granularity)

    w_place = st.sidebar.selectbox(global_format_func(w_granularity),
                                   options=options_place,
                                   index=options_place.get_loc(DEFAULT_PLACE),
                                   format_func=global_format_func)
    try:
        raw_widget_values = (pd.read_csv('data/params.csv').set_index(
            'place').T.to_dict()[w_place])
        widget_values = {
            k: v
            for k, v in raw_widget_values.items() if not np.isnan(v)
        }
    except:
        widget_values = {}

    if widget_values:
        st.markdown("---")
        st.markdown("### Parâmetros carregados")
        st.write(
            f"Foram carregados parâmetros pré-selecionados para a unidade escolhida:  **{w_place}**."
        )
        st.write('  \n'.join(f"{param}: {value}"
                             for param, value in widget_values.items()))

    options_date = make_date_options(cases_df, w_place)
    w_date = st.sidebar.selectbox('Data inicial',
                                  options=options_date,
                                  index=len(options_date) - 1)

    # Configurações da simulação
    st.markdown(texts.SIMULATION_CONFIG)

    # Estimativa R0
    st.markdown(texts.r0_ESTIMATION_TITLE)
    should_estimate_r0 = st.checkbox('Estimar R0 a partir de dados históricos',
                                     value=True)
    if should_estimate_r0:
        r0_samples, used_brazil = estimate_r0(cases_df, w_place, SAMPLE_SIZE,
                                              MIN_DAYS_r0_ESTIMATE, w_date)
        if used_brazil:
            st.write(texts.r0_NOT_ENOUGH_DATA(w_place, w_date))

        _place = 'Brasil' if used_brazil else w_place
        st.markdown(texts.r0_ESTIMATION(_place, w_date))

        st.altair_chart(
            plot_r0(r0_samples, w_date, _place, MIN_DAYS_r0_ESTIMATE))
        r0_dist = r0_samples[:, -1]
        st.markdown(
            f'*O $R_{{0}}$ estimado está entre '
            f'${np.quantile(r0_dist, 0.01):.03}$ e ${np.quantile(r0_dist, 0.99):.03}$*'
        )
        st.markdown(texts.r0_CITATION)
    else:
        r0_dist = make_r0_widgets(widget_values)
        st.markdown(texts.r0_ESTIMATION_DONT)
    NEIR0 = make_NEIR0(cases_df, population_df, w_place, w_date,
                       np.mean(r0_dist))
    # Explicação dos parâmetros de óbito e leitos
    st.markdown(texts.DESC_PARAMS_DEATHS)
    st.markdown(texts.DESC_PARAMS_LEITOS)

    # Previsão de infectados
    (w_params, lethality_mean_place, lethality_type, death_subr_enable_place,
     death_subr_place) = make_param_widgets(NEIR0, widget_values,
                                            vulnerable_population.loc[w_place],
                                            w_place)

    # Deaths params
    lethality_mean_est, show_leth_age_message = estimate_lethality(
        cases_df[w_place]["deaths"], cases_df[w_place]["totalCases"],
        w_granularity, w_place, lethality_type)
    lethality_mean = make_death_widget(lethality_mean_est,
                                       lethality_mean_place, lethality_type,
                                       widget_values)
    death_subnotification = make_death_subr_widget(srag_death_subnotification,
                                                   w_place,
                                                   death_subr_enable_place,
                                                   death_subr_place)

    w_params['deaths'] = {
        "death_rate": lethality_mean / 100,
        "init_deaths": cases_df[w_place]["deaths"][-1]
    }
    w_params['leitos'] = DERIVATIVES['values']["Leitos"] / 100
    #Definições do modelo
    model = SEIRBayes(**w_params, r0_dist=r0_dist)
    model_output = model.sample(SAMPLE_SIZE)

    # Parâmetros de simulação
    dists = [w_params['alpha_inv_dist'], w_params['gamma_inv_dist'], r0_dist]
    SEIR0 = model._params['init_conditions']
    params_intro_txt, seir0_dict, other_params_txt = texts.make_SIMULATION_PARAMS(
        SEIR0, dists, should_estimate_r0)

    #Outros parâmetros
    st.markdown(params_intro_txt)
    st.write(pd.DataFrame(seir0_dict).set_index("Compartimento"))

    st.markdown(other_params_txt)

    ei_df = make_EI_df(model, model_output, SAMPLE_SIZE)
    st.markdown(texts.MODEL_INTRO)
    w_scale = st.selectbox('Escala do eixo Y', ['log', 'linear'], index=1)

    fig = plot_EI(model_output, w_scale, w_date)
    st.altair_chart(fig)
    download_placeholder = st.empty()
    if download_placeholder.button('Preparar dados para download em CSV'):
        href = make_download_href(ei_df, w_params, r0_dist, should_estimate_r0)
        st.markdown(href, unsafe_allow_html=True)
        download_placeholder.empty()

    st.markdown(texts.INFECTED_INTRO)

    (infected_total_lower_bound, infected_total_upper_bound,
     infected_total_mean,
     fig_infected) = plot_infected(model_output, 'linear', w_date,
                                   w_params['fator_subr'])
    st.altair_chart(fig_infected)
    st.markdown(
        texts.INFECTED_TOTAL_COUNT(infected_total_lower_bound,
                                   infected_total_mean,
                                   infected_total_upper_bound))
    # Plot Deaths
    st.markdown(texts.DEATHS_INTRO)

    if show_leth_age_message:
        st.markdown(
            f"**Este estado não apresentou dados de faixa etária."
            f" Por isso, são usados dados do Brasil para estimar as taxas de letalidade.**"
        )

    (deaths_total_lower_bound, deaths_total_upper_bound, deaths_total_mean,
     fig_deaths) = plot_deaths(model_output, 'linear', w_date,
                               lethality_mean * death_subnotification,
                               w_params['fator_subr'])

    st.altair_chart(fig_deaths)
    st.markdown(
        texts.DEATHS_TOTAL_COUNT(deaths_total_lower_bound, deaths_total_mean,
                                 deaths_total_upper_bound))
    st.markdown(texts.DEATH_DETAIL, unsafe_allow_html=True)
    st.markdown(texts.LEITOS_INTRO)
    derivatives = make_EI_derivatives(ei_df, w_params['fator_subr'])
    derivatives_chart = plot_derivatives(derivatives, w_date)
    st.altair_chart(derivatives_chart)
    st.markdown(texts.LEITOS_DETAIL, unsafe_allow_html=True)

    # Fontes dos dados
    st.markdown(texts.DATA_SOURCES)
Beispiel #4
0
def write():
    st.markdown("## Modelo Epidemiológico (SEIR-Bayes)")
    st.sidebar.markdown(texts.PARAMETER_SELECTION)
    w_granularity = st.sidebar.selectbox('Unidade',
                                         options=['state', 'city'],
                                         index=1,
                                         format_func=global_format_func)

    source = 'ms' if w_granularity == 'state' else 'wcota'
    cases_df = data.load_cases(w_granularity, source)
    population_df = data.load_population(w_granularity)

    DEFAULT_PLACE = (DEFAULT_CITY
                     if w_granularity == 'city' else DEFAULT_STATE)

    options_place = make_place_options(cases_df, population_df)
    w_place = st.sidebar.selectbox('Município',
                                   options=options_place,
                                   index=options_place.get_loc(DEFAULT_PLACE),
                                   format_func=global_format_func)

    options_date = make_date_options(cases_df, w_place)
    w_date = st.sidebar.selectbox('Data inicial',
                                  options=options_date,
                                  index=len(options_date) - 1)
    NEIR0 = make_NEIR0(cases_df, population_df, w_place, w_date)

    # Estimativa R0
    st.markdown(texts.r0_ESTIMATION_TITLE)
    should_estimate_r0 = st.checkbox('Estimar R0 a partir de dados históricos',
                                     value=True)
    if should_estimate_r0:
        r0_samples, used_brazil = estimate_r0(cases_df, w_place, SAMPLE_SIZE,
                                              MIN_DAYS_r0_ESTIMATE, w_date)
        if used_brazil:
            st.write(texts.r0_NOT_ENOUGH_DATA(w_place, w_date))

        _place = 'Brasil' if used_brazil else w_place
        st.markdown(texts.r0_ESTIMATION(_place, w_date))

        st.altair_chart(
            plot_r0(r0_samples, w_date, _place, MIN_DAYS_r0_ESTIMATE))
        r0_dist = r0_samples[:, -1]
        st.markdown(
            f'*O $R_{{0}}$ estimado está entre '
            f'${np.quantile(r0_dist, 0.01):.03}$ e ${np.quantile(r0_dist, 0.99):.03}$*'
        )
        st.markdown(texts.r0_CITATION)
    else:
        r0_dist = make_r0_widgets()
        st.markdown(texts.r0_ESTIMATION_DONT)

    # Previsão de infectados
    w_params = make_param_widgets(NEIR0)
    model = SEIRBayes(**w_params, r0_dist=r0_dist)
    model_output = model.sample(SAMPLE_SIZE)
    ei_df = make_EI_df(model, model_output, SAMPLE_SIZE)
    st.markdown(texts.MODEL_INTRO)
    w_scale = st.selectbox('Escala do eixo Y', ['log', 'linear'], index=1)
    fig = plot_EI(model_output, w_scale, w_date)
    st.altair_chart(fig)
    download_placeholder = st.empty()
    if download_placeholder.button('Preparar dados para download em CSV'):
        href = make_download_href(ei_df, w_params, r0_dist, should_estimate_r0)
        st.markdown(href, unsafe_allow_html=True)
        download_placeholder.empty()

    # Parâmetros de simulação
    dists = [w_params['alpha_inv_dist'], w_params['gamma_inv_dist'], r0_dist]
    SEIR0 = model._params['init_conditions']
    params_intro_txt, seir0_dict, other_params_txt = texts.make_SIMULATION_PARAMS(
        SEIR0, dists, should_estimate_r0)
    st.markdown(params_intro_txt)
    st.write(pd.DataFrame(seir0_dict).set_index("Compartimento"))
    st.markdown(other_params_txt)

    # Configurações da simulação
    st.markdown(texts.SIMULATION_CONFIG)
    # Fontes dos dados
    st.markdown(texts.DATA_SOURCES)
Beispiel #5
0
        st.altair_chart(
            plot_r0(r0_samples, w_date, _place, MIN_DAYS_r0_ESTIMATE))
        r0_dist = r0_samples[:, -1]
        st.markdown(
            f'**O $R_{{0}}$ estimado está entre '
            f'${np.quantile(r0_dist, 0.01):.03}$ e ${np.quantile(r0_dist, 0.99):.03}$**'
        )
        st.markdown(texts.r0_CITATION)
    else:
        r0_dist = make_r0_widgets()
        st.markdown(texts.r0_ESTIMATION_DONT)

    w_params = make_param_widgets(NEIR0)
    model = SEIRBayes(**w_params, r0_dist=r0_dist)
    model_output = model.sample(SAMPLE_SIZE)
    ei_df = make_EI_df(model_output, SAMPLE_SIZE)
    st.markdown(texts.MODEL_INTRO)
    st.write(texts.SEIRBAYES_DESC)
    w_scale = st.selectbox('Escala do eixo Y', ['log', 'linear'], index=1)
    fig = plot_EI(model_output, w_scale)
    st.altair_chart(fig)
    download_placeholder = st.empty()
    if download_placeholder.button('Preparar dados para download em CSV'):
        href = make_download_href(ei_df, w_params, r0_dist, should_estimate_r0)
        st.markdown(href, unsafe_allow_html=True)
        download_placeholder.empty()

    dists = [w_params['alpha_inv_dist'], w_params['gamma_inv_dist'], r0_dist]
    SEIR0 = model._params['init_conditions']
    st.markdown(texts.make_SIMULATION_PARAMS(SEIR0, dists, should_estimate_r0))