Пример #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()])
Пример #2
0
def population_callback(value):
    set_variable('population_forecast_correction', value)
    pop_df = get_adjusted_population_forecast()
    target_year = get_variable('target_year')
    pop_in_target_year = pop_df.loc[target_year].Population
    last_hist = pop_df[~pop_df.Forecast].iloc[-1]
    fig = generate_population_forecast_graph(pop_df)
    cd = CardDescription()
    cd.set_values(
        pop_in_target_year=pop_in_target_year,
        pop_adj=get_variable('population_forecast_correction'),
        pop_diff=(1 - last_hist.Population / pop_in_target_year) * 100,
    )
    cd.set_variables(last_year=last_hist.name)
    pop_desc = cd.render("""
        {municipality_genitive} väkiluku vuonna {target_year} on {pop_in_target_year}.
        Muutos viralliseen väestöennusteeseen on {pop_adj:noround} %.
        Väkiluvun muutos vuoteen {last_year} verrattuna on {pop_diff} %.
    """)

    bar = StickyBar(
        label="Väkiluku %s" % get_variable('municipality_locative'),
        value=pop_in_target_year,
        unit='asukasta',
    )

    # return fig, pop_in_target_year.round()
    return [fig, dbc.Col(pop_desc), bar.render()]
Пример #3
0
def population_callback(value):
    set_variable('population_forecast_correction', value)
    pop_df = predict_population()
    target_year = get_variable('target_year')
    pop_in_target_year = pop_df.loc[target_year].Population
    last_hist = pop_df[~pop_df.Forecast].iloc[-1]
    fig = generate_population_forecast_graph(pop_df)
    cd = CardDescription()
    cd.set_values(
        pop_in_target_year=pop_in_target_year,
        pop_adj=get_variable('population_forecast_correction'),
        pop_diff=(1 - last_hist.Population / pop_in_target_year) * 100,
    )
    cd.set_variables(last_year=last_hist.name)
    pop_desc = cd.render("""
        The population of {municipality} in the year {target_year} will be {pop_in_target_year}.
        The difference compared to the official population forecast is {pop_adj:noround} %.
        Population change compared to {last_year} is {pop_diff} %.
    """)
    # pop_desc = cd.render("""
    #    {municipality_genitive} väkiluku vuonna {target_year} on {pop_in_target_year}.
    #    Muutos viralliseen väestöennusteeseen on {pop_adj:noround} %.
    #    Väkiluvun muutos vuoteen {last_year} verrattuna on {pop_diff} %.
    #""")

    bar = StickyBar(
        label=gettext('Population in %(municipality)s') %
        dict(municipality=get_variable('municipality_name')),
        value=pop_in_target_year,
        unit=gettext('residents'),
    )

    # return fig, pop_in_target_year.round()
    return [fig, dbc.Col(pop_desc), bar.render()]
Пример #4
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()])
Пример #5
0
def make_bottom_bar(df):
    last_emissions = df.iloc[-1].loc['Emissions']

    bar = StickyBar(
        label="Henkilöautojen päästöt",
        value=last_emissions,
        # goal=CARS_GOAL,
        unit='kt (CO₂e.) / a',
        current_page=page,
    )
    return bar.render()
def make_bottom_bar(df):
    s = df['District heat consumption emissions']
    last_emissions = s.iloc[-1]
    target_emissions = DISTRICT_HEATING_GOAL

    bar = StickyBar(label="Kaukolämmön kulutuksen päästöt",
                    value=last_emissions,
                    goal=target_emissions,
                    unit='kt (CO₂e.)',
                    current_page=page)
    return bar.render()
Пример #7
0
def make_bottom_bar(df):
    s = df['NetEmissions']
    last_emissions = s.iloc[-1]
    target_emissions = DISTRICT_HEATING_GOAL

    bar = StickyBar(
        label=_('District heating emissions'),
        value=last_emissions,
        # goal=target_emissions,
        unit='kt (CO₂e.)',
        current_page=page)
    return bar.render()
