<jupyter_start><jupyter_text>Achate a curva> Número de casos ativos e estimativa de leitos de UTI total e para pacientes covid-19- toc: true- badges: true- comments: true- author: <NAME>- categories: [jupyter]- image: images/brazil-flatten-the-curve.png<jupyter_code>#hide
import pandas as pd
import numpy as np
import altair as alt
import math
from IPython.display import HTML

CHART_WIDTH = 600
CHART_HEIGHT = 400
#hide
STATE_COLUMN = "Estado"
DATE_COLUMN = "Data"
MEAN_FUNCTION = '_Média'
MEDIAN_FUNCTION = '_Mediana'
SUM_FUNCTION = '_Brasil'
CONFIRMED_CASES = 'Casos confirmados'
DEATHS = 'Mortes'
NEWCONFIRMED_CASES = "Novo Confirmado"
NEWDEATH_COLUMN = "Nova Morte"
NEWRECOVERY_COLUMN = "Novo Recuperado"
DAYS_SINCE_100_CASES = 'Dias desde 100 casos'
DAYS_SINCE_10_DEATHS = 'Dias desde 10 mortes'
COMPARE_TRAJECTORY_WITH = 'Comparativo da trajetória entre os estados'
ACTIVE_COLUMN = "Casos Ativos"
VALUE = "Valor"
CASES_NEED_ICU = 0.12
POPULATION = 211000000
ICU_PER_100k = 20
TOTAL_ICU = (211000000 / 100000 * 20) + 1456
AVAILABLE_PERCENTAGE_ICU = 0.3
TOTAL_AVAILABLE_ICU = TOTAL_ICU * AVAILABLE_PERCENTAGE_ICU
CASES_NEED_ICU_COLUMN = "Precisam de UTI"
CASES_DONT_NEED_ICU_COLUMN = "Sem necessidade de UTI"
#hide
url_cases = ('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
url_deaths = ('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')
url_recoveries = ('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')

src_cases = pd.read_csv(url_cases)
df_cases = src_cases[(src_cases['Country/Region'] == 'Brazil')]
df_cases['base'] = 'cases'

src_deaths = pd.read_csv(url_recoveries)
df_recoveries = src_deaths[(src_deaths['Country/Region'] == 'Brazil')]
df_recoveries['base'] = 'recoveries'

src_recoveries = pd.read_csv(url_deaths)
df_deaths = src_recoveries[(src_recoveries['Country/Region'] == 'Brazil')]
df_deaths['base'] = 'deaths'

df = [df_cases, df_recoveries, df_deaths]
df = pd.concat(df)

df = df.drop(['Province/State', 'Country/Region', 'Lat', 'Long'], axis=1)

# Add active cases row
df = df.set_index('base')
new_row = df.loc['cases'] - df.loc['recoveries']
new_row.name = 'actives'
df = df.append([new_row])
# Reset index after added new row
df = df.reset_index()
df = df.rename(columns={"index":"base"})

# Melt structure (unpivot)
dt_cols = list(df.columns[~df.columns.isin(['base','index'])])
df = df.melt(id_vars=['base'], value_vars=dt_cols)
df = df.rename(columns={
     "base": STATE_COLUMN, 
     "variable":DATE_COLUMN, 
     "value":VALUE,
     "actives": ACTIVE_COLUMN
})
df[DATE_COLUMN] = pd.to_datetime(df[DATE_COLUMN])
df[DATE_COLUMN] = df[DATE_COLUMN].dt.strftime('%m/%d/%y')
df = df.sort_values(by=[DATE_COLUMN])

df = df[df[STATE_COLUMN].isin(['actives'])]

data = df.copy()
#df.tail()
#hide
df = data.copy()
STATE_COLUMN = "Pacientes"
df[VALUE] = df[VALUE] * (CASES_NEED_ICU)
df[STATE_COLUMN] = CASES_NEED_ICU_COLUMN
df = df.rename(columns={VALUE:ACTIVE_COLUMN})
#hide_input
input_dropdown = alt.binding_select(options=df[STATE_COLUMN].unique())
selection = alt.selection_multi(fields=[STATE_COLUMN], on='mouseover')
color = alt.condition(selection,
                    alt.Color(STATE_COLUMN+':N', 
                              scale=alt.Scale(scheme='tableau20', reverse=False), legend=None),
                              alt.value('#ffbf79')
                     )

chart = alt.Chart(df).mark_bar().encode(
    x=alt.X(DATE_COLUMN+':O', axis=alt.Axis(title=DATE_COLUMN)),
    y=alt.Y(ACTIVE_COLUMN, axis=alt.Axis(title=ACTIVE_COLUMN)),
    color=color,
    tooltip=[DATE_COLUMN, ACTIVE_COLUMN],
    order=alt.Order(
    STATE_COLUMN,
    sort='ascending'
    )
).properties(
    title=[
        "Achate a curva - apenas os ativos que estima-se que precisem de UTI",
        " * ver premissas"
    ]
).add_selection(
    selection
)

legend = alt.Chart(df).mark_point().encode(
    y=alt.Y(STATE_COLUMN+':N', axis=alt.Axis(orient='right')),
    color=color
)

x1line = alt.Chart(pd.DataFrame({'y': [TOTAL_AVAILABLE_ICU]})).mark_rule(color='#e42726', strokeWidth=2).encode(
    y='y:Q'
)
text1 = x1line.mark_text(align='left', x=5, dy=10, color='#e42726', strokeWidth=1).encode(
    text=alt.value("UTIs para pacientes COVID19: "+"{:.0f}".format(TOTAL_AVAILABLE_ICU))
)

chart.properties(width=CHART_WIDTH, height=CHART_HEIGHT) + x1line + text1 | legend
#hide
df1 = data.copy()
STATE_COLUMN = "Pacientes"
df1[VALUE] = df1[VALUE] * (CASES_NEED_ICU)
df1[STATE_COLUMN] = CASES_NEED_ICU_COLUMN
df2 = data.copy()
df2[VALUE] = df2[VALUE] * (1-CASES_NEED_ICU)
df2[STATE_COLUMN] = CASES_DONT_NEED_ICU_COLUMN
df = pd.concat([df1, df2])
df = df.rename(columns={VALUE:ACTIVE_COLUMN})
#hide_input
input_dropdown = alt.binding_select(options=df[STATE_COLUMN].unique())
selection = alt.selection_multi(fields=[STATE_COLUMN], on='mouseover')
color = alt.condition(selection,
                    alt.Color(STATE_COLUMN+':N', 
                              scale=alt.Scale(scheme='tableau20', reverse=False), legend=None),
                              alt.value('#ffbf79')
                     )

chart = alt.Chart(df).mark_bar().encode(
    x=alt.X(DATE_COLUMN+':O', axis=alt.Axis(title=DATE_COLUMN)),
    y=alt.Y(ACTIVE_COLUMN, axis=alt.Axis(title=ACTIVE_COLUMN)),
    color=color,
    tooltip=[DATE_COLUMN, ACTIVE_COLUMN],
    order=alt.Order(
    STATE_COLUMN,
    sort='ascending'
    )
).properties(
    title=[
        "Achate a curva - todos os casos ativos",
        " * ver premissas"
    ]
).add_selection(
    selection
)

legend = alt.Chart(df).mark_point().encode(
    y=alt.Y(STATE_COLUMN+':N', axis=alt.Axis(orient='right')),
    color=color
)

x1line = alt.Chart(pd.DataFrame({'y': [TOTAL_AVAILABLE_ICU]})).mark_rule(color='#e42726', strokeWidth=2).encode(
    y='y:Q'
)
text1 = x1line.mark_text(align='left', x=5, dy=10, color='#e42726', strokeWidth=1).encode(
    text=alt.value("UTIs para pacientes COVID19: "+"{:.0f}".format(TOTAL_AVAILABLE_ICU))
)

x2line = alt.Chart(pd.DataFrame({'y': [TOTAL_ICU]})).mark_rule(color='darkred', strokeWidth=2).encode(
    y='y:Q'
)
text2 = x2line.mark_text(align='left', x=5, dy=10, color='darkred', strokeWidth=1).encode(
    text=alt.value("Total de UTIs: "+"{:.0f}".format(TOTAL_ICU))
)

chart.properties(width=CHART_WIDTH, height=CHART_HEIGHT) + x1line + text1 + x2line + text2 | legend
#hide
#It could be used to filter per state but I still don't have a database with recoveries per state
ICU_STATE = pd.DataFrame(np.array([['SE',1.5],['PA',2.9],['MG',7.2],
                                   ['RR',0.2],['DF',4.6],['MS',1.5],
                                   ['MT',2.2],['PR',3.4],['SC',0.9],
                                   ['CE',3.9],['GO',4.1],['PB',1.4],
                                   ['AP',0.3],['AL',1.3],['AM',2.3],
                                   ['RN',1.9],['TO',0.6],['RS',4.1],
                                   ['RO',0.9],['PE',5.7],['AC',0.3],
                                   ['RJ',16.6],['BA',5.5],['MA',2.1],
                                   ['SP',22.2],['PI',1.0],['ES',1.3]
                                  ]), 
                         columns=['Estado','Percentual UTI'])
ICU_STATE = ICU_STATE.set_index(['Estado'])
ICU_STATE['Percentual UTI'] = ICU_STATE['Percentual UTI'].astype(np.float)
df = [df_cases, df_recoveries, df_deaths]
df = pd.concat(df)
df = df.drop(['Country/Region', 'Lat', 'Long'], axis=1)
#df.tail()
#hide_input
print("Premissas :")
print("- A população brasileira estimada é de "+"{:.0f}".format(POPULATION/1000000)+" milhões de habitantes (fonte: ibge)")
print("- O Brasil tem cerca de "+str(ICU_PER_100k)+" leitos de UTI para cada 100 mil habitantes (fonte: bcc). Outros leitos foram construídos para combater a covid-19 (fonte: ministério da saúde)")
print("- Baseado nos dados acima, estima-se que haja "+"{:.0f}".format(TOTAL_ICU)+" UTIs no país.")
print("- {:.0f}".format(AVAILABLE_PERCENTAGE_ICU*100)+"% de UTIs disponíveis para pacientes com covid19 (fonte: artigo oglobo)")
print("- Cerca de "+"{:.0f}".format(CASES_NEED_ICU*100)+"% dos pacientes com covid-19 precisam de tratamento intensivo (fonte: artigo the lancet)")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16425005942476825, 'fraction_numerical': 0.029118136439267885, 'mean_word_length': 4.143643031784841, 'pattern_counts': {'":': 5, '<': 6, '<?xml version=': 0, '>': 7, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '344658', 'license': 'Apache-2.0', 'n_tokens_mistral': 3406, 'n_tokens_neox': 3257, 'n_words': 532, 'path': '_drafts/2020-05-11-brazil-flatten-the-curve_per_state.ipynb', 'repo_name': 'cleberjamaral/fastpages', 'size': '8427'}