예제 #1
0
 def test_nodes_with_none_exclusion_old_name(self):
     param_results = processing.parameter_as_dict(self.es,
                                                  exclude_none=True)
     param_results = processing.convert_keys_to_strings(param_results,
                                                        keep_none_type=True)
     assert_series_equal(
         param_results[('storage', None)]['scalars'],
         pandas.Series({
             'balanced': True,
             'initial_storage_level': 0,
             'invest_relation_input_capacity': 1 / 6,
             'invest_relation_output_capacity': 1 / 6,
             'investment_ep_costs': 0.4,
             'investment_existing': 0,
             'investment_maximum': float('inf'),
             'investment_minimum': 0,
             'label': 'storage',
             'inflow_conversion_factor': 1,
             'loss_rate': 0,
             'max_storage_level': 1,
             'min_storage_level': 0,
             'outflow_conversion_factor': 0.8,
         }))
     assert_frame_equal(param_results[('storage', None)]['sequences'],
                        pandas.DataFrame())
예제 #2
0
 def test_flows_without_none_exclusion(self):
     b_el2 = self.es.groups['b_el2']
     demand = self.es.groups['demand_el']
     param_results = processing.parameter_as_dict(self.es,
                                                  exclude_none=False)
     scalar_attributes = {
         'fixed': True,
         'integer': None,
         'investment': None,
         'nominal_value': 1,
         'nonconvex': None,
         'summed_max': None,
         'summed_min': None,
         'max': 1,
         'min': 0,
         'negative_gradient_ub': None,
         'negative_gradient_costs': 0,
         'positive_gradient_ub': None,
         'positive_gradient_costs': 0,
         'variable_costs': 0
     }
     assert_series_equal(param_results[(b_el2, demand)]['scalars'],
                         pandas.Series(scalar_attributes))
     sequences_attributes = {
         'actual_value': self.demand_values,
     }
     default_sequences = ['actual_value']
     for attr in default_sequences:
         if attr not in sequences_attributes:
             sequences_attributes[attr] = [None]
     assert_frame_equal(param_results[(b_el2, demand)]['sequences'],
                        pandas.DataFrame(sequences_attributes))
예제 #3
0
    def solve(self, with_duals=False, tee=True, logfile=None, solver=None):
        logging.info("Optimising using {0}.".format(solver))

        if with_duals:
            self.model.receive_duals()

        if self.debug:
            filename = os.path.join(helpers.extend_basic_path("lp_files"),
                                    "reegis.lp")
            logging.info("Store lp-file in {0}.".format(filename))
            self.model.write(filename,
                             io_options={"symbolic_solver_labels": True})

        self.model.solve(solver=solver,
                         solve_kwargs={
                             "tee": tee,
                             "logfile": logfile
                         })
        self.es.results["main"] = processing.results(self.model)
        self.es.results["meta"] = processing.meta_results(self.model)
        self.es.results["param"] = processing.parameter_as_dict(self.es)
        self.es.results["meta"]["scenario"] = self.scenario_info(solver)
        self.es.results["meta"]["in_location"] = self.location
        self.es.results["meta"]["file_date"] = datetime.datetime.fromtimestamp(
            os.path.getmtime(self.location))
        self.es.results["meta"]["oemof_version"] = logger.get_version()
        self.results = self.es.results["main"]
예제 #4
0
    def test_parameter_with_node_view(self):
        param_results = processing.parameter_as_dict(self.es,
                                                     exclude_none=True)
        bel1 = views.node(param_results, 'b_el1')
        eq_(bel1['scalars'][(('b_el1', 'storage'), 'variable_costs')], 3)

        bel1_m = views.node(param_results, 'b_el1', multiindex=True)
        eq_(bel1_m['scalars'].loc[('b_el1', 'storage', 'variable_costs')], 3)
예제 #5
0
 def test_nodes_without_none_exclusion(self):
     diesel = self.es.groups['diesel']
     param_results = processing.parameter_as_dict(self.es,
                                                  exclude_none=False)
     assert_series_equal(
         param_results[(diesel, None)]['scalars'],
         pandas.Series({
             'label': 'diesel',
             'conversion_factors_b_el1': 2,
             'conversion_factors_b_diesel': 1,
         }))
     assert_frame_equal(param_results[(diesel, None)]['sequences'],
                        pandas.DataFrame())
