Exemple #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()])
Exemple #2
0
def make_intervention_shapes(df):
    Y_START = -0.3

    shapes = []
    annotations = []

    cur_y = Y_START

    ivs = get_variable('interventions')
    icu_units = get_variable('icu_units')
    hospital_beds = get_variable('hospital_beds')

    out = []
    for iv in ivs:
        name = iv[0]
        # Disable limit mass gatherings for now
        if name == 'limit-mass-gatherings':
            continue

        if name == 'test-all-with-symptoms':
            name = 'testing-mode'
            strength = 0.3
        elif name == 'test-only-severe-symptoms':
            name = 'testing-mode'
            strength = 0.2
        elif name == 'test-with-contact-tracing':
            name = 'testing-mode'
            strength = 0.3 + (iv[2] / 100) * 0.7
        elif name == 'limit-mobility':
            strength = iv[2] / 100
        elif name == 'limit-mass-gatherings':
            if iv[2] >= 500:
                strength = 0.1
            elif iv[2] >= 100:
                strength = 0.3
            elif iv[2] >= 50:
                strength = 0.5
            elif iv[2] >= 10:
                strength = 0.8
            elif iv[2] >= 2:
                strength = 1.0
        elif name == 'import-infections':
            strength = 0.5
        else:
            continue

        out.append((name, iv[1], strength))

    ivs = sorted(out, key=lambda x: (INTERVENTION_TYPES[x[0]]['order'], x[0], x[1]))
    bar_count = 0
    for name, group in groupby(ivs, lambda x: x[0]):
        ranges = [InterventionRange(date.fromisoformat(x[1]), x[2]) for x in group]

        s, a = _draw_one_intervention(df.index, ranges, name, cur_y)
        shapes += s
        annotations += a
        cur_y -= IV_Y_MARGIN
        bar_count += 1

    return shapes, annotations, bar_count
 def make_cards(self):
     self.add_graph_card(
         id='existing-buildings',
         slider=dict(
             min=0,
             max=90,
             step=5,
             value=get_variable('solar_power_existing_buildings_percentage'),
             marks={x: '%d %%' % x for x in range(0, 90 + 1, 10)},
         ),
         title='Vanhan rakennuskannan aurinkopaneelien piikkiteho',
         title_i18n=dict(en='Peak power of PV panels on existing building stock')
     )
     self.add_graph_card(
         id='new-buildings',
         slider=dict(
             min=20,
             max=100,
             step=5,
             value=get_variable('solar_power_new_buildings_percentage'),
             marks={x: '%d %%' % x for x in range(20, 100 + 1, 10)},
         ),
         title='Uuden rakennuskannan aurinkopaneelien piikkiteho',
         title_i18n=dict(en='Peak power of PV panels on future building stock')
     )
     self.add_graph_card(
         id='production',
         title='Aurinkopaneelien sähköntuotanto',
         title_i18n=dict(en='PV panel energy production')
     )
     self.add_graph_card(
         id='emission-impact',
         title='Aurinkopaneelien päästövaikutukset',
         title_i18n=dict(en='Emission impact of PV energy production')
     )
Exemple #4
0
    def resolve_validation_metrics(query, info):
        df = get_detected_cases()
        sim_start = date.fromisoformat(get_variable('start_date'))
        sim_end = sim_start + timedelta(days=get_variable('simulation_days'))
        df = df[df.index < sim_end]
        df['detected'] = df['all_detected'].diff()
        df['detected'] = df['detected'].rolling(window=14).mean().round().astype('Int64').replace({np.nan: None})
        dates = df.index.astype(str).values

        metrics = []

        for col in df.columns:
            m = get_metric(col)
            if not m:
                raise Exception('no metric found for %s' % col)
            int_values = df[col].to_numpy()
            metrics.append(
                Metric(
                    type=m.id,
                    label=m.label,
                    description=m.description,
                    unit=m.unit,
                    color=m.color,
                    is_integer=m.is_integer,
                    is_simulated=False,
                    int_values=int_values
                )
            )
        return DailyMetrics(dates=dates, metrics=metrics)
