コード例 #1
0
def get_result_dict(energysystem):
    logging.info('Check the results')
    storage = energysystem.groups['storage']
    myresults = outputlib.DataFramePlot(energy_system=energysystem)

    pp_gas = myresults.slice_by(obj_label='pp_gas', type='to_bus',
                                date_from='2012-01-01 00:00:00',
                                date_to='2012-12-31 23:00:00')

    demand = myresults.slice_by(obj_label='demand',
                                date_from='2012-01-01 00:00:00',
                                date_to='2012-12-31 23:00:00')

    wind = myresults.slice_by(obj_label='wind',
                              date_from='2012-01-01 00:00:00',
                              date_to='2012-12-31 23:00:00')

    pv = myresults.slice_by(obj_label='pv',
                            date_from='2012-01-01 00:00:00',
                            date_to='2012-12-31 23:00:00')

    return {'pp_gas_sum': pp_gas.sum(),
            'demand_sum': demand.sum(),
            'demand_max': demand.max(),
            'wind_sum': wind.sum(),
            'wind_inst': wind.max()/0.99989,
            'pv_sum': pv.sum(),
            'pv_inst': pv.max()/0.76474,
            'storage_cap': energysystem.results[storage][storage].invest,
            'objective': energysystem.results.objective
            }
コード例 #2
0
def plot_results(energysystem):
    logging.info("Plot results")
    # define colors
    cdict = {'wind': '#00bfff', 'pv': '#ffd700', 'pp_gas': '#8b1a1a',
             'pp_coal': '#838b8b', 'pp_lig': '#8b7355', 'pp_oil': '#000000',
             'pp_chp': '#20b2aa', 'demand_el': '#fff8dc'}

    # create multiindex dataframe with result values
    esplot = output.DataFramePlot(energy_system=energysystem)

    # select input results of electrical bus (i.e. power delivered by plants)
    esplot.slice_unstacked(bus_label="b_el", type="to_bus",
                           date_from='2012-01-01 00:00:00',
                           date_to='2012-01-07 00:00:00')

    # set colorlist for esplot
    colorlist = esplot.color_from_dict(cdict)

    esplot.plot(color=colorlist, title="January 2016", stacked=True, width=1,
                lw=0.1, kind='bar')
    esplot.ax.set_ylabel('Power in MW')
    esplot.ax.set_xlabel('Date')
    esplot.set_datetime_ticks(tick_distance=24, date_format='%d-%m')
    esplot.outside_legend(reverse=True)
    plt.show()
コード例 #3
0
def create_plots(energysystem):

    logging.info('Plot the results')

    cdict = {
        'wind': '#5b5bae',
        'pv': '#ffde32',
        'storage': '#42c77a',
        'gridsource': '#636f6b',
        'demand': '#ce4aff',
        'excess_bel': '#555555'
    }

    # Plotting the input flows of the electricity bus for January
    myplot = outputlib.DataFramePlot(energy_system=energysystem)
    myplot.slice_unstacked(bus_label="electricity",
                           type="to_bus",
                           date_from=str(year) + '-01-01 00:00:00',
                           date_to=str(year) + '-01-31 00:00:00')
    colorlist = myplot.color_from_dict(cdict)
    myplot.plot(color=colorlist, linewidth=2, title='January' + str(year))
    myplot.ax.legend(loc='upper right')
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.set_datetime_ticks(date_format='%d-%m-%Y', tick_distance=24 * 7)

    # Plotting the output flows of the electricity bus for January
    myplot.slice_unstacked(bus_label="electricity", type="from_bus")
    myplot.plot(title="Year 2016", colormap='Spectral', linewidth=2)
    myplot.ax.legend(loc='upper right')
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.set_datetime_ticks()

    plt.show()

    # Plotting a combined stacked plot
    fig = plt.figure(figsize=(24, 14))
    plt.rc('legend', **{'fontsize': 19})
    plt.rcParams.update({'font.size': 19})
    plt.style.use('grayscale')

    handles, labels = myplot.io_plot(
        bus_label='electricity',
        cdict=cdict,
        barorder=['pv', 'wind', 'gridsource', 'storage'],
        lineorder=['demand', 'storage', 'excess_bel'],
        line_kwa={'linewidth': 4},
        ax=fig.add_subplot(1, 1, 1),
        date_from=str(year) + '-06-01 00:00:00',
        date_to=str(year) + '-06-8 00:00:00',
    )
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.ax.set_title("Electricity bus")
    myplot.set_datetime_ticks(tick_distance=24, date_format='%d-%m-%Y')
    myplot.outside_legend(handles=handles, labels=labels)

    plt.show()
