def _refresh_emission_cards(self):
        card = self.get_card('parking-emission-reductions')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='kt (CO2e.)/a',
            fill=True,
            smoothing=True,
        )

        with override_variable(
                'residential_parking_fee_share_of_cars_impacted', 0):
            df0 = predict_cars_emissions()

        df1 = predict_cars_emissions()

        df1['Emissions'] -= df0['Emissions']
        self.yearly_emissions_impact = df1['Emissions'].iloc[-1]
        df_forecast = df1[df1.Forecast]

        fig.add_series(df=df_forecast,
                       column_name='Emissions',
                       trace_name=_('Emissions'))
        card.set_figure(fig)

        card = self.get_card('car-emission-factor')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='g/km',
        )
        fig.add_series(df=df1,
                       column_name='EmissionFactor',
                       trace_name=_('Emission factor'))
        card.set_figure(fig)
Beispiel #2
0
    def render(self):
        self._calc_emissions()
        pötkylä = dbc.Col([
            html.H6(
                _('Emission reductions according to scenario') + ' %s–%s' %
                (self.last_historical_year, self.target_year)),
            self._render_emissions_bar()
        ],
                          md=6)

        emissions_summary = self._render_value_summary(
            self.scenario_emissions, self.target_emissions,
            _('Total net emissions'), _('kt/year'), True)
        emissions_summary = dbc.Col(emissions_summary, md=3)

        if self.value is not None:
            summary = self._render_value_summary(self.value, self.goal,
                                                 self.label, self.unit,
                                                 self.below_goal_good)
            summary = dbc.Col(summary, md=3)
        else:
            summary = dbc.Col(md=3)

        return dbc.Alert([dbc.Row([pötkylä, summary, emissions_summary])],
                         className="page-summary fixed-bottom")
Beispiel #3
0
    def _make_navbar(self):
        if flask.has_request_context():
            custom_setting_count = len(
                [k for k in session.keys() if not k.startswith('_')])
        else:
            custom_setting_count = 0
        badge_el = None
        if custom_setting_count:
            badge_el = dbc.Badge(f'{custom_setting_count} ',
                                 className='badge-danger')

        els = [
            dbc.DropdownMenu(
                [
                    dbc.DropdownMenuItem(_('Population'), href='/vaesto'),
                    dbc.DropdownMenuItem(_('Buildings'), href='/rakennukset')
                ],
                nav=True,
                in_navbar=True,
                label=_("Defaults"),
                # id="dropdown-nav"
            ),
            dbc.NavItem(
                dbc.NavLink(href='/omat-asetukset',
                            children=[
                                _("Own settings"),
                                badge_el,
                            ])),
            dbc.NavItem(html.Span(html.I(className='language-icon')),
                        className='nav-link pr-0'),
            dbc.DropdownMenu(
                [
                    dbc.DropdownMenuItem(
                        "Suomi", href='/language/fi', external_link=True),
                    dbc.DropdownMenuItem(
                        "English", href='/language/en', external_link=True)
                ],
                nav=True,
                in_navbar=True,
                label=get_active_locale().upper(),
                right=True,
            ),
        ]
        return dbc.NavbarSimple(brand=get_variable('site_name_%s' %
                                                   get_active_locale()),
                                brand_href="/",
                                color="primary",
                                dark=True,
                                fluid=True,
                                children=els)