Exemple #5
0
    def make_cards(self):
        from .modal_share import ModalSharePage
        from .car_fleet import CarFleetPage

        self.add_graph_card(
            id='bev-percentage',
            title='Sähköautojen ajosuoriteosuus',
            title_i18n=dict(en='BEV mileage share'),
            link_to_page=CarFleetPage,
        )
        self.add_graph_card(
            id='mileage-per-resident',
            title='Ajokilometrit asukasta kohti',
            title_i18n=dict(en='Car mileage per resident'),
            link_to_page=ModalSharePage,
        )
        self.add_graph_card(
            id='total-mileage',
            title='%s ajetut henkilöautokilometrit' % get_variable('municipality_locative'),
            title_i18n=dict(en='Car mileage driven in %s' % get_variable('municipality_name')),
        )
        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='emissions',
            title='Henkilöautoilun päästöt',
            title_i18n=dict(en='Emissions from car transport'),
        )
Exemple #6
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()]
def get_active_interventions(variables=None):
    if variables:
        scenarios = variables['scenarios']
        active_scenario = variables['active_scenario']
        interventions = variables['interventions']
    else:
        scenarios = get_variable('scenarios')
        active_scenario = get_variable('active_scenario')
        interventions = get_variable('interventions')

    out = []
    for idx, iv in enumerate(interventions):
        obj = iv_tuple_to_obj(iv)
        obj.id = str(idx)
        out.append(obj)

    mobility_ivs = generate_mobility_ivs(variable_store=variables)
    for iv in mobility_ivs:
        out.append(iv_tuple_to_obj(iv))

    vaccinate_ivs = generate_vaccination_ivs(variable_store=variables)
    for iv in vaccinate_ivs:
        out.append(iv_tuple_to_obj(iv))

    if active_scenario:
        for s in scenarios:
            if s['id'] == active_scenario:
                break
        else:
            raise Exception('Invalid active scenario: %s' % active_scenario)
        added_ivs = s.get('add_interventions', [])
        for iv in added_ivs:
            out.append(iv_tuple_to_obj(iv))

    return out
Exemple #8
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()]
Exemple #9
0
def get_active_interventions(variables=None):
    if variables:
        scenarios = variables['scenarios']
        active_scenario = variables['active_scenario']
        interventions = variables['interventions']
    else:
        scenarios = get_variable('scenarios')
        active_scenario = get_variable('active_scenario')
        interventions = get_variable('interventions')

    out = []
    for iv in interventions:
        out.append(iv_tuple_to_obj(iv))

    if active_scenario:
        for s in scenarios:
            if s['id'] == active_scenario:
                break
        else:
            raise Exception('Invalid active scenario: %s' % active_scenario)
        added_ivs = s.get('add_interventions', [])
        for iv in added_ivs:
            out.append(iv_tuple_to_obj(iv))

    return out
Exemple #10
0
 def _get_default_context(self):
     return dict(
         org_genitive=get_variable('org_genitive'),
         org_nominative=get_variable('org_nominative'),
         municipality_genitive=get_variable('municipality_genitive'),
         municipality_locative=get_variable('municipality_locative'),
         target_year=get_variable('target_year'),
     )
Exemple #11
0
def generate_page():
    grid = ConnectedCardGrid()
    bev_perc_card = GraphCard(
        id='cars-bev-percentage',
        slider=dict(
            min=0,
            max=100,
            step=5,
            value=get_variable('cars_bev_percentage'),
            marks={x: '%d %%' % x for x in range(0, 100 + 1, 10)},
        ),
    )
    per_resident_card = GraphCard(
        id='cars-mileage-per-resident',
        slider=dict(
            min=-60,
            max=20,
            step=5,
            value=get_variable('cars_mileage_per_resident_adjustment'),
            marks={x: '%d %%' % (x) for x in range(-60, 20 + 1, 10)},
        ),
    )
    mileage_card = GraphCard(
        id='cars-total-mileage',
    )
    emission_factor_card = GraphCard(
        id='cars-emission-factor',
    )
    emissions_card = GraphCard(
        id='cars-emissions',
    )
    """
    biofuel_card = GraphCard(
        id='cars-biofuel-percentage',
    )
    """
    grid.make_new_row()
    grid.add_card(bev_perc_card)
    #grid.add_card(biofuel_card)
    grid.add_card(per_resident_card)
    grid.make_new_row()
    grid.add_card(emission_factor_card)
    grid.add_card(mileage_card)
    grid.make_new_row()
    grid.add_card(emissions_card)

    bev_perc_card.connect_to(emission_factor_card)
    #biofuel_card.connect_to(emission_factor_card)
    emission_factor_card.connect_to(emissions_card)

    per_resident_card.connect_to(mileage_card)
    mileage_card.connect_to(emissions_card)

    return html.Div([
        grid.render(),
        html.Div(id='cars-sticky-page-summary-container')
    ])
