outputs={elbus: Flow(variable_costs=1e20)}) el_storage = GenericStorage(label='el_storage', inputs={elbus: Flow(variable_costs=0.0001)}, outputs={elbus: Flow()}, loss_rate=0.00, initial_storage_level=0.5, invest_relation_input_capacity=1 / 6, invest_relation_output_capacity=1 / 6, inflow_conversion_factor=0.9, outflow_conversion_factor=0.9, investment=Investment(ep_costs=epc_storage)) # Adding all the components to the energy system es.add(excess_el, demand_el, el_storage, shortage_el, pv, elbus) # Create the model for optimization and run the optimization opt_model = Model(es) opt_model.solve(solver='cbc') logging.info('Optimization successful') # Collect and plot the results results = processing.results(opt_model) results_el = views.node(results, 'electricity') meta_results = processing.meta_results(opt_model) pp.pprint(meta_results)
ext = fc.ExtractionTurbine(label='ext', carrier=gas, tech='ext', commitable=False, electricity_bus=el1, heat_bus=heat, capacity=10, thermal_efficiency=0.4, electric_efficiency=0.4, condensing_efficiency=0.5) conv = fc.Conversion('conv', from_bus=el2, to_bus=heat, efficiency=0.95, capacity=2) load = fc.Load('load', bus=el1, amount=1000, profile=[0.005, 0.00034, 0.0434]) # Connection conn = fc.Connection('conn', from_bus=el1, to_bus=el2, loss=0.07, capacity=100) es.add(el1, el2, heat, biomass, bp, st, wind, sto, conv, load, conn, gas, ext) m = Model(es) m.pprint() m.write('model.lp', io_options={'symbolic_solver_labels': True})
def test_dispatch_example(solver='cbc', periods=24*5): """Create an energy system and optimize the dispatch at least costs.""" Node.registry = None filename = os.path.join(os.path.dirname(__file__), 'input_data.csv') data = pd.read_csv(filename, sep=",") # ######################### create energysystem components ################ # resource buses bcoal = Bus(label='coal', balanced=False) bgas = Bus(label='gas', balanced=False) boil = Bus(label='oil', balanced=False) blig = Bus(label='lignite', balanced=False) # electricity and heat bel = Bus(label='b_el') bth = Bus(label='b_th') # an excess and a shortage variable can help to avoid infeasible problems excess_el = Sink(label='excess_el', inputs={bel: Flow()}) # shortage_el = Source(label='shortage_el', # outputs={bel: Flow(variable_costs=200)}) # sources ep_wind = economics.annuity(capex=1000, n=20, wacc=0.05) wind = Source(label='wind', outputs={bel: Flow( fix=data['wind'], investment=Investment(ep_costs=ep_wind, existing=100))}) ep_pv = economics.annuity(capex=1500, n=20, wacc=0.05) pv = Source(label='pv', outputs={bel: Flow( fix=data['pv'], investment=Investment(ep_costs=ep_pv, existing=80))}) # demands (electricity/heat) demand_el = Sink(label='demand_elec', inputs={bel: Flow(nominal_value=85, fix=data['demand_el'])}) demand_th = Sink(label='demand_therm', inputs={bth: Flow(nominal_value=40, fix=data['demand_th'])}) # power plants pp_coal = Transformer(label='pp_coal', inputs={bcoal: Flow()}, outputs={bel: Flow(nominal_value=20.2, variable_costs=25)}, conversion_factors={bel: 0.39}) pp_lig = Transformer(label='pp_lig', inputs={blig: Flow()}, outputs={bel: Flow(nominal_value=11.8, variable_costs=19)}, conversion_factors={bel: 0.41}) pp_gas = Transformer(label='pp_gas', inputs={bgas: Flow()}, outputs={bel: Flow(nominal_value=41, variable_costs=40)}, conversion_factors={bel: 0.50}) pp_oil = Transformer(label='pp_oil', inputs={boil: Flow()}, outputs={bel: Flow(nominal_value=5, variable_costs=50)}, conversion_factors={bel: 0.28}) # combined heat and power plant (chp) pp_chp = Transformer(label='pp_chp', inputs={bgas: Flow()}, outputs={bel: Flow(nominal_value=30, variable_costs=42), bth: Flow(nominal_value=40)}, conversion_factors={bel: 0.3, bth: 0.4}) # heatpump with a coefficient of performance (COP) of 3 b_heat_source = Bus(label='b_heat_source') heat_source = Source(label='heat_source', outputs={b_heat_source: Flow()}) cop = 3 heat_pump = Transformer(label='el_heat_pump', inputs={bel: Flow(), b_heat_source: Flow()}, outputs={bth: Flow(nominal_value=10)}, conversion_factors={ bel: 1/3, b_heat_source: (cop-1)/cop}) datetimeindex = pd.date_range('1/1/2012', periods=periods, freq='H') energysystem = EnergySystem(timeindex=datetimeindex) energysystem.add(bcoal, bgas, boil, bel, bth, blig, excess_el, wind, pv, demand_el, demand_th, pp_coal, pp_lig, pp_oil, pp_gas, pp_chp, b_heat_source, heat_source, heat_pump) # ################################ optimization ########################### # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver) # write back results from optimization object to energysystem optimization_model.results() # ################################ results ################################ # generic result object results = processing.results(om=optimization_model) # subset of results that includes all flows into and from electrical bus # sequences are stored within a pandas.DataFrames and scalars e.g. # investment values within a pandas.Series object. # in this case the entry data['scalars'] does not exist since no investment # variables are used data = views.node(results, 'b_el') # generate results to be evaluated in tests comp_results = data['sequences'].sum(axis=0).to_dict() comp_results['pv_capacity'] = results[(pv, bel)]['scalars'].invest comp_results['wind_capacity'] = results[(wind, bel)]['scalars'].invest test_results = { (('wind', 'b_el'), 'flow'): 9239, (('pv', 'b_el'), 'flow'): 1147, (('b_el', 'demand_elec'), 'flow'): 7440, (('b_el', 'excess_el'), 'flow'): 6261, (('pp_chp', 'b_el'), 'flow'): 477, (('pp_lig', 'b_el'), 'flow'): 850, (('pp_gas', 'b_el'), 'flow'): 934, (('pp_coal', 'b_el'), 'flow'): 1256, (('pp_oil', 'b_el'), 'flow'): 0, (('b_el', 'el_heat_pump'), 'flow'): 202, 'pv_capacity': 44, 'wind_capacity': 246, } for key in test_results.keys(): eq_(int(round(comp_results[key])), int(round(test_results[key])))
}, conversion_factors={bus_el: 0.39}) pp_gas = Transformer(label='pp_gas', inputs={bus_gas: Flow()}, outputs={ bus_el: Flow(investment=Investment(ep_costs=epc_gas, maximum=5e9, existing=0), variable_costs=40) }, conversion_factors={bus_el: 0.50}) # add all components to energysystem energysystem.add(bus_coal, bus_gas, bus_el, wind, pv, excess, shortage, demand_el, pp_coal, pp_gas) # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver, solve_kwargs={ 'tee': False, 'keepfiles': False }) # postprocessing results = outputlib.processing.results(optimization_model) string_results = outputlib.processing.convert_keys_to_strings(results)
# show output if plot is True: plt.show() datetimeindex = pd.date_range("1/1/2017", periods=2, freq="H") es = EnergySystem(timeindex=datetimeindex) b_el0 = custom.ElectricalBus(label="b_0", v_min=-1, v_max=1) b_el1 = custom.ElectricalBus(label="b_1", v_min=-1, v_max=1) b_el2 = custom.ElectricalBus(label="b_2", v_min=-1, v_max=1) es.add(b_el0, b_el1, b_el2) es.add( custom.ElectricalLine( input=b_el0, output=b_el1, reactance=0.0001, investment=Investment(ep_costs=10), min=-1, max=1, ) ) es.add( custom.ElectricalLine( input=b_el1,
# Creating the demands eldemand = Sink(label='eldemand', inputs={elbus: Flow(nominal_value=85, actual_value=data['demand_el'], fixed=True)}) thdemand = Sink(label='thdemand', inputs={thbus: Flow(nominal_value=40, actual_value=data['demand_th'], fixed=True)}) # Creating the excess sink and the shortage source excess_el = Sink(label='excess_el', inputs={elbus: Flow()}) shortage_el = Source(label='shortage_el', outputs={elbus: Flow(variable_costs=1e20)}) # Adding all the components to the energy system es.add(excess_el, shortage_el, thdemand, eldemand, heat_pump, el_storage, chp_gas, pv, gas, gasbus, thbus, elbus) # Create the model for optimization and run the optimization opt_model = Model(es) opt_model.solve(solver='cbc') logging.info('Optimization successful') # Post-processing and data visualization results_main = outputlib.processing.results(opt_model) results_meta = outputlib.processing.meta_results(opt_model) params = outputlib.processing.parameter_as_dict(es) print(results_meta)
# ## Specify solver solver = 'cbc' # ## Create an energy system and load data datetimeindex = pd.date_range('1/1/2016', periods=24 * 365, freq='H') energysystem = EnergySystem(timeindex=datetimeindex) filename = '' data = pd.read_csv(filename, sep=",") # ## Create Buses # ## Create components # ## Add all to the energysystem energysystem.add() # ## Create an Optimization Model and solve it # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver) # ## Get results results_main = outputlib.processing.results(optimization_model) results_meta = outputlib.processing.meta_results(optimization_model) params = outputlib.processing.parameter_as_dict(energysystem) # ## Pass results to energysystem.results object before saving energysystem.results['main'] = results_main
variable_costs=20 ) } ) pp2 = Source( label='powerplant_2', outputs={ el_bus: Flow( nominal_value=12.5, variable_costs=10 ) } ) es.add(el_bus, demand, pp1, pp2) om = Model(es) lp_file_dir = 'dispatch.lp' om.write(lp_file_dir, io_options={'symbolic_solver_labels': True}) om.solve() results = om.results() string_results = outputlib.processing.convert_keys_to_strings(results) string_results = outputlib.processing.convert_keys_to_strings(results)
pv = Source(label='pv', outputs={bus_el: Flow(nominal_value=5, fixed=True, actual_value=pv_ts)}) demand_el = Sink(label='electricity_demand', inputs={bus_el: Flow(nominal_value=2, fixed=True, actual_value=demand_ts)}) curtailment = Sink(label='curtailment', inputs={bus_el: Flow(nominal_value=5, max=pv_ts)}) es.add(bus_el, bus_gas, source_gas, gas_pp, pv, demand_el, curtailment) optimodel = Model(es) optimodel.solve() results = optimodel.results() string_results = outputlib.processing.convert_keys_to_strings(results) # collect all timeseries in a DataFrame sequences = {k: v['sequences'] for k, v in string_results.items()} sequences = pd.concat(sequences, axis=1) print(sequences)
filename = os.path.join(os.getcwd(), "input_data.csv") data = pd.read_csv(filename, sep=",") # ######################### create energysystem components ################ # resource buses bcoal = Bus(label="coal", balanced=False) bgas = Bus(label="gas", balanced=False) boil = Bus(label="oil", balanced=False) blig = Bus(label="lignite", balanced=False) # electricity and heat bel = Bus(label="bel") bth = Bus(label="bth") energysystem.add(bcoal, bgas, boil, blig, bel, bth) # an excess and a shortage variable can help to avoid infeasible problems energysystem.add(Sink(label="excess_el", inputs={bel: Flow()})) # shortage_el = Source(label='shortage_el', # outputs={bel: Flow(variable_costs=200)}) # sources energysystem.add( Source(label="wind", outputs={bel: Flow(fix=data["wind"], nominal_value=66.3)})) energysystem.add( Source(label="pv", outputs={bel: Flow(fix=data["pv"], nominal_value=65.3)}))
def test_lopf(solver="cbc"): logging.info("Initialize the energy system") # create time index for 192 hours in May. date_time_index = pd.date_range("5/5/2012", periods=1, freq="H") es = EnergySystem(timeindex=date_time_index) ########################################################################## # Create oemof.solph objects ########################################################################## logging.info("Create oemof.solph objects") b_el0 = custom.ElectricalBus(label="b_0", v_min=-1, v_max=1) b_el1 = custom.ElectricalBus(label="b_1", v_min=-1, v_max=1) b_el2 = custom.ElectricalBus(label="b_2", v_min=-1, v_max=1) es.add(b_el0, b_el1, b_el2) es.add( custom.ElectricalLine( input=b_el0, output=b_el1, reactance=0.0001, investment=Investment(ep_costs=10), min=-1, max=1, )) es.add( custom.ElectricalLine( input=b_el1, output=b_el2, reactance=0.0001, nominal_value=60, min=-1, max=1, )) es.add( custom.ElectricalLine( input=b_el2, output=b_el0, reactance=0.0001, nominal_value=60, min=-1, max=1, )) es.add( Source( label="gen_0", outputs={b_el0: Flow(nominal_value=100, variable_costs=50)}, )) es.add( Source( label="gen_1", outputs={b_el1: Flow(nominal_value=100, variable_costs=25)}, )) es.add(Sink( label="load", inputs={b_el2: Flow(nominal_value=100, fix=1)}, )) ########################################################################## # Optimise the energy system and plot the results ########################################################################## logging.info("Creating optimisation model") om = Model(es) logging.info("Running lopf on 3-Node exmaple system") om.solve(solver=solver) results = processing.results(om) generators = views.node_output_by_type(results, Source) generators_test_results = { (es.groups["gen_0"], es.groups["b_0"], "flow"): 20, (es.groups["gen_1"], es.groups["b_1"], "flow"): 80, } for key in generators_test_results.keys(): logging.debug("Test genertor production of {0}".format(key)) eq_( int(round(generators[key])), int(round(generators_test_results[key])), ) eq_( results[es.groups["b_2"], es.groups["b_0"]]["sequences"]["flow"][0], -40, ) eq_(results[es.groups["b_1"], es.groups["b_2"]]["sequences"]["flow"][0], 60) eq_( results[es.groups["b_0"], es.groups["b_1"]]["sequences"]["flow"][0], -20, ) # objective function eq_(round(processing.meta_results(om)["objective"]), 3200)
# heatpump with a coefficient of performance (COP) of 3 b_heat_source = Bus(label='b_heat_source') heat_source = Source(label='heat_source', outputs={b_heat_source: Flow()}) cop = 3 heat_pump = Transformer(label='heat_pump', inputs={ bel: Flow(), b_heat_source: Flow() }, outputs={bth: Flow(nominal_value=10)}, conversion_factors={ bel: 1 / 3, b_heat_source: (cop - 1) / cop }) datetimeindex = pd.date_range('1/1/2012', periods=24, freq='H') energysystem = EnergySystem(timeindex=datetimeindex) energysystem.add(bcoal, bgas, boil, bel, bth, blig, excess_el, wind, pv, demand_el, demand_th, pp_coal, pp_lig, pp_oil, pp_gas, pp_chp, b_heat_source, heat_source, heat_pump) # ################################ optimization ########################### # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve()
def test_dispatch_fix_example(solver='cbc', periods=10): """Invest in a flow with a `fix` sequence containing values > 1.""" Node.registry = None filename = os.path.join(os.path.dirname(__file__), 'input_data.csv') data = pd.read_csv(filename, sep=",") # ######################### create energysystem components ################ # electricity and heat bel = Bus(label='b_el') # an excess and a shortage variable can help to avoid infeasible problems excess_el = Sink(label='excess_el', inputs={bel: Flow()}) # shortage_el = Source(label='shortage_el', # outputs={bel: Flow(variable_costs=200)}) # sources ep_pv = economics.annuity(capex=1500, n=20, wacc=0.05) pv = Source(label='pv', outputs={ bel: Flow(fix=data['pv'], investment=Investment(ep_costs=ep_pv)) }) # demands (electricity/heat) demand_el = Sink( label='demand_elec', inputs={bel: Flow(nominal_value=85, fix=data['demand_el'])}) datetimeindex = pd.date_range('1/1/2012', periods=periods, freq='H') energysystem = EnergySystem(timeindex=datetimeindex) energysystem.add(bel, excess_el, pv, demand_el) # ################################ optimization ########################### # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver) # ################################ results ################################ # generic result object results = processing.results(om=optimization_model) # subset of results that includes all flows into and from electrical bus # sequences are stored within a pandas.DataFrames and scalars e.g. # investment values within a pandas.Series object. # in this case the entry data['scalars'] does not exist since no investment # variables are used data = views.node(results, 'b_el') # generate results to be evaluated in tests comp_results = data['sequences'].sum(axis=0).to_dict() comp_results['pv_capacity'] = results[(pv, bel)]['scalars'].invest assert comp_results[(('pv', 'b_el'), 'flow')] > 0
# show output if plot is True: plt.show() datetimeindex = pd.date_range('1/1/2017', periods=2, freq='H') es = EnergySystem(timeindex=datetimeindex) b_el0 = custom.ElectricalBus(label="b_0", v_min=-1, v_max=1) b_el1 = custom.ElectricalBus(label="b_1", v_min=-1, v_max=1) b_el2 = custom.ElectricalBus(label="b_2", v_min=-1, v_max=1) es.add(b_el0, b_el1, b_el2) es.add( custom.ElectricalLine( label="line0", inputs={b_el0: Flow()}, outputs={b_el1: Flow(investment=Investment(), min=-1, max=1)}, reactance=0.0001)) es.add( custom.ElectricalLine( label="line1", inputs={b_el1: Flow()}, outputs={b_el2: Flow(nominal_value=60, min=-1, max=1)}, reactance=0.0001))
datetimeindex = pd.date_range("1/1/2022", periods=24 * 365, freq="H") energysystem = EnergySystem(timeindex=datetimeindex) filename = os.path.join(os.getcwd(), "storage_investment_ambon1.csv") data = pd.read_csv(filename, sep=",") # ######################### create energysystem components ################ # resource buses bcoal = Bus(label="coal", balanced=False) bgas = Bus(label="gas", balanced=False) boil = Bus(label="oil", balanced=False) # electricity and heat bel = Bus(label="bel") energysystem.add(bcoal, bgas, boil, bel) # an excess and a shortage variable can help to avoid infeasible problems energysystem.add(Sink(label="excess_el", inputs={bel: Flow()})) shortage_el = Source(label='shortage_el', outputs={bel: Flow(variable_costs=20000)}, conversion_factors={bel: 0.33}) energysystem.add(shortage_el) # sources energysystem.add( Source(label="pv", outputs={bel: Flow(fix=data["pv"], nominal_value=256e3)})) # demands (electricity/heat)
def run_basic_energysystem(args): n_val_wind = args[0] n_val_solar = args[1] start = time.time() # initialize and provide data energysystem = EnergySystem(timeindex=datetimeindex) # buses bcoal = Bus(label='coal', balanced=False) bgas = Bus(label='gas', balanced=False) bel = Bus(label='electricity') energysystem.add(bcoal, bgas, bel) # sources energysystem.add( Source(label='wind', outputs={ bel: Flow(actual_value=data['wind'], nominal_value=n_val_wind, fixed=True) })) energysystem.add( Source(label='pv', outputs={ bel: Flow(actual_value=data['pv'], nominal_value=n_val_solar, fixed=True) })) # excess and shortage to avoid infeasibilies energysystem.add(Sink(label='excess_el', inputs={bel: Flow()})) energysystem.add( Source(label='shortage_el', outputs={bel: Flow(variable_costs=200)})) # demands (electricity/heat) energysystem.add( Sink(label='demand_el', inputs={ bel: Flow(nominal_value=65, actual_value=data['demand_el'], fixed=True) })) # power plants energysystem.add( Transformer(label='pp_coal', inputs={bcoal: Flow()}, outputs={bel: Flow(nominal_value=20.2, variable_costs=25)}, conversion_factors={bel: 0.39})) energysystem.add( Transformer(label='pp_gas', inputs={bgas: Flow()}, outputs={bel: Flow(nominal_value=41, variable_costs=40)}, conversion_factors={bel: 0.50})) # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver, solve_kwargs={ 'tee': False, 'keepfiles': False }) results = outputlib.processing.results(optimization_model) results_el = outputlib.views.node(results, 'electricity') el_sequences = results_el['sequences'] el_prod = el_sequences[[(('wind', 'electricity'), 'flow'), (('pv', 'electricity'), 'flow'), (('pp_coal', 'electricity'), 'flow'), (('pp_gas', 'electricity'), 'flow'), (('shortage_el', 'electricity'), 'flow')]] inputs = outputlib.processing.convert_keys_to_strings( outputlib.processing.parameter_as_dict(optimization_model)) nom_vals = [[key, value['scalars']['nominal_value']] for key, value in inputs.items() if 'nominal_value' in value['scalars']] nom_vals = pd.DataFrame(nom_vals, columns=['flow', 'nominal_value']) summed_flows = [ (key, value['sequences'].sum()[0]) for key, value in outputlib.processing.convert_keys_to_strings( results).items() ] summed_flows = pd.DataFrame(summed_flows, columns=['flow', 'summed_flows']) end = time.time() print('simulation lasted: ', end - start, 'sec') return el_prod
filename = os.path.join(os.path.dirname(__file__), 'input_data.csv') data = pd.read_csv(filename, sep=",") # ######################### create energysystem components ################ # resource buses bcoal = Bus(label='coal', balanced=False) bgas = Bus(label='gas', balanced=False) boil = Bus(label='oil', balanced=False) blig = Bus(label='lignite', balanced=False) # electricity and heat bel = Bus(label='bel') bth = Bus(label='bth') energysystem.add(bcoal, bgas, boil, blig, bel, bth) # an excess and a shortage variable can help to avoid infeasible problems energysystem.add(Sink(label='excess_el', inputs={bel: Flow()})) # shortage_el = Source(label='shortage_el', # outputs={bel: Flow(variable_costs=200)}) # sources energysystem.add( Source(label='wind', outputs={ bel: Flow(actual_value=data['wind'], nominal_value=66.3, fixed=True) }))
outflow_conversion_factor=0.9, investment=Investment(ep_costs=epc_storage)) grid = GenericStorage(label='grid', inputs={elbus: Flow(variable_costs=-0.005)}, outputs={elbus: Flow(variable_costs=1.5)}, loss_rate=0.00, nominal_storage_capacity=10000000, initial_storage_level=0.5, balanced=True, invest_relation_input_capacity=1, invest_relation_output_capacity=1, inflow_conversion_factor=1, outflow_conversion_factor=1) # Adding all the components to the energy system es.add(demand_el, el_storage, pv, elbus, grid) # Create the model for optimization and run the optimization opt_model = Model(es) opt_model.solve(solver='cbc') logging.info('Optimization successful') # Collect and plot the results results = processing.results(opt_model) custom_storage = views.node(results, 'el_storage') electricity_bus = views.node(results, 'elbus')
def run_add_constraints_example(solver='cbc', nologg=False): if not nologg: logging.basicConfig(level=logging.INFO) # ##### creating an oemof solph optimization model, nothing special here ## # create an energy system object for the oemof solph nodes es = EnergySystem(timeindex=pd.date_range('1/1/2017', periods=4, freq='H')) # add some nodes boil = Bus(label="oil", balanced=False) blig = Bus(label="lignite", balanced=False) b_el = Bus(label="b_el") es.add(boil, blig, b_el) sink = Sink(label="Sink", inputs={ b_el: Flow(nominal_value=40, actual_value=[0.5, 0.4, 0.3, 1], fixed=True) }) pp_oil = Transformer( label='pp_oil', inputs={boil: Flow()}, outputs={b_el: Flow(nominal_value=50, variable_costs=25)}, conversion_factors={b_el: 0.39}) pp_lig = Transformer( label='pp_lig', inputs={blig: Flow()}, outputs={b_el: Flow(nominal_value=50, variable_costs=10)}, conversion_factors={b_el: 0.41}) es.add(sink, pp_oil, pp_lig) # create the model om = Model(energysystem=es) # add specific emission values to flow objects if source is a commodity bus for s, t in om.flows.keys(): if s is boil: om.flows[s, t].emission_factor = 0.27 # t/MWh if s is blig: om.flows[s, t].emission_factor = 0.39 # t/MWh emission_limit = 60e3 # add the outflow share om.flows[(boil, pp_oil)].outflow_share = [1, 0.5, 0, 0.3] # Now we are going to add a 'sub-model' and add a user specific constraint # first we add a pyomo Block() instance that we can use to add our # constraints. Then, we add this Block to our previous defined # Model instance and add the constraints. myblock = po.Block() # create a pyomo set with the flows (i.e. list of tuples), # there will of course be only one flow inside this set, the one we used to # add outflow_share myblock.MYFLOWS = po.Set(initialize=[ k for (k, v) in om.flows.items() if hasattr(v, 'outflow_share') ]) # pyomo does not need a po.Set, we can use a simple list as well myblock.COMMODITYFLOWS = [ k for (k, v) in om.flows.items() if hasattr(v, 'emission_factor') ] # add the sub-model to the oemof Model instance om.add_component('MyBlock', myblock) def _inflow_share_rule(m, s, e, t): """pyomo rule definition: Here we can use all objects from the block or the om object, in this case we don't need anything from the block except the newly defined set MYFLOWS. """ expr = (om.flow[s, e, t] >= om.flows[s, e].outflow_share[t] * sum(om.flow[i, o, t] for (i, o) in om.FLOWS if o == e)) return expr myblock.inflow_share = po.Constraint(myblock.MYFLOWS, om.TIMESTEPS, rule=_inflow_share_rule) # add emission constraint myblock.emission_constr = po.Constraint( expr=(sum(om.flow[i, o, t] for (i, o) in myblock.COMMODITYFLOWS for t in om.TIMESTEPS) <= emission_limit)) # solve and write results to dictionary # you may print the model with om.pprint() om.solve(solver=solver) logging.info("Successfully finished.")
Sink, Source, Transformer, Bus, Flow, GenericStorage, ) from oemof_visio import ESGraphRenderer es = EnergySystem() bus_ac = Bus(label="AC") bus_dc = Bus(label="DC") wind = Source(label="wind", outputs={bus_ac: Flow()}) pv = Source(label="pv", outputs={bus_dc: Flow()}) demand_el = Sink(label="demand_el", inputs={bus_ac: Flow()}) storage_el = GenericStorage( label="storage_el", inputs={bus_ac: Flow()}, outputs={bus_ac: Flow()}, ) pv_converter = Transformer(label="chp_gas", inputs={bus_dc: Flow()}, outputs={bus_ac: Flow()}) excess_el = Sink(label="excess_el", inputs={bus_ac: Flow()}) es.add(bus_ac, bus_dc, wind, pv, demand_el, storage_el, excess_el, pv_converter) gr = ESGraphRenderer(energy_system=es, filepath="energy_system", img_format="png") gr.view()
es = EnergySystem() el0 = elec.ElectricalBus('el0') el1 = elec.ElectricalBus('el1') el2 = elec.ElectricalBus('el2') line0 = elec.Line(from_bus=el0, to_bus=el1, capacity=60, reactance=0.0001) line1 = elec.Line(from_bus=el1, to_bus=el2, capacity=60, reactance=0.0001) line2 = elec.Line(from_bus=el2, to_bus=el0, capacity=60, reactance=0.0001) gen0 = fc.Dispatchable("gen0", capacity=100, bus=el0, marginal_cost=50, carrier='coal') gen1 = fc.Dispatchable("gen1", capacity=100, bus=el1, marginal_cost=25, carrier='gas') load0 = fc.Load("load0", bus=el2, amount=100, profile=[1]) es.add(el0, el1, el2, line0, line1, line2, gen0, gen1, load0) m = Model(es) m.solve() m.write('lopf-model.lp')
def test_dispatch_one_time_step(solver='cbc', periods=1): """Create an energy system and optimize the dispatch at least costs.""" # ######################### create energysystem components ################ Node.registry = None # resource buses bgas = Bus(label='gas', balanced=False) # electricity and heat bel = Bus(label='b_el') bth = Bus(label='b_th') # an excess and a shortage variable can help to avoid infeasible problems excess_el = Sink(label='excess_el', inputs={bel: Flow()}) # sources wind = Source( label='wind', outputs={bel: Flow(actual_value=0.5, nominal_value=66.3, fixed=True)}) # demands (electricity/heat) demand_el = Sink( label='demand_elec', inputs={bel: Flow(nominal_value=85, actual_value=0.3, fixed=True)}) demand_th = Sink( label='demand_therm', inputs={bth: Flow(nominal_value=40, actual_value=0.2, fixed=True)}) # combined heat and power plant (chp) pp_chp = Transformer(label='pp_chp', inputs={bgas: Flow()}, outputs={ bel: Flow(nominal_value=30, variable_costs=42), bth: Flow(nominal_value=40) }, conversion_factors={ bel: 0.3, bth: 0.4 }) # heatpump with a coefficient of performance (COP) of 3 b_heat_source = Bus(label='b_heat_source') heat_source = Source(label='heat_source', outputs={b_heat_source: Flow()}) cop = 3 heat_pump = Transformer(label='heat_pump', inputs={ bel: Flow(), b_heat_source: Flow() }, outputs={bth: Flow(nominal_value=10)}, conversion_factors={ bel: 1 / 3, b_heat_source: (cop - 1) / cop }) energysystem = EnergySystem(timeindex=[1]) energysystem.add(bgas, bel, bth, excess_el, wind, demand_el, demand_th, pp_chp, b_heat_source, heat_source, heat_pump) # ################################ optimization ########################### # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem, timeincrement=1) # solve problem optimization_model.solve(solver=solver) # write back results from optimization object to energysystem optimization_model.results() # ################################ results ################################ data = views.node(processing.results(om=optimization_model), 'b_el') # generate results to be evaluated in tests results = data['sequences'].sum(axis=0).to_dict() test_results = { (('wind', 'b_el'), 'flow'): 33, (('b_el', 'demand_elec'), 'flow'): 26, (('b_el', 'excess_el'), 'flow'): 5, (('b_el', 'heat_pump'), 'flow'): 3, } for key in test_results.keys(): eq_(int(round(results[key])), int(round(test_results[key])))
nx.draw_networkx_edge_labels(grph, pos=pos, edge_labels=labels) # show output if plot is True: plt.show() datetimeindex = pd.date_range('1/1/2017', periods=2, freq='H') es = EnergySystem(timeindex=datetimeindex) b_0 = Bus(label='b_0') b_1 = Bus(label='b_1') es.add(b_0, b_1) es.add(custom.Link(label="line_0", inputs={ b_0: Flow(), b_1: Flow()}, outputs={ b_1: Flow(investment=Investment()), b_0: Flow(investment=Investment())}, conversion_factors={ (b_0, b_1): 0.95, (b_1, b_0): 0.9})) es.add(Source(label="gen_0", outputs={ b_0: Flow(nominal_value=100, variable_costs=50)}))
print_results() # Set up an energy system model solver = 'cbc' periods = 800 datetimeindex = pd.date_range('1/1/2019', periods=periods, freq='H') energysystem = EnergySystem(timeindex=datetimeindex) storage_list = [] bus_simple_thermal_storage = Bus(label='bus_simple_thermal_storage', balanced=False) energysystem.add(bus_simple_thermal_storage) storage_list.append( GenericStorage( label='simple_thermal_storage', inputs={ bus_simple_thermal_storage: Flow(nominal_value=input_data['maximum_heat_flow_charging'], variable_costs=0.0001) }, outputs={ bus_simple_thermal_storage: Flow(nominal_value=input_data['maximum_heat_flow_discharging'], variable_costs=0.0001) }, nominal_storage_capacity=nominal_storage_capacity,
inputs={bus_el: Flow(nominal_value=200)}, outputs={bus_el: Flow(nominal_value=200)}, loss_rate=0.01, initial_storage_level=0, max_storage_level=0.9, inflow_conversion_factor=0.9, outflow_conversion_factor=0.9) # an excess and a shortage variable can help to avoid infeasible problems excess_el = Sink(label='excess_el', inputs={bus_el: Flow()}) shortage_el = Source(label='shortage_el', outputs={bus_el: Flow(variable_costs=100000)}) # ## Add all to the energysystem energysystem.add(bus_coal, bus_gas, bus_el, source_gas, source_coal, wind, pv, demand_el, pp_coal, storage_el, excess_el, shortage_el) # ## Create an Optimization Model and solve it # create optimization model based on energy_system optimization_model = Model(energysystem=energysystem) # solve problem optimization_model.solve(solver=solver) # ## Get results results_main = outputlib.processing.results(optimization_model) results_meta = outputlib.processing.meta_results(optimization_model) params = outputlib.processing.parameter_as_dict(energysystem) # ## Pass results to energysystem.results object before saving energysystem.results['main'] = results_main
# Energy System Creation es = EnergySystem(timeindex=timeseries.index) setattr(es, "typemap", fc.TYPEMAP) print("The energy system has been created.") # Bus Creation elec_bus_NDE = Bus(label="elec_Bus_NDE") elec_bus_SDE = Bus(label="elec_Bus_SDE") heat_bus_NDE = Bus(label="heat_Bus_NDE") heat_bus_SDE = Bus(label="heat_Bus_SDE") fuel_bus_NDE = Bus(label="fuel_Bus_NDE") fuel_bus_SDE = Bus(label="fuel_Bus_SDE") # Bus Addition to the Energy Sytem es.add(elec_bus_NDE, elec_bus_SDE, heat_bus_NDE, heat_bus_SDE, fuel_bus_NDE, fuel_bus_SDE) # Bus Linking es.add( fc.Link(label='link', carrier='electricity', from_bus=elec_bus_NDE, to_bus=elec_bus_SDE, capacity=capacity.at["transmission_capacity", "link"], loss=capacity.at["loss", "link"])) print("The buses have been created, added, and linked.") # Energy System Components # Onshore Wind es.add(
diameter=input_data[ 'diameter'], # TODO: setting to zero should give an error temp_h=input_data['temp_h'], temp_c=input_data['temp_c'], temp_env=input_data['temp_env'], u_value=u_value, expandable=True, capacity_cost=50, storage_capacity_cost=400, minimum_storage_capacity=1, # TODO: setting to zero should give an error! min_storage_level=input_data['min_storage_level'], max_storage_level=input_data['max_storage_level'], efficiency=1, marginal_cost=0.0001) energysystem.add(bus_heat, heat_source, shortage, excess, heat_demand, thermal_storage) # Create and solve the optimization model optimization_model = Model(energysystem) optimization_model.solve(solver=solver, solve_kwargs={ 'tee': False, 'keepfiles': False }) # Get results results = processing.results(optimization_model) string_results = processing.convert_keys_to_strings(results) sequences = {k: v['sequences'] for k, v in string_results.items()} df = pd.concat(sequences, axis=1)
el_storage = GenericStorage(label='el_storage', inputs={elbus: Flow(variable_costs=0.0001)}, outputs={elbus: Flow()}, loss_rate=0.00, initial_storage_level=0.5, invest_relation_input_capacity=1 / 6, invest_relation_output_capacity=1 / 6, inflow_conversion_factor=0.9, outflow_conversion_factor=0.9, investment=Investment(ep_costs=epc_storage)) cop = 3 es.add( Transformer(label='heat_pump', inputs={elbus: Flow()}, outputs={thbus: Flow(nominal_value=10)}, conversion_factors={elbus: 1 / cop})) th_storage = GenericStorage(label='th_storage', nominal_storage_capacity=1000, inputs={thbus: Flow(nominal_value=20)}, outputs={thbus: Flow(nominal_value=20)}, loss_rate=0.01, initial_storage_level=0, max_storage_level=0.9, inflow_conversion_factor=0.9, outflow_conversion_factor=0.9) # Adding all the components to the energy system
import numpy as np import matplotlib.pyplot as plt solver = 'cbc' # set timeindex and create data periods = 20 datetimeindex = pd.date_range('1/1/2019', periods=periods, freq='H') step = 5 demand = np.arange(0, step * periods, step) # set up EnergySystem energysystem = EnergySystem(timeindex=datetimeindex) b_gas = Bus(label='gas', balanced=False) b_el = Bus(label='electricity') energysystem.add(b_gas, b_el) energysystem.add( Source(label='shortage', outputs={b_el: Flow(variable_costs=1e6)})) energysystem.add( Sink(label='demand', inputs={b_el: Flow(nominal_value=1, actual_value=demand, fixed=True)})) conv_func = lambda x: 0.01 * x**2 in_breakpoints = np.arange(0, 110, 25) pwltf = solph.custom.PiecewiseLinearTransformer( label='pwltf', inputs={b_gas: solph.Flow(nominal_value=100, variable_costs=1)}, outputs={b_el: solph.Flow()}, in_breakpoints=in_breakpoints,
def initialize_basic_energysystem(): # initialize and provide data datetimeindex = pd.date_range('1/1/2016', periods=24, freq='H') filename = 'input_data.csv' data = pd.read_csv(filename, sep=",") energysystem = EnergySystem(timeindex=datetimeindex) # buses bcoal = Bus(label='coal', balanced=False) bgas = Bus(label='gas', balanced=False) bel = Bus(label='electricity') energysystem.add(bcoal, bgas, bel) # sources energysystem.add( Source(label='wind', outputs={ bel: Flow(actual_value=data['wind'], nominal_value=66.3, fixed=True) })) energysystem.add( Source(label='pv', outputs={ bel: Flow(actual_value=data['pv'], nominal_value=65.3, fixed=True) })) # excess and shortage to avoid infeasibilies energysystem.add(Sink(label='excess_el', inputs={bel: Flow()})) energysystem.add( Source(label='shortage_el', outputs={bel: Flow(variable_costs=200)})) # demands (electricity/heat) energysystem.add( Sink(label='demand_el', inputs={ bel: Flow(nominal_value=85, actual_value=data['demand_el'], fixed=True) })) return bcoal, bgas, bel, energysystem