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.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)

    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']
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
    def generate_seir(
        # Municipio
        city,
        date,

        # Condições iniciais
        S0=None,  # População total (N)
        I0=None,  # Indivíduos infecciosos inicialmente (I0)
        E0=None,  # Indivíduos expostos inicialmente (E0)
        R0=0,  # Indivíduos removidos com imunidade inicialmente (R0)

        # R0, período de infecção (1/γ) e tempo incubação (1/α)
        r0_inf=1.9,  # Limite inferior do número básico de reprodução médio (R0)
        r0_sup=5,  # Limite superior do número básico de reprodução médio (R0)
        reduce_r0=[0, 0.25, 0.50, 0.65],
        gamma_inf=10,  # Limite inferior do período infeccioso médio em dias (1/γ)
        gamma_sup=14,  # Limite superior do período infeccioso médio em dias (1/γ)
        alpha_inf=4.2,  # Limite inferior do tempo de incubação médio em dias (1/α)
        alpha_sup=5,  # Limite superior do tempo de incubação médio em dias (1/α)

        # Parâmetros gerais
        t_max=180,  # Período de simulação em dias (t_max)
        sample_size=1000  #Qtde. de iterações da simulação (runs)
    ):

        cases = load_cases('city')[city]
        population = load_population('city')[city]

        S0 = S0 or population
        I0 = I0 or cases.loc[date]['totalCases']
        E0 = E0 or 2 * I0
        R0 = R0 or 0

        sample_size = sample_size or 1000
        t_max = t_max or 180

        for reduce_by in reduce_r0:
            model = SEIRBayes.init_from_intervals(
                NEIR0=(S0, E0, I0, R0),
                r0_interval=((1 - reduce_by) * r0_inf,
                             (1 - reduce_by) * r0_sup, 0.95),
                gamma_inv_interval=(gamma_inf, gamma_sup, 0.95),
                alpha_inv_interval=(alpha_inf, alpha_sup, 0.95),
                t_max=t_max)

            S, E, I, R, t = model.sample(sample_size)
            pred = pd.DataFrame(index=(pd.date_range(
                start=date, periods=t.shape[0]).strftime('%Y-%m-%d')),
                                data={
                                    'S': S.mean(axis=1),
                                    'E': E.mean(axis=1),
                                    'I': I.mean(axis=1),
                                    'R': R.mean(axis=1)
                                })

            df = (pred.join(cases, how='outer').assign(
                cases=lambda df: df.totalCases.fillna(df.I)).assign(
                    newly_infected=lambda df: df.cases - df.cases.shift(
                        1) + df.R - df.R.shift(1)).assign(
                            newly_R=lambda df: df.R.diff()).rename(
                                columns={'cases': 'totalCases OR I'}))

            df = df.assign(days=range(1, len(df) + 1))

            print(model._params)

            df.to_csv(f'seir_output-{reduce_by}_2.csv')
Beispiel #6
0
if __name__ == '__main__':
    city = 'Rio de Janeiro/RJ'
    cases = load_cases('city')[city]
    population = load_population('city')[city]

    date_for_pred = '2020-03-24'
    S0 = population
    I0 = cases.loc[date_for_pred]['totalCases']
    E0 = 2 * I0
    R0 = 0

    for reduce_by in [0, 0.25, 0.50, 0.65]:
        model = SEIRBayes.init_from_intervals(
            NEIR0=(population, E0, I0, R0),
            r0_interval=((1 - reduce_by) * 1.9, (1 - reduce_by) * 5, 0.95),
            gamma_inv_interval=(10, 14, 0.95),
            alpha_inv_interval=(4.2, 5, 0.95),
            t_max=180)
        S, E, I, R, t = model.sample(1000)
        pred = pd.DataFrame(index=(pd.date_range(
            start=date_for_pred, periods=t.shape[0]).strftime('%Y-%m-%d')),
                            data={
                                'S': S.mean(axis=1),
                                'E': E.mean(axis=1),
                                'I': I.mean(axis=1),
                                'R': R.mean(axis=1)
                            })

        df = (pred.join(cases, how='outer').assign(
            cases=lambda df: df.totalCases.fillna(df.I)).assign(
                newly_infected=lambda df: df.cases - df.cases.shift(1) + df.R -
Beispiel #7
0
                                  options=options_date,
                                  index=len(options_date) - 1)
    NEIR0 = make_NEIR0(cases_df, population_df, w_place, w_date)
    w_params = make_param_widgets(NEIR0)
    sample_size = st.sidebar.number_input(
        'Qtde. de iterações da simulação (runs)',
        min_value=1,
        max_value=3_000,
        step=100,
        value=300)

    st.markdown(texts.MODEL_INTRO)
    w_scale = st.selectbox('Escala do eixo Y', ['log', 'linear'], index=1)
    w_show_uncertainty = st.checkbox('Mostrar intervalo de confiança',
                                     value=True)
    model = SEIRBayes.init_from_intervals(**w_params)
    model_output = model.sample(sample_size)
    ei_df = make_EI_df(model_output, sample_size)
    fig = plot(model_output, w_scale, w_show_uncertainty)
    st.altair_chart(fig)
    download_placeholder = st.empty()
    if download_placeholder.button('Preparar dados para download em CSV'):
        href = make_download_df_href(ei_df)
        st.markdown(href, unsafe_allow_html=True)
        download_placeholder.empty()

    intervals = [
        w_params['alpha_inv_interval'], w_params['gamma_inv_interval'],
        w_params['r0_interval']
    ]
    SEIR0 = model._params['init_conditions']
Beispiel #8
0
        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)

    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']