예제 #6
0
 def test_flows_with_none_exclusion(self):
     b_el2 = self.es.groups['b_el2']
     demand = self.es.groups['demand_el']
     param_results = processing.parameter_as_dict(self.es,
                                                  exclude_none=True)
     assert_series_equal(
         param_results[(b_el2, demand)]['scalars'],
         pandas.Series({
             'fixed': True,
             'nominal_value': 1,
             'max': 1,
             'min': 0,
             'negative_gradient_costs': 0,
             'positive_gradient_costs': 0,
             'variable_costs': 0
         }))
     assert_frame_equal(
         param_results[(b_el2, demand)]['sequences'],
         pandas.DataFrame({'actual_value': self.demand_values}))
예제 #7
0
파일: test_views.py 프로젝트: yuson95/oemof
 def setup(self):
     self.results = processing.results(optimization_model)
     self.param_results = processing.parameter_as_dict(optimization_model)
def run_model(params, wind_invest=False, pv_invest=False, storage_invest=False):
    logging.info('Initialize the energy system')
    energysystem = solph.EnergySystem(timeindex=date_time_index)
    Node.registry = energysystem
    logging.info('Create oemof objects')
    bgas = solph.Bus(label="natural_gas")
    bel = solph.Bus(label="electricity")

    solph.Sink(label='excess_bel', inputs={bel: solph.Flow()})

    solph.Source(label='rgas', outputs={bgas: solph.Flow(nominal_value=params['rgas_nom_val'],
                                                         summed_max=1)})

    if wind_invest == True:
        solph.Source(label='wind', outputs={bel: solph.Flow(
            actual_value=data['wind'], fixed=True,
            investment=solph.Investment(ep_costs=params['epc_wind']))})
    else:
        solph.Source(label='wind', outputs={bel: solph.Flow(
            actual_value=data['wind'], nominal_value=params['wind_nom_val'], fixed=True)})

    if pv_invest == True:
        pv = solph.Source(label='pv', outputs={bel: solph.Flow(
            actual_value=data['pv'], fixed=True,
            investment=solph.Investment(ep_costs=params['epc_pv']))})
    else:
        solph.Source(label='pv', outputs={bel: solph.Flow(
           actual_value=data['pv'], nominal_value=params['pv_nom_val'], fixed=True)})

    solph.Sink(label='demand', inputs={bel: solph.Flow(
        actual_value=data['demand_el'], fixed=True, nominal_value=1)})

    solph.Transformer(
        label="pp_gas",
        inputs={bgas: solph.Flow()},
        outputs={bel: solph.Flow(nominal_value=10e10, variable_costs=50)},
        conversion_factors={bel: 0.58})


    storage = solph.components.GenericStorage(
        label='storage',
        inputs={bel: solph.Flow(variable_costs=10e10)},
        outputs={bel: solph.Flow(variable_costs=10e10)},
        capacity_loss=0.00, initial_capacity=0,
        nominal_input_capacity_ratio=1/6,
        nominal_output_capacity_ratio=1/6,
        inflow_conversion_factor=1, outflow_conversion_factor=0.8,
        investment=solph.Investment(ep_costs=params['epc_storage']),
    )

    logging.info('Optimise the energy system')

    om = solph.Model(energysystem)
    test_var = 2
    print(test_var)

    logging.info('Solve the optimization problem')
    om.solve(solver='cbc')

    string_results = processing.convert_keys_to_strings(processing.results(om))
    electricity_results = views.node(string_results, 'electricity')
    param_dict = processing.convert_keys_to_strings(processing.parameter_as_dict(energysystem))
    param_dict_scalars = {key: value['scalars'] for (key,value) in param_dict.items()}

    print(string_results.keys())
    print(string_results[('wind','electricity')]['scalars']['invest'])
    print(string_results[('pv','electricity')]['scalars']['invest'])
예제 #9
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