Пример #8
0
def district_heating_callback(*args):
    # set_variable('bio_emission_factor', bio_emission_factor)

    args = list(args)
    weights = [args.pop(0) for m in production_methods]

    total_weights = sum(weights)
    if total_weights == 0:
        shares = [1 / len(weights)] * len(weights)
    else:
        shares = [val / total_weights for val in weights]
    shares = [int(x * 100) for x in shares]

    # Make sure the sum is 100
    diff = 100 - sum(shares)
    shares[0] += diff

    for method, share in zip(production_methods, shares):
        method.set_ratio(share)
        vals = [args.pop(0) for o in method.get_extra_inputs()]
        if vals:
            method.set_extra_input_values(vals)

    production_stats, production_source = calc_district_heating_unit_emissions_forecast(
    )
    ef_fig = generate_district_heating_emission_factor_graph(production_stats)
    fig = generate_district_heating_forecast_graph(production_stats)
    table = generate_district_heating_forecast_table(production_stats)

    last_row = production_stats.iloc[-1]
    sticky = StickyBar(
        label='Kaukolämmöntuotannon päästökerroin',
        value=last_row['Emission factor'],
        unit='g/kWh',
        current_page=page,
    )

    method_outputs = []
    for method in production_methods:
        method_outputs += method.get_output_values(production_stats,
                                                   production_source)

    return [ef_fig, fig, table, sticky.render(), *method_outputs]
Пример #9
0
def solar_power_callback(existing_building_perc, new_building_perc):
    # First see what the maximum solar production capacity is to set the
    # Y axis maximum.
    set_variable('solar_power_existing_buildings_percentage', 100)
    set_variable('solar_power_new_buildings_percentage', 100)
    kwp_max = predict_solar_power_production()

    # Then predict with the given percentages.
    set_variable('solar_power_existing_buildings_percentage',
                 existing_building_perc)
    set_variable('solar_power_new_buildings_percentage', new_building_perc)
    kwp_df = predict_solar_power_production()

    ymax = kwp_max.SolarPowerExisting.iloc[-1]
    fig_old = generate_solar_power_graph(kwp_df, "Vanhan",
                                         "SolarPowerExisting", ymax, True)
    # ymax = kwp_max.SolarPowerNew.iloc[-1]
    fig_new = generate_solar_power_graph(kwp_df, "Uuden", "SolarPowerNew",
                                         ymax, False)
    fig_tot, ekwpa, nkwpa = generate_solar_power_stacked(kwp_df)

    graph = PredictionFigure(sector_name='ElectricityConsumption',
                             unit_name='kt',
                             title='Aurinkopaneelien päästövaikutukset',
                             fill=True)
    ef_df = predict_electricity_emission_factor()
    kwp_df['NetEmissions'] = -kwp_df['SolarProduction'] * ef_df[
        'EmissionFactor'] / 1000
    graph.add_series(df=kwp_df,
                     column_name='NetEmissions',
                     trace_name='Päästövaikutukset')
    fig_emissions = graph.get_figure()

    s = kwp_df.SolarProduction

    cd = CardDescription()

    city_owned = get_variable('building_area_owned_by_org') / 100
    cd.set_values(existing_building_perc=existing_building_perc,
                  org_existing_building_kwp=1000 * ekwpa * city_owned,
                  others_existing_building_kwp=1000 * ekwpa * (1 - city_owned))

    existing_kwpa = cd.render("""
    Kun aurinkopaneeleita rakennetaan {existing_building_perc:noround} % kaikesta vanhan
    rakennuskannan kattopotentiaalista, {org_genitive} tulee rakentaa aurinkopaneeleita
    {org_existing_building_kwp} kWp vuodessa skenaarion toteutumiseksi. Muiden kuin {org_genitive}
    tulee rakentaa {others_existing_building_kwp} kWp aurinkopaneeleita vuodessa.
    """)

    cd.set_values(new_building_perc=new_building_perc,
                  org_new_building_kwp=1000 * nkwpa * city_owned,
                  others_new_building_kwp=1000 * nkwpa * (1 - city_owned))
    new_kwpa = cd.render("""
    Kun uuteen rakennuskantaan rakennetaan aurinkopaneeleja {new_building_perc:noround} %
    kaikesta kattopotentiaalista, {org_genitive} tulee rakentaa aurinkopaneeleja
    {org_new_building_kwp} kWp vuodessa skenaarion toteutumiseksi. Muiden kuin {org_genitive}
    tulee rakentaa {others_new_building_kwp} kWp aurinkopaneeleita vuodessa.
    """)

    forecast = s.iloc[-1] * get_variable('yearly_pv_energy_production_kwh_wp')

    sticky = StickyBar(
        label='Aurinkosähkön tuotanto',
        value=forecast,
        unit='GWh',
        current_page=page,
    )

    return [
        fig_old, fig_new, fig_tot, fig_emissions, existing_kwpa, new_kwpa,
        sticky.render()
    ]