コード例 #4
0
def test_plots(berlin_e_system):
    logging.info('Plot the results')

    cdict = {
        'wind': '#5b5bae',
        'pv': '#ffde32',
        'storage': '#42c77a',
        'pp_gas': '#636f6b',
        'elec_demand': '#ce4aff',
        'slack_bus_el': '#42c77a',
        'excess_bus_el': '#555555',
        'wp': '#5b5bae',
        'slack_bus_wp': '#ffde32',
        'demand_wp': '#ce4aff'
    }

    # Plotting the input flows of the electricity bus for January
    myplot = outputlib.DataFramePlot(energy_system=berlin_e_system)
    myplot.slice_unstacked(bus_label="bus_el", type="to_bus")
    # colorlist = myplot.color_from_dict(cdict)
    myplot.plot(linewidth=2, title="January 2012")
    myplot.ax.legend(loc='upper right')
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.set_datetime_ticks(date_format='%d-%m-%Y', tick_distance=24 * 7)

    # Plotting the output flows of the electricity bus for January
    myplot.slice_unstacked(bus_label="bus_el", type="from_bus")
    myplot.plot(title="Year 2016", colormap='Spectral', linewidth=2)
    myplot.ax.legend(loc='upper right')
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.set_datetime_ticks()

    plt.show()

    # Plotting a combined stacked plot
    # fig = plt.figure()
    # plt.rc('legend', **{'fontsize': 19})
    # plt.rcParams.update({'font.size': 19})
    plt.style.use('grayscale')

    handles, labels = myplot.io_plot(
        bus_label='bus_el',
        cdict=cdict,
        # barorder=['pv', 'wind', 'pp_gas', 'storage'],
        # lineorder=['demand', 'storage', 'excess_bel'],
        line_kwa={'linewidth': 4},
        # ax=fig.add_subplot(1, 1, 1),
        date_from="2012-06-01 00:00:00",
        date_to="2012-06-8 00:00:00",
    )
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('Date')
    myplot.ax.set_title("Electricity bus")
    myplot.set_datetime_ticks(tick_distance=24 * 30, date_format='%d-%m-%Y')
    myplot.outside_legend(handles=handles, labels=labels)

    plt.show()
コード例 #5
0
def get_result_dict(energysystem):
    logging.info('Check the results')
    myresults = outputlib.DataFramePlot(energy_system=energysystem)

    pp_gas = myresults.slice_by(bus_label='bus_district_z', type='to_bus')
    pp_gas.unstack(level='obj_label').plot()
    plt.show()

    return pp_gas
コード例 #6
0
def get_results(energysystem):
    """
    """
    logging.info('Check the results')

    myresults = output.DataFramePlot(energy_system=energysystem)

    grouped = myresults.groupby(level=[0, 1, 2]).sum()
    rdict = {
        r + (k, ): v
        for r, kv in grouped.iterrows() for k, v in kv.to_dict().items()
    }

    rdict['objective'] = energysystem.results.objective

    return rdict
コード例 #7
0
def get_result_dict(energysystem):
    """Shows how to extract single time series from results.

    Parameters
    ----------
    energysystem : solph.EnergySystem

    Returns
    -------
    dict : Some results.
    """
    logging.info('Check the results')
    storage = energysystem.groups['storage']
    myresults = outputlib.DataFramePlot(energy_system=energysystem)

    # electrical output of natural gas power plant
    pp_gas = myresults.slice_by(obj_label='pp_gas',
                                type='to_bus',
                                date_from='2012-01-01 00:00:00',
                                date_to='2012-12-31 23:00:00')

    # electrical demand
    demand = myresults.slice_by(obj_label='demand',
                                date_from='2012-01-01 00:00:00',
                                date_to='2012-12-31 23:00:00')

    # electrical output of wind power plant
    wind = myresults.slice_by(obj_label='wind',
                              date_from='2012-01-01 00:00:00',
                              date_to='2012-12-31 23:00:00')

    # electrical output of pv power plant
    pv = myresults.slice_by(obj_label='pv',
                            date_from='2012-01-01 00:00:00',
                            date_to='2012-12-31 23:00:00')

    return {
        'pp_gas_sum': pp_gas.sum(),
        'demand_sum': demand.sum(),
        'demand_max': demand.max(),
        'wind_sum': wind.sum(),
        'wind_inst': wind.max() / 0.99989,
        'pv_sum': pv.sum(),
        'pv_inst': pv.max() / 0.76474,
        'storage_cap': energysystem.results[storage][storage].invest,
        'objective': energysystem.results.objective
    }