Beispiel #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)
            name = metadata.get('name_%s' % get_active_locale())
            if name is None:
                name = metadata['name']
            item = _make_nav_item(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(_('Total'), sector_emissions.sum(), 0, None, bold=True))

    return html.Div([
        html.H6(_('Emissions in year %(year)d', year=target_year)),
        dbc.ListGroup(children=items)
    ])
    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),
        ])
 def make_sector_fig(self, df, name, metadata, base_color):
     lang = get_active_locale()
     fig = PredictionFigure(
         sector_name=name,
         unit_name='kt',
         title=metadata.get('name_%s' % lang, metadata['name']),
         smoothing=True,
         # allow_nonconsecutive_years=True,
         fill=True,
         stacked=True,
     )
     if len(df.columns) == 2:
         fig.add_series(df=df,
                        trace_name=_('Emissions'),
                        column_name='',
                        historical_color=base_color)
     else:
         fig.legend = True
         fig.legend_x = 0.8
         column_names = list(df.columns)
         column_names.remove('Forecast')
         colors = generate_color_scale(base_color, len(column_names))
         for idx, col_name in enumerate(column_names):
             subsector = metadata['subsectors'][col_name]
             fig.add_series(df=df,
                            trace_name=subsector.get(
                                'name_%s' % lang, metadata['name']),
                            column_name=col_name,
                            historical_color=colors[idx])
     return fig.get_figure()
Beispiel #7
0
    def _render_value_summary(self, value, goal, label, unit, below_goal_good):
        classes = []
        if goal is not None:
            if (value <= goal and below_goal_good) or \
                    (value >= goal and not below_goal_good):
                classes.append('page-summary__total--good')
            else:
                classes.append('page-summary__total--bad')

            target_el = html.Div([
                _("goal") + ' %.0f' % goal,
                html.Span(" %s" % unit, className="unit")
            ],
                                 className="page-summary__target")
        else:
            target_el = None

        classes.append('page-summary__total')

        summary = [
            html.H6(f'{label} ({self.target_year})'),
            html.Div([
                html.Div([
                    "%.0f" % value,
                    html.Span(" %s" % unit, className="unit")
                ],
                         className=' '.join(classes)),
                target_el,
            ],
                     className="page-summary__totals"),
        ]
        return summary
Beispiel #8
0
def generate_buildings_forecast_graph():
    df = generate_building_floor_area_forecast()

    cdf = pd.DataFrame(index=df.index)
    for name, attrs in BUILDING_USES.items():
        cdf[name] = df[attrs['types']].sum(axis=1) / 1000000

    # Sort columns based on the amounts in the last measured year
    last_year = cdf.loc[cdf.index.max()]
    columns = list(last_year.sort_values(ascending=False).index.values)

    traces = []
    lang = get_active_locale()
    for name in columns:
        attrs = BUILDING_USES[name]
        val = df[attrs['types']].sum(axis=1) / 1000000
        label = name
        if lang == 'en':
            label = BUILDINGS_EN[name]
        trace = go.Bar(x=df.index,
                       y=val,
                       name=label,
                       marker=dict(color=attrs['color']),
                       hoverinfo='name',
                       hovertemplate='%{x}: %{y} Mkem²')
        traces.append(trace)

    last_hist_year = df[~df.Forecast].index.max()
    forecast_divider = dict(type='line',
                            x0=last_hist_year + 0.5,
                            x1=last_hist_year + 0.5,
                            xref='x',
                            y0=0,
                            y1=1,
                            yref='paper',
                            line=dict(dash='dot', color='grey'))

    layout = make_layout(
        barmode='stack',
        yaxis=dict(title='1 000 000 kem²', ),
        xaxis=dict(title=_('Year')),
        title=_('Floor area by building purpose'),
        shapes=[forecast_divider],
        showlegend=True,
        autosize=True,
    )
    return dict(data=traces, layout=layout)
    def _refresh_trip_cards(self):
        df = predict_passenger_kms()

        card = self.get_card('number-of-passenger-kms')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='km',
        )
        fig.add_series(df,
                       column_name='KmsPerResident',
                       trace_name=_('passenger kms (p.c.)'))
        card.set_figure(fig)
        df.pop('KmsPerResident')

        total = df.sum(axis=1)

        fc = df.pop('Forecast')
        df = df.div(total, axis=0)
        df *= 100

        # df['Other'] += df.pop('Taxi')
        df['Rail'] = df.pop('Metro') + df.pop('Tram') + df.pop('Train')

        ccard = self.get_card('modal-share-car')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
        )
        fig.add_series(df=df,
                       forecast=fc,
                       column_name='Car',
                       trace_name='Henkilöautot')
        ccard.set_figure(fig)
        df.pop('Car')

        mcard = self.get_card('modal-shares-rest')
        color_scale = len(df.columns)
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
            legend=True,
            color_scale=color_scale,
        )
        last_hist_year = fc[~fc].index.max()
        columns = list(
            df.loc[last_hist_year].sort_values(ascending=False).index)
        for idx, col in enumerate(columns):
            name = MODE_TRANSLATIONS.get(col)
            if name is not None:
                name = name.get(get_active_locale())
            if name is None:
                name = col
            fig.add_series(df=df,
                           forecast=fc,
                           column_name=col,
                           trace_name=name,
                           color_idx=idx)

        mcard.set_figure(fig)