Пример #10
0
 def _make_summary_bar(self):
     bar = StickyBar(current_page=self, **self.get_summary_vars())
     return bar.render()
Пример #11
0
def electricity_consumption_callback(value):
    set_variable('electricity_consumption_per_capita_adjustment', value / 10)

    df = predict_electricity_consumption_emissions()

    graph = PredictionFigure(sector_name='ElectricityConsumption',
                             title=_('Electricity consumption per resident'),
                             unit_name='kWh/as.')
    graph.add_series(df=df,
                     trace_name=_('Consumption/res.'),
                     column_name='ElectricityConsumptionPerCapita')
    per_capita_fig = graph.get_figure()

    graph = PredictionFigure(
        sector_name='ElectricityConsumption',
        title=_('Electricity consumption'),
        unit_name='GWh',
        fill=True,
    )
    graph.add_series(df=df,
                     trace_name=_('Electricity consumption'),
                     column_name='NetConsumption')
    consumption_fig = graph.get_figure()

    graph = PredictionFigure(
        sector_name='ElectricityConsumption',
        title=_('Electricity production emission factor'),
        unit_name='g/kWh',
        smoothing=True,
    )
    graph.add_series(df=df,
                     trace_name=_('Emission factor'),
                     column_name='EmissionFactor')
    factor_fig = graph.get_figure()

    graph = PredictionFigure(
        sector_name='ElectricityConsumption',
        title=_('Electricity consumption emissions'),
        unit_name='kt',
        smoothing=True,
        fill=True,
    )
    graph.add_series(df=df, trace_name='Päästöt', column_name='NetEmissions')
    emission_fig = graph.get_figure()

    graph = PredictionFigure(
        sector_name='ElectricityConsumption',
        title=_('Local PV production'),
        unit_name='GWh',
        smoothing=True,
        fill=True,
    )
    graph.add_series(df=df,
                     trace_name='Tuotanto',
                     column_name='SolarProduction')
    solar_fig = graph.get_figure()

    first_forecast = df[df.Forecast].iloc[0]
    last_forecast = df[df.Forecast].iloc[-1]
    last_history = df[~df.Forecast].iloc[-1]
    last_history_year = df[~df.Forecast].index.max()

    cd = CardDescription()
    cd.set_values(
        per_resident_adj=get_variable(
            'electricity_consumption_per_capita_adjustment'),
        per_resident_change=(
            (last_forecast.ElectricityConsumptionPerCapita /
             last_history.ElectricityConsumptionPerCapita) - 1) * 100,
        last_history_year=last_history.name,
        solar_production_target=last_forecast.SolarProduction,
        solar_production_perc=(last_forecast.SolarProduction * 100) /
        last_forecast.ElectricityConsumption,
        solar_production_hist=last_history.SolarProduction,
    )
    per_resident_desc = cd.render("""
        Skenaariossa asukaskohtainen sähkönkulutus pienenee {per_resident_adj:noround} % vuodessa.
        Vuonna {target_year} asukaskohtainen kulutus on muuttunut {per_resident_change} % nykyhetkestä.
    """)
    solar_desc = cd.render("""
        Vuonna {target_year} {municipality_locative} sijaitsevilla aurinkopaneeleilla
        tuotetaan {solar_production_target} GWh, joka on {solar_production_perc} %
        kaikesta vuoden {target_year} kulutussähköstä.
    """)

    bar = StickyBar(label=_('Electicity consumption emissions'),
                    value=last_forecast.NetEmissions,
                    unit='kt',
                    current_page=page)

    return [
        per_capita_fig,
        dbc.Col(per_resident_desc, style=dict(minHeight='6rem')), solar_fig,
        dbc.Col(solar_desc, style=dict(minHeight='6rem')), consumption_fig,
        factor_fig, emission_fig,
        bar.render()
    ]