コード例 #8
0
def get_result_dict(energysystem):
    logging.info('Check the results')
    storage = energysystem.groups['storage']
    myresults = outputlib.DataFramePlot(energy_system=energysystem)

    demand = myresults.slice_by(obj_label='demand',
                                date_from=str(year) + '-01-01 00:00:00',
                                date_to=str(year) + '-12-31 23:00:00')

    wind = myresults.slice_by(obj_label='wind',
                              date_from=str(year) + '-01-01 00:00:00',
                              date_to=str(year) + '-12-31 23:00:00')

    pv = myresults.slice_by(obj_label='pv',
                            date_from=str(year) + '-01-01 00:00:00',
                            date_to=str(year) + '-12-31 23:00:00')

    storage_input = myresults.slice_by(obj_label='storage',
                                       type='from_bus',
                                       date_from=str(year) + '-01-01 00:00:00',
                                       date_to=str(year) + '-12-31 23:00:00')

    storage_output = myresults.slice_by(obj_label='storage',
                                        type='to_bus',
                                        date_from=str(year) +
                                        '-01-01 00:00:00',
                                        date_to=str(year) + '-12-31 23:00:00')

    storage_soc = myresults.slice_by(obj_label='storage',
                                     type='other',
                                     date_from=str(year) + '-01-01 00:00:00',
                                     date_to=str(year) + '-12-31 23:00:00')

    results_dc = {}
    results_dc['ts_storage_input'] = storage_input
    results_dc['ts_storage_output'] = storage_output
    results_dc['ts_storage_soc'] = storage_soc
    results_dc['storage_cap'] = energysystem.results[storage][storage].invest
    results_dc['objective'] = energysystem.results.objective

    return results_dc
コード例 #9
0
def get_results(energysystem):
    """Shows how to extract single time series from DataFrame.

    Parameters
    ----------
    energysystem : solph.EnergySystem

    Returns
    -------
    dict : Some results.
    """
    logging.info('Check the results')

    myresults = output.DataFramePlot(energy_system=energysystem)

    grouped = myresults.groupby(level=[0, 1, 2]).sum()
    rdict = {r + (k,): v
             for r, kv in grouped.iterrows()
             for k, v in kv.to_dict().items()}

    rdict['objective'] = energysystem.results.objective

    return rdict