Exemple #12
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()])
Exemple #13
0
def generate_page():
    grid = ConnectedCardGrid()

    existing_card = GraphCard(
        id='district-heating-existing-building-unit-heat-factor',
        slider=dict(
            min=-60,
            max=20,
            step=5,
            value=get_variable(
                'district_heating_existing_building_efficiency_change') * 10,
            marks={x: '%.1f %%' % (x / 10)
                   for x in range(-60, 20 + 1, 10)},
        ))
    new_card = GraphCard(
        id='district-heating-new-building-unit-heat-factor',
        slider=dict(
            min=-60,
            max=20,
            step=5,
            value=get_variable(
                'district_heating_new_building_efficiency_change') * 10,
            marks={x: '%.1f %%' % (x / 10)
                   for x in range(-60, 20 + 1, 10)},
        ),
    )
    geo_card = GraphCard(id='district-heating-geothermal-production',
                         link_to_page=('BuildingHeating', 'GeothermalHeating'))

    row = grid.make_new_row()
    row.add_card(existing_card)
    row.add_card(new_card)
    row.add_card(geo_card)

    consumption_card = GraphCard(
        id='district-heating-consumption',
        extra_content=html.Div(id='district-heating-unit-emissions-card'))
    existing_card.connect_to(consumption_card)
    new_card.connect_to(consumption_card)
    geo_card.connect_to(consumption_card)

    row = grid.make_new_row()
    row.add_card(consumption_card)

    emissions_card = GraphCard(id='district-heating-consumption-emissions')
    consumption_card.connect_to(emissions_card)
    row = grid.make_new_row()
    row.add_card(emissions_card)

    return html.Div([
        grid.render(),
        html.Div(id='district-heating-sticky-page-summary-container')
    ])
Exemple #14
0
 def resolve_area(query, info):
     name = get_variable('area_name')
     name_long = get_variable('area_name_long')
     s = get_age_grouped_population()
     total = s.sum()
     age_groups = [dict(label=x, count=y) for x, y in zip(s.index, s)]
     return dict(
         name=name,
         name_long=name_long,
         total_population=total,
         age_groups=age_groups,
     )
Exemple #15
0
def get_population_forecast():
    correction_perc = get_variable('population_forecast_correction')
    target_year = get_variable('target_year')

    df = population_forecast[population_forecast.index <= target_year].copy()
    forecast = df.loc[df.Forecast]
    n_years = forecast.index.max() - forecast.index.min()
    base = (1 + (correction_perc / 100))**(1 / n_years)
    multipliers = [base**year for year in range(n_years + 1)]
    m_series = pd.Series(multipliers, index=forecast.index)
    df.loc[df.Forecast, 'Population'] *= m_series
    df.Population = df.Population.astype(int)
    return df
Exemple #16
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
Exemple #17
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()
Exemple #18
0
    def render(self):
        if (self.value <= self.goal and self.below_goal_good) or \
                (self.value >= self.goal and not self.below_goal_good):
            sticky_class = 'page-summary__total--good'
        else:
            sticky_class = 'page-summary__total--bad'

        target_year = get_variable('target_year')

        summary = dbc.Col([
            html.H6(f'{self.label} ({target_year})'),
            html.Div([
                html.Div([
                    "%.0f" % self.value,
                    html.Span(" %s" % self.unit, className="unit")
                ],
                         className="page-summary__total " + sticky_class),
                html.Div([
                    "tavoite %.0f" % self.goal,
                    html.Span(" %s" % self.unit, className="unit")
                ],
                         className="page-summary__target")
            ],
                     className="page-summary__totals"),
        ],
                          md=6)

        pötkylä = dbc.Col(
            [html.H6('Päästövähennykset'),
             self._render_emissions_bar()], md=6)
        return dbc.Alert([dbc.Row([pötkylä, summary])],
                         className="page-summary fixed-bottom")
Exemple #19
0
def render_page():
    grid = ConnectedCardGrid()

    per_capita_card = GraphCard(
        id='electricity-consumption-per-capita',
        slider=dict(
            min=-50,
            max=20,
            step=5,
            value=get_variable(
                'electricity_consumption_per_capita_adjustment'),
            marks={x: '%d %%' % (x / 10)
                   for x in range(-50, 20 + 1, 10)},
        ))
    grid.make_new_row()
    grid.add_card(per_capita_card)

    consumption_card = GraphCard(id='electricity-consumption')
    emission_factor_card = GraphCard(
        id='electricity-consumption-emission-factor')
    per_capita_card.connect_to(consumption_card)

    grid.make_new_row()
    grid.add_card(consumption_card)
    grid.add_card(emission_factor_card)

    emission_card = GraphCard(id='electricity-consumption-emissions')
    consumption_card.connect_to(emission_card)
    emission_factor_card.connect_to(emission_card)

    grid.make_new_row()
    grid.add_card(emission_card)

    return grid.render()