Beispiel #10
0
    def _refresh_parking_fee_cards(self):
        pcard = self.get_card('residential-parking-fee')
        self.set_variable('residential_parking_fee_increase',
                          pcard.get_slider_value())
        icard = self.get_card('cars-affected-by-residential-parking-fee')
        self.set_variable('residential_parking_fee_share_of_cars_impacted',
                          icard.get_slider_value())

        cd = CardDescription()
        df = predict_parking_fee_impact()

        last_hist_year = df[~df.Forecast].index.max()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('€/year'),
            smoothing=False,
            # y_min=df['Fees'].min(),
            y_max=df.loc[last_hist_year]['ResidentialFees'] *
            (1 + MAX_PARKING_FEE_INCREASE_PERC / 100))
        fig.add_series(df=df,
                       column_name='ResidentialFees',
                       trace_name='Asukaspysäköinnin hinta')
        pcard.set_figure(fig)

        pcard.set_description(
            cd.render("""
        Oletuksena on Wienin tutkimus maksullisen pysäköinnin vaikutuksesta, jonka mukaan pysäköintimaksun
        kaksinkertaistaminen vähentää pysäköintiä ja siten autoliikennettä siihen kohdistuvilla alueilla
        noin 8,8 %. Asukaspysäköintimaksujen korotus alkoi vuonna 2015 ja vuosimaksu nousee
        120 eurosta 360 euroon vuoteen 2021 mennessä. Asukaspysäköintitunnusten määrä on vuosina 2014–2019
        vähentynyt noin 600 kpl vaikka asukasluku on kasvanut kantakaupungissa."""
                      ))
        """{municipality_locative} lyhytaikainen pysäköinti on vähentynyt vuoden 2017 pysäköintimaksujen korotuksen
        jälkeen noin 10%."""

        fig = PredictionFigure(sector_name='Transportation',
                               unit_name='%',
                               smoothing=False,
                               y_max=100)
        df['ResidentialShareOfCarsImpacted'] *= 100
        cd.set_values(
            residential_share_target=df['ResidentialShareOfCarsImpacted'].
            iloc[-1],
            residential_share=df[~df.Forecast]
            ['ResidentialShareOfCarsImpacted'].iloc[-1],
        )
        fig.add_series(df=df,
                       column_name='ResidentialShareOfCarsImpacted',
                       trace_name='Osuus')
        icard.set_figure(fig)
        icard.set_description(
            cd.render("""
        Tarkastelussa on mukana vain keskustan asukaspysäköintivyöhykkeet.
        Asukaspysäköintilupia on myönnetty nyt n. {residential_share} % {municipality_genitive}
        liikennekäytössä olevalle henkilöautokannalle.
        Skenaariossa vuonna {target_year} asukaspysäköinnin piirissä on {residential_share_target} %
        auton omistajista.
        """))
Beispiel #11
0
    layout = make_layout(
        barmode='stack',
        yaxis=dict(title='1 000 000 kem²', ),
        xaxis=dict(title=_('Year')),
        title=_('Floor area by building purpose'),
        shapes=[forecast_divider],
        showlegend=True,
        autosize=True,
    )
    return dict(data=traces, layout=layout)


