예제 #1
0
    def plot_nodes(self, show=None, filename=None, **kwargs):

        rm_nodes = kwargs.get('remove_nodes_with_substrings')

        g = graph.create_nx_graph(self.es,
                                  filename=filename,
                                  remove_nodes_with_substrings=rm_nodes)
        if show is True:
            draw_graph(g, **kwargs)
        return g
예제 #2
0
def create_om(input_data, timesteps):
    """
    Creates an oemof model for given input, time steps

    Args:
        input_data: input data
        timesteps: simulation timesteps

    Returns:
        model: a model instance
    """
    # create oemof energy system
    print('CREATING oemof MODEL')
    start = time.perf_counter()
    es, model = oemofm.create_model(input_data, timesteps)
    end = time.perf_counter()

    # solve model and read results
    model.solve(solver='glpk',
                solve_kwargs={
                    'logfile': 'oemof_log.txt',
                    'tee': False
                })

    # write LP file
    filename = os.path.join(os.path.dirname(__file__), 'mimo_oemof.lp')
    model.write(filename, io_options={'symbolic_solver_labels': True})

    # draw graph
    graph = False
    if graph:
        graph = create_nx_graph(es, model)
        oemofm.draw_graph(graph,
                          plot=True,
                          layout='neato',
                          node_size=3000,
                          node_color={
                              'b_0': '#cd3333',
                              'b_1': '#7EC0EE',
                              'b_2': '#eeac7e'
                          })

    # get results
    es.results['main'] = outputlib.processing.results(model)
    es.dump(dpath=None, filename=None)

    return model, end - start
