Ejemplo n.º 1
0
def render_page():
    cols = []
    edf = predict_emissions().dropna(axis=1, how='all')
    forecast = edf.pop('Forecast')
    graph = PredictionFigure(sector_name=None,
                             unit_name='kt',
                             title='Päästöt yhteensä',
                             smoothing=True,
                             fill=True,
                             stacked=True,
                             legend=True,
                             legend_x=0.8)
    for sector_name, sector_metadata in SECTORS.items():
        df = pd.DataFrame(edf[sector_name])
        df['Forecast'] = forecast

        fig = make_sector_fig(df, sector_name, sector_metadata)
        sector_page = get_page_for_emission_sector(sector_name, None)
        card = GraphCard(id='emissions-%s' % sector_name,
                         graph=dict(figure=fig),
                         link_to_page=sector_page)
        cols.append(dbc.Col(card.render(), md=6))

        # Add the summed sector to the all emissions graph
        df = df.drop(columns=['Forecast'])
        s = df.sum(axis=1)
        s.name = 'Emissions'
        df = pd.DataFrame(s)
        df['Forecast'] = forecast
        graph.add_series(df=df,
                         trace_name=sector_metadata['name'],
                         column_name='Emissions',
                         historical_color=sector_metadata['color'])

    target_year = get_variable('target_year')
    ref_year = get_variable('ghg_reductions_reference_year')
    perc_off = get_variable('ghg_reductions_percentage_in_target_year')

    last_hist_year = edf.loc[~forecast].index.max()
    last_hist = edf.loc[last_hist_year].sum()
    end_emissions = edf.loc[target_year].sum()
    ref_emissions = edf.loc[ref_year].sum()
    target_emissions = ref_emissions * (1 - perc_off / 100)

    target_year_emissions = edf.loc[target_year].sum()
    sticky = StickyBar(
        label='Päästövähennykset yhteensä',
        goal=last_hist - target_emissions,
        value=last_hist - end_emissions,
        unit='kt',
        below_goal_good=False,
    )

    card = GraphCard(id='emissions-total',
                     graph=dict(figure=graph.get_figure()))

    return html.Div(
        [dbc.Row(dbc.Col(card.render())),
         dbc.Row(cols),
         sticky.render()])
Ejemplo n.º 2
0
    def get_content(self):
        lang = get_active_locale()
        main_sector_name = self.emission_sector[0]
        main_sector_metadata = SECTORS[main_sector_name]

        cols = []

        edf = predict_emissions().dropna(axis=1, how='all')
        forecast = edf.pop('Forecast')
        edf = edf[main_sector_name]

        subsectors = main_sector_metadata['subsectors']
        colors = generate_color_scale(main_sector_metadata['color'],
                                      len(subsectors))

        graph = PredictionFigure(sector_name=main_sector_name,
                                 unit_name='kt',
                                 title=_('Total emissions'),
                                 smoothing=True,
                                 fill=True,
                                 stacked=True,
                                 legend=True,
                                 legend_x=0.8)

        for idx, (sector_name,
                  sector_metadata) in enumerate(subsectors.items()):
            df = pd.DataFrame(edf[sector_name])
            df['Forecast'] = forecast

            fig = self.make_sector_fig(df, sector_name, sector_metadata,
                                       colors[idx])
            sector_page = get_page_for_emission_sector(main_sector_name,
                                                       sector_name)
            card = GraphCard(id='emissions-%s-%s' %
                             (main_sector_name, sector_name),
                             graph=dict(figure=fig),
                             link_to_page=sector_page)
            cols.append(dbc.Col(card.render(), md=6))

            # Add the summed sector to the all emissions graph
            df = df.drop(columns=['Forecast'])
            s = df.sum(axis=1)
            s.name = 'Emissions'
            df = pd.DataFrame(s)
            df['Forecast'] = forecast
            graph.add_series(df=df,
                             trace_name=sector_metadata.get(
                                 'name_%s' % lang, sector_metadata['name']),
                             column_name='Emissions',
                             historical_color=colors[idx])

        self.total_emissions = edf.iloc[-1].sum()

        card = GraphCard(id='%s-emissions-total' % main_sector_name,
                         graph=dict(figure=graph.get_figure()))

        return html.Div([
            dbc.Row(dbc.Col(card.render())),
            dbc.Row(cols),
        ])
