### Install energyscope Python Library Source: https://library.energyscope.ch/latest/getting-started Install the energyscope Python library using pip. This option automatically installs and configures AMPL. ```bash pip install energyscope ``` -------------------------------- ### Print Example Message Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/01_monthly/plot_01_test Prints a confirmation message indicating that the sine plot example is being shown. ```python print('This example shows a sin plot!') ``` -------------------------------- ### Install EnergyScope and Mescal Libraries Source: https://library.energyscope.ch/latest/library/run-with-lca Install the required libraries, EnergyScope and Mescal, using pip. Ensure you are using compatible versions. ```python %pip install mescal==1.2.4 %pip install energyscope==2.1.2 ``` -------------------------------- ### Set Up Brightway Project Source: https://library.energyscope.ch/latest/library/generate-lcia-metrics Set the current Brightway project. Ensure the project name matches your Brightway setup. ```python # Set up your Brightway project bd.projects.set_current('ecoinvent3.10.1') # put the name of your brightway project here ``` -------------------------------- ### Monthly Example Documentation Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/01_monthly/plot_01_test This is a documentation string for the monthly version of EnergyScope. It serves as a placeholder or introductory text. ```python """ Monthly example =================================== This could be an example for the monthly version of EnergyScope. """ ``` -------------------------------- ### Print Message Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/00_hourly/plot_general_example Prints a confirmation message to the console indicating the example has run. ```python print('This example shows a sin plot!') ``` -------------------------------- ### Install amplpy Package Source: https://library.energyscope.ch/latest/getting-started Install the amplpy package using pip. This is required for Option A, running EnergyScope directly with AMPL. ```bash pip install amplpy ``` -------------------------------- ### Gurobi Solver Output Example Source: https://library.energyscope.ch/latest/library/run-with-lca Example output from the Gurobi solver during the LCA calculation. This log provides details on the optimization process, including model size, presolve reductions, and iteration progress. ```text Gurobi 11.0.0: Set parameter LogToConsole to value 1 tech:outlev = 1 Set parameter NumericFocus to value 2 alg:numericfocus = 2 Set parameter Method to value 2 alg:method = 2 Set parameter InfUnbdInfo to value 1 Gurobi Optimizer version 11.0.0 build v11.0.0rc2 (mac64[arm] - Darwin 23.5.0 23F79) CPU model: Apple M2 Pro Thread count: 10 physical cores, 10 logical processors, using up to 10 threads Optimize a model with 491079 rows, 268733 columns and 1576042 nonzeros Model fingerprint: 0x489b5254 Coefficient statistics: Matrix range [1e-06, 7e+04] Objective range [1e+00, 1e+00] Bounds range [2e-02, 6e+01] RHS range [1e+00, 4e+04] Presolve removed 243247 rows and 128451 columns Presolve time: 1.11s Presolved: 247832 rows, 140282 columns, 798471 nonzeros Elapsed ordering time = 5s Ordering time: 5.65s Barrier statistics: Dense cols : 98 AA' NZ : 3.806e+06 Factor NZ : 1.871e+07 (roughly 300 MB of memory) Factor Ops : 7.223e+09 (less than 1 second per iteration) Threads : 10 Objective Residual Iter Primal Dual Primal Dual Compl Time 0 1.26214894e+07 -1.08114072e+06 1.99e+05 7.82e-14 1.00e+06 8s 1 1.35339311e+07 -2.45874867e+06 1.48e+05 8.36e+02 9.01e+05 8s 2 1.38220425e+07 -4.82323219e+06 1.43e+05 8.19e+02 8.29e+05 9s 3 1.55994536e+07 -5.80812720e+07 9.43e+04 6.18e+02 6.47e+05 10s 4 1.69376975e+07 -8.75794573e+07 6.41e+04 2.55e+02 2.99e+05 10s 5 1.67070071e+07 -9.53004389e+07 4.38e+04 8.43e+01 1.23e+05 11s 6 1.49631224e+07 -9.21859993e+07 2.77e+04 2.79e+01 5.37e+04 11s 7 1.24321302e+07 -9.04378015e+07 1.43e+04 1.76e+01 3.09e+04 11s 8 1.17871098e+07 -8.62747350e+07 1.17e+04 1.15e+01 2.23e+04 12s 9 9.83264710e+06 -8.06615974e+07 5.15e+03 5.91e+00 1.11e+04 12s 10 8.27717146e+06 -7.19404442e+07 1.52e+03 2.11e+00 3.83e+03 13s 11 7.07560975e+06 -4.98458760e+07 5.99e+02 4.49e-01 1.06e+03 13s 12 4.69555157e+06 -2.83726138e+07 1.19e+02 1.45e-01 3.27e+02 14s 13 2.73919161e+06 -8.60861758e+06 2.36e+01 3.31e-02 8.11e+01 14s 14 1.58495883e+06 -5.04289313e+06 9.81e+00 1.89e-02 4.50e+01 15s 15 1.15002761e+06 -3.73458586e+06 5.92e+00 1.38e-02 3.26e+01 15s 16 1.00327382e+06 -2.27155989e+06 4.78e+00 8.30e-03 2.07e+01 15s 17 6.05300251e+05 -1.23203779e+06 2.28e+00 4.45e-03 1.13e+01 16s 18 4.64584361e+05 -6.32348880e+05 1.58e+00 2.30e-03 6.34e+00 16s 19 3.55194859e+05 -5.01622560e+05 1.08e+00 1.88e-03 5.02e+00 17s 20 2.94192951e+05 -3.71479342e+05 7.98e-01 1.44e-03 3.88e+00 17s 21 2.02704421e+05 -3.00907689e+05 4.08e-01 1.18e-03 3.00e+00 17s 22 1.67462697e+05 -1.68280621e+05 2.63e-01 6.95e-04 1.92e+00 18s 23 1.16017225e+05 -7.11479718e+04 6.35e-02 3.46e-04 1.04e+00 18s 24 1.05167669e+05 -3.62786352e+04 2.30e-02 2.23e-04 7.56e-01 18s 25 1.01090645e+05 -2.44646310e+04 1.27e-02 1.82e-04 6.60e-01 19s 26 9.11274044e+04 -9.36211225e+03 1.07e-02 1.30e-04 5.18e-01 19s 27 8.07349691e+04 2.69477488e+03 8.50e-03 9.13e-05 3.95e-01 20s 28 7.16514186e+04 1.64619174e+04 6.44e-03 5.70e-05 2.76e-01 20s 29 6.10425774e+04 2.63738488e+04 3.78e-03 3.10e-05 1.74e-01 21s 30 5.53785573e+04 3.41295145e+04 2.51e-03 1.81e-05 1.03e-01 21s 31 5.16638429e+04 3.70952997e+04 1.75e-03 1.40e-05 7.05e-02 21s ``` -------------------------------- ### Plot Installed Capacity of Technologies and Storages Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/00_hourly/plot_installed_capacity Use this code to generate a bar chart comparing the installed capacity of conversion technologies and storage systems. Ensure 'results' and 'thresh' are defined and 'plt' is imported. ```python F = results.variables["F"] storages = results.sets['STORAGE_TECH']["STORAGE_TECH"].values F_storage = F[F.index.get_level_values(0).isin(storages)] F_tech = F[~F.index.get_level_values(0).isin(storages)] # Sort by size F_storage = F_storage.sort_values(by=F_storage.columns[0], ascending=False) F_storage = F_storage[F_storage.values[:,0]>thresh] F_tech = F_tech[F_tech.values[:,0]>thresh] F_tech = F_tech.sort_values(by=F_tech.columns[0], ascending=False) # Calculate subplot widths proportional to number of bars n_tech = len(F_tech) n_storage = len(F_storage) total = n_tech + n_storage widths = [n_tech, n_storage] if total > 0 else [1, 1] fig, axes = plt.subplots(1, 2, figsize=figsize, gridspec_kw={'width_ratios': widths}) # Technologies subplot (left) axes[0].bar(x=range(n_tech), height=F_tech.values[:, 0]) axes[0].set_xticks(range(n_tech)) axes[0].set_xticklabels(F_tech.index, rotation=90) axes[0].set_ylabel('Installed Capacity of Conversion Technologies [GW]') axes[0].set_xlim(-1, n_tech) axes[0].set_title('Conversion Technologies', fontsize=20) # Storages subplot (right) axes[1].bar(x=range(n_storage), height=F_storage.values[:, 0], color='orange') axes[1].set_xticks(range(n_storage)) axes[1].set_xticklabels(F_storage.index, rotation=90) axes[1].set_ylabel('Installed Capacity of Storages [GWh]') axes[1].set_xlim(-1, n_storage) axes[1].set_title('Storages', fontsize=20) plt.tight_layout() plt.show() ``` -------------------------------- ### Python Implementation for TD Generation Setup Source: https://library.energyscope.ch/latest/library/td-generation Sets up the 'td_model' object with parameters and dimensions for typical day generation. It configures the number of typical days, dimensions, and processes the input data 'n_data' by setting indices, ensuring column types, transposing, and assigning column names. ```python td_model.param['Nbr_TD'] = nbr_td # Use only the second level of the index for DAYS n_data.index = n_data.index.get_level_values(1) # Ensure columns are integers for DIMENSIONS n_data.columns = n_data.columns.astype(int) n_data = n_data.transpose() # td_model.set['DAYS'] = list(n_data.index.unique()) td_model.set['DIMENSIONS'] = list(range(1,len(n_data.columns)+1)) # should be 144 n_data.columns = list(range(1,len(n_data.columns)+1)) ``` -------------------------------- ### Initialize Parameters and Paths (Python) Source: https://library.energyscope.ch/latest/library/td-generation Sets up key parameters like the number of representative days and time series thresholds, and defines the path for typical day data. Imports necessary libraries for data manipulation and analysis. ```python import matplotlib.pyplot as plt import seaborn as sns import matplotlib.dates as mdates import pandas as pd import numpy as np import sys from amplpy import AMPL # Parameters & Paths nbr_td = 12 # Number of representative days ts_threshold = 1e-3 # Threshold below which timeseries values are set to 0 path_td_data = 'tutorial_input/td-generation/' ``` -------------------------------- ### Plotly Example Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/00_hourly/plot_using_plotly A basic example demonstrating the use of Plotly for creating visualizations. This snippet is a placeholder and does not contain executable code. ```python """ Plotly example =================================== This is an example using plotly. """ ``` -------------------------------- ### Import Libraries and Initialize Model Source: https://library.energyscope.ch/latest/library/add_technology Import necessary classes from the energyscope package and initialize the 'infrastructure' model. This sets up the environment for adding new technologies. ```python from energyscope.energyscope import Energyscope from energyscope.result import postprocessing from energyscope.plots import plot_sankey from energyscope.models import infrastructure_ch_2050 # Initialize the EnergyScope model with the 'infrastructure' dataset es_infra_ch = Energyscope(model=infrastructure_ch_2050) ``` -------------------------------- ### Grid Installation Size Constraint Source: https://library.energyscope.ch/latest/features/module_infra Determines the required grid installation size by ensuring it is greater than or equal to the grid operation in any period. ```mathematica F(g)≥Ft(g,t),∀g∈GRIDS,t∈PERIODS ``` -------------------------------- ### Initialize and Calculate EnergyScope Model Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/01_monthly/plot_11_resources_treemap Instantiate the Energyscope model and perform calculations. This step requires a valid AMPL license. ```python es_core = Energyscope(model=core) results_core = postprocessing(es_core.calc(), df_monthly=False) ``` -------------------------------- ### Model Class Initialization Source: https://library.energyscope.ch/latest/reference/models Illustrates the initialization of the Model class, which accepts a list of file tuples (type, path). ```python def __init__(self, files: list[tuple[str, Union[str, PathLike]]]): """ Initializes the Model class with an ordered list of files to load. Parameters: files (list[tuple[str, Union[str, PathLike]]]): A list of tuples where each tuple contains the file type ('mod' or 'dat') and the file path. """ self.files = files ``` -------------------------------- ### Install mescal Package Source: https://library.energyscope.ch/latest/library/generate-lcia-metrics Install the mescal package with a specific version. Note potential dependency issues with numpy versions between energyscope and brightway2. ```python %pip install mescal==1.2.4 ``` -------------------------------- ### Create and calculate Energyscope model Source: https://library.energyscope.ch/latest/es_gallery/generated/gallery/00_hourly/plot_installed_capacity Instantiate the Energyscope model with the core configuration and run the calculation. Note: This step requires a valid AMPL license. ```python # Create a model and calculate the results es_core = Energyscope(model=core) results = es_core.calc() ``` -------------------------------- ### Calculate Grid Investment Costs Source: https://library.energyscope.ch/latest/features/module_infra Calculates the investment costs for a grid based on installed size, specific investment costs, and installed grid length. ```mathematica Cginv=Sginst⋅cginv⋅lginst,∀g∈GRIDS ``` -------------------------------- ### Inspect Installed Capacities Source: https://library.energyscope.ch/latest/library/basic-run-pyomo Retrieve and display the 'F_Mult' variable from the result object to view installed capacities. Filters for entries with a value greater than 0 and shows the first 10. ```python # View installed capacities (F_Mult) f_mult = result.variables['F_Mult'] f_mult[f_mult['F_Mult'] > 0].head(10) ``` -------------------------------- ### PyomoModel Class Initialization Source: https://library.energyscope.ch/latest/reference/models Demonstrates the initialization of the PyomoModel class, requiring model and data paths. ```python def __init__(self, model_path: Union[str, PathLike], data_path: Union[str, PathLike]): self.model_path = model_path self.data_path = data_path ``` -------------------------------- ### Calculate Annual Production and Installed Capacity Source: https://library.energyscope.ch/latest/library/run-with-lca Merges production ('F_t') and operating time ('t_op') data to calculate annual production. It also retrieves installed capacity ('F'). Requires pandas library. ```python df_annual_prod = pd.merge(results.variables['F_t'].reset_index(), results.parameters['t_op'].reset_index(), left_on=['index1', 'index2'], right_on=['index0', 'index1'], suffixes=('', '_')) df_annual_prod['Annual_Prod'] = df_annual_prod['F_t'] * df_annual_prod['t_op'] df_annual_prod = df_annual_prod.groupby(['index0', 'Run'])['Annual_Prod'].sum().reset_index() df_installed_cap = results.variables['F'].reset_index() ``` -------------------------------- ### Define Input and Output Folders Source: https://library.energyscope.ch/latest/library/run-with-lca Set the paths for your input data folder, LCA results folder, and provide your AMPL license UUID. Replace placeholder paths with your actual file locations. ```python INPUT_DATA_FOLDER = 'path/to/your/input/files/' # put the path of your data folder here LCA_RESULTS_FOLDER = 'path/to/your/lca/results/files/' # put the path of your LCA results folder here license_uuid = 'xxx' # put your AMPL licence UUID here ``` -------------------------------- ### Initialize Quebec Transition Dataset Source: https://library.energyscope.ch/latest/reference/datasets Initializes the 'quebec_transition' dataset, focusing on Quebec's energy transition. It loads data from CSV files for technologies, demands, and resources relevant to this scenario. ```python quebec_transition = Dataset( read_csv( __from_data( "infrastructure/quebec/transition/quebec_transition_technologies.csv" ) ), read_csv( __from_data( "infrastructure/quebec/transition/quebec_transition_demands.csv" ) ), read_csv( __from_data( "infrastructure/quebec/transition/quebec_transition_resources.csv" ) ), ) ``` -------------------------------- ### Set up and Solve AMPL Model for Typical Day Selection Source: https://library.energyscope.ch/latest/library/td-generation Configures CPLEX options, initializes an AMPL model, defines the MILP formulation for typical day selection, and solves the model. Ensure data is preprocessed correctly before assignment. ```python cplex_options = ['mipdisplay=5', 'mipinterval=1000', 'mipgap=1e-6'] cplex_options_str = ' '.join(cplex_options) options = {'show_stats': 3, 'times': 1, 'gentimes': 1, 'solver': 'cplex', 'cplex_options': cplex_options_str} td_model = AMPL() td_model.setOption('solver', 'cplex') td_model.setOption('cplex_options', cplex_options_str) td_model.eval(r""" #---------------------------------------------------------------------------------- # TYPICAL DAY SELECTION # from F. Dominguez-Munoz et al., Selection of typical demand days for CHP optimization, 2011 #---------------------------------------------------------------------------------- ############################ ### MILP formulation ### ############################ set DIMENSIONS ; # Number of input data per day (24h x nbr of time series) set DAYS := 1 .. 365; # Number of days param Nbr_TD default 12; #Number of TD days param Ndata{DAYS,DIMENSIONS}; #Input data (already normalized) param Distance{i in DAYS,j in DAYS} := sum{k in DIMENSIONS}((Ndata[i,k]-Ndata[j,k])*(Ndata[i,k]-Ndata[j,k])) ; # Distance matrix. ### Variables var Selected_TD {DAYS} binary;# default 0; #which are the typical days var Cluster_matrix {DAYS,DAYS} binary;# default 0; #which day corresponds to which typical day ### Constraints # Allocate one cluster centre (i) to each day (j) subject to allocate_1TD_per_day{j in DAYS}: sum{i in DAYS} Cluster_matrix[i,j] = 1; # If cluster not allocated, it needs to be null subject to other_TD_null {i in DAYS,j in DAYS}: Cluster_matrix[i,j] <= Selected_TD[i]; # Limit the number of TD subject to limit_number_of_TD: sum{i in DAYS} Selected_TD[i] = Nbr_TD; #-Objective minimize Euclidean_distance: sum{i in DAYS,j in DAYS} Distance[i,j]*Cluster_matrix[i,j]; """) td_model.param['Nbr_TD'] = nbr_td # Use only the second level of the index for DAYS n_data.index = n_data.index.get_level_values(1) # Ensure columns are integers for DIMENSIONS n_data.columns = n_data.columns.astype(int) n_data = n_data.transpose() # td_model.set['DAYS'] = list(n_data.index.unique()) td_model.set['DIMENSIONS'] = list(range(1,len(n_data.columns)+1)) # should be 144 n_data.columns = list(range(1,len(n_data.columns)+1)) # Now convert to long format and assign to parameter td_model.param['Ndata'] = n_data.stack() td_model.solve() ``` -------------------------------- ### Import Libraries for Uncertainty Analysis Source: https://library.energyscope.ch/latest/library/uncertainty-analysis Imports essential libraries for data manipulation, numerical operations, visualization, and EnergyScope model functionalities. Ensure these libraries are installed before running. ```python import pandas as pd import numpy as np import seaborn as sns from energyscope.energyscope import Energyscope from energyscope.models import infrastructure_ch_2050 from energyscope.result import postprocessing from energyscope.datasets import gen_sobol_sequence ``` -------------------------------- ### Initialize EnergyScope Model Source: https://library.energyscope.ch/latest/library/multiple-runs Loads the EnergyScope model using a predefined configuration ('infrastructure_ch_2050') and the specified solver options. This step prepares the model for calculations. ```python # Load the model with the chosen dataset and solver options es_infra_ch = Energyscope(model=infrastructure_ch_2050, solver_options=solver_options) ``` -------------------------------- ### Initialize Energyscope with Gurobi Solver Source: https://library.energyscope.ch/latest/library/run-with-lca Instantiate the Energyscope object, specifying the core model, Gurobi solver options, and necessary modules. Ensure you have the Gurobi license. ```python energyscope_lca = Energyscope( model=core, solver_options={'solver': 'gurobi', 'gurobi_options':'outlev=1 NumericFocus=2 method=2'}, modules=['gurobi'], license_uuid=license_uuid, ) ``` -------------------------------- ### Combine Production and Resource DataFrames Source: https://library.energyscope.ch/latest/library/run-with-lca Merges the processed annual production and installed capacity dataframes, renaming columns for clarity. Also renames the resource dataframe columns. ```python esm_results_tech = pd.merge( df_annual_prod, df_installed_cap, on=['index', 'Run'] ).rename(columns={'index':'Name', 'Annual_Prod': 'Production', 'F': 'Capacity'}) esm_results_res = df_annual_res.rename(columns={'index': 'Name', 'Annual_Res': 'Import'}) ``` -------------------------------- ### Initialize EnergyScope Model Source: https://library.energyscope.ch/latest/library/basic-run Create an instance of the Energyscope class using a predefined model configuration like 'infrastructure_ch_2050'. This sets up the model with its parameters and datasets for optimization. ```python es_infra_ch = Energyscope(model=infrastructure_ch_2050) ``` -------------------------------- ### Thermal Solar Production Constraint Source: https://library.energyscope.ch/latest/explanation/core_version_documentation Constrains the actual production of solar thermal based on installed capacity and solar capacity factor. This applies to each backup technology 'j' and time step. ```mathematica Ftsol(j,h,td)≤Fsol(j)cp,t(′DecSolar′,h,td) ∀j∈TECH OF EUT(HeatLowTDec)∖{′DecSolar′},∀h∈H,∀td∈TD ``` -------------------------------- ### Constant LCA Impact Calculation Source: https://library.energyscope.ch/latest/features/module_lca Calculates the annualized environmental impact score for a technology's construction and end-of-life stages. Requires installed technology size and specific impact factors. ```mathematical LCIAstat(i,tec)=lciastat(i,tec)⋅F(tec)⋅1n(tec) ``` -------------------------------- ### Inspect Solver Options Source: https://library.energyscope.ch/latest/library/choose-datasets Display the loaded solver options to verify they have been set correctly. ```python solver_options ``` -------------------------------- ### Thermal Solar Capacity Calculation Source: https://library.energyscope.ch/latest/explanation/core_version_documentation Calculates the total installed capacity of solar thermal, summing capacities associated with backup technologies. This formula is used when solar thermal is implemented as a decentralized technology. ```mathematica F(DecSolar)=∑j∈TECH OF EUT(HeatLowTDec)∖{′DecSolar′}Fsol(j) ``` -------------------------------- ### Define Parameters for Uncertainty Analysis Source: https://library.energyscope.ch/latest/library/uncertainty-analysis Manually defines a list of parameters to vary during the uncertainty analysis, along with their lower and upper bounds. This setup is crucial for defining the scope of the parameter space to be explored. ```python varying_parameter = 'c_inv' parameters = [ {'name': 'PV_LV', 'lower_bound': 0, 'upper_bound': 50}, {'name': 'WIND', 'lower_bound': 0, 'upper_bound': 20}, {'name': 'CCGT', 'lower_bound': 0, 'upper_bound': 10} ] ```