Esempio n. 1
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()]
Esempio n. 2
0
def population_callback(value):
    set_variable('population_forecast_correction', value)
    pop_df = get_population_forecast()
    pop_in_target_year = pop_df.loc[[get_variable('target_year')]].Population
    fig = generate_population_forecast_graph(pop_df)

    return fig, pop_in_target_year.round()
Esempio n. 3
0
def run_simulation_callback(n_clicks, simulation_days):
    print('run simulation (days %d)' % simulation_days)
    print(generate_cache_key(simulate_individuals))
    set_variable('simulation_days', simulation_days)
    if n_clicks:
        set_variable('random_seed', n_clicks)

    df = simulate_individuals(only_if_in_cache=True)
    if df is not None:
        return render_results(df)

    if settings.RESTRICT_TO_PRESET_SCENARIOS:
        return [html.Div('Palvelussa ruuhkaa, osa simulaatiotoiminnallisuuksista on pois käytöstä')]

    existing_thread_id = session.get('thread_id', None)
    if existing_thread_id:
        cache.set('thread-%s-kill' % existing_thread_id, True)

    process = SimulationThread(variables=session.copy())
    session['thread_id'] = process.uuid
    process.start()

    return [
        dcc.Interval(id='simulation-output-interval', interval=500, max_intervals=60),
        html.Div(id='simulation-output-results'),
    ]
Esempio n. 4
0
def run_simulation_callback(n_clicks, simulation_days):
    from flask import session
    from common import cache

    print('run simulation (days %d)' % simulation_days)
    set_variable('simulation_days', simulation_days)
    if n_clicks:
        set_variable('random_seed', n_clicks)

    df = simulate_individuals(only_if_in_cache=True)
    if df is not None:
        return render_results(df)

    existing_thread_id = session.get('thread_id', None)
    if existing_thread_id:
        cache.set('thread-%s-kill' % existing_thread_id, True)

    process = SimulationThread(variables=session.copy())
    session['thread_id'] = process.uuid
    process.start()

    return [
        dcc.Interval(id='simulation-output-interval',
                     interval=500,
                     max_intervals=60),
        html.Div(id='simulation-output-results'),
    ]
Esempio n. 5
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()]
Esempio n. 6
0
 def mutate(root, info, event_id):
     iv_id = int(event_id)
     iv_list = list(get_variable('interventions'))
     if iv_id >= len(iv_list):
         raise GraphQLError('invalid intervention ID')
     del iv_list[iv_id]
     set_variable('interventions', iv_list)
     return dict(ok=True)
Esempio n. 7
0
def simulate_monte_carlo(seed):
    from variables import allow_set_variable, get_variable, set_variable

    with allow_set_variable():
        set_variable('random_seed', seed)
        print(seed)
        df = simulate_individuals(skip_cache=True)
        df['run'] = seed

    return df
Esempio n. 8
0
    def apply(self):
        super().apply()

        ivs = get_variable('interventions')
        out = []
        for iv in ivs:
            iv = list(iv)
            if iv[0] == 'limit-mobility':
                iv[2] = iv[2] // 2
            out.append(iv)
        set_variable('interventions', out)
Esempio n. 9
0
    def mutate(root, info, event):
        iv_type = event.type.value

        iv_list = list(get_variable('interventions'))
        obj = get_intervention(iv_type).copy()
        obj.date = event.date
        for p in event.parameters:
            obj.set_param(p.id, p.choice or p.value)
        iv_list.append(obj.make_iv_tuple())
        set_variable('interventions', iv_list)

        return dict(id=len(iv_list) - 1)