예제 #3
0
def create_plots(config_path, results_dir):
    r"""
    Runs the plot production pipeline.
    """
    # open config
    abs_path = os.path.dirname(os.path.abspath(os.path.join(__file__, '..')))
    with open(config_path, 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

    energysystem = solph.EnergySystem()
    energysystem.restore(dpath=results_dir + '/optimisation_results',
                         filename='es.dump')
    energysystem_graph = graph.create_nx_graph(energysystem)

    node_color = {
        'natural gas': '#19A8B8',
        'ccgt': '#19A8B8',
        'electricity': '#F9FF00',
        'power_to_heat': '#F9FF00',
        'storage_heat': '#FF0000',
        'heat_prim': '#FF0000',
        'dhn_prim': '#686868',
        'heat_sec': '#FF5300',
        'dhn_sec': '#686868',
        'heat_end': '#FF9900',
        'shortage_heat': '#FF0000',
        'demand_heat': '#eeac7e'
    }
    draw_graph(energysystem_graph,
               plot=False,
               store=True,
               filename=results_dir + '/plots/' + 'es_graph.pdf',
               node_size=5000,
               edge_color='k',
               node_color=node_color)
    rcParams['figure.figsize'] = [10.0, 10.0]

    demand = pd.read_csv(
        os.path.join(results_dir, cfg['timeseries']['timeseries_demand_heat']))
    plot_heat_demand(demand, filename=results_dir + '/plots/heat_demand.pdf')

    node_results_bel = outputlib.views.node(energysystem.results['main'],
                                            'heat_prim')['sequences']
    plot_dispatch(node_results_bel,
                  filename=results_dir + '/plots/' + 'dispatch_stack_plot.pdf')
예제 #4
0
es.add(Sink(label="load_1", inputs={
                                b_1: Flow(nominal_value=150,
                                          actual_value=[1, 0],
                                          fixed=True)}))

m = Model(energysystem=es)

# m.write('transshipment.lp', io_options={'symbolic_solver_labels': True})

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

m.results()

graph = create_nx_graph(es, m)

draw_graph(graph, plot=True, layout='neato', node_size=3000,
           node_color={
                  'b_0': '#cd3333',
                  'b_1': '#7EC0EE',
                  'b_2': '#eeac7e'})

results = processing.results(m)

print(views.node(results, 'gen_0'))
print(views.node(results, 'gen_1'))

views.node(results, 'line_0')['sequences'].plot(kind='bar')

# look at constraints of Links in the pyomo model LinkBlock
예제 #5
0
def test_depreciated_graph_call():
    es = ES()
    om = Model(energysystem=es)
    warnings.filterwarnings('ignore', category=FutureWarning)
    graph.create_nx_graph(optimization_model=om)
예제 #6
0
for n in esys.nodes:
    oobj = str(type(n)).replace("<class 'oemof.solph.", "").replace("'>", "")
    print(oobj + ':', n.label)
print("*********************************************************")

# creation of a least cost model from the energy system
om = solph.Model(esys)
om.receive_duals()

# solving the linear problem using the given solver
om.solve(solver='cbc')

# create graph of esys
# You can use argument filename='/home/somebody/my_graph.graphml'
# to dump your graph to disc. You can open it using e.g. yEd or gephi
graph = create_nx_graph(esys)

# plot esys graph
draw_graph(grph=graph, plot=True, layout='neato', node_size=1000,
           node_color={
               'R1_bus_el': '#cd3333',
               'R2_bus_el': '#cd3333'
           })

# print and plot some results
results = outputlib.processing.results(om)

region2 = outputlib.views.node(results, 'R2_bus_el')
region1 = outputlib.views.node(results, 'R1_bus_el')

print(region2['sequences'].sum())
예제 #7
0
def run_model_dessau(config_path, results_dir):
    r"""
    Create the energy system and run the optimisation model.

    Parameters
    ----------
    config_path : Path to experiment config
    results_dir : Directory for results

    Returns
    -------
    energysystem.results : Dict containing results
    """
    abs_path = os.path.dirname(os.path.abspath(os.path.join(__file__, '..')))
    with open(config_path, 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

    # load input parameter
    in_param = pd.read_csv(os.path.join(abs_path, cfg['input_parameter']), index_col=[1, 2])['var_value']
    wacc = in_param['general', 'wacc']

    # load timeseries
    demand_heat_timeseries = pd.read_csv(os.path.join(results_dir, cfg['timeseries']['timeseries_demand_heat']),
                                         index_col=0, names=['demand_heat'], sep=',')['demand_heat']
    print(demand_heat_timeseries.head())

    # create timeindex
    if cfg['debug']:
        number_timesteps = 200
    else:
        number_timesteps = 8760

    date_time_index = pd.date_range('1/1/2017',
                                    periods=number_timesteps,
                                    freq='H')

    logging.info('Initialize the energy system')
    energysystem = solph.EnergySystem(timeindex=date_time_index)

    #####################################################################
    logging.info('Create oemof objects')
    #####################################################################

    bgas = solph.Bus(label="natural_gas", balanced=False)
    bel = solph.Bus(label="electricity", balanced=False)
    bth_prim = solph.Bus(label="heat_prim")
    bth_sec = solph.Bus(label="heat_sec")
    bth_end = solph.Bus(label="heat_end")

    energysystem.add(bgas, bth_prim, bth_sec, bth_end, bel)

    # energysystem.add(solph.Sink(label='excess_heat',
        # inputs={bth: solph.Flow()}))

    energysystem.add(solph.Source(label='shortage_heat',
        outputs={bth_prim: solph.Flow(variable_costs=in_param['shortage_heat','var_costs'])}))

    # energysystem.add(solph.Source(label='rgas',
    #     outputs={bgas: solph.Flow(
    #         variable_costs=0)}))

    if cfg['investment']['invest_chp']:
        energysystem.add(solph.Transformer(
            label='ccgt',
            inputs={bgas: solph.Flow(variable_costs=in_param['bgas','price_gas'])},
            outputs={bth_prim: solph.Flow(
                investment=solph.Investment(
                    ep_costs=economics.annuity(
                        capex=in_param['ccgt','capex'], n=in_param['ccgt','inv_period'], wacc=wacc)),
                variable_costs=0)},
            conversion_factors={bth_prim: 0.5}))

    else:
        energysystem.add(solph.Transformer(
            label='ccgt',
            inputs={bgas: solph.Flow(variable_costs=in_param['bgas','price_gas'])},
            outputs={bth_prim: solph.Flow(
                nominal_value=in_param['ccgt','nominal_value'],
                variable_costs=0)},
            conversion_factors={bth_prim: 0.5}))

    if cfg['investment']['invest_pth']:
        energysystem.add(solph.Transformer(
            label='power_to_heat',
            inputs={bel: solph.Flow(variable_costs=in_param['bel','price_el'])},
            outputs={bth_prim: solph.Flow(
                investment=solph.Investment(
                    ep_costs=economics.annuity(
                        capex=in_param['power_to_heat','capex'], n=in_param['power_to_heat','inv_period'], wacc=wacc)),
                variable_costs=0)},
            conversion_factors={bth_prim: 1}))

    else:
        energysystem.add(solph.Transformer(label='power_to_heat',
            inputs={bel: solph.Flow(variable_costs=in_param['bel','price_el'])},
            outputs={bth_prim: solph.Flow(
                nominal_value=in_param['power_to_heat','nominal_value'],
                variable_costs=0)},
            conversion_factors={bth_prim: 1}))

    energysystem.add(solph.Transformer(
        label='dhn_prim',
        inputs={bth_prim: solph.Flow()},
        outputs={bth_sec: solph.Flow()},
        conversion_factors={bth_sec: 1.}))

    energysystem.add(solph.Transformer(
        label='dhn_sec',
        inputs={bth_sec: solph.Flow()},
        outputs={bth_end: solph.Flow()},
        conversion_factors={bth_end: 1.}))

    energysystem.add(solph.Sink(
        label='demand_heat',
        inputs={bth_end: solph.Flow(
            actual_value=demand_heat_timeseries,
            fixed=True,
            nominal_value=1.,
            summed_min=1)}))

    energysystem.add(solph.components.GenericStorage(
        label='storage_heat',
        nominal_capacity=in_param['storage_heat','nominal_capacity'],
        inputs={bth_prim: solph.Flow(
            variable_costs=0,
            nominal_value=in_param['storage_heat','input_nominal_value'])},
        outputs={bth_prim: solph.Flow(
            nominal_value=in_param['storage_heat','output_nominal_value'])},
        capacity_loss=in_param['storage_heat','capacity_loss'],
        initial_capacity=in_param['storage_heat','initial_capacity'],
        capacity_max=in_param['storage_heat','nominal_capacity'],
        inflow_conversion_factor=1,
        outflow_conversion_factor=1))

    energysystem_graph = graph.create_nx_graph(energysystem)
    graph_file_name = os.path.join(results_dir, 'energysystem_graph.pkl')
    nx.readwrite.write_gpickle(G=energysystem_graph, path=graph_file_name)

    #####################################################################
    logging.info('Solve the optimization problem')


    om = solph.Model(energysystem)
    om.solve(solver=cfg['solver'], solve_kwargs={'tee': True})

    if cfg['debug']:
        filename = os.path.join(
            oemof.tools.helpers.extend_basic_path('lp_files'),
            'app_district_heating.lp')
        logging.info('Store lp-file in {0}.'.format(filename))
        om.write(filename, io_options={'symbolic_solver_labels': True})


    #####################################################################
    logging.info('Check the results')
    #####################################################################

    energysystem.results['main'] = processing.results(om)
    energysystem.results['meta'] = processing.meta_results(om)
    energysystem.results['param'] = processing.parameter_as_dict(om)
    energysystem.dump(dpath=results_dir + '/optimisation_results', filename='es.dump')

    return energysystem.results