コード例 #10
0
ファイル: scenario.py プロジェクト: znes/openmod.sh
def simulate(folder, **kwargs):
    # This is how you get a scenario object from the database.
    # Since the iD editor prefixes element ids with their type ('r' for
    # relation, 'w' for way and 'n' for node), we have to strip a leading
    # character from the scenario id string before converting it to int.
    # This is what the [1:] is for.

    engine = db.engine(osm.configsection)

    Session = sessionmaker(bind=engine)
    session = Session()

    scenario = session.query(
        osm.Relation).filter_by(id=int(kwargs['scenario'][1:])).first()
    #id = 1).first()

    # Delete the scenario id from `kwargs` so that is doesn't show up in the
    # response later.
    del kwargs['scenario']

    # Now you can access the nodes, ways and relations this scenario contains
    # and build oemof objects from them. I'll only show you how to access the
    # contents here.
    # These are lists with Node, Way and Relation objects.
    # See the .schemas.osm module for the API.
    elements = scenario.elements
    nodes = [n for n in elements if isinstance(n, osm.Node)]
    ways = [w for w in elements if isinstance(w, osm.Way)]
    relations = [r for r in elements if isinstance(r, osm.Relation)]

    # emission factor (hardcoded for now....) t/MWh
    emission_factors = {
        'gas': 0.2,
        'coal': 0.34,
        'oil': 0.27,
        'lignite': 0.4,
        'waste': 0.3,
        'biomass': 0,
        'wind': 0,
        'solar': 0
    }
    #########################################################################
    # OEMOF SOLPH
    #########################################################################
    # We need a datetimeindex for the optimization problem / energysystem
    first = pd.to_datetime(scenario.tags.get('scenario_year' + '0101', '2016'))
    start = first + pd.DateOffset(
        hours=int(scenario.tags.get('start_timestep', 1)) - 1)
    end = first + pd.DateOffset(
        hours=int(scenario.tags.get('end_timestep', 8760)) - 1)
    datetimeindex = pd.date_range(start=start, end=end, freq='H')

    energy_system = EnergySystem(groupings=GROUPINGS, timeindex=datetimeindex)

    ## CREATE BUSES FROM RELATIONS OF TYPE "HUB RELATION"
    buses = {}
    for r in relations:
        if r.tags.get('type') is not None:
            if r.tags['type'] == 'hub_relation':
                name = r.tags.get('name')
                buses[name] = Bus(label=str(name))
                buses[name].energy_sector = r.tags['energy_sector']
        else:
            raise ValueError('Missing tag type of component with ' +
                             'name {0}.'.format(r.tags['name']))

    ## GLOBAL FUEL BUSES FOR TRANSFORMER INPUTS (THAT ARE NOT IN RELATIONS)
    global_buses = {}
    for n in nodes:
        if n.tags.get('oemof_class') == 'linear_transformer':
            # Only create global bus if not already exist
            if global_buses.get(n.tags['fuel_type']) is None:
                global_buses[n.tags['fuel_type']] = Bus(
                    label=n.tags['fuel_type'], balanced=False)

    ## Create Nodes (added automatically to energysystem)
    for n in nodes:
        # GET RELATIONS 'HUB ASSIGNMENT' FOR NODE
        node_bus = [
            r.tags['name'] for r in n.referencing_relations
            if r.tags['name'] in list(buses.keys())
        ]
        # create the variable cost timeseries if specified, otherwise use
        # variable costs key from tags
        if n.tags.get('variable_costs', 0) == 'timeseries':
            variable_costs = n.timeseries.get('variable_costs')
            if variable_costs is None:
                raise ValueError('No timeseries `variable cost` found for ' +
                                 'node {0}.'.format(n.tags.get('name')))
        else:
            variable_costs = _float(n, 'variable_costs')

        # CREATE SINK OBJECTS
        if n.tags.get('oemof_class') == 'sink':
            if n.tags.get('energy_amount') is None:
                nominal_value = None
                if n.timeseries.get('load_profile') is not None:
                    raise ValueError('No enery amount has been specified' +
                                     ' but the load_profile has been set!')
            else:
                nominal_value = _float(n, 'energy_amount')
            # calculate actual value
            if n.timeseries.get('load_profile') is None:
                actual_value = None
            else:
                try:
                    actual_value = [
                        i / sum(n.timeseries.get('load_profile'))
                        for i in n.timeseries.get('load_profile')
                    ]
                except Exception:
                    actual_value = None
            s = Sink(label=n.tags['name'],
                     inputs={
                         buses[node_bus[0]]:
                         Flow(nominal_value=nominal_value,
                              actual_value=actual_value,
                              variable_costs=variable_costs,
                              fixed=True)
                     })
            s.type = n.tags['type']
        # CREATE SOURCE OBJECTS
        if n.tags.get('oemof_class') == 'source':
            s = Source(label=n.tags['name'],
                       outputs={
                           buses[node_bus[0]]:
                           Flow(nominal_value=_float(n, 'installed_power'),
                                actual_value=n.timeseries['load_profile'],
                                variable_costs=variable_costs,
                                fixed=True)
                       })
            s.fuel_type = n.tags['fuel_type']
            s.type = n.tags['type']
        # CREATE TRANSFORMER OBJECTS
        if n.tags.get('oemof_class') == 'linear_transformer':
            # CREATE LINEAR TRANSFORMER
            if n.tags.get('type') == 'flexible_generator':
                ins = global_buses[n.tags['fuel_type']]
                outs = buses[node_bus[0]]
                t = LinearTransformer(
                    label=n.tags['name'],
                    inputs={ins: Flow(variable_costs=variable_costs)},
                    outputs={
                        outs: Flow(nominal_value=_float(n, 'installed_power'))
                    },
                    conversion_factors={outs: _float(n, 'efficiency')})
                # store fuel_type as attribute for identification
                t.fuel_type = n.tags['fuel_type']
                t.type = n.tags['type']

            # CREATE COMBINED HEAT AND POWER AS LINEAR TRANSFORMER
            if n.tags.get('type') == 'combined_flexible_generator':
                ins = global_buses[n.tags['fuel_type']]
                heat_out = [
                    buses[k] for k in node_bus
                    if buses[k].energy_sector == 'heat'
                ][0]
                power_out = [
                    buses[k] for k in node_bus
                    if buses[k].energy_sector == 'electricity'
                ][0]
                t = LinearTransformer(
                    label=n.tags['name'],
                    inputs={ins: Flow(variable_costs=variable_costs)},
                    outputs={
                        power_out:
                        Flow(nominal_value=_float(n, 'installed_power')),
                        heat_out: Flow()
                    },
                    conversion_factors={
                        heat_out: _float(n, 'thermal_efficiency'),
                        power_out: _float(n, 'electrical_efficiency')
                    })
                t.fuel_type = n.tags['fuel_type']
                t.type = n.tags['type']

        # CRAETE STORAGE OBJECTS
        if n.tags.get('oemof_class') == 'storage':
            # Oemof solph does not provide direct way to set power in/out of
            # storage hence, we need to caculate the needed ratios upfront
            nicr = (_float(n, 'installed_power') /
                    _float(n, 'installed_energy'))
            nocr = (_float(n, 'installed_power') /
                    _float(n, 'installed_energy'))
            s = Storage(label=n.tags['name'],
                        inputs={
                            buses[node_bus[0]]:
                            Flow(variable_costs=variable_costs)
                        },
                        outputs={
                            buses[node_bus[0]]:
                            Flow(variable_costs=variable_costs)
                        },
                        nominal_capacity=_float(n, 'installed_energy'),
                        nominal_input_capacity_ratio=nicr,
                        nominal_output_capacity_ration=nocr)
            s.energy_sector = n.tags['energy_sector']
            s.type = n.tags['type']

    # loop over all ways to create transmission objects
    for w in ways:
        way_bus = [
            r.tags['name'] for r in w.referencing_relations
            if r.tags['name'] in list(buses.keys())
        ]
        if w.tags.get('oemof_class') == 'linear_transformer':
            # CREATE TWO TRANSFORMER OBJECTS WITH DIFFERENT DIRECTIONS IN/OUTS
            if w.tags.get('type') == 'transmission':
                # transmission lines are modelled as two transformers with
                # the same technical parameters
                ins = buses[way_bus[0]]
                outs = buses[way_bus[1]]
                # 1st transformer
                t1 = LinearTransformer(
                    label=w.tags['name'] + '_1',
                    inputs={outs: Flow()},
                    outputs={
                        ins: Flow(nominal_value=_float(w, 'installed_power'))
                    },
                    conversion_factors={ins: _float(w, 'efficiency')})
                t1.type = w.tags.get('type')
                # 2nd transformer
                t2 = LinearTransformer(
                    label=w.tags['name'] + '_2',
                    inputs={ins: Flow()},
                    outputs={
                        outs: Flow(nominal_value=_float(w, 'installed_power'))
                    },
                    conversion_factors={outs: _float(w, 'efficiency')})
                t2.type = w.tags.get('type')

    # Create optimization model, solve it, wrtie back results
    om = OperationalModel(es=energy_system)

    solver = scenario.tags.get('solver')
    if solver is None:
        solver = 'glpk'

    om.solve(solver=solver, solve_kwargs={'tee': True, 'keepfiles': False})
    om.results()

    # create results dataframe based on oemof's outputlib (multiindex)
    esplot = output.DataFramePlot(energy_system=energy_system)

    # select subsets of data frame (full hub balances) and write to temp-csv
    csv_links = {}
    for b in buses.values():
        subset = esplot.slice_by(bus_label=b.label,
                                 type='to_bus').unstack([0, 1, 2])
        fd, temp_path = mkstemp(dir=folder, suffix='.csv')
        file = open(temp_path, 'w')
        file.write(subset.to_csv())
        file.close()
        os.close(fd)

        head, tail = os.path.split(temp_path)
        link = "/static/" + tail
        # storage csv-file links in dictionary for html result page
        csv_links[b.label] = link

    ####################### CALCULATIONS FOR OUTPUT ###########################
    # get electical hubs production

    el_buses = [
        b.label for b in buses.values() if b.energy_sector == 'electricity'
    ]
    components = [n for n in energy_system.nodes if not isinstance(n, Bus)]

    #plot_nodes = [c.label for c in components if c.type != 'transmission']
    renewables = [c for c in components if isinstance(c, Source)]
    wind = [c.label for c in renewables if c.fuel_type == 'wind']
    solar = [c.label for c in renewables if c.fuel_type == 'solar']

    wind_production = esplot.slice_by(bus_label=el_buses,
                                      obj_label=wind,
                                      type='to_bus').unstack(2).sum(axis=1)
    wind_production.index = wind_production.index.droplevel(1)
    wind_production = wind_production.unstack(0)
    #pdb.set_trace()
    if not wind_production.empty:
        wind_production.columns = ['wind']
    solar_production = esplot.slice_by(bus_label=el_buses,
                                       obj_label=solar,
                                       type='to_bus').unstack(2).sum(axis=1)
    solar_production.index = solar_production.index.droplevel(1)
    solar_production = solar_production.unstack(0)
    if not solar_production.empty:
        solar_production.columns = ['solar']

    # slice fuel types, unstack components and sum components by fuel type
    fossil_production = esplot.slice_by(bus_label=global_buses.keys(),
                                        type='from_bus').unstack(2).sum(axis=1)
    # drop level 'from_bus' that all rows have anyway
    fossil_production.index = fossil_production.index.droplevel(1)
    # turn index with fuel type to columns
    fossil_production = fossil_production.unstack(0)

    all_production = pd.concat(
        [fossil_production, wind_production, solar_production], axis=1)
    all_production = all_production.resample('1D', how='sum')

    fossil_emissions = fossil_production.copy()
    #pdb.set_trace()
    for col in fossil_production:
        fossil_emissions[col] = fossil_production[col] * emission_factors[col]
    # sum total emissions
    emission = fossil_emissions.sum(axis=1)
    emission = emission.resample('1D', how='sum')
    # helpers for generating python-html ouput
    help_fill = ['tozeroy'] + ['tonexty'] * (len(all_production.columns) - 1)
    fill_dict = dict(zip(all_production.columns, help_fill))

    colors = {
        'gas': '#9bc8c8',
        'coal': '#9b9499',
        'oil': '#2e1629',
        'lignite': '#c89b9b',
        'waste': '#8b862a',
        'biomass': '#187c66',
        'wind': '#2b99ff',
        'solar': '#ffc125'
    }
    p = Bar(all_production.sum() / 1e3,
            legend=False,
            title="Summend energy production",
            xlabel="Type",
            ylabel="Energy Production in GWh",
            width=400,
            height=300,
            palette=[colors[col] for col in all_production])
    output_file(os.path.join(folder, 'all_production.html'))

    #show(p)

    e = Bar(fossil_emissions.sum(),
            legend=False,
            title="Summend CO2-emissions of production",
            xlabel="Type",
            ylabel="Energy Production in tons",
            width=400,
            height=300,
            palette=[colors[col] for col in all_production])
    output_file(os.path.join(folder, 'emissions.html'))
    #show(e)

    plots = {'production': p, 'emissions': e}
    script, div = bokeh_components(plots)

    ########## RENDER PLOTS ################

    # Define our html template for out plots
    template = Template('''<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8">
            <title>openmod.sh Scenario Results</title>
            {{ js_resources }}
            {{ css_resources }}
            <script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
        </head>
        <body>
        <table>
            <tr>
                <td>
                    <h3> Total CO2 - Emission </h3>
                    {{ plot_div.emissions }}
                </td>
                <td>
                </td>
                <td>
                    <h3> Total energy production </h3>
                    {{ plot_div.production }}
                </td>
            </tr>
       </table>

        {{ plot_script }}

      <h3> Daily production and emissions </h3>
        {{ timeplot }}
      <h3> Download your results </h3>
        {{ download }}
        </body>
    </html>
    ''')

    timeplot = (
        "<div id='myDiv' style='width: 800px; height: 500px;'></div>" +
        "<script>" + "var traces = [" + ", ".join([
            "{{x: {0}, y: {1}, fill: '{fillarg}', name: '{name}'}}".format(
                list(range(len(all_production.index.values))),
                list(all_production[col].values),
                name=col,
                fillarg=fill_dict[col]) for col in all_production
        ]) + "];" + "function stackedArea(traces) {" +
        "for(var i=1; i<traces.length; i++) {" +
        "for(var j=0; j<(Math.min(traces[i]['y'].length, traces[i-1]['y'].length)); j++) {"
        + "traces[i]['y'][j] += traces[i-1]['y'][j];}}" + "return traces;}" +
        "var layout = {title: 'Total electricity production on all hubs'," +
        "xaxis: {title: 'Day of the year'}," +
        "yaxis : {title: 'Energy in MWh'}," +
        "yaxis2: {title: 'CO2-emissions in tons', " +
        "range: [0, {0}],".format(emission.max() * 1.1) +
        #"titlefont: {color: 'rgb(148, 103, 189)'}, " +
        #"tickfont: {color: 'rgb(148, 103, 189)'}," +
        "overlaying: 'y', side: 'right'}," + "legend: {x: 0, y: 1,}};" +
        #"var data = " + "["+",".join(["{0}".format(col) for col in subset]) + "];"
        "var emission = {{x: {0}, y: {1}, type: 'scatter', yaxis: 'y2', name: 'CO2-Emissions'}};"
        .format(list(range(len(emission.index.values))), list(emission.values))
        + "data = stackedArea(traces);" + "data.push(emission);" +
        "Plotly.newPlot('myDiv', data, layout);" + "</script>")

    download = (
        "<br />You can download your results below:<br />  Hub: " +
        "<br /> Hub: ".join(
            ["<a href='{1}'>{0}</a>".format(*x) for x in csv_links.items()]))
    resources = INLINE

    js_resources = resources.render_js()
    css_resources = resources.render_css()

    html = template.render(js_resources=js_resources,
                           css_resources=css_resources,
                           plot_script=script,
                           plot_div=div,
                           download=download,
                           timeplot=timeplot)

    #filename = 'embed_multiple_responsive.html'

    #with open(filename, 'w') as f:
    #    f.write(html)
    #pdb.set_trace()
    response = (html)

    return response