Ejemplo n.º 3
0
def render_page():
    cols = []
    edf = predict_emissions().set_index('Year')
    forecast = edf.groupby('Year')['Forecast'].first()
    graph = PredictionGraph(sector_name=None,
                            unit_name='kt',
                            title='Päästöt yhteensä',
                            smoothing=True,
                            fill=True,
                            stacked=True)
    for sector_name, sector_metadata in SECTORS.items():
        df = edf.loc[edf.Sector1 == sector_name,
                     ['Sector2', 'Forecast', 'Emissions']]
        df = df.pivot(columns='Sector2', values='Emissions')
        df['Forecast'] = forecast
        fig = make_sector_fig(df, sector_name, sector_metadata)
        sector_page = get_page_for_emission_sector(sector_name, None)
        card = GraphCard(id='emissions-%s' % sector_name,
                         graph=dict(figure=fig),
                         link_to_page=sector_page)
        cols.append(dbc.Col(card.render(), md=6))

        # Add the summed sector to the all emissions graph
        df = df.drop(columns=['Forecast'])
        s = df.sum(axis=1)
        s.name = 'Emissions'
        df = pd.DataFrame(s)
        df['Forecast'] = forecast
        graph.add_series(df=df,
                         trace_name=sector_metadata['name'],
                         column_name='Emissions',
                         historical_color=sector_metadata['color'])

    target_year = get_variable('target_year')
    ref_year = get_variable('ghg_reductions_reference_year')
    perc_off = get_variable('ghg_reductions_percentage_in_target_year')

    ref_emissions = edf.loc[ref_year].Emissions.sum()
    target_emissions = ref_emissions * (1 - perc_off / 100)

    target_year_emissions = edf.loc[target_year].Emissions.sum()
    sticky = StickyBar(
        label='Päästöt yhteensä',
        goal=target_emissions,
        value=target_year_emissions,
        unit='kt',
        below_goal_good=True,
    )

    card = GraphCard(id='emissions-total',
                     graph=dict(figure=graph.get_figure()))

    return html.Div(
        [dbc.Row(cols),
         dbc.Row(dbc.Col(card.render())),
         sticky.render()])
Ejemplo n.º 4
0
def make_emission_nav(current_page):
    df = predict_emissions()
    target_year = get_variable('target_year')

    ts = df.sort_index().drop(columns='Forecast', level=0).loc[target_year]

    items = []

    current_sector = current_page.emission_sector if current_page and current_page.emission_sector else None
    # Sort sectors based on the target year emissions
    sector_emissions = ts.sum(level=0).sort_values(ascending=False)

    def render_sector(s, sector_path, level):
        sector_emissions = s.sum(level=0).sort_values(ascending=False)
        for subsector_name, emissions in sector_emissions.iteritems():
            if not subsector_name:
                continue
            subsector_path = tuple([*sector_path, subsector_name])

            next_metadata = SECTORS
            for sp in subsector_path:
                metadata = next_metadata[sp]
                next_metadata = metadata.get('subsectors', {})

            if current_sector == subsector_path:
                active = True
            else:
                active = False

            page = get_page_for_emission_sector(*subsector_path)
            item = _make_nav_item(metadata['name'],
                                  emissions,
                                  level,
                                  page,
                                  active=active)
            items.append(item)

            ss = s[subsector_name]
            if isinstance(ss, pd.Series):
                render_sector(ss, subsector_path, level + 1)

    render_sector(ts, tuple(), 0)

    items.append(
        _make_nav_item('Yhteensä', sector_emissions.sum(), 0, None, bold=True))

    return html.Div([
        html.H6('Päästöt vuonna %s' % target_year),
        dbc.ListGroup(children=items)
    ])
Ejemplo n.º 5
0
    def _calc_emissions(self):
        df = predict_emissions()
        forecast = df.pop('Forecast')
        self.emissions_df = df

        df = df.sum(axis=1)
        self.last_historical_year = df.loc[~forecast].index.max()
        self.target_year = get_variable('target_year')
        ref_year = get_variable('ghg_reductions_reference_year')
        perc = get_variable('ghg_reductions_percentage_in_target_year')
        ref_emissions = df.loc[ref_year]
        last_emissions = df.loc[self.last_historical_year]
        target_emissions = ref_emissions * (1 - perc / 100)
        self.target_emissions = target_emissions
        self.needed_reductions = last_emissions - target_emissions
        self.scenario_emissions = df.loc[self.target_year]
        self.scenario_reductions = last_emissions - self.scenario_emissions
