go = get_alerta_table(state='GO', doenca='dengue')

go

municipios = geobr.read_municipality(code_muni='GO')
municipios

municipios['code_muni'] = municipios.code_muni.astype('int')
municipios.plot(figsize=(10,10));

goias = pd.merge(go.reset_index(), municipios,how='left', left_on='municipio_geocodigo', right_on='code_muni')
goias

goias = gpd.GeoDataFrame(goias)

ax = goias[goias.SE==202144].plot(figsize=(10,10),
                             column='casos_est',
                             scheme="naturalbreaks",
                             legend=True,
                             legend_kwds={'title': "Casos estimados"},

                             );
ax.set_axis_off();

"""
Explanation: Fetching data from Infodengue
We can download the data from a full state. Let's pick Goiás.
End of explanation
"""


from functools import lru_cache
from IPython.display import display, Markdown
import pandas_bokeh
pandas_bokeh.output_notebook()
pd.options.plotting.backend = "pandas_bokeh"

@lru_cache(maxsize=27)
def get_dados(sigla='PR', doenca='dengue'):
    df = get_alerta_table(state=sigla, doenca=doenca)
    municipios = geobr.read_municipality(code_muni=sigla)
    municipios['code_muni'] = municipios.code_muni.astype('int')
    dados = pd.merge(df.reset_index(), municipios,how='left', left_on='municipio_geocodigo', right_on='code_muni')
    dados = dados.sort_values('SE')
    return gpd.GeoDataFrame(dados)


def gera_SE_seq(anoi, anof):
    ses=[]
    for a in range(anoi,anof+1):
        for w in range(1,52):
            w = str(w).zfill(2)
            ses.append(int(f'{a}{w}'))
    return ses

estado='TO'

doenca='chik'
doenca='dengue'
gdf = get_dados(estado, doenca)
try:
    gdf.set_index('data_iniSE', inplace=True)
except KeyError:
    pass
munis = list(set(gdf.name_muni))
try: 
    munis = sorted(munis)
except: pass

@interact
def painel(mun=widgets.Select(options=munis, description='Municipio'), 
           week=widgets.SelectionSlider(options=gera_SE_seq(2021,2022), description='SE'), 
           ):
    week = gdf.SE.max() if week > gdf.SE.max() else week
    
    umid = pd.DataFrame(gdf.reset_index())[['data_iniSE','umidmin', 'umidmax']].plot_bokeh(kind='line', x='data_iniSE')
    temp = pd.DataFrame(gdf.reset_index())[['data_iniSE','tempmin','tempmax']].plot_bokeh(kind='line', x='data_iniSE')
    mapplot = gdf[gdf.SE==int(week)].plot_bokeh(simplify_shapes=5000,
                                                dropdown=['casos_est','casos','p_inc100k','nivel'],
                                                colormap='Viridis', 
                                                  hovertool_string=f"""<h1>@name_muni</h1>
                                                <h3>Casos: @casos </h3>""",
                                                 )
    cases = pd.DataFrame(gdf[gdf.name_muni==mun].reset_index())[['data_iniSE','casos','casos_est']].plot_bokeh(kind='line', x='data_iniSE')
    mapplot.width = 900
    umid.width = 450
    temp.width = 450
    cases.width = 900

    layout = pandas_bokeh.column(mapplot,
                    pandas_bokeh.row(umid, temp),
                    cases)
    pandas_bokeh.plot_grid(layout, width=1200)

estado='TO'
doenca='chik'
doenca='dengue'
gdf = get_dados(estado, doenca)
try:
    gdf.set_index('data_iniSE', inplace=True)
except KeyError:
    pass
munis = list(set(gdf.name_muni))
try: 
    munis = sorted(munis)
except: pass

pd.options.plotting.backend = "matplotlib"