コード例 #11
0
def create_plots(energysystem):
    """Create a plot with 6 tiles that shows the difference between the
    LinearTransformer and the VariableFractionTransformer used for chp plants.

    Parameters
    ----------
    energysystem : solph.EnergySystem
    """
    logging.info('Plot the results')

    cdict = {
        'variable_chp_gas': '#42c77a',
        'fixed_chp_gas': '#20b4b6',
        'fixed_chp_gas_2': '#20b4b6',
        'heat_gas': '#12341f',
        'demand_therm': '#5b5bae',
        'demand_th_2': '#5b5bae',
        'demand_elec': '#5b5bae',
        'demand_el_2': '#5b5bae',
        'free': '#ffde32',
        'excess_therm': '#f22222',
        'excess_bth_2': '#f22222',
        'excess_elec': '#f22222',
        'excess_bel_2': '#f22222'
    }

    myplot = outputlib.DataFramePlot(energy_system=energysystem)

    # Plotting
    fig = plt.figure(figsize=(18, 9))
    plt.rc('legend', **{'fontsize': 13})
    plt.rcParams.update({'font.size': 13})
    fig.subplots_adjust(left=0.07,
                        bottom=0.12,
                        right=0.86,
                        top=0.93,
                        wspace=0.03,
                        hspace=0.2)

    # subplot of electricity bus (fixed chp) [1]
    myplot.io_plot(bus_label='electricity_2',
                   cdict=cdict,
                   barorder=['fixed_chp_gas_2'],
                   lineorder=['demand_el_2', 'excess_bel_2'],
                   line_kwa={'linewidth': 4},
                   ax=fig.add_subplot(3, 2, 1))
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_xlabel('')
    myplot.ax.get_xaxis().set_visible(False)
    myplot.ax.set_title("Electricity output (fixed chp)")
    myplot.ax.legend_.remove()

    # subplot of electricity bus (variable chp) [2]
    handles, labels = myplot.io_plot(
        bus_label='electricity',
        cdict=cdict,
        barorder=['variable_chp_gas', 'fixed_chp_gas'],
        lineorder=['demand_elec', 'excess_elec'],
        line_kwa={'linewidth': 4},
        ax=fig.add_subplot(3, 2, 2))
    myplot.ax.get_yaxis().set_visible(False)
    myplot.ax.set_xlabel('')
    myplot.ax.get_xaxis().set_visible(False)
    myplot.ax.set_title("Electricity output (variable chp)")
    myplot.outside_legend(handles=handles, labels=labels, plotshare=1)

    # subplot of heat bus (fixed chp) [3]
    myplot.io_plot(bus_label='heat_2',
                   cdict=cdict,
                   barorder=['fixed_chp_gas_2'],
                   lineorder=['demand_th_2', 'excess_bth_2'],
                   line_kwa={'linewidth': 4},
                   ax=fig.add_subplot(3, 2, 3))
    myplot.ax.set_ylabel('Power in MW')
    myplot.ax.set_ylim([0, 600000])
    myplot.ax.get_xaxis().set_visible(False)
    myplot.ax.set_title("Heat output (fixed chp)")
    myplot.ax.legend_.remove()

    # subplot of heat bus (variable chp) [4]
    handles, labels = myplot.io_plot(
        bus_label='heat',
        cdict=cdict,
        barorder=['variable_chp_gas', 'fixed_chp_gas', 'heat_gas'],
        lineorder=['demand_therm', 'excess_therm'],
        line_kwa={'linewidth': 4},
        ax=fig.add_subplot(3, 2, 4))
    myplot.ax.set_ylim([0, 600000])
    myplot.ax.get_yaxis().set_visible(False)
    myplot.ax.get_xaxis().set_visible(False)
    myplot.ax.set_title("Heat output (variable chp)")
    myplot.outside_legend(handles=handles, labels=labels, plotshare=1)

    # subplot of efficiency (fixed chp) [5]
    ngas = myplot.loc['natural_gas', 'from_bus', 'fixed_chp_gas_2']['val']
    elec = myplot.loc['electricity_2', 'to_bus', 'fixed_chp_gas_2']['val']
    heat = myplot.loc['heat_2', 'to_bus', 'fixed_chp_gas_2']['val']
    e_ef = elec.div(ngas)
    h_ef = heat.div(ngas)
    df = pd.concat([h_ef, e_ef], axis=1)
    my_ax = df.plot(ax=fig.add_subplot(3, 2, 5), linewidth=2)
    my_ax.set_ylabel('efficiency')
    my_ax.set_ylim([0, 0.55])
    my_ax.set_xlabel('Date')
    my_ax.set_title('Efficiency (fixed chp)')
    my_ax.legend_.remove()

    # subplot of efficiency (variable chp) [6]
    ngas = myplot.loc['natural_gas', 'from_bus', 'variable_chp_gas']['val']
    elec = myplot.loc['electricity', 'to_bus', 'variable_chp_gas']['val']
    heat = myplot.loc['heat', 'to_bus', 'variable_chp_gas']['val']
    e_ef = elec.div(ngas)
    h_ef = heat.div(ngas)
    e_ef.name = 'electricity           '
    h_ef.name = 'heat'
    df = pd.concat([h_ef, e_ef], axis=1)
    my_ax = df.plot(ax=fig.add_subplot(3, 2, 6), linewidth=2)
    my_ax.set_ylim([0, 0.55])
    my_ax.get_yaxis().set_visible(False)
    my_ax.set_xlabel('Date')
    my_ax.set_title('Efficiency (variable chp)')
    box = my_ax.get_position()
    my_ax.set_position([box.x0, box.y0, box.width * 1, box.height])
    my_ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), ncol=1)

    plt.show()