Ejemplo n.º 6
0
    def _render_emissions_bar(self):
        df = predict_emissions()

        last_historical_year = df.loc[~df.Forecast].Year.max()
        start_s = df[df.Year == last_historical_year].groupby(
            'Sector1')['Emissions'].sum()
        target_s = df[df.Year == df.Year.max()].groupby(
            'Sector1')['Emissions'].sum()

        reductions = (start_s - target_s).sort_values(ascending=False)
        traces = []
        page = self.current_page
        for sector_name, emissions in reductions.iteritems():
            sector_metadata = SECTORS[sector_name]
            if page is not None and page.emission_sector is not None and \
                    page.emission_sector[0] == sector_name:
                active = True
            else:
                active = False

            bar = dict(type='bar',
                       x=[emissions],
                       name=sector_metadata['name'],
                       orientation='h',
                       hovertemplate='%{x: .0f}',
                       marker=dict(color=GHG_MAIN_SECTOR_COLORS[sector_name]))
            if active:
                bar['marker'].update(dict(
                    line_color='#888',
                    line_width=4,
                ))
            traces.append(bar)

        sum_reductions = reductions.sum()

        fig = go.Figure(data=traces,
                        layout=go.Layout(
                            xaxis=dict(
                                showgrid=False,
                                showline=False,
                                showticklabels=False,
                                zeroline=False,
                                domain=[0.15, 1],
                                autorange=False,
                                range=[0, sum_reductions],
                            ),
                            yaxis=dict(
                                showgrid=False,
                                showline=False,
                                showticklabels=False,
                                zeroline=False,
                            ),
                            margin=dict(l=0, r=0, b=0, t=0),
                            barmode='stack',
                            paper_bgcolor='rgba(0,0,0,0)',
                            plot_bgcolor='rgba(0,0,0,0)',
                            showlegend=False,
                            width=None,
                            autosize=True,
                            clickmode='none',
                            dragmode=False,
                        ))

        graph = dcc.Graph(
            config={
                'displayModeBar': False,
                'responsive': True,
            },
            style={
                'height': 60,
                'width': '100%'
            },
            figure=fig,
        )
        return graph
Ejemplo n.º 7
0
def make_emission_nav(current_page):
    df = predict_emissions()
    target_year = get_variable('target_year')

    df = df[df.Year == df.Year.max()]

    items = []

    current_sector = current_page.emission_sector if current_page and current_page.emission_sector else None

    # Sort sectors based on the target year emissions
    sector_emissions = df.groupby('Sector1').Emissions.sum().sort_values(
        ascending=False)
    for sector_name, emissions in sector_emissions.iteritems():
        sector_metadata = SECTORS[sector_name]
        sdf = df.loc[df.Sector1 == sector_name]
        page = get_page_for_emission_sector(sector_name, None)

        subsectors = sdf.Sector2.unique()

        if current_sector and sector_name == current_sector[0] and len(
                subsectors) <= 1:
            active = True
        else:
            active = False

        item = _make_nav_item(sector_metadata['name'],
                              emissions,
                              False,
                              page,
                              active=active)
        items.append(item)

        if len(subsectors) <= 1:
            continue

        sdf = sdf.sort_values('Sector2',
                              ascending=True).set_index('Sector2').Emissions
        for subsector_name, emissions in sdf.iteritems():
            if current_sector and sector_name == current_sector[
                    0] and subsector_name == current_sector[1]:
                active = True
            else:
                active = False

            page = get_page_for_emission_sector(sector_name, subsector_name)
            item = _make_nav_item(
                sector_metadata['subsectors'][subsector_name]['name'],
                emissions,
                True,
                page,
                active=active)
            items.append(item)

    sum_emissions = sector_emissions.sum()
    items.append(
        _make_nav_item('Yhteensä', sum_emissions, False, None, bold=True))

    return html.Div([
        html.H6('Päästöt vuonna %s' % target_year),
        dbc.ListGroup(children=items)
    ])