Пример #12
0
def solar_power_callback(existing_building_perc, new_building_perc):
    # First see what the maximum solar production capacity is to set the
    # Y axis maximum.
    set_variable('solar_power_existing_buildings_percentage', 100)
    set_variable('solar_power_new_buildings_percentage', 100)
    kwp_max = predict_solar_power_production()

    # Then predict with the given percentages.
    set_variable('solar_power_existing_buildings_percentage',
                 existing_building_perc)
    set_variable('solar_power_new_buildings_percentage', new_building_perc)
    kwp_df = predict_solar_power_production()

    ymax = kwp_max.SolarPowerExisting.iloc[-1]
    fig_old = generate_solar_power_graph(kwp_df, "Vanhan",
                                         "SolarPowerExisting", ymax, True)
    ymax = kwp_max.SolarPowerNew.iloc[-1]
    fig_new = generate_solar_power_graph(kwp_df, "Uuden", "SolarPowerNew",
                                         ymax, False)
    fig_tot, ekwpa, nkwpa = generate_solar_power_stacked(kwp_df)

    ef_df = predict_electricity_emission_factor()
    kwp_df['EmissionReductions'] = ef_df['EmissionFactor'] * kwp_df[
        'SolarPowerAll'] / 1000
    graph = PredictionGraph(
        sector_name='ElectricityConsumption',
        unit_name='kt',
        title='Aurinkopaneelien päästövähennykset',
    )
    graph.add_series(kwp_df,
                     trace_name='Päästövähennykset',
                     column_name='EmissionReductions')
    fig_emissions = graph.get_figure()

    s = kwp_df.SolarPowerAll
    forecast = s.iloc[-1] * get_variable('yearly_pv_energy_production_kwh_wp')

    existing_kwpa = html.Div([
        html.Span("Kun aurinkopaneeleita rakennetaan "),
        html.Span('%d %%' % existing_building_perc,
                  className='summary-card__value'),
        html.Span(
            " kaikesta vanhan rakennuskannan kattopotentiaalista, Helsingin kaupunkikonsernin tulee rakentaa aurinkopaneeleja "
        ),
        html.Span("%d kWp" % (1000 * ekwpa * CITY_OWNED / 100),
                  className='summary-card__value'),
        html.Span(
            " vuodessa skenaarion toteutumiseksi. Muiden kuin Helsingin kaupungin tulee rakentaa "
        ),
        html.Span("%d kWp" % (1000 * ekwpa * (100 - CITY_OWNED) / 100),
                  className='summary-card__value'),
        html.Span(" vuodessa."),
    ])

    new_kwpa = html.Div([
        html.Span("Kun uuteen rakennuskantaan rakennetaan aurinkopaneeleja "),
        html.Span('%d %%' % new_building_perc,
                  className='summary-card__value'),
        html.Span(
            " kaikesta kattopotentiaalista, Helsingin kaupunkikonsernin tulee rakentaa aurinkopaneeleja "
        ),
        html.Span("%d kWp" % (1000 * nkwpa * CITY_OWNED / 100),
                  className='summary-card__value'),
        html.Span(
            " vuodessa skenaarion toteutumiseksi. Muiden kuin Helsingin kaupungin tulee rakentaa "
        ),
        html.Span("%d kWp" % (1000 * nkwpa * (100 - CITY_OWNED) / 100),
                  className='summary-card__value'),
        html.Span(" vuodessa."),
    ])

    sticky = StickyBar(
        label='Aurinkosähkön tuotanto',
        value=forecast,
        goal=SOLAR_POWER_GOAL,
        unit='GWh',
        current_page=page,
        below_goal_good=False,
    )

    return [
        fig_old, fig_new, fig_tot, fig_emissions, existing_kwpa, new_kwpa,
        sticky.render()
    ]