def render_page():
    fig = generate_buildings_forecast_graph()
    ret = dbc.Row([
        dbc.Col([GraphCard(id='buildings', graph=dict(figure=fig)).render()],
                md=8)
    ])

    return ret


page = Page(id='rakennukset',
            path='/rakennukset',
            name=_('Buildings'),
            content=render_page)

if __name__ == '__main__':
    generate_buildings_forecast_graph()
Beispiel #12
0
def render_page():
    language = get_active_locale()
    cols = []
    edf = predict_emissions().dropna(axis=1, how='all')
    forecast = edf.pop('Forecast')
    graph = PredictionFigure(sector_name=None,
                             unit_name='kt',
                             title=_('Total emissions'),
                             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
        name = sector_metadata.get('name_%s' % language,
                                   sector_metadata['name'])
        graph.add_series(df=df,
                         trace_name=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=_('Total emission reductions'),
        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()])
Beispiel #13
0
class CarFleetPage(Page):
    id = 'car-fleet'
    path = '/car-fleet'
    emission_sector = ('Transportation', )
    name = _('Car fleet')

    def make_cards(self):
        from .modal_share import ModalSharePage

        self.add_graph_card(
            id='ev-parking-fee-discount',
            title='Sähköautolle myönnetty pysäköintietuus',
            title_i18n=dict(en='Parking fee discount given to EVs'),
            slider=dict(
                min=0,
                max=1000,
                step=50,
                value=get_variable('parking_subsidy_for_evs'),
                marks={x: '%d €' % x
                       for x in range(0, 1001, 100)},
            ),
        )
        self.add_graph_card(
            id='share-of-ev-charging-stations-built',
            title='Rakennettu osuus tarvittavista julkisista latausasemista',
            title_i18n=dict(
                en='Share of needed public EV charging stations built'),
            slider=dict(
                min=0,
                max=100,
                step=10,
                value=get_variable(
                    'share_of_ev_charging_station_demand_built'),
                marks={x: '%d %%' % x
                       for x in range(0, 101, 10)},
            ),
        )
        self.add_graph_card(
            id='newly-registered-evs',
            title='Ensirekisteröityjen autojen osuudet käyttövoiman mukaan',
            title_i18n=dict(
                en='Share of newly registered cars by engine type'),
        )
        self.add_graph_card(
            id='yearly-fleet-turnover',
            title='Autokannan vuosittainen uudistuminen',
            title_i18n=dict(en='Yearly turnover of car fleet'),
        )
        self.add_graph_card(
            id='cars-per-resident',
            title='Liikennekäytössä olevat henkilöautot asukasta kohti',
            title_i18n=dict(
                en='Cars registered for transportation per resident'),
        )
        self.add_graph_card(
            id='car-fleet',
            title='Liikennekäytössä olevat henkilöautot',
            title_i18n=dict(en='Cars registered for transportation'),
        )

        self.add_graph_card(
            id='mileage',
            title='%s ajetut henkilöautokilometrit' %
            get_variable('municipality_locative'),
            title_i18n=dict(en='%s ajetut henkilöautokilometrit' %
                            get_variable('municipality_name')),
            link_to_page=ModalSharePage,
        )
        self.add_graph_card(
            id='emission-factor',
            title='Henkilöautojen päästökerroin',
            title_i18n=dict(en='Emission factor of cars'),
        )

        self.add_graph_card(
            id='emission-impact',
            title='Toimenpiteiden päästövaikutukset',
            title_i18n=dict(en='Emission impact of actions'),
        )

    def get_content(self):
        grid = ConnectedCardGrid()

        grid.make_new_row()
        c1a = self.get_card('ev-parking-fee-discount')
        c1b = self.get_card('share-of-ev-charging-stations-built')
        c1c = self.get_card('cars-per-resident')
        grid.add_card(c1a)
        grid.add_card(c1b)
        grid.add_card(c1c)

        grid.make_new_row()
        c2a = self.get_card('newly-registered-evs')
        c2b = self.get_card('yearly-fleet-turnover')
        grid.add_card(c2a)
        grid.add_card(c2b)
        c1a.connect_to(c2a)
        c1b.connect_to(c2a)
        c1c.connect_to(c2b)

        grid.make_new_row()
        c3 = self.get_card('car-fleet')
        grid.add_card(c3)
        c2a.connect_to(c3)
        c2b.connect_to(c3)

        grid.make_new_row()
        c4a = self.get_card('emission-factor')
        c4b = self.get_card('mileage')
        grid.add_card(c4a)
        grid.add_card(c4b)
        c3.connect_to(c4a)

        grid.make_new_row()
        c5 = self.get_card('emission-impact')
        grid.add_card(c5)
        c4a.connect_to(c5)
        c4b.connect_to(c5)

        return grid.render()

    def get_summary_vars(self):
        return dict(label=_('Emission reductions'),
                    value=self.yearly_emissions_impact,
                    unit='kt/a')

    def refresh_graph_cards(self):
        card = self.get_card('ev-parking-fee-discount')
        self.set_variable('parking_subsidy_for_evs', card.get_slider_value())

        df = predict_parking_fee_impact()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('€/year'),
            y_max=1000,
        )
        fig.add_series(df=df,
                       column_name='ParkingSubsidyForEVs',
                       trace_name=_('Yearly subsidy'))
        card.set_figure(fig)
        cd = CardDescription()
        cd.set_values(
            parking_subsidy_for_evs=get_variable('parking_subsidy_for_evs'))
        card.set_description(
            cd.render("""
            Skenaariossa täyssähköautoille myönnetään pysäköintietuuksia
            jatkossa yhteensä {parking_subsidy_for_evs} €/vuosi.
        """))
        card.set_description(cd.render("""
            In this scenario, BEVs will be given extra parking subsidies
            in total {parking_subsidy_for_evs} € per year.
        """),
                             lang='en')

        card = self.get_card('share-of-ev-charging-stations-built')
        self.set_variable('share_of_ev_charging_station_demand_built',
                          card.get_slider_value())

        df = predict_ev_charging_station_demand()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('charging stations'),
            color_scale=2,
        )
        fig.add_series(df=df,
                       column_name='Built',
                       trace_name=_('Built'),
                       color_idx=0)
        fig.add_series(df=df,
                       column_name='Demand',
                       trace_name=_('Demand'),
                       color_idx=1)
        card.set_figure(fig)

        cd.set_values(
            stations_per_bev=int(
                get_variable('number_of_charging_stations_per_bev') * 100),
            share_stations=get_variable(
                'share_of_ev_charging_station_demand_built'),
            built=df.iloc[-1].Built,
            demand=df.iloc[-1].Demand,
        )
        card.set_description(
            cd.render("""
            Täyssähköautoihin siirtyminen on nopeinta, kun julkisia latauspisteitä
            rakennetaan {stations_per_bev:noround} kpl jokaista 100 sähköautoa kohti. Skenaariossa
            tästä määrästä rakennetaan {share_stations} %. Vuonna {target_year} olisi
            tarve {demand} latauspisteelle ja rakennettuna on {built} latauspistettä.
        """))
        card.set_description(cd.render("""
            Moving to BEVs will happen the fastest when public charging stations are being
            built so that there will be {stations_per_bev:noround} stations for each 
            100 electric vehicles. In this scenario, the city will build {share_stations} %.
            In the year {target_year} there would be demand for {demand} stations and
            there will be {built} stations built.
        """),
                             lang='en')

        card = self.get_card('yearly-fleet-turnover')
        df = predict_cars_in_use()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
            smoothing=True,
        )
        df['YearlyTurnover'] *= 100
        fig.add_series(df=df,
                       column_name='YearlyTurnover',
                       trace_name=_('Turnover'))
        card.set_figure(fig)
        cd.set_values(mean_yearly_turnover=df[~df.Forecast]
                      ['YearlyTurnover'].tail(8).mean())
        card.set_description(
            cd.render("""
            Viime vuosina {municipality_locative} henkilöautokannasta uusittiin noin
            {mean_yearly_turnover} % vuodessa. Laskentamallissa oletataan, että
            uusiutumisnopeus ei juuri muutu.
        """))

        card = self.get_card('cars-per-resident')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('cars/1,000 res.'),
            smoothing=True,
        )
        df['CarsPerResident'] *= 1000
        fig.add_series(df=df,
                       column_name='CarsPerResident',
                       trace_name=_('Cars'))
        card.set_figure(fig)
        cd.set_values(
            cars_in_use=df[~df.Forecast]['NumberOfCars'].iloc[-1],
            cars_in_use_year=df[~df.Forecast].index.max(),
        )
        card.set_description(
            cd.render("""
            Laskentamallissa tarkastellaan ainoastaan liikennekäyttöön rekisteröityjä
            henkilöautoja. Vuonna {cars_in_use_year} {municipality_locative} oli liikennekäytössä
            {cars_in_use} henkilöautoa.
        """))

        card = self.get_card('newly-registered-evs')
        df = predict_newly_registered_cars()
        fc = df.pop('Forecast')
        total = df.sum(axis=1)
        df = df.div(total, axis=0)
        df *= 100
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
            smoothing=True,
            color_scale=4,
            legend=True,
        )
        for engine_type in ('BEV', 'PHEV', 'gasoline', 'diesel', 'other'):
            et = ENGINE_TYPES[engine_type]
            fig.add_series(df=df,
                           forecast=fc,
                           column_name=engine_type,
                           trace_name=et['name'],
                           historical_color=et['color'])
        card.set_figure(fig)
        cd.set_values(
            bev_share=df[~fc]['BEV'].iloc[-1],
            phev_share=df[~fc]['PHEV'].iloc[-1],
            hist_year=df[~fc].index.max(),
        )
        card.set_description(
            cd.render("""
            Vuonna {hist_year} {municipality_genitive} ensirekisteröidyistä
            henkilöautoista {bev_share} % oli täyssähköautoja (BEV) ja
            {phev_share} % ladattavia hybridiautoja (PHEV).
        """))

        card = self.get_card('car-fleet')
        df = predict_cars_in_use_by_engine_type()
        df = df.sum(axis=1, level='EngineType')
        df['Forecast'] = True
        fc = df.pop('Forecast')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('cars'),
            fill=True,
            stacked=True,
            legend=True,
        )
        for engine_type in ('BEV', 'PHEV', 'gasoline', 'diesel', 'other'):
            fig.add_series(df=df,
                           forecast=fc,
                           column_name=engine_type,
                           trace_name=_(engine_type),
                           forecast_color=ENGINE_TYPE_COLORS[engine_type])
        card.set_figure(fig)

        df = predict_cars_emissions()
        with override_variable('share_of_ev_charging_station_demand_built', 0):
            with override_variable('parking_subsidy_for_evs', 0):
                df0 = predict_cars_emissions()

        card = self.get_card('emission-factor')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='g/km',
            color_scale=2,
            legend=True,
            legend_x=0.6,
        )
        fig.add_series(df=df,
                       column_name='EmissionFactor',
                       trace_name=_('Emission factor with actions'),
                       color_idx=0)
        fig.add_series(df=df0,
                       column_name='EmissionFactor',
                       trace_name=_('Emission factor without actions'),
                       color_idx=1)
        card.set_figure(fig)

        df.Mileage /= 1000000
        card = self.get_card('mileage')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('M km'),
            fill=True,
        )
        fig.add_series(
            df=df,
            column_name='Mileage',
            trace_name=_('Vehicle mileage'),
        )
        card.set_figure(fig)

        card = self.get_card('emission-impact')

        df['Emissions'] -= df0['Emissions']
        df = df[df.Forecast]
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('kt/a'),
            fill=True,
        )
        fig.add_series(df=df,
                       column_name='Emissions',
                       trace_name=_('Reductions'))
        self.net_emissions_impact = df['Emissions'].sum()
        self.yearly_emissions_impact = df['Emissions'].iloc[-1]
        card.set_figure(fig)
