Advertisement
eltonsantana

infodengue

Mar 21st, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.58 KB | None | 0 0
  1. import altair as alt
  2. import pandas as pd
  3.  
  4. class ReportCityCharts:
  5.     @classmethod
  6.     def create_incidence_chart(
  7.         cls,
  8.         df: pd.DataFrame,
  9.         year_week: int,
  10.         threshold_pre_epidemic: float,
  11.         threshold_pos_epidemic: float,
  12.         threshold_epidemic: float,
  13.     ):
  14.         """
  15.  
  16.        @see: https://stackoverflow.com/questions/45526734/
  17.            hide-legend-entries-in-a-plotly-figure
  18.  
  19.        :param df:
  20.        :param year_week:
  21.        :param threshold_pre_epidemic: float,
  22.        :param threshold_pos_epidemic: float
  23.        :param threshold_epidemic: float
  24.        :return:
  25.        """
  26.         df = df.reset_index()[
  27.             ['SE', 'incidência', 'casos notif.', 'level_code']
  28.         ]
  29.  
  30.         # 200 = 2 years
  31.         df = df[df.SE >= year_week - 200]
  32.  
  33.         df['SE'] = df.SE.map(lambda v: '%s/%s' % (str(v)[:4], str(v)[-2:]))
  34.  
  35.         k = 'incidência'
  36.  
  37.         df['alerta verde'] = df[df.level_code == 1][k]
  38.         df['alerta amarelo'] = df[df.level_code == 2][k]
  39.         df['alerta laranja'] = df[df.level_code == 3][k]
  40.         df['alerta vermelho'] = df[df.level_code == 4][k]
  41.  
  42.         df['limiar epidêmico'] = threshold_epidemic
  43.         df['limiar pós epidêmico'] = threshold_pos_epidemic
  44.         df['limiar pré epidêmico'] = threshold_pre_epidemic
  45.  
  46.         """
  47.        figure_bar = df.iplot(
  48.            asFigure=True,
  49.            kind='bar',
  50.            x=['SE'],
  51.            y=[
  52.                'alerta verde',
  53.                'alerta amarelo',
  54.                'alerta laranja',
  55.                'alerta vermelho',
  56.            ],
  57.            legend=True,
  58.            showlegend=True,
  59.            yTitle='Incidência',
  60.            xTitle='Período (Ano/Semana)',
  61.            color=[
  62.                'rgb(0,255,0)',
  63.                'rgb(255,255,0)',
  64.                'rgb(255,150,0)',
  65.                'rgb(255,0,0)',
  66.            ],
  67.            hoverinfo='x+y+name',
  68.        )
  69.  
  70.        figure_threshold = df.iplot(
  71.            asFigure=True,
  72.            x=['SE'],
  73.            y=[
  74.                'limiar pré epidêmico',
  75.                'limiar pós epidêmico',
  76.                'limiar epidêmico',
  77.            ],
  78.            legend=False,
  79.            showlegend=False,
  80.            color=['rgb(0,255,0)', 'rgb(255,150,0)', 'rgb(255,0,0)'],
  81.            hoverinfo='none',
  82.        )
  83.  
  84.        figure_line = df.iplot(
  85.            asFigure=True,
  86.            x=['SE'],
  87.            y=['casos notif.'],
  88.            legend=False,
  89.            showlegend=False,
  90.            secondary_y=['casos notif.'],
  91.            secondary_y_title='Casos',
  92.            hoverinfo='x+y+name',
  93.            color=['rgb(33,33,33)'],
  94.        )
  95.  
  96.        figure_line['layout']['legend'].update(
  97.            x=-0.27,
  98.            y=0.5,
  99.            traceorder='normal',
  100.            font=dict(family='sans-serif', size=12, color='#000'),
  101.            bgcolor='#FFFFFF',
  102.            bordercolor='#E2E2E2',
  103.            borderwidth=1,
  104.            orientation='l',
  105.        )
  106.  
  107.        figure_line['layout']['yaxis1'].update(title='Incidência')
  108.  
  109.        figure_line['layout'].update(
  110.            title=(
  111.                'Limiares de incidência:: '
  112.                + 'pré epidêmico=%s; '
  113.                + 'pós epidêmico=%s; '
  114.                + 'epidêmico=%s;'
  115.            )
  116.            % (
  117.                '{:.1f}'.format(threshold_pre_epidemic),
  118.                '{:.1f}'.format(threshold_pos_epidemic),
  119.                '{:.1f}'.format(threshold_epidemic),
  120.            ),
  121.            showlegend=True,
  122.        )
  123.  
  124.        figure_threshold.data.extend(figure_bar.data)
  125.        figure_line.data.extend(figure_threshold.data)
  126.  
  127.        figure_line['layout']['yaxis2'].update(
  128.            showgrid=False, range=[0, df['casos notif.'].max()]
  129.        )
  130.  
  131.        figure_line['layout']['xaxis1'].update(
  132.            tickangle=-60, nticks=len(df) // 4, title='Período (Ano/Semana)'
  133.        )
  134.  
  135.        for trace in figure_line['data']:
  136.            if trace['name'] == 'casos notif.':
  137.                trace['visible'] = 'legendonly'
  138.  
  139.        return _plot_html(
  140.            figure_or_data=figure_line,
  141.            config={},
  142.            validate=True,
  143.            default_width='100%',
  144.            default_height=500,
  145.            global_requirejs='',
  146.        )[0]
  147.        """
  148.        
  149.         df_casos = df.rename(columns = {"casos notif.": "casosnotif"})
  150.         base = alt.Chart(df_casos).encode(alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')))
  151.         bar = base.mark_bar().encode(alt.Y('incidência', axis=alt.Axis(title='Incidência')))
  152.         line = base.mark_line(color="#ffd100", strokeWidth=5).encode(alt.Y('casosnotif', axis=alt.Axis(title='Casos')))
  153.         return (bar + line).resolve_scale(y='independent').properties(width=1000)
  154.  
  155.     @classmethod
  156.     def create_climate_chart(
  157.         cls,
  158.         df: pd.DataFrame,
  159.         var_climate,
  160.         year_week,
  161.         climate_crit,
  162.         climate_title,
  163.     ):
  164.         """
  165.  
  166.        :param df:
  167.        :param var_climate:
  168.        :param year_week:
  169.        :param climate_crit:
  170.        :param climate_title:
  171.        :return:
  172.        """
  173.         k = var_climate.replace('_', '.')
  174.         df_climate = df.reset_index()[['SE', k]]
  175.         df_climate = df_climate[df_climate.SE >= year_week - 200]
  176.  
  177.         df_climate['SE'] = df_climate.SE.map(
  178.             lambda v: '%s/%s' % (str(v)[:4], str(v)[-2:])
  179.         )
  180.  
  181.         df_climate['Limiar favorável transmissão'] = climate_crit
  182.         """
  183.        figure = df_climate.iplot(
  184.            asFigure=True,
  185.            x=['SE'],
  186.            y=[k, 'Limiar favorável transmissão'],
  187.            showlegend=True,
  188.            yTitle=climate_title,
  189.            xTitle='Período (Ano/Semana)',
  190.        )
  191.  
  192.        figure['layout']['xaxis1'].update(
  193.            tickangle=-60, nticks=len(df_climate) // 4
  194.        )
  195.  
  196.        figure['layout']['legend'].update(
  197.            x=-0.1,
  198.            y=1.2,
  199.            traceorder='normal',
  200.            font=dict(family='sans-serif', size=12, color='#000'),
  201.            bgcolor='#FFFFFF',
  202.            bordercolor='#E2E2E2',
  203.            borderwidth=1,
  204.        )
  205.  
  206.        return _plot_html(
  207.            figure_or_data=figure,
  208.            config={},
  209.            validate=True,
  210.            default_width='100%',
  211.            default_height=500,
  212.            global_requirejs='',
  213.        )[0]
  214.        """
  215.        
  216.         df_climate_chart = df_climate.rename(columns = {
  217.             "temp.min":"temp_min",
  218.             "Limiar favorável transmissão": "limiar_transmissao"})
  219.  
  220.         return alt.Chart(df_climate_chart).mark_trail().encode(
  221.             alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  222.             alt.Y('temp_min', axis=alt.Axis(title='Temperatura'))
  223.         ).properties(width=1050)
  224.  
  225.     @classmethod
  226.     def create_tweet_chart(cls, df: pd.DataFrame, year_week):
  227.         """
  228.  
  229.        :param df:
  230.        :param var_climate:
  231.        :param year_week:
  232.        :param climate_crit:
  233.        :param climate_title:
  234.        :return:
  235.        """
  236.         df_tweet = df.reset_index()[['SE', 'tweets']]
  237.         df_tweet = df_tweet[df_tweet.SE >= year_week - 200]
  238.  
  239.         df_tweet['SE'] = df_tweet.SE.map(
  240.             lambda v: '%s/%s' % (str(v)[:4], str(v)[-2:])
  241.         )
  242.  
  243.         #df_tweet.rename(columns={'tweets': 'menções'}, inplace=True)
  244.        
  245.         """
  246.        figure = df_tweet.iplot(
  247.            x=['SE'],
  248.            y=['menções'],
  249.            asFigure=True,
  250.            showlegend=True,
  251.            xTitle='Período (Ano/Semana)',
  252.        )
  253.        figure['layout']['xaxis1'].update(
  254.            tickangle=-60, nticks=len(df_tweet) // 4
  255.        )
  256.        figure['layout']['yaxis1'].update(title='Tweets')
  257.  
  258.        figure['layout']['legend'].update(
  259.            x=-0.1,
  260.            y=1.2,
  261.            traceorder='normal',
  262.            font=dict(family='sans-serif', size=12, color='#000'),
  263.            bgcolor='#FFFFFF',
  264.            bordercolor='#E2E2E2',
  265.            borderwidth=1,
  266.        )
  267.  
  268.        return _plot_html(
  269.            figure_or_data=figure,
  270.            config={},
  271.            validate=True,
  272.            default_width='100%',
  273.            default_height=500,
  274.            global_requirejs='',
  275.        )[0]
  276.        """
  277.         return alt.Chart(df_tweet).mark_trail().encode(
  278.             alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  279.             alt.Y('tweets', axis=alt.Axis(title='Tweets'))
  280.         ).properties(width=1050)
  281.  
  282. class ReportStateCharts:
  283.     @classmethod
  284.     def create_tweet_chart(cls, df: pd.DataFrame, year_week, disease: str):
  285.         """
  286.        :param df:
  287.        :param year_week:
  288.        :param disease:
  289.        :return:
  290.        """
  291.  
  292.         # print(cls)
  293.         # <class 'dados.charts.ReportStateCharts'>
  294.  
  295.         ks_cases = ['casos notif. {}'.format(disease)]
  296.         # print(ks_cases)
  297.         # ['casos notif. zika']
  298.  
  299.         df_tweet = df.reset_index()[['SE', 'tweets'] + ks_cases]
  300.         df_tweet.to_csv('df_tweet01.csv')
  301.  
  302.         # filtro
  303.         # print(year_week)
  304.         # 201923
  305.         df_tweet = df_tweet[df_tweet.SE >= year_week - 200]
  306.         df_tweet.to_csv('df_tweet02.csv')
  307.  
  308.  
  309.         # rename
  310.         df_tweet.rename(columns={'tweets':'mencoes'}, inplace=True)
  311.         df_tweet.to_csv('df_tweet03.csv')
  312.  
  313.         #df.to_csv('df2.csv')
  314.  
  315.         #print(df.index)
  316.         """
  317.        Int64Index([201723, 201723, 201723, 201723, 201723, 201723, 201723, 201723,
  318.                    201723, 201723,
  319.                    ...
  320.                    201923, 201923, 201923, 201923, 201923, 201923, 201923, 201923,
  321.                    201923, 201923],
  322.                   dtype='int64', name='SE', length=1680)
  323.        """
  324.        
  325.         if ks_cases :
  326.            
  327.  
  328.         df_grp = (
  329.             df_tweet.groupby(df.index)[['mencoes'] + ks_cases]
  330.             .sum()
  331.             .reset_index()
  332.         )
  333.  
  334.         # df_grp.info()
  335.         df_grp.to_csv('df_grp0001.csv')
  336.  
  337.         df_grp['SE'] = df_grp.SE.map(
  338.             lambda v: '%s/%s' % (str(v)[:4], str(v)[-2:])
  339.         )
  340.  
  341.         df_grp.to_csv('df_grp0002.csv')
  342.  
  343.         """
  344.        fig_tweet = df_grp.iplot(
  345.            x=['SE'],
  346.            y=['menções'],
  347.            asFigure=True,
  348.            showlegend=True,
  349.            xTitle='Período (Ano/Semana)',
  350.            color=['rgb(128,128,128)'],
  351.        )
  352.  
  353.        fig_cases = df_grp.iplot(
  354.            x=['SE'],
  355.            y=ks_cases,
  356.            asFigure=True,
  357.            secondary_y=ks_cases,
  358.            secondary_y_title='Casos',
  359.            showlegend=True,
  360.            xTitle='Período (Ano/Semana)',
  361.            color=['rgb(0,0,255)'],
  362.        )
  363.  
  364.        fig_cases.data.extend(fig_tweet.data)
  365.  
  366.        fig_cases['layout']['xaxis1'].update(
  367.            tickangle=-60, nticks=len(df_grp) // 24
  368.        )
  369.        fig_cases['layout']['yaxis1'].update(
  370.            title='Tweets', range=[0, df_grp['menções'].max()]
  371.        )
  372.        fig_cases['layout']['yaxis2'].update(
  373.            range=[0, df_grp[ks_cases].max().max()]
  374.        )
  375.  
  376.        fig_cases['layout'].update(
  377.            title='Casos {} / Menções mídia social'.format(disease)
  378.        )
  379.  
  380.        fig_cases['layout']['legend'].update(
  381.            x=-0.1,
  382.            y=1.2,
  383.            traceorder='normal',
  384.            font=dict(family='sans-serif', size=12, color='#000'),
  385.            bgcolor='#FFFFFF',
  386.            bordercolor='#E2E2E2',
  387.            borderwidth=1,
  388.        )
  389.        
  390.        return _plot_html(
  391.            figure_or_data=fig_cases,
  392.            config={},
  393.            validate=True,
  394.            default_width='100%',
  395.            default_height=300,
  396.            global_requirejs='',
  397.        )[0]
  398.        """
  399.    
  400.         """
  401.        se = alt.Chart(df_grp).encode(
  402.            alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)'))
  403.        )
  404.        tweets = se.mark_trail().encode(
  405.            alt.Y('mencoes', axis=alt.Axis(title='Tweets'))
  406.        )
  407.        casos = se.mark_trail().encode(
  408.            alt.Y('casos notif dengue', axis=alt.Axis(title='Casos'))
  409.        )
  410.        return (tweets, casos).resolve_scale(y='independent')
  411.        """
  412.  
  413.        
  414.         if disease == 'dengue':
  415.             df_grp.rename(columns={'casos notif. dengue':'casos notif dengue'}, inplace=True)
  416.             df_grp.info()
  417.             return alt.Chart(df_grp).mark_trail().encode(
  418.                 alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  419.                 alt.Y('mencoes', axis=alt.Axis(title='Tweets')),
  420.                 #alt.Y('casos notif dengue', axis=alt.Axis(title='Casos'))
  421.             ).resolve_scale(y='independent').properties(width=1020)
  422.  
  423.         elif disease == 'chik':
  424.             df_grp.rename(columns={'casos notif. chik':'casos notif chik'}, inplace=True)
  425.             df_grp.info()
  426.             return alt.Chart(df_grp).mark_trail().encode(
  427.                 alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  428.                 alt.Y('mencoes', axis=alt.Axis(title='Tweets')),
  429.                 #alt.Y('casos notif chik', axis=alt.Axis(title='Casos'))
  430.             ).resolve_scale(y='independent').properties(width=1020)
  431.  
  432.         elif disease == 'zika':
  433.             df_grp.rename(columns={'casos notif. zika':'casos notif zika'}, inplace=True)
  434.             df_grp.info()
  435.             return alt.Chart(df_grp).mark_trail().encode(
  436.                 alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  437.                 alt.Y('mencoes', axis=alt.Axis(title='Tweets')),
  438.                 #alt.Y('casos notif zika', axis=alt.Axis(title='Casos'))
  439.             ).resolve_scale(y='independent').properties(width=1020)
  440.         else :
  441.             df_grp.info()
  442.             return alt.Chart(df_grp).mark_trail().encode(
  443.                 alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  444.                 alt.Y('mencoes', axis=alt.Axis(title='Tweets')),
  445.             ).resolve_scale(y='independent').properties(width=1020)
  446.  
  447.         """
  448.        df.to_csv('df_agora.csv')
  449.        df_grp.rename(columns={'casos notif. dengue':'casos notif dengue'}, inplace=True)
  450.        df_grp.rename(columns={'casos notif. chik':'casos notif chik'}, inplace=True)
  451.        df_grp.rename(columns={'casos notif. zika':'casos notif zika'}, inplace=True)
  452.        df_grp.info()
  453.        return alt.Chart(df_grp).mark_trail().encode(
  454.            alt.X('SE:T', axis=alt.Axis(title='Período (Ano/Semana)')),
  455.            alt.Y('mencoes', axis=alt.Axis(title='Tweets')),
  456.        ).resolve_scale(y='independent').properties(width=1020)
  457.        """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement