Basic run¶
First, we import the essential libraries and modules that will be used throughout this tutorial:
pickle
: Used for saving and loading Python objects to and from files.Energyscope
fromenergyscope.energyscope
: The main class for initializing and running the EnergyScope model.infrastructure_ch_2050
,Model
fromenergyscope.models
: The specific model configuration we will use, which focuses on energy infrastructure. And the object Model to create your own model from external files.postprocessing
fromenergyscope.result
: Functions for processing and analyzing the results after optimization.plot_sankey
fromenergyscope.plots
: A function to generate Sankey diagrams for visualizing energy flows.
import pickle
from energyscope.energyscope import Energyscope
from energyscope.models import infrastructure_ch_2050, Model
from energyscope.result import postprocessing
from energyscope.plots import plot_sankey
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[1], line 5 3 from energyscope.models import infrastructure_ch_2050, Model 4 from energyscope.result import postprocessing ----> 5 from energyscope.plots import plot_sankey File /builds/energyscope/energyscope/src/energyscope/plots.py:19 13 import numpy as np 14 from pandas.api.types import ( 15 is_integer_dtype, 16 is_datetime64_any_dtype, 17 is_period_dtype, 18 ) ---> 19 from ipywidgets import Dropdown, HBox, VBox, Button, Output 20 from ipywidgets import Dropdown, HBox, VBox, Button, Output 21 import matplotlib.pyplot as plt ModuleNotFoundError: No module named 'ipywidgets'
Initialize and Run the Model¶
In this section, we initialize the EnergyScope model using the infrastructure dataset and perform a single optimization run.
Initialize the Model¶
Create an instance of the Energyscope
class with the infrastructure
model. This sets up the model with predefined parameters and datasets.
es_infra_ch = Energyscope(model=infrastructure_ch_2050)
Export Model to AMPL and GLPK¶
For compatibility and further analysis, we export the model files in both AMPL and GLPK formats.
# Export model to AMPL
es_infra_ch.export_ampl(mod_filename='tutorial_output/AMPL_infrastructure_ch_2050.mod',dat_filename='tutorial_output/AMPL_infrastructure_ch_2050.dat')
# Export model to GLPK
es_infra_ch.export_glpk(mod_filename='tutorial_output/GLPK_infrastructure_ch_2050.mod',dat_filename='tutorial_output/GLPK_infrastructure_ch_2050.dat')
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[3], line 2 1 # Export model to AMPL ----> 2 es_infra_ch.export_ampl(mod_filename='tutorial_output/AMPL_infrastructure_ch_2050.mod',dat_filename='tutorial_output/AMPL_infrastructure_ch_2050.dat') 4 # Export model to GLPK 5 es_infra_ch.export_glpk(mod_filename='tutorial_output/GLPK_infrastructure_ch_2050.mod',dat_filename='tutorial_output/GLPK_infrastructure_ch_2050.dat') File /builds/energyscope/energyscope/src/energyscope/energyscope.py:92, in Energyscope.export_ampl(self, mod_filename, dat_filename) 84 """ 85 Exports the model and data to .mod and .dat files for AMPL. 86 (...) 89 dat_filename (str): Path to the .dat file to export the data. 90 """ 91 # Reset the AMPL model ---> 92 self.es_model.reset() 94 # Load the model and data files 95 for file_type, file_path in self.model.files: File /builds/energyscope/energyscope/src/energyscope/energyscope.py:30, in Energyscope.es_model(self) 28 else: 29 try: ---> 30 self.__es_model = AMPL(Environment(os.environ["AMPL_PATH"])) 31 except SystemError: 32 # Try to create the object a second time to prevent errors when starting `ampl_lic` 33 self.__es_model = AMPL() File /usr/local/lib/python3.10/os.py:680, in _Environ.__getitem__(self, key) 677 value = self._data[self.encodekey(key)] 678 except KeyError: 679 # raise KeyError with the original key value --> 680 raise KeyError(key) from None 681 return self.decodevalue(value) KeyError: 'AMPL_PATH'
Load External AMPL files¶
To load external files from AMPL you need to create a new Model as follow.
# Create you own Model object from imported AMPL files
Model_es_infra_ch = Model([
('mod', "tutorial_output/AMPL_infrastructure_ch_2050.mod"),
('dat', "tutorial_output/AMPL_infrastructure_ch_2050.dat")
])
# Create an instance of the Energyscope class with your own model.
es_infra_ch = Energyscope(model=Model_es_infra_ch)
Solve the Model¶
Perform the optimization calculation. This step runs the solver and computes the optimal configuration based on the model.
results_ch = es_infra_ch.calc()
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[5], line 1 ----> 1 results_ch = es_infra_ch.calc() File /builds/energyscope/energyscope/src/energyscope/energyscope.py:72, in Energyscope.calc(self, ds, parser) 68 def calc(self, ds: Dataset = None, parser: Callable[[AMPL], Result] = parse_result) -> Result: 69 """ 70 Calls AMPL with `df` as .dat and returns the parsed result. 71 """ ---> 72 if self.es_model.getSets().__len__() == 0: # Check if AMPL instance is empty 73 self._initial_run(ds=ds) 75 # Solve the model File /builds/energyscope/energyscope/src/energyscope/energyscope.py:30, in Energyscope.es_model(self) 28 else: 29 try: ---> 30 self.__es_model = AMPL(Environment(os.environ["AMPL_PATH"])) 31 except SystemError: 32 # Try to create the object a second time to prevent errors when starting `ampl_lic` 33 self.__es_model = AMPL() File /usr/local/lib/python3.10/os.py:680, in _Environ.__getitem__(self, key) 677 value = self._data[self.encodekey(key)] 678 except KeyError: 679 # raise KeyError with the original key value --> 680 raise KeyError(key) from None 681 return self.decodevalue(value) KeyError: 'AMPL_PATH'
Post-Process Results¶
After obtaining the raw results, we apply post-processing to compute Key Performance Indicators (KPIs) and prepare the data for visualization.
results_ch = postprocessing(results_ch)
# Example of how to extract post-processed data
results_ch.postprocessing['df_annual'].loc['WIND',:]
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[6], line 1 ----> 1 results_ch = postprocessing(results_ch) 3 # Example of how to extract post-processed data 4 results_ch.postprocessing['df_annual'].loc['WIND',:] NameError: name 'results_ch' is not defined
fig = plot_sankey(results_ch)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[7], line 1 ----> 1 fig = plot_sankey(results_ch) NameError: name 'plot_sankey' is not defined
Display the Diagram¶
Render the Sankey diagram within the notebook for immediate visualization.
Optional: You can save the diagram as an HTML file or an image for external use by uncommenting the following lines:
# fig.write_html("tutorial_output/sankey_infrastructure_ch_2050.html")
# fig.write_image('tutorial_output/sankey_infrastructure_ch_2050.png')
fig.show(renderer="notebook")
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[9], line 1 ----> 1 fig.show(renderer="notebook") NameError: name 'fig' is not defined
def save_result_to_pickle(data, filename):
"""
Save the Result object to a pickle file.
Parameters:
data: The Result object to save.
filename (str): The file path to save the object to.
"""
with open(filename, 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
Define Load Function¶
Create a function to load the Result
object from a pickle file.
Note: These utility functions could be integrated into the EnergyScope library for convenience.
def load_result_from_pickle(filename):
"""
Load the Result object from a pickle file.
Parameters:
filename (str): The file path to load the object from.
Returns:
The loaded Result object.
"""
with open(filename, 'rb') as handle:
result = pickle.load(handle)
return result
Save the Results¶
Use the save_result_to_pickle
function to save the results to a file.
save_result_to_pickle(results_ch, "tutorial_input/infrastructure_ch_2050.pickle")
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[12], line 1 ----> 1 save_result_to_pickle(results_ch, "tutorial_input/infrastructure_ch_2050.pickle") NameError: name 'results_ch' is not defined
Clear the Results Variable¶
Empty the results_ch
variable to simulate a fresh environment.
results_ch = None
Load the Results¶
Load the previously saved results using the load_result_from_pickle
function.
results_ch = load_result_from_pickle("tutorial_input/infrastructure_ch_2050.pickle")
Display Total Cost¶
Access and display the total cost from the loaded results to verify that the data was correctly saved and loaded.
results_ch.variables['TotalCost']
TotalCost | Run | |
---|---|---|
0 | 9229.741872 | 0 |
This should output a table showing the total cost of the optimized energy system configuration.
By following these steps, you can perform a basic run of the EnergyScope model, visualize the results, and save/load the data for future use. This tutorial serves as a foundation for more complex analyses and customizations.