Exemple #20
0
def generate_solar_power_stacked(df):
    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

    graph = PredictionFigure(sector_name='ElectricityConsumption',
                             unit_name='GWh',
                             title='Aurinkopaneelien sähköntuotanto',
                             stacked=True,
                             fill=True,
                             color_scale=2)
    graph.add_series(df=df,
                     trace_name='Vanhat rakennukset',
                     column_name='SolarPowerExisting',
                     color_idx=0)
    graph.add_series(df=df,
                     trace_name='Uudet rakennukset',
                     column_name='SolarPowerNew',
                     color_idx=1)

    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

    return graph.get_figure(), ekwpa / pv_kwh_wp, nkwpa / pv_kwh_wp
Exemple #21
0
def _calculate_cache_key(hash_data):
    funcs = hash_data['funcs']
    variables = hash_data['variables']
    var_data = json.dumps({x: get_variable(x) for x in variables}, sort_keys=True)
    func_hash = 0
    for func in funcs:
        func_hash ^= hash(func)
    return '%s:%s' % (hash(var_data), func_hash)
Exemple #22
0
def generate_page():
    grid = ConnectedCardGrid()

    existing_card = GraphCard(
        id='solar-power-existing-buildings',
        slider=dict(
            min=0,
            max=90,
            step=5,
            value=get_variable('solar_power_existing_buildings_percentage'),
            marks={x: '%d %%' % x
                   for x in range(0, 90 + 1, 10)},
        ),
        extra_content=html.Div(id='solar-power-existing-kwpa'),
    )
    new_card = GraphCard(
        id='solar-power-new-buildings',
        slider=dict(
            min=20,
            max=100,
            step=5,
            value=get_variable('solar_power_new_buildings_percentage'),
            marks={x: '%d %%' % x
                   for x in range(20, 100 + 1, 10)},
        ),
        extra_content=html.Div(id='solar-power-new-kwpa'),
    )
    grid.make_new_row()
    grid.add_card(existing_card)
    grid.add_card(new_card)

    production_card = GraphCard(id='solar-power-production')
    existing_card.connect_to(production_card)
    new_card.connect_to(production_card)
    grid.make_new_row()
    grid.add_card(production_card)

    emission_card = GraphCard(id='solar-power-emission-reductions')
    production_card.connect_to(emission_card)
    grid.make_new_row()
    grid.add_card(emission_card)

    return html.Div([
        grid.render(),
        html.Div(id='solar-power-sticky-page-summary-container')
    ])
Exemple #23
0
    def _calc_emissions(self):
        df = predict_emissions()
        forecast = df.pop('Forecast')
        self.emissions_df = df

        df = df.sum(axis=1)
        self.last_historical_year = df.loc[~forecast].index.max()
        self.target_year = get_variable('target_year')
        ref_year = get_variable('ghg_reductions_reference_year')
        perc = get_variable('ghg_reductions_percentage_in_target_year')
        ref_emissions = df.loc[ref_year]
        last_emissions = df.loc[self.last_historical_year]
        target_emissions = ref_emissions * (1 - perc / 100)
        self.target_emissions = target_emissions
        self.needed_reductions = last_emissions - target_emissions
        self.scenario_emissions = df.loc[self.target_year]
        self.scenario_reductions = last_emissions - self.scenario_emissions
Exemple #24
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)
Exemple #25
0
def _calculate_cache_key(func, hash_data, var_store):
    funcs = hash_data['funcs']
    variables = hash_data['variables']
    var_data = json.dumps({x: get_variable(x, var_store=var_store) for x in variables}, sort_keys=True)

    func_hash = _hash_funcs(funcs)
    func_name = '.'.join((func.__module__, func.__name__))

    return '%s:%s:%s' % (func_name, hashlib.md5(var_data.encode()).hexdigest(), func_hash)