Esempio n. 10
0
def interventions_callback(ts, reset_clicks, add_intervention_clicks, rows,
                           new_date, new_id, new_val):
    ctx = dash.callback_context
    is_reset = False
    changed = False

    if ctx.triggered:
        c_id = ctx.triggered[0]['prop_id'].split('.')[0]
        if reset_clicks is not None and c_id == 'interventions-reset-defaults':
            reset_variable('interventions')
            is_reset = True
        if add_intervention_clicks is not None and c_id == 'new-intervention-add':
            d = date.fromisoformat(new_date)
            sstart = date.fromisoformat(get_variable('start_date'))
            if d < sstart or d > sstart + timedelta(
                    days=get_variable('simulation_days')):
                raise dash.exceptions.PreventUpdate()

            if new_id in ('test-all-with-symptoms', ):
                new_val = None
            elif new_id == ('test-with-contact-tracing',
                            'test-only-severe-symptoms'):
                if new_val > 100 or new_val < 0:
                    raise dash.exceptions.PreventUpdate()
            elif new_id in ('limit-mobility', ):
                if new_val > 100 or new_val < 0:
                    raise dash.exceptions.PreventUpdate()
            elif new_id in ('limit-mass-gatherings', 'import-infections',
                            'build-new-icu-units', 'build-new-hospital-beds'):
                if new_val < 0:
                    raise dash.exceptions.PreventUpdate()
            else:
                raise dash.exceptions.PreventUpdate()

            changed = True
            rows.append(dict(name=new_id, date=d.isoformat(), value=new_val))
        if c_id == 'interventions-table':
            changed = True

    if not is_reset and changed:
        ivs = []
        for row in sorted(rows, key=lambda x: x['date']):
            val = row['value']
            if isinstance(val, str):
                val = int(val)
            ivs.append([row['name'], row['date'], val])

        set_variable('interventions', ivs)

    rows = interventions_to_rows()
    return rows
Esempio n. 11
0
    def mutate(root, info, scenario_id):
        scenarios = get_variable('scenarios')
        if scenario_id:
            for s in scenarios:
                if scenario_id == s['id']:
                    break
            else:
                raise GraphQLError('invalid scenario ID')
        else:
            scenario_id = ''

        reset_variables()
        set_variable('active_scenario', scenario_id)
        return dict(ok=True)
Esempio n. 12
0
def ghg_slider_callback(*values):
    sectors = [x.id.split('-')[1] for x in ghg_sliders]
    new_values = {s: val for s, val in zip(sectors, values)}
    set_variable('ghg_reductions_weights', new_values)
    df = get_ghg_emissions_forecast()
    fig = generate_ghg_emission_graph(df)

    df['Yhteensä'] = df.sum(axis=1)
    last_hist_year = df[~df.Forecast].index.max()
    data_columns = list(df.loc[df.index == last_hist_year].stack().sort_values(
        ascending=False).index.get_level_values(1))

    data_columns.remove('Forecast')
    data_columns.insert(0, 'Vuosi')
    data_columns.remove('Yhteensä')
    data_columns.append('Yhteensä')

    last_forecast_year = df[df.Forecast].index.max()
    table_df = df.loc[df.index.isin([
        last_hist_year, last_forecast_year - 5, last_forecast_year - 10,
        last_forecast_year
    ])]
    table_data = table_df.reset_index().to_dict('rows')
    table_cols = []
    for col_name in data_columns:
        col = dict(id=col_name, name=col_name)
        if col_name == 'Vuosi':
            pass
        else:
            col['type'] = 'numeric'
            col['format'] = Format(precision=0, scheme=Scheme.fixed)
        table_cols.append(col)
    table = dash_table.DataTable(
        data=table_data,
        columns=table_cols,
        # style_as_list_view=True,
        style_cell={'padding': '5px'},
        style_header={'fontWeight': 'bold'},
        style_cell_conditional=[{
            'if': {
                'column_id': 'Vuosi'
            },
            'fontWeight': 'bold',
        }])

    return [fig, table]
Esempio n. 13
0
def electricity_consumption_callback(value):
    set_variable('electricity_consumption_per_capita_adjustment', value / 10)

    df = predict_electricity_consumption_emissions()

    graph = PredictionGraph(sector_name='ElectricityConsumption',
                            title='Sähkönkulutus asukasta kohti',
                            unit_name='kWh/as.')
    graph.add_series(df=df,
                     trace_name='Sähkönkulutus/as.',
                     column_name='ElectricityConsumptionPerCapita')
    per_capita_fig = graph.get_figure()

    graph = PredictionGraph(
        sector_name='ElectricityConsumption',
        title='Kulutussähkön kulutus',
        unit_name='GWh',
    )
    graph.add_series(df=df,
                     trace_name='Sähkönkulutus',
                     column_name='ElectricityConsumption')
    consumption_fig = graph.get_figure()

    graph = PredictionGraph(
        sector_name='ElectricityConsumption',
        title='Sähköntuotannon päästökerroin',
        unit_name='g/kWh',
        smoothing=True,
    )
    graph.add_series(df=df,
                     trace_name='Päästökerroin',
                     column_name='EmissionFactor')
    factor_fig = graph.get_figure()
    print(factor_fig)

    graph = PredictionGraph(
        sector_name='ElectricityConsumption',
        title='Kulutussähkön päästöt',
        unit_name='kt (CO2e)',
        smoothing=True,
    )
    graph.add_series(df=df, trace_name='Päästöt', column_name='Emissions')
    emission_fig = graph.get_figure()

    return [per_capita_fig, consumption_fig, factor_fig, emission_fig]
