Ejemplo n.º 1
0
        min_value=0.01,
        max_value=10.0,
        step=0.25,
        value=defaults['r0_dist'][1])
    return (r0_inf, r0_sup, .95, 'lognorm')


if __name__ == '__main__':
    st.markdown(texts.INTRODUCTION)
    st.sidebar.markdown(texts.PARAMETER_SELECTION)
    w_granularity = st.sidebar.selectbox('Unidade',
                                         options=['state', 'city'],
                                         index=1,
                                         format_func=global_format_func)

    cases_df = data.load_cases(w_granularity)
    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',
                                  options=options_date,
                                  index=len(options_date) - 1)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0

def generateR0DistributionByDate(r0_samples, date, place, min_days):
    r0_samples_cut = r0_samples[-min_days:]
    columns = pd.date_range(end=date, periods=r0_samples_cut.shape[1])
    data = (pd.DataFrame(
        r0_samples_cut,
        columns=columns).stack(level=0).reset_index().rename(columns={
            "level_1": "Dias",
            0: "r0"
        })[["Dias", "r0"]])
    data = data.groupby('Dias').mean()
    return data


cases_df = data.load_cases('state', 'fiocruz')
cases_df.head()
cases_df.info()
SAMPLE_SIZE = 500
MIN_CASES_TH = 10
MIN_DAYS_r0_ESTIMATE = 14
EndDate = '2021-02-05'
Estado = 'RJ'

r0_samples = estimate_r0(
    cases_df,
    Estado,  # estado da estimativa
    SAMPLE_SIZE,  # dias da estimativa
    MIN_DAYS_r0_ESTIMATE,  # 
    EndDate)
data = generateR0DistributionByDate(r0_samples, EndDate, Estado,
Ejemplo n.º 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)
Ejemplo n.º 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')
Ejemplo n.º 6
0
import pandas as pd
from covid19.models import SEIRBayes
from covid19.data import load_cases, load_population

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)
                            })
Ejemplo n.º 7
0
def create_basic_sidebar():

    MIN_DATA_BRAZIL = '2020-03-26'
    DEFAULT_CITY = 'São Paulo/SP'
    DEFAULT_STATE = 'SP'
    MIN_CASES_TH = 10

    def format_local(key):
        return {'state': 'Estado', 'city': 'Município'}.get(key, key)

    def format_date(date):
        return (datetime.strptime(date, "%Y-%m-%d").strftime("%d/%m/%Y"))

    @st.cache(show_spinner=False)
    def make_place_options(cases_df, population_df):
        return (cases_df.swaplevel(
            0, 1,
            axis=1)['totalCases'].pipe(lambda df: df >= MIN_CASES_TH).any().
                pipe(lambda s: s[s & s.index.isin(population_df.index)]).index)

    @st.cache(show_spinner=False)
    def make_date_options(cases_df, place):
        return (cases_df[place]['totalCases'].pipe(lambda s: s[
            s >= MIN_CASES_TH])[MIN_DATA_BRAZIL:].index.strftime('%Y-%m-%d'))

    st.sidebar.markdown(texts.INTRODUCTION_SIDEBAR)

    w_r0_model = st.sidebar.checkbox(texts.R0_MODEL_DESC)
    w_seir_model = st.sidebar.checkbox(texts.SEIR_MODEL_DESC)
    w_queue_model = st.sidebar.checkbox(texts.QUEUE_MODEL_DESC)

    st.sidebar.markdown(texts.BASE_PARAMETERS_DESCRIPTION)

    st.sidebar.markdown("**Parâmetro de UF/Município**")

    w_location_granularity = st.sidebar.radio("Unidade",
                                              options=("state", "city"),
                                              index=1,
                                              format_func=format_local)

    cases_df = data.load_cases(w_location_granularity)

    if w_location_granularity == 'city':

        population_df = data.load_population(w_location_granularity)
        options_place = make_place_options(cases_df, population_df)

        index = options_place.get_loc(DEFAULT_CITY)

        w_location = st.sidebar.selectbox('Município',
                                          options=options_place,
                                          index=index)

    elif w_location_granularity == "state":

        population_df = data.load_population(w_location_granularity)
        options_place = make_place_options(cases_df, population_df)

        index = options_place.get_loc(DEFAULT_STATE)

        w_location = st.sidebar.selectbox('Estado',
                                          options=options_place,
                                          index=index)

    options_date = make_date_options(cases_df, w_location)
    w_date = st.sidebar.selectbox('Data',
                                  options=options_date,
                                  index=len(options_date) - 1,
                                  format_func=format_date)

    real_cases = ur.estimate_subnotification(w_location,
                                             w_date,
                                             w_location_granularity,
                                             period=True)

    return {
        "location_granularity": w_location_granularity,
        "date": w_date,
        "location": w_location,
        "cases": cases_df,
        "real_cases": real_cases,
        "population": population_df,
        "r0_model": w_r0_model,
        "seir_model": w_seir_model,
        "queue_model": w_queue_model
    }
Ejemplo n.º 8
0
    cCFR_place = calculateCCFR(cases)
    subnotification_rate = FATAL_RATE_BASELINE / cCFR_place
    return subnotification_rate, cCFR_place


if __name__ == '__main__':
    st.markdown(texts.INTRODUCTION)
    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',
                                  options=options_date,
                                  index=len(options_date) - 1)