@interact
def painel(mun=widgets.Select(options=munis, description='Municipio'), 
           week=widgets.SelectionSlider(options=gera_SE_seq(2021,2022), value=202215, description='SE'),
           variable=['casos','casos_est','p_inc100k']
           ):
    week = gdf.SE.max() if week > gdf.SE.max() else week
    display(Markdown(f"# {doenca}"))
    fig, axs = plt.subplot_mosaic([['a', 'c'], ['b', 'c'], ['d', 'd']],
                                  figsize=(20, 20),
                                  constrained_layout=True)
    
    for label, ax in axs.items():
        if label == 'a':
            gdf[(gdf.name_muni==mun)&(gdf.SE>=202101)].umidmax.plot(kind='area',ax=ax,alpha=0.3, label='máxima')
            gdf[(gdf.name_muni==mun)&(gdf.SE>=202101)].umidmin.plot(kind='area',ax=ax,alpha=0.3, label='mínima')
            ax.set_title('Umidade')
            ax.legend()
        elif label == 'b':
            gdf[(gdf.name_muni==mun)&(gdf.SE>=202101)].tempmin.plot(ax=ax, label='mínima')
            # gdf.tempmax.plot(ax=ax, label='máxima')
            ax.set_title('Temperatura')
            ax.legend()
        elif label == 'c':
            leg = 'Casos estimados' if variable=='casos_est' else 'Casos notificados'
            gdf[gdf.SE==int(week)].plot(ax=ax,column=variable,scheme="User_defined",
                             legend=True,
                            classification_kwds=dict(bins=[20,50,100,500,2000,5000]),
                             legend_kwds={'title': f"{leg}",'loc':'lower right'})
            ax.set_axis_off();
            ax.set_title(str(week));
        elif label == 'd':
            gdf[(gdf.name_muni==mun)&(gdf.SE>=202101)].casos.plot(ax=ax,label='casos')
            gdf[(gdf.name_muni==mun)&(gdf.SE>=202101)].casos_est.plot(ax=ax,label='casos_est')
            ax.legend()
            ax.vlines(x=gdf[gdf.SE==int(week)].index,ymin=0,ymax=500)
            ax.set_title(mun)
    
    plt.show();

"""
Explanation: Building the dashboard
End of explanation
"""


data_path = Path('./data/')
map_path = Path("./maps/")

os.makedirs(data_path, exist_ok=True)
os.makedirs(map_path, exist_ok=True)

"""
Explanation: Building Animated films
End of explanation
"""


from infodenguepredict.data.infodengue import get_full_alerta_table

diseases = ['dengue','chik','zika']
for dis in diseases:
    os.makedirs(data_path/dis, exist_ok=True)

for dis in diseases:
    get_full_alerta_table(dis, output_dir=data_path/dis, chunksize=50000, start_SE=202140)

brmunis = geobr.read_municipality(code_muni='all')
brmunis.plot();

def merge(munis, df):
    munis['code_muni'] = munis.code_muni.astype('int')
    dados = pd.merge(df.reset_index(), munis,how='left', left_on='municipio_geocodigo', right_on='code_muni')
    dados = dados.sort_values('SE')
    return gpd.GeoDataFrame(dados)

def create_frames(dados, doenca='dengue', variable='casos_est'):
    vnames = {'casos_est': 'Casos Estimados', 'casos': 'Casos Notificados', 'p_inc100k': 'Incidência por 100 mil hab.'}
    leg = vnames[variable]
    if doenca == 'dengue':
        bins = {'casos_est':[20,50,100,500,1000],'p_inc100k':[50,500,1000,2500] }
    elif doenca == 'chik':
        bins = {'casos_est':[5,15,50,120,300],'p_inc100k':[50,100,500,1000] }
    elif doenca == 'zika':
        bins = {'casos_est':[5,15,50,120,300],'p_inc100k':[50,100,500,1000] }
    acumulados = 0
    ews = sorted(list(set(dados.SE)))
    for i,se in enumerate(ews):
        fig = dados[dados.SE==se].plot(figsize=(10,10),
                                       column=variable,
                                       scheme="user_defined",
                                       cmap='plasma',
                                       classification_kwds={'bins':bins[variable]},
                                       legend=True,
                                       legend_kwds={'title': f"{leg}",'loc':'lower right'}
                                       );
        acumulados += dados[dados.SE==se].casos_est.sum()
        fig.set_axis_off();
        fig.text(-50,2, f'Casos: {int(acumulados)}', fontsize=24)
        fig.set_title(f'{leg} de {doenca}\nna semana {str(se)[-2:]} de {str(se)[:-2]}', fontdict={'fontsize': 14});
        opath = map_path/variable
        os.makedirs(opath, exist_ok=True)
        plt.savefig(opath/f'{doenca}_{i:0>3}.png', dpi=200)
        plt.close()
    

"""
Explanation: Downloading data
We will start by Downloading the full alerta table for all diseases.
End of explanation
"""


dengue = pd.read_parquet(data_path/'dengue')
dengue.sort_values('SE',inplace=True)
chik = pd.read_parquet(data_path/'chik')
chik.sort_values('SE',inplace=True)
zika = pd.read_parquet(data_path/'zika')
zika.sort_values('SE',inplace=True)
dengue

dmdf = merge(brmunis,dengue)
cmdf = merge(brmunis, chik)
zmdf = merge(brmunis, zika)

dmdf[dmdf.SE==202208].plot(column='casos_est',scheme="naturalbreaks");

os.getcwd()

create_frames(dmdf)
create_frames(dmdf, variable='p_inc100k')

create_frames(cmdf, doenca='chik')
create_frames(cmdf, doenca='chik', variable='p_inc100k')

create_frames(zmdf, doenca='zika')
create_frames(zmdf, doenca='zika', variable='p_inc100k')

"""
Explanation: loading data from disk
we can load all chunks at once,into a single dataframe, since they are parquet files.doenca
End of explanation
"""