Exemple #26
0
def calculate_district_heating_unit_emissions(fuel_use_df, production_df):
    emissionless_bio = get_variable('bio_is_emissionless')

    fuel_co2 = fuel_classification[['code', 'co2e_emission_factor',
                                    'is_bio']].set_index('code')
    df = fuel_use_df.merge(fuel_co2,
                           how='left',
                           left_on='StatfiFuelCode',
                           right_index=True)
    df.co2e_emission_factor = df.co2e_emission_factor.astype('pint[t/TJ]')
    df.Value = df.Value.astype('pint[GWh]')
    df['Emissions'] = (df.Value *
                       df.co2e_emission_factor).pint.to('tonne').pint.m

    #df = production_df
    #print(df.loc[df.index == 2017])
    #print(df.loc[df.index == 2018])

    if emissionless_bio:
        df.loc[df.is_bio == True, 'Emissions'] = 0  # noqa

    emissions = df.groupby('Year')['Emissions'].sum()
    emissions.name = 'Emissions'

    df = production_df
    heat_production = df[HEAT_DEMAND_COL]
    heat_production.name = 'Heat production'
    chp_electricity_production = df[CHP_ELECTRICITY_PRODUCTION_COL]
    chp_electricity_production.name = 'Electricity production'

    # Determine the CHP alternate production energy consumptions according to the efficiency method
    electricity_production_alternate = chp_electricity_production / 0.39
    heat_production_alternate = heat_production / 0.90
    total = electricity_production_alternate + heat_production_alternate
    heat_share = heat_production_alternate / total
    heat_share.name = 'Fuel share of heat production in CHP'

    heat_demand = df[HEAT_DEMAND_COL]
    heat_demand.name = 'Heat demand'

    heat_pump_prod = production_df[HEAT_PUMP_COL]
    heat_pump_prod.name = 'Production with heat pumps'

    df = pd.concat([
        heat_demand, chp_electricity_production, heat_share, heat_pump_prod,
        emissions
    ],
                   axis=1)
    df['Unit emissions'] = df.Emissions * heat_share / heat_demand
    df['Emissions'] /= 1000

    df['District heat consumption emissions'] = heat_demand * df[
        'Unit emissions'] / 1000
    df['Forecast'] = production_df['Forecast']

    return df
Exemple #27
0
def render_page():
    slider = dict(
        min=-20,
        max=20,
        step=5,
        value=get_variable('population_forecast_correction'),
        marks={x: '%d %%' % x for x in range(-20, 20 + 1, 5)},
    )
    card = GraphCard(id='population', slider=slider).render()
    return dbc.Row(dbc.Col(card, md=6))
Exemple #28
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
Exemple #29
0
def get_district_heating_unit_emissions_forecast():
    operator = get_variable('district_heating_operator')
    target_ratios = get_variable('district_heating_target_production_ratios')
    target_year = get_variable('target_year')
    target_demand_change = get_variable(
        'district_heating_target_demand_change')

    assert sum(target_ratios.values()) == 100

    df = dh_fuel_df
    fuel_df = df[df.Operator == operator].drop(
        columns=['Operator', 'OperatorName'])

    df = dh_production_df
    df = df[df.Operator == operator].drop(columns=['Operator', 'OperatorName'])
    df = df.set_index('Year').drop(columns='Unit').pivot(columns='Quantity',
                                                         values='Value')

    # Fill in the missing columns from previous years
    df[HEAT_PUMP_COL] = df[HEAT_PUMP_COL].fillna(0)
    df[FUEL_NET_PRODUCTION_COL] = df[TOTAL_PRODUCTION_COL] - df['Osto'] - df[
        HEAT_PUMP_COL]
    production_df = df

    heat_pump_share = target_ratios.get('Lämpöpumput') / 100
    production_forecast = generate_production_forecast(
        production_df, target_year, target_demand_change / 100,
        heat_pump_share)
    fuel_use_forecast = generate_fuel_use_forecast(fuel_df,
                                                   production_forecast,
                                                   target_year, target_ratios)

    production_df['Forecast'] = False
    production_forecast['Forecast'] = True
    production_df = pd.concat([production_df, production_forecast],
                              sort=False).sort_index()

    fuel_df = pd.concat([fuel_df, fuel_use_forecast],
                        sort=False).set_index('Year').sort_index()
    df = calculate_district_heating_unit_emissions(fuel_df, production_df)

    return df
Exemple #30
0
 def resolve_scenarios(query, info):
     scenarios = get_variable('scenarios')
     active_scenario = get_variable('active_scenario')
     out = []
     customized_variables = list(get_session_variables().keys())
     if 'active_scenario' in customized_variables:
         customized_variables.remove('active_scenario')
     if len(customized_variables):
         customized = True
     else:
         customized = False
     for s in scenarios:
         if s['id'] == active_scenario and not customized:
             active = True
         else:
             active = False
         out.append(Scenario(
             id=s['id'], label=s['label'], description=s['description'], active=active
         ))
     return out