def run_simple_least_costs_example(): import pprint as pp logger.define_logging() esys = initialise_energysystem() om = simulate(esys) plot_results(esys) pp.pprint(get_results(esys))
def run_simple_dispatch_example(**kwargs): import pprint as pp logger.define_logging() esys = initialise_energysystem() simulate(esys, **kwargs) plot_results(esys) pp.pprint(get_results(esys))
def run_investment_example(): logger.define_logging() # %% model creation and solving date_from = '2050-01-01 00:00:00' date_to = '2050-01-01 23:00:00' datetime_index = pd.date_range(date_from, date_to, freq='60min') es = EnergySystem(timeindex=datetime_index) data_path = os.path.join(os.path.dirname(__file__), 'data') nodes = NodesFromCSV(file_nodes_flows=os.path.join(data_path, 'nodes_flows.csv'), file_nodes_flows_sequences=os.path.join( data_path, 'nodes_flows_seq.csv'), delimiter=',') stopwatch() om = OperationalModel(es) logging.info('OM creation time: ' + stopwatch()) #om.receive_duals() om.solve(solver='glpk', solve_kwargs={'tee': True}) logging.info('Optimization time: ' + stopwatch()) logging.info('Done! \n Check the results')
def run_storage_invest_example(): logger.define_logging() esys = optimise_storage_size() # esys.dump() # esys.restore() import pprint as pp pp.pprint(get_result_dict(esys)) create_plots(esys)
def run_storage_invest_example(): logger.define_logging() esys = optimise_storage_size() # esys.dump() # esys.restore() import pprint as pp results = get_result_dict(esys) # Print some results print(results['ts_storage_soc']) print(results['storage_cap']) # Write results to csv results['ts_storage_input'].to_csv('ts_storage_input_' + str(year) + '.csv') results['ts_storage_soc'].to_csv('ts_storage_soc_' + str(year) + '.csv')
def run_storage_investment_example(**kwargs): logger.define_logging() esys = optimise_storage_size(**kwargs) # ** Dump an energy system ** # esys.dump() # ** Restore an energy system ** # esys = solph.EnergySystem() # esys.restore() if plt is not None: create_plots(esys) else: import pprint as pp pp.pprint(get_result_dict(esys)) msg = ("\nIt is not possible to plot the results, due to a missing " + "python package: 'matplotlib'. \nType 'pip install " + "matplotlib' to see the plots.") warnings.warn(msg)
def run_operational_example(): logger.define_logging() filepath = os.path.join(os.path.dirname(__file__), 'scenarios') # configuration cfg = { 'scenario_path': os.path.join(os.path.dirname(__file__), 'scenarios'), 'date_from': '2030-01-01 00:00:00', 'date_to': '2030-01-14 23:00:00', 'nodes_flows': os.path.join(filepath, 'example_energy_system.csv'), 'nodes_flows_sequences': os.path.join( filepath, 'example_energy_system_seq.csv'), 'results_path': 'results/', # has to be created in advance! 'solver': 'glpk', 'verbose': True, } my_results = run_example(config=cfg) plotting(my_results)
def run_variable_chp_example(**kwargs): logger.define_logging() plot_only = False # set to True if you want to plot your stored results # Switch to True to show the solver output kwargs.setdefault('tee_switch', False) esys = initialise_energy_system() if not plot_only: esys = optimise_storage_size(esys, **kwargs) esys.dump() else: esys.restore() if plt is not None: create_plots(esys) else: msg = ("\nIt is not possible to plot the results, due to a missing " + "python package: 'matplotlib'. \nType 'pip install " + "matplotlib' to see the plots.") warnings.warn(msg) for k, v in get_result_dict(esys).items(): logging.info('{0}: {1}'.format(k, v))
cdict["('transport', 'bus', 'Stadt Dessau-Rosslau', 'elec', 'bus', 'Landkreis Wittenberg', 'elec')"] = '#643780' cdict["('transformer', 'Landkreis Wittenberg', 'natural_gas')"] = '#7c7c7c' cdict["('transformer', 'Stadt Dessau-Rosslau', 'natural_gas')"] = '#7c7c7c' cdict["('transformer', 'Landkreis Wittenberg', 'lignite')"] = '#000000' cdict["('transformer', 'Stadt Dessau-Rosslau', 'lignite')"] = '#000000' cdict["('sto_simple', 'Landkreis Wittenberg', 'elec')"] = '#ff5e5e' cdict["('sto_simple', 'Stadt Dessau-Rosslau', 'elec')"] = '#ff5e5e' cdict["('sink', 'Landkreis Wittenberg', 'elec')"] = '#0cce1e' cdict["('sink', 'Stadt Dessau-Rosslau', 'elec')"] = '#0cce1e' # Define the oemof default logger logger.define_logging() # Create an energy system TwoRegExample = es.EnergySystem() # Restoring a dumped EnergySystem logging.info(TwoRegExample.restore()) es_df = tpd.EnergySystemDataFrame(energy_system=TwoRegExample) fig = plt.figure(figsize=(24, 14)) plt.rc('legend', **{'fontsize': 19}) plt.rcParams.update({'font.size': 14}) plt.style.use('ggplot') n = 1
def run_example_checks(): # ********* storage invest example ***************************************** key = "stor_inv" testdict[key] = {"name": "Storage invest example", "solver": "cbc"} number_of_timesteps = 500 try: esys = storage_invest.optimise_storage_size( number_timesteps=number_of_timesteps, solvername=testdict[key]["solver"], debug=False, tee_switch=False ) esys.dump() esys.restore() results = storage_invest.get_result_dict(esys) testdict[key]["run"] = True except Exception as e: testdict[key]["messages"] = {"error": e} testdict[key]["run"] = False results = None stor_invest_dict = { 8760: { "pp_gas_sum": 112750260.00000007, "demand_sum": 2255000000.000008, "demand_max": 368693.14440990007, "wind_sum": 3085699499.7, "wind_inst": 1000000, "pv_sum": 553984766.734176, "pv_inst": 582000, "storage_cap": 10805267, "objective": 8.93136532898235e19, }, 500: { "demand_max": 341499.463487, "demand_sum": 1.339972e08, "objective": 2.806796142614384e17, "pp_gas_sum": 6.435517e06, "pv_inst": 260771.373277, "pv_sum": 9.806339e06, "storage_cap": 615506.94, "wind_inst": 999979.9978, "wind_sum": 391216886.0, }, } check(stor_invest_dict[number_of_timesteps], testdict[key]["run"], testdict[key], results) # ********* end of storage invest example ********************************** # *********** simple least cost example *********************************** key = "least_costs" testdict[key] = {"name": "Simple least costs optimization", "solver": "cbc"} try: esys = simple_least_costs.initialise_energysystem(periods=2000) simple_least_costs.simulate(esys, solver=testdict[key]["solver"], tee_switch=False) results = simple_least_costs.get_results(esys) testdict[key]["run"] = True except Exception as e: testdict[key]["messages"] = {"error": e} testdict[key]["run"] = False results = None test_results = { "objective": 2947725.249402091, ("b_el", "to_bus", "pp_chp", "val"): 11161.357450000065, ("b_el", "to_bus", "pp_coal", "val"): 33723.047672110595, ("b_el", "to_bus", "pp_gas", "val"): 30412.377779000046, ("b_el", "to_bus", "pp_lig", "val"): 22066.451080999268, ("b_el", "to_bus", "pp_oil", "val"): 2.2872599999999998, ("b_el", "to_bus", "pv", "val"): 7796.8431880300122, ("b_el", "to_bus", "wind", "val"): 28009.549502999955, ("b_el", "from_bus", "demand_el", "val"): 132243.7904593189, ("b_el", "from_bus", "excess", "val"): 928.12139200000013, ("b_th", "to_bus", "pp_chp", "val"): 14881.810039999958, ("b_th", "from_bus", "demand_th", "val"): 14881.80983624002, ("coal", "from_bus", "pp_coal", "val"): 86469.394787298472, ("gas", "from_bus", "pp_chp", "val"): 37204.525720000034, ("gas", "from_bus", "pp_gas", "val"): 60824.751778000136, ("lignite", "from_bus", "pp_lig", "val"): 53820.634704001102, ("oil", "from_bus", "pp_oil", "val"): 8.1687949999999994, } check(test_results, testdict[key]["run"], testdict[key], results) # *********** end of simple least cost example **************************** # *********** flexible modelling example *********************************** key = "flexible_modelling" testdict[key] = {"name": "Flexible Modelling", "solver": "cbc"} try: add_constraints.run_add_constraints_example(testdict[key]["solver"]) testdict[key]["run"] = True except Exception as e: testdict[key]["messages"] = {"error": e} testdict[key]["run"] = False test_results = {} check(test_results, testdict[key]["run"], testdict[key]) # *********** end of flexible modelling example **************************** # *********** csv reader operational example ******************************* key = "csv_operational" testdict[key] = { "name": "Operational model with csv reader", "solver": "cbc", "verbose": False, "scenario_path": os.path.join(basic_path, "solph", "csv_reader", "operational_example", "scenarios"), "date_from": "2030-01-01 00:00:00", "date_to": "2030-01-14 23:00:00", "nodes_flows": "example_energy_system.csv", "nodes_flows_sequences": "example_energy_system_seq.csv", } try: res = operational_example.run_example(config=testdict[key]) results = operational_example.create_result_dict(res) testdict[key]["run"] = True except Exception as e: testdict[key]["messages"] = {"error": e} testdict[key]["run"] = False results = None test_results = { "objective": 2326255732.5299315, "R2_storage_phs": 88911.484028, "R2_wind": 1758697.51, "R2_R1_powerline": 2.277989e06, } check(test_results, testdict[key]["run"], testdict[key], results) # *********** end of csv reader operational example ************************ logger.define_logging() for tests in testdict.values(): logging.info("*********************************************") logging.info(tests["name"]) logging.info("Used solver: {0}".format(tests["solver"])) logging.info("Run check: {0}".format(tests["run"])) logging.info("Result check: {0}".format(tests["results"])) if show_messages and "messages" in tests: for message in tests["messages"].values(): logging.error(message) if PASSED: check_nosetests() print("All example tests passed!") else: check_nosetests() text = "Some example tests failed." text += "See the output above for more information!" print(text)
def run_example_checks(): # ********* storage invest example ***************************************** key = 'stor_inv' testdict[key] = {'name': "Storage invest example", 'solver': 'cbc'} number_of_timesteps = 500 try: esys = storage_investment.optimise_storage_size( number_timesteps=number_of_timesteps, solver=testdict[key]['solver'], debug=False, tee_switch=False) esys.dump() esys.restore() results = storage_investment.get_result_dict(esys) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None stor_invest_dict = {8760: { 'pp_gas_sum': 112750260.00000007, 'demand_sum': 2255000000.000008, 'demand_max': 368693.14440990007, 'wind_sum': 3085699499.7, 'wind_inst': 1000000, 'pv_sum': 553984766.734176, 'pv_inst': 582000, 'storage_cap': 10805267, 'objective': 8.93136532898235e+19}, 500: { 'demand_max': 341499.463487, 'demand_sum': 1.339972e+08, 'objective': 2.806796142614384e+17, 'pp_gas_sum': 6.435517e+06, 'pv_inst': 260771.373277, 'pv_sum': 9.806339e+06, 'storage_cap': 615506.94, 'wind_inst': 999979.9978, 'wind_sum': 391216886.0, }} check(stor_invest_dict[number_of_timesteps], testdict[key]['run'], testdict[key], results) # ********* end of storage invest example ********************************** # *********** simple least cost example *********************************** key = 'least_costs' testdict[key] = {'name': "Simple least costs optimization", 'solver': 'cbc'} try: esys = simple_dispatch.initialise_energysystem(periods=2000) simple_dispatch.simulate(esys, solver=testdict[key]['solver'], tee_switch=False, keep=False) results = simple_dispatch.get_results(esys) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None test_results = { 'objective': 2919760.79345538, ('b_el', 'from_bus', 'demand_el', 'val'): 132243.7904593189, ('b_el', 'from_bus', 'excess', 'val'): 444.60716131999982, ('b_el', 'from_bus', 'heat_pump', 'val'): 931.24215460999926, ('b_el', 'to_bus', 'pp_chp', 'val'): 9066.0625217479828, ('b_el', 'to_bus', 'pp_coal', 'val'): 35676.475654468377, ('b_el', 'to_bus', 'pp_gas', 'val'): 30412.376285770013, ('b_el', 'to_bus', 'pp_lig', 'val'): 22656.045354479214, ('b_el', 'to_bus', 'pp_oil', 'val'): 2.2872602799999999, ('b_el', 'to_bus', 'pv', 'val'): 7796.8431880300122, ('b_el', 'to_bus', 'wind', 'val'): 28009.549502999955, ('b_heat_source', 'from_bus', 'heat_pump', 'val'): 1862.4843137140017, ('b_heat_source', 'to_bus', 'heat_source', 'val'): 1862.4843137140017, ('b_th', 'from_bus', 'demand_th', 'val'): 14881.80983624002, ('b_th', 'to_bus', 'heat_pump', 'val'): 2793.7264708619978, ('b_th', 'to_bus', 'pp_chp', 'val'): 12088.083361442017, ('coal', 'from_bus', 'pp_coal', 'val'): 91478.143053327163, ('gas', 'from_bus', 'pp_chp', 'val'): 30220.208378289819, ('gas', 'from_bus', 'pp_gas', 'val'): 60824.752549570097, ('lignite', 'from_bus', 'pp_lig', 'val'): 55258.647579137803, ('oil', 'from_bus', 'pp_oil', 'val'): 8.1687867099999991 } check(test_results, testdict[key]['run'], testdict[key], results) # *********** end of simple least cost example **************************** # *********** flexible modelling example *********************************** key = 'flexible_modelling' testdict[key] = {'name': "Flexible Modelling", 'solver': 'cbc'} try: add_constraints.run_add_constraints_example(testdict[key]['solver'], nologg=True) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False test_results = {} check(test_results, testdict[key]['run'], testdict[key]) # *********** end of flexible modelling example **************************** # *********** csv reader dispatch example ********************************** key = 'csv_reader_dispatch' testdict[key] = { 'name': "Dispatch model with csv reader", 'solver': 'cbc', 'verbose': False, 'scenario_path': os.path.join(basic_path, 'solph', 'csv_reader', 'dispatch', 'scenarios'), 'date_from': '2030-01-01 00:00:00', 'date_to': '2030-01-14 23:00:00', 'nodes_flows': 'example_energy_system.csv', 'nodes_flows_sequences': 'example_energy_system_seq.csv', 'results_path': os.path.join(os.path.expanduser("~"), 'csv_dispatch'), } if not os.path.isdir(testdict[key]['results_path']): os.mkdir(testdict[key]['results_path']) try: res = dispatch.run_example(config=testdict[key], ) results = dispatch.create_result_dict(res) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None test_results = { 'objective': 2326255732.5299315, 'R2_storage_phs': 88911.484028, 'R2_wind': 1758697.51, 'R2_R1_powerline': 2.277989e+06} check(test_results, testdict[key]['run'], testdict[key], results) # *********** end of csv reader dispatch example *************************** # *********** csv reader investment example ******************************** key = 'csv_reader_investment' testdict[key] = {'name': "Investment model with csv reader", 'solver': 'cbc'} try: investment.run_investment_example(solver=testdict[key]['solver'], verbose=False, nologg=True) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False test_results = {} check(test_results, testdict[key]['run'], testdict[key]) # *********** end of csv reader investment example ************************* # ********* variable chp example ******************************************* key = 'variable_chp' testdict[key] = {'name': "Variable CHP example", 'solver': 'cbc'} try: esys = variable_chp.initialise_energy_system(192) esys = variable_chp.optimise_storage_size( esys, solver=testdict[key]['solver'], tee_switch=False) results = variable_chp.get_result_dict(esys) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None variable_chp_dict = { 'objective': 14267160965.0, 'input_fixed_chp': 157717049.49999994, 'natural_gas': 285343219.29999995, 'input_variable_chp': 127626169.47000004} check(variable_chp_dict, testdict[key]['run'], testdict[key], results) # ********* end of storage invest example ********************************** logger.define_logging() for tests in testdict.values(): logging.info('*********************************************') logging.info(tests['name']) logging.info("Used solver: {0}".format(tests['solver'])) logging.info("Run check: {0}".format(tests['run'])) logging.info("Result check: {0}".format(tests['results'])) if show_messages and 'messages' in tests: for message in tests['messages'].values(): logging.error(message) if PASSED: check_nosetests() print("All example tests passed!") else: check_nosetests() text = "Some example tests failed." text += "See the output above for more information!" print(text)
def run_example_checks(): # ********* storage invest example ***************************************** key = 'stor_inv' testdict[key] = {'name': "Storage invest example", 'solver': 'cbc'} number_of_timesteps = 500 try: esys = storage_invest.optimise_storage_size( number_timesteps=number_of_timesteps, solvername=testdict[key]['solver'], debug=False, tee_switch=False) esys.dump() esys.restore() results = storage_invest.get_result_dict(esys) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None stor_invest_dict = {8760: { 'pp_gas_sum': 112750260.00000007, 'demand_sum': 2255000000.000008, 'demand_max': 368693.14440990007, 'wind_sum': 3085699499.7, 'wind_inst': 1000000, 'pv_sum': 553984766.734176, 'pv_inst': 582000, 'storage_cap': 10805267, 'objective': 8.93136532898235e+19}, 500: { 'demand_max': 341499.463487, 'demand_sum': 1.339972e+08, 'objective': 2.806796142614384e+17, 'pp_gas_sum': 6.435517e+06, 'pv_inst': 260771.373277, 'pv_sum': 9.806339e+06, 'storage_cap': 615506.94, 'wind_inst': 999979.9978, 'wind_sum': 391216886.0, }} check(stor_invest_dict[number_of_timesteps], testdict[key]['run'], testdict[key], results) # ********* end of storage invest example ********************************** # *********** simple least cost example *********************************** key = 'least_costs' testdict[key] = {'name': "Simple least costs optimization", 'solver': 'cbc'} try: esys = simple_least_costs.initialise_energysystem(periods=2000) simple_least_costs.simulate(esys, solver=testdict[key]['solver'], tee_switch=False) results = simple_least_costs.get_results(esys) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None test_results = { 'objective': 2947725.249402091, ('b_el', 'to_bus', 'pp_chp', 'val'): 11161.357450000065, ('b_el', 'to_bus', 'pp_coal', 'val'): 33723.047672110595, ('b_el', 'to_bus', 'pp_gas', 'val'): 30412.377779000046, ('b_el', 'to_bus', 'pp_lig', 'val'): 22066.451080999268, ('b_el', 'to_bus', 'pp_oil', 'val'): 2.2872599999999998, ('b_el', 'to_bus', 'pv', 'val'): 7796.8431880300122, ('b_el', 'to_bus', 'wind', 'val'): 28009.549502999955, ('b_el', 'from_bus', 'demand_el', 'val'): 132243.7904593189, ('b_el', 'from_bus', 'excess', 'val'): 928.12139200000013, ('b_th', 'to_bus', 'pp_chp', 'val'): 14881.810039999958, ('b_th', 'from_bus', 'demand_th', 'val'): 14881.80983624002, ('coal', 'from_bus', 'pp_coal', 'val'): 86469.394787298472, ('gas', 'from_bus', 'pp_chp', 'val'): 37204.525720000034, ('gas', 'from_bus', 'pp_gas', 'val'): 60824.751778000136, ('lignite', 'from_bus', 'pp_lig', 'val'): 53820.634704001102, ('oil', 'from_bus', 'pp_oil', 'val'): 8.1687949999999994} check(test_results, testdict[key]['run'], testdict[key], results) # *********** end of simple least cost example **************************** # *********** flexible modelling example *********************************** key = 'flexible_modelling' testdict[key] = {'name': "Flexible Modelling", 'solver': 'cbc'} try: add_constraints.run_add_constraints_example(testdict[key]['solver']) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False test_results = {} check(test_results, testdict[key]['run'], testdict[key]) # *********** end of flexible modelling example **************************** # *********** csv reader operational example ******************************* key = 'csv_operational' testdict[key] = { 'name': "Operational model with csv reader", 'solver': 'cbc', 'verbose': False, 'scenario_path': os.path.join(basic_path, 'solph', 'csv_reader', 'operational_example', 'scenarios'), 'date_from': '2030-01-01 00:00:00', 'date_to': '2030-01-14 23:00:00', 'nodes_flows': 'example_energy_system.csv', 'nodes_flows_sequences': 'example_energy_system_seq.csv', } try: res = operational_example.run_example(config=testdict[key]) results = operational_example.create_result_dict(res) testdict[key]['run'] = True except Exception as e: testdict[key]['messages'] = {'error': e} testdict[key]['run'] = False results = None test_results = { 'objective': 2326255732.5299315, 'R2_storage_phs': 88911.484028, 'R2_wind': 1758697.51, 'R2_R1_powerline': 2.277989e+06} check(test_results, testdict[key]['run'], testdict[key], results) # *********** end of csv reader operational example ************************ logger.define_logging() for tests in testdict.values(): logging.info('*********************************************') logging.info(tests['name']) logging.info("Used solver: {0}".format(tests['solver'])) logging.info("Run check: {0}".format(tests['run'])) logging.info("Result check: {0}".format(tests['results'])) if show_messages and 'messages' in tests: for message in tests['messages'].values(): logging.error(message) if PASSED: check_nosetests() print("All example tests passed!") else: check_nosetests() text = "Some example tests failed." text += "See the output above for more information!" print(text)
def sesmg_main(scenario_file: str, result_path: str, num_threads: int, graph: bool, criterion_switch: bool, xlsx_results: bool, console_results: bool, timeseries_prep: list, solver: str): """ Main function of the Spreadsheet System Model Generator :param scenario_file: The scenario_file must contain the components specified above. :type scenario_file: str ['xlsx'] :param result_path: path of the folder where the results will be saved :type result_path: str ['folder'] :param num_threads: number of threads that the method may use :type num_threads: int :param graph: defines if the graph should be created :type graph: bool :param results: defines if the results should be created :type results: bool :param plotly: defines if the plotly dash should be started :type plotly: bool Christian Klemm - [email protected] """ # SETS NUMBER OF THREADS FOR NUMPY os.environ['NUMEXPR_NUM_THREADS'] = str(num_threads) # DEFINES A LOGGING FILE logger.define_logging(logpath=result_path) # IMPORTS DATA FROM THE EXCEL FILE AND RETURNS IT AS DICTIONARY nodes_data = create_energy_system.import_scenario(filepath=scenario_file) # CRITERION SWITCH if criterion_switch: data_preparation.change_optimization_criterion(nodes_data) if sys.platform.startswith("win"): scheme_path = \ os.path.join(os.path.dirname(__file__) + r'\technical_data\hierarchical_selection' r'_schemes.xlsx') else: scheme_path = \ os.path.join(os.path.dirname(__file__) + r'/technical_data/hierarchical_selection' r'_schemes.xlsx') # Timeseries Preprocessing data_preparation.timeseries_preparation( timeseries_prep_param=timeseries_prep, nodes_data=nodes_data, scheme_path=scheme_path, result_path=result_path) if timeseries_prep[0] != 'none': scenario_file = result_path + "/modified_scenario.xlsx" # CREATES AN ENERGYSYSTEM AS DEFINED IN THE SCENARIO FILE esys = create_energy_system.define_energy_system(nodes_data=nodes_data) weather_data = nodes_data['weather data'] time_series = nodes_data['timeseries'] # CREATES AN LIST OF COMPONENTS nodes = [] # CREATES BUS OBJECTS, EXCESS SINKS, AND SHORTAGE SOURCES AS DEFINED IN THE # SCENARIO FILE AND ADDS THEM TO THE lIST OF COMPONENTS busd = create_objects.buses(nodes_data=nodes_data, nodes=nodes) # PARALLEL CREATION OF ALL OBJECTS OF THE SCENARIO FILE # CREATES SOURCE OBJECTS AS DEFINED IN THE SCENARIO FILE AND ADDS THEM TO # THE lIST OF COMPONENTS t1 = Thread(target=create_objects.Sources, args=(nodes_data, nodes, busd, time_series, weather_data)) t1.start() # CREATES SINK OBJECTS AS DEFINED IN THE SCENARIO FILE AND ADDS THEM TO # THE lIST OF COMPONENTS t2 = Thread(target=create_objects.Sinks, args=(nodes_data, busd, nodes, time_series, weather_data)) t2.start() # CREATES TRANSFORMER OBJECTS AS DEFINED IN THE SCENARIO FILE AND ADDS THEM # TO THE lIST OF COMPONENTS t3 = Thread(target=create_objects.Transformers, args=(nodes_data, nodes, busd, weather_data)) t3.start() # CREATES STORAGE OBJECTS AS DEFINED IN THE SCENARIO FILE AND ADDS THEM TO # THE lIST OF COMPONENTS t4 = Thread(target=create_objects.Storages, args=( nodes_data, nodes, busd, )) t4.start() # CREATES LINK OBJECTS AS DEFINED IN THE SCENARIO FILE AND ADDS THEM TO # THE lIST OF COMPONENTS t5 = Thread(target=create_objects.Links, args=( nodes_data, nodes, busd, )) t5.start() # WAIT UNTIL THE THREADS HAVE DONE THEIR JOBS t1.join() t2.join() t3.join() t4.join() t5.join() # ADDS THE COMPONENTS TO THE ENERGYSYSTEM esys.add(*nodes) # PRINTS A GRAPH OF THE ENERGY SYSTEM create_graph.create_graph(filepath=result_path, nodes_data=nodes_data, show=graph) # OPTIMIZES THE ENERGYSYSTEM AND RETURNS THE OPTIMIZED ENERGY SYSTEM om = optimize_model.least_cost_model(esys, num_threads, nodes_data, busd, solver) # SHOWS AND SAVES RESULTS OF THE OPTIMIZED MODEL / POST-PROCESSING if xlsx_results: create_results.xlsx(nodes_data=nodes_data, optimization_model=om, filepath=result_path) # CREATES PLOTLY RESULTS AND LOGS RESULTS OF CBC SOLVER create_results.Results(nodes_data, om, esys, result_path, console_log=console_results) logging.info(' ' + '----------------------------------------------' '----------') logging.info(' ' + 'Modelling and optimization successfully completed!')
def create_optimization_model(mode, feedin, initial_batt_cap, cost, cap_pv, cap_batt, iterstatus=None, PV_source=True, storage_source=True, logger=False): if logger == 1: logger.define_logging() ##################################### Initialize the energy system################################################## # times = pd.DatetimeIndex(start='04/01/2017', periods=10, freq='H') times = feedin.index energysystem = EnergySystem(timeindex=times) # switch on automatic registration of entities of EnergySystem-object=energysystem Node.registry = energysystem # add components b_el = Bus(label='electricity') b_dc = Bus(label='electricity_dc') b_oil = Bus(label='diesel_source') demand_feedin = feedin['demand_el'] Sink(label='demand', inputs={ b_el: Flow(actual_value=demand_feedin, nominal_value=1, fixed=True) }) Sink(label='excess', inputs={b_el: Flow()}) Source(label='diesel', outputs={b_oil: Flow()}) generator1 = custom.DieselGenerator( label='pp_oil_1', fuel_input={b_oil: Flow(variable_costs=cost['pp_oil_1']['var'])}, electrical_output={ b_el: Flow(nominal_value=186, min=0.3, max=1, nonconvex=NonConvex(om_costs=cost['pp_oil_1']['o&m']), fixed_costs=cost['pp_oil_1']['fix']) }, fuel_curve={ '1': 42, '0.75': 33, '0.5': 22, '0.25': 16 }) generator2 = custom.DieselGenerator( label='pp_oil_2', fuel_input={b_oil: Flow(variable_costs=cost['pp_oil_2']['var'])}, electrical_output={ b_el: Flow(nominal_value=186, min=0.3, max=1, nonconvex=NonConvex(om_costs=cost['pp_oil_2']['o&m']), fixed_costs=cost['pp_oil_2']['fix'], variable_costs=0) }, fuel_curve={ '1': 42, '0.75': 33, '0.5': 22, '0.25': 16 }) generator3 = custom.DieselGenerator( label='pp_oil_3', fuel_input={b_oil: Flow(variable_costs=cost['pp_oil_3']['var'])}, electrical_output={ b_el: Flow(nominal_value=320, min=0.3, max=1, nonconvex=NonConvex(om_costs=cost['pp_oil_3']['o&m']), fixed_costs=cost['pp_oil_3']['fix'], variable_costs=0) }, fuel_curve={ '1': 73, '0.75': 57, '0.5': 38, '0.25': 27 }) # List all generators in a list called gen_set gen_set = [generator1, generator2, generator3] if PV_source == 1: PV = Source(label='PV', outputs={ b_dc: Flow(nominal_value=cap_pv, fixed_costs=cost['pv']['fix'] + cost['pv']['epc'], actual_value=feedin['PV'], fixed=True) }) else: PV = None if storage_source == 1: storage = components.GenericStorage( label='storage', inputs={b_dc: Flow()}, outputs={ b_dc: Flow(variable_costs=cost['storage']['var'], fixed_costs=cost['storage']['fix']) }, nominal_capacity=cap_batt, fixed_costs=cost['storage']['epc'], capacity_loss=0.00, initial_capacity=initial_batt_cap, nominal_input_capacity_ratio=0.546, nominal_output_capacity_ratio=0.546, inflow_conversion_factor=0.92, outflow_conversion_factor=0.92, capacity_min=0.5, capacity_max=1, initial_iteration=iterstatus) else: storage = None if storage_source == 1 or PV_source == 1: inverter1 = add_inverter(b_dc, b_el, 'Inv_pv') ################################# optimization ############################ # create Optimization model based on energy_system logging.info("Create optimization problem") m = Model(energysystem) ################################# constraints ############################ sr_requirement = 0.2 sr_limit = demand_feedin * sr_requirement rm_requirement = 0.4 rm_limit = demand_feedin * rm_requirement constraints.spinning_reserve_constraint(m, sr_limit, groups=gen_set, storage=storage) # constraints.n1_constraint(m, demand_feedin, groups=gen_set) constraints.gen_order_constraint(m, groups=gen_set) constraints.rotating_mass_constraint(m, rm_limit, groups=gen_set, storage=storage) return [m, gen_set]
def test_logger(): filepath = define_logging() assert isinstance(filepath, str) assert filepath[-9:] == 'oemof.log' assert os.path.isfile(filepath)
import pprint as pp try: import matplotlib.pyplot as plt except ImportError: plt = None solver = "cbc" # 'glpk', 'gurobi',.... debug = False # Set number_of_timesteps to 3 to get a readable lp-file. number_of_time_steps = 24 * 7 * 8 solver_verbose = False # show/hide solver output # initiate the logger (see the API docs for more information) logger.define_logging( logfile="oemof_example.log", screen_level=logging.INFO, file_level=logging.DEBUG, ) logging.info("Initialize the energy system") date_time_index = pd.date_range("1/1/2012", periods=number_of_time_steps, freq="H") energysystem = solph.EnergySystem(timeindex=date_time_index) # Read data file filename = os.path.join(os.getcwd(), "basic_example.csv") data = pd.read_csv(filename) ##########################################################################