Beispiel #14
0
    def refresh_graph_cards(self):
        card = self.get_card('ev-parking-fee-discount')
        self.set_variable('parking_subsidy_for_evs', card.get_slider_value())

        df = predict_parking_fee_impact()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('€/year'),
            y_max=1000,
        )
        fig.add_series(df=df,
                       column_name='ParkingSubsidyForEVs',
                       trace_name=_('Yearly subsidy'))
        card.set_figure(fig)
        cd = CardDescription()
        cd.set_values(
            parking_subsidy_for_evs=get_variable('parking_subsidy_for_evs'))
        card.set_description(
            cd.render("""
            Skenaariossa täyssähköautoille myönnetään pysäköintietuuksia
            jatkossa yhteensä {parking_subsidy_for_evs} €/vuosi.
        """))
        card.set_description(cd.render("""
            In this scenario, BEVs will be given extra parking subsidies
            in total {parking_subsidy_for_evs} € per year.
        """),
                             lang='en')

        card = self.get_card('share-of-ev-charging-stations-built')
        self.set_variable('share_of_ev_charging_station_demand_built',
                          card.get_slider_value())

        df = predict_ev_charging_station_demand()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('charging stations'),
            color_scale=2,
        )
        fig.add_series(df=df,
                       column_name='Built',
                       trace_name=_('Built'),
                       color_idx=0)
        fig.add_series(df=df,
                       column_name='Demand',
                       trace_name=_('Demand'),
                       color_idx=1)
        card.set_figure(fig)

        cd.set_values(
            stations_per_bev=int(
                get_variable('number_of_charging_stations_per_bev') * 100),
            share_stations=get_variable(
                'share_of_ev_charging_station_demand_built'),
            built=df.iloc[-1].Built,
            demand=df.iloc[-1].Demand,
        )
        card.set_description(
            cd.render("""
            Täyssähköautoihin siirtyminen on nopeinta, kun julkisia latauspisteitä
            rakennetaan {stations_per_bev:noround} kpl jokaista 100 sähköautoa kohti. Skenaariossa
            tästä määrästä rakennetaan {share_stations} %. Vuonna {target_year} olisi
            tarve {demand} latauspisteelle ja rakennettuna on {built} latauspistettä.
        """))
        card.set_description(cd.render("""
            Moving to BEVs will happen the fastest when public charging stations are being
            built so that there will be {stations_per_bev:noround} stations for each 
            100 electric vehicles. In this scenario, the city will build {share_stations} %.
            In the year {target_year} there would be demand for {demand} stations and
            there will be {built} stations built.
        """),
                             lang='en')

        card = self.get_card('yearly-fleet-turnover')
        df = predict_cars_in_use()
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
            smoothing=True,
        )
        df['YearlyTurnover'] *= 100
        fig.add_series(df=df,
                       column_name='YearlyTurnover',
                       trace_name=_('Turnover'))
        card.set_figure(fig)
        cd.set_values(mean_yearly_turnover=df[~df.Forecast]
                      ['YearlyTurnover'].tail(8).mean())
        card.set_description(
            cd.render("""
            Viime vuosina {municipality_locative} henkilöautokannasta uusittiin noin
            {mean_yearly_turnover} % vuodessa. Laskentamallissa oletataan, että
            uusiutumisnopeus ei juuri muutu.
        """))

        card = self.get_card('cars-per-resident')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('cars/1,000 res.'),
            smoothing=True,
        )
        df['CarsPerResident'] *= 1000
        fig.add_series(df=df,
                       column_name='CarsPerResident',
                       trace_name=_('Cars'))
        card.set_figure(fig)
        cd.set_values(
            cars_in_use=df[~df.Forecast]['NumberOfCars'].iloc[-1],
            cars_in_use_year=df[~df.Forecast].index.max(),
        )
        card.set_description(
            cd.render("""
            Laskentamallissa tarkastellaan ainoastaan liikennekäyttöön rekisteröityjä
            henkilöautoja. Vuonna {cars_in_use_year} {municipality_locative} oli liikennekäytössä
            {cars_in_use} henkilöautoa.
        """))

        card = self.get_card('newly-registered-evs')
        df = predict_newly_registered_cars()
        fc = df.pop('Forecast')
        total = df.sum(axis=1)
        df = df.div(total, axis=0)
        df *= 100
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='%',
            smoothing=True,
            color_scale=4,
            legend=True,
        )
        for engine_type in ('BEV', 'PHEV', 'gasoline', 'diesel', 'other'):
            et = ENGINE_TYPES[engine_type]
            fig.add_series(df=df,
                           forecast=fc,
                           column_name=engine_type,
                           trace_name=et['name'],
                           historical_color=et['color'])
        card.set_figure(fig)
        cd.set_values(
            bev_share=df[~fc]['BEV'].iloc[-1],
            phev_share=df[~fc]['PHEV'].iloc[-1],
            hist_year=df[~fc].index.max(),
        )
        card.set_description(
            cd.render("""
            Vuonna {hist_year} {municipality_genitive} ensirekisteröidyistä
            henkilöautoista {bev_share} % oli täyssähköautoja (BEV) ja
            {phev_share} % ladattavia hybridiautoja (PHEV).
        """))

        card = self.get_card('car-fleet')
        df = predict_cars_in_use_by_engine_type()
        df = df.sum(axis=1, level='EngineType')
        df['Forecast'] = True
        fc = df.pop('Forecast')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('cars'),
            fill=True,
            stacked=True,
            legend=True,
        )
        for engine_type in ('BEV', 'PHEV', 'gasoline', 'diesel', 'other'):
            fig.add_series(df=df,
                           forecast=fc,
                           column_name=engine_type,
                           trace_name=_(engine_type),
                           forecast_color=ENGINE_TYPE_COLORS[engine_type])
        card.set_figure(fig)

        df = predict_cars_emissions()
        with override_variable('share_of_ev_charging_station_demand_built', 0):
            with override_variable('parking_subsidy_for_evs', 0):
                df0 = predict_cars_emissions()

        card = self.get_card('emission-factor')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name='g/km',
            color_scale=2,
            legend=True,
            legend_x=0.6,
        )
        fig.add_series(df=df,
                       column_name='EmissionFactor',
                       trace_name=_('Emission factor with actions'),
                       color_idx=0)
        fig.add_series(df=df0,
                       column_name='EmissionFactor',
                       trace_name=_('Emission factor without actions'),
                       color_idx=1)
        card.set_figure(fig)

        df.Mileage /= 1000000
        card = self.get_card('mileage')
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('M km'),
            fill=True,
        )
        fig.add_series(
            df=df,
            column_name='Mileage',
            trace_name=_('Vehicle mileage'),
        )
        card.set_figure(fig)

        card = self.get_card('emission-impact')

        df['Emissions'] -= df0['Emissions']
        df = df[df.Forecast]
        fig = PredictionFigure(
            sector_name='Transportation',
            unit_name=_('kt/a'),
            fill=True,
        )
        fig.add_series(df=df,
                       column_name='Emissions',
                       trace_name=_('Reductions'))
        self.net_emissions_impact = df['Emissions'].sum()
        self.yearly_emissions_impact = df['Emissions'].iloc[-1]
        card.set_figure(fig)
class TransportationPage(MainSectorPage):
    id = 'transportation'
    path = '/liikenne'
    emission_sector = ('Transportation', )
    emission_name = _('Transportation emissions')
    is_main_page = True
Beispiel #16
0
 def get_summary_vars(self):
     return dict(label=_('Emission reductions'),
                 value=self.yearly_emissions_impact,
                 unit='kt/a')
Beispiel #17
0
    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=_('Total emission reductions'),
        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()])


page = Page(
    id='emissions',
    name=_('Total GHG emissions'),
    content=render_page,
    path='/',
)

if __name__ == '__main__':
    render_page()