def district_heating_consumption_callback(existing_building_perc,
                                          new_building_perc):
    set_variable('district_heating_existing_building_efficiency_change',
                 existing_building_perc / 10)
    set_variable('district_heating_new_building_efficiency_change',
                 new_building_perc / 10)

    df = predict_district_heat_consumption()
    fig1 = draw_existing_building_unit_heat_factor_graph(df)
    fig2 = draw_new_building_unit_heat_factor_graph(df)
    fig3 = draw_heat_consumption(df)

    df = predict_district_heating_emissions()
    unit_emissions_card = make_unit_emissions_card(df)
    fig4 = draw_district_heat_consumption_emissions(df)
    sticky = make_bottom_bar(df)

    return [fig1, fig2, fig3, unit_emissions_card, fig4, sticky]
Esempio n. 15
0
    def disease_params_data_callback(ts, reset_clicks, rows):
        ctx = dash.callback_context
        if ctx.triggered:
            c_id = ctx.triggered[0]['prop_id'].split('.')[0]
            if reset_clicks is not None and c_id == 'disease-params-reset-defaults':
                for row in rows:
                    reset_variable(row['id'])
                    row['value'] = get_variable(row['id'])

        for row in rows:
            if not isinstance(row['value'], (int, float)):
                row['value'] = get_variable(row['id'])
            if row['value'] < 0:
                row['value'] = 0
            elif row['value'] > 100:
                row['value'] = 100
            set_variable(row['id'], float(row['value']))

        return rows
Esempio n. 16
0
    def mutate(root, info, event_id):
        iv_objs = get_active_interventions()

        for iv in iv_objs:
            if iv.id and event_id == iv.id:
                break

        iv_tuple = iv.make_iv_tuple()

        iv_id = int(event_id)
        iv_list = list(get_variable('interventions'))
        for iv in iv_list:
            if iv == iv_tuple:
                break
        else:
            raise GraphQLError('invalid intervention ID')
        iv_list.remove(iv)
        set_variable('interventions', iv_list)
        return dict(ok=True)
Esempio n. 17
0
def district_heating_callback(bio_emission_factor, *args):
    set_variable('bio_emission_factor', bio_emission_factor)

    ratios = get_variable('district_heating_target_production_ratios')

    total_sum = sum(args)
    shares = [val / total_sum for val in args]

    for slider, share in zip(ratio_sliders, shares):
        ratios[slider.method] = int(share * 100)

    diff = 100 - sum(ratios.values())
    ratios[list(ratios.keys())[0]] += diff

    set_variable('district_heating_target_production_ratios', ratios)

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

    fuel_fig = generate_production_mix_graph(production_source)

    return [fig, table, fuel_fig]
Esempio n. 18
0
    def apply(self):
        reset_variables()
        ivs = get_variable('interventions')
        if self.interventions:
            ivs += self.interventions
            set_variable('interventions', ivs)

        if self.variables:
            for key, val in self.variables.items():
                set_variable(key, val)

        set_variable('preset_scenario', self.id)
Esempio n. 19
0
def district_heating_callback(demand_value, heat_pump_value, emissionless_bio):
    set_variable('district_heating_target_demand_change', demand_value)
    set_variable('bio_is_emissionless', emissionless_bio)

    ratios = get_variable('district_heating_target_production_ratios')
    ratios.pop('Lämpöpumput')
    rest_sum = sum(ratios.values())
    rest_shares = {key: val / rest_sum for key, val in ratios.items()}

    heat_pump_share = heat_pump_value / 100
    for_rest = 1 - heat_pump_share
    new_ratios = {
        key: int(100 * val * for_rest)
        for key, val in rest_shares.items()
    }
    new_ratios['Lämpöpumput'] = 100 - sum(new_ratios.values())
    set_variable('district_heating_target_production_ratios', new_ratios)

    df = get_district_heating_unit_emissions_forecast()
    fig = generate_district_heating_forecast_graph(df)
    table = generate_district_heating_forecast_table(df)

    return fig, table
Esempio n. 20
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()
    ]
Esempio n. 21
0
 def set_variable(self, name, val):
     return set_variable(name, val)
Esempio n. 22
0
 def person_age_callback(age, mobility_limit):
     set_variable('sample_limit_mobility', mobility_limit)
     return render_model_param_graphs(age)
Esempio n. 23
0
        dfs = pool.map(simulate_monte_carlo, range(1000))

    df = pd.concat(dfs)
    df.index.name = 'date'
    df = df.reset_index()
    df['scenario'] = scenario.id
    df.to_csv('reina_%s.csv' % scenario.id, index=False)

    return df


if __name__ == '__main__':
    if False:
        from variables import allow_set_variable, get_variable, set_variable
        with allow_set_variable():
            set_variable('simulation_days', 50)
            df = simulate_individuals()
            exit()
    if False:
        from scenarios import SCENARIOS
        for scenario in SCENARIOS:
            df = run_monte_carlo(scenario.id)
            print(df[df.date == df.date.max()])
            last = df[df.date == df.date.max()]
            print(last.dead.describe(percentiles=[.25, .5, .75]))
        exit()

    if False:
        sample_model_parameters('symptom_severity', 90)
        exit()
Esempio n. 24
0
def district_heating_consumption_callback(existing_building_perc,
                                          new_building_perc):
    set_variable('district_heating_existing_building_efficiency_change',
                 existing_building_perc / 10)
    set_variable('district_heating_new_building_efficiency_change',
                 new_building_perc / 10)

    df = predict_district_heat_consumption()
    geo_df = predict_geothermal_production()
    geo_df = geo_df[geo_df.Forecast]
    df['GeoEnergyProductionExisting'] = geo_df['GeoEnergyProductionExisting']
    df['GeoEnergyProductionNew'] = geo_df['GeoEnergyProductionNew']

    df['ExistingBuildingHeatUse'] -= df['GeoEnergyProductionExisting'].fillna(
        0)
    df['NewBuildingHeatUse'] -= df['GeoEnergyProductionNew'].fillna(0)

    first_forecast = df[df.Forecast].iloc[0]
    last_forecast = df[df.Forecast].iloc[-1]
    last_history = df[~df.Forecast].iloc[-1]

    cd = CardDescription()
    org_owned = get_variable('building_area_owned_by_org') / 100
    geo_production = last_forecast.GeoEnergyProductionExisting + last_forecast.GeoEnergyProductionNew
    cd.set_values(
        existing_renovation=get_variable(
            'district_heating_existing_building_efficiency_change'),
        new_improvement=get_variable(
            'district_heating_new_building_efficiency_change'),
        existing_next_year_reduction=(1 -
                                      (first_forecast.ExistingBuildingHeatUse -
                                       last_history.ExistingBuildingHeatUse)) *
        org_owned,
        new_area=last_forecast.NewBuildingNetArea,
        existing_area=last_forecast.ExistingBuildingNetArea,
        geo_production=geo_production,
        geo_percentage=(geo_production / last_forecast.TotalHeatConsumption) *
        100,
    )
    existing_desc = cd.render("""
        Skenaarion mukaan nykyistä rakennuskantaa remontoidaan siten, että rakennuksien
        energiatehokkuus paranee {existing_renovation:noround} % vuodessa. Ensi vuonna {org_genitive}
        omistamien rakennuksien lämmönkulutuksen pitää pudota {existing_next_year_reduction} GWh.
    """)
    new_desc = cd.render("""
        Uuden rakennuskannan energiatehokkuus paranee skenaariossa {new_improvement:noround} % vuodessa.
        Vuonna {target_year} nykyistä rakennuskantaa on {existing_area} milj. kem² ja uutta rakennuskantaa
        {new_area} milj. kem².
    """)
    geo_desc = cd.render("""
        Vanhassa ja uudessa rakennuskannassa korvataan kaukolämpöä paikallisesti tuotetulla
        maalämmöllä siten, että vuonna {target_year} kaukolämpöä korvataan {geo_production} GWh
        ({geo_percentage} % sen vuoden kaukolämmönkulutuksesta).
    """)

    fig1 = draw_existing_building_unit_heat_factor_graph(df)
    fig2 = draw_new_building_unit_heat_factor_graph(df)

    geo_fig = PredictionFigure(
        sector_name='BuildingHeating',
        unit_name='GWh',
        title='Maalämmöllä korvattu kaukolämpö',
        fill=True,
    )
    geo_fig.add_series(
        df=geo_df,
        column_name='GeoEnergyProduction',
        trace_name='Maalämpötuotanto',
    )

    fig3 = draw_heat_consumption(df)

    df = predict_district_heating_emissions()
    unit_emissions_card = make_unit_emissions_card(df)
    fig4 = draw_district_heat_consumption_emissions(df)
    sticky = make_bottom_bar(df)

    return [
        fig1,
        dbc.Col(existing_desc, style=dict(minHeight='8rem')), fig2,
        dbc.Col(new_desc, style=dict(minHeight='8rem')),
        geo_fig.get_figure(),
        dbc.Col(geo_desc, style=dict(minHeight='8rem')), fig3,
        unit_emissions_card, fig4, sticky
    ]
Esempio n. 25
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()
    ]
Esempio n. 26
0
    def refresh_graph_cards(self):
        # 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_df = predict_solar_power_production()

        # Then predict with the given percentages.
        existing_card = self.get_card('existing-buildings')
        set_variable('solar_power_existing_buildings_percentage', existing_card.get_slider_value())

        future_card = self.get_card('new-buildings')
        set_variable('solar_power_new_buildings_percentage', future_card.get_slider_value())

        df = predict_solar_power_production()

        forecast_df = df[df.Forecast]
        hist_df = df[~df.Forecast]
        years_left = forecast_df.index.max() - hist_df.index.max()
        ekwpa = (forecast_df.SolarPowerExisting.iloc[-1] - hist_df.SolarPowerExisting.iloc[-1]) / years_left
        nkwpa = forecast_df.SolarPowerNew.iloc[-1] / years_left

        cd = CardDescription()
        city_owned = get_variable('building_area_owned_by_org') / 100
        cd.set_values(
            existing_building_perc=existing_card.get_slider_value(),
            org_existing_building_kwp=1000 * ekwpa * city_owned,
            others_existing_building_kwp=1000 * ekwpa * (1 - city_owned)
        )
        existing_card.set_description(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=future_card.get_slider_value(),
            org_new_building_kwp=1000 * nkwpa * city_owned,
            others_new_building_kwp=1000 * nkwpa * (1 - city_owned)
        )
        future_card.set_description(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.
        """))

        ymax = kwp_max_df.SolarPowerExisting.iloc[-1]
        fig = PredictionFigure(
            sector_name='ElectricityConsumption', unit_name='MWp',
            y_max=ymax, color_scale=2
        )
        fig.add_series(df=df, trace_name=_('Peak power'), column_name='SolarPowerExisting', color_idx=0)
        existing_card.set_figure(fig)

        fig = PredictionFigure(
            sector_name='ElectricityConsumption', unit_name='MWp',
            y_max=ymax, color_scale=2
        )
        fig.add_series(df=df, trace_name=_('Peak power'), column_name='SolarPowerNew', color_idx=1)
        future_card.set_figure(fig)

        pv_kwh_wp = get_variable('yearly_pv_energy_production_kwh_wp')
        df.SolarPowerNew = df.SolarPowerNew * pv_kwh_wp
        df.SolarPowerExisting = df.SolarPowerExisting * pv_kwh_wp
        df.loc[~df.Forecast, 'SolarPowerNew'] = np.nan

        card = self.get_card('production')
        fig = PredictionFigure(
            sector_name='ElectricityConsumption', unit_name='GWh',
            stacked=True, fill=True, color_scale=2
        )
        fig.add_series(df=df, trace_name=_('Existing buildings'), column_name='SolarPowerExisting', color_idx=0)
        fig.add_series(df=df, trace_name=_('Future buildings'), column_name='SolarPowerNew', color_idx=1)
        card.set_figure(fig)

        card = self.get_card('emission-impact')
        fig = PredictionFigure(
            sector_name='ElectricityConsumption', unit_name='kt',
            fill=True
        )
        ef_df = predict_electricity_emission_factor()
        df['NetEmissions'] = -df['SolarProduction'] * ef_df['EmissionFactor'] / 1000
        fig.add_series(df=df, column_name='NetEmissions', trace_name=_('Emissions'))
        card.set_figure(fig)

        s = df.SolarProduction
        self.solar_production_forecast = s.iloc[-1] * get_variable('yearly_pv_energy_production_kwh_wp')
Esempio n. 27
0
 def set_extra_input_values(self, args):
     bio = args[0]
     set_variable('bio_emission_factor', bio)
Esempio n. 28
0
def cars_callback(bev_percentage, mileage_adj):
    set_variable('cars_bev_percentage', bev_percentage)
    set_variable('cars_mileage_per_resident_adjustment', mileage_adj)

    df = predict_cars_emissions()
    df['Mileage'] /= 1000000

    bev_chart = draw_bev_chart(df)
    """
    graph = PredictionFigure(
        sector_name='Transportation',
        unit_name='%',
        title='Biopolttoaineiden osuus myydyissä polttoaineissa',
    )
    graph.add_series(
        df=df, column_name='electric', trace_name='Bion osuus'
    )
    biofuel_chart = graph.get_figure()
    """

    graph = PredictionFigure(
        sector_name='Transportation',
        unit_name='km/as.',
        title='Ajokilometrit asukasta kohti',
    )
    graph.add_series(
        df=df, column_name='PerResident', trace_name='Suorite/as.',
    )
    per_resident_chart = graph.get_figure()

    # Total mileage
    graph = PredictionFigure(
        sector_name='Transportation',
        unit_name='milj. km',
        title='%s ajetut henkilöautokilometrit' % get_variable('municipality_locative'),
        fill=True,
    )
    graph.add_series(
        df=df, column_name='Mileage', trace_name='Ajosuorite',
    )
    mileage_chart = graph.get_figure()

    # Total emissions
    graph = PredictionFigure(
        sector_name='Transportation',
        unit_name='g/km',
        title='Henkilöautojen päästökerroin',
    )
    graph.add_series(
        df=df, column_name='EmissionFactor', trace_name='Päästökerroin',
    )
    emission_factor_chart = graph.get_figure()

    # Total emissions
    graph = PredictionFigure(
        sector_name='Transportation',
        unit_name='kt (CO₂e.)',
        title='Henkilöautoilun päästöt',
        fill=True,
    )
    graph.add_series(
        df=df, column_name='Emissions', trace_name='Päästöt',
    )
    emissions_chart = graph.get_figure()

    cd = CardDescription()
    first_forecast = df[df.Forecast].iloc[0]
    last_forecast = df[df.Forecast].iloc[-1]
    last_history = df[~df.Forecast].iloc[-1]

    cd.set_values(
        bev_percentage=get_variable('cars_bev_percentage'),
        bev_mileage=last_forecast.Mileage * last_forecast.electric,
        per_resident_adjustment=get_variable('cars_mileage_per_resident_adjustment'),
        target_population=last_forecast.Population,
    )
    bev_desc = cd.render("""
        Skenaariossa polttomoottorihenkilöautot korvautuvat sähköautoilla siten,
        että vuonna {target_year} {municipality_genitive} kaduilla ja teillä
        ajetaan sähköautoilla {bev_percentage:noround} % kaikista ajokilometreistä
        ({bev_mileage} milj. km).
    """)
    pr_desc = cd.render("""
        Vuonna {target_year} {municipality_locative} asuu {target_population} ihmistä.
        Skenaariossa ajokilometrit asukasta kohti muuttuvat vuoteen {target_year} mennessä
        {per_resident_adjustment:noround} %.
    """)

    sticky = make_bottom_bar(df)

    return [
        bev_chart, dbc.Col(bev_desc), emission_factor_chart,
        per_resident_chart, dbc.Col(pr_desc), mileage_chart,
        emissions_chart, sticky
    ]
Esempio n. 29
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()
    ]
Esempio n. 30
0
 def set_extra_input_values(self, args):
     cop = args[0]
     set_variable('district_heating_heat_pump_cop', float(cop / 10))