Skip to content

Commit

Permalink
Added support for OptiFlow_MainResults (#18)
Browse files Browse the repository at this point in the history
* Added support for OptiFlow_MainResults

* Columns never used, if input

* Small cleanup

* Release 0.3.12
  • Loading branch information
frederikfristed authored Oct 2, 2024
1 parent d5a5fbf commit fa1bf60
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 79 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
project = "pybalmorel"
copyright = "2024, Mathias Berg Rosendal, Théodore Le Nalinec"
author = "Mathias Berg Rosendal, Théodore Le Nalinec"
release = "0.3.11"
release = "0.3.12"

exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".testenv", ".testenv/**"]

Expand Down
2 changes: 1 addition & 1 deletion docs/get_started/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ dependencies:
- pip:
- gamsapi[transfer]>=45.7.0
- eel>=0.17.0
- pybalmorel==0.3.11
- pybalmorel==0.3.12
```
2 changes: 1 addition & 1 deletion environment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ dependencies:
- pip:
- gamsapi[transfer]>=45.7.0
- eel>=0.17.0
- pybalmorel==0.3.11
- pybalmorel==0.3.12
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pybalmorel"
version = "0.3.11"
version = "0.3.12"
maintainers = [
{ name="Mathias Berg Rosendal", email="[email protected]"},
{ name="Théodore Le Nalinec"},
Expand Down
9 changes: 6 additions & 3 deletions src/pybalmorel/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ class MainResults:
def __init__(self, files: Union[str, list, tuple],
paths: Union[str, list, tuple] = '.',
scenario_names: Union[str, list, tuple] = None,
system_directory: str = None):
system_directory: str = None,
result_type: str = 'balmorel'):
"""
Initialises the MainResults class and loads gdx result file(s)
Expand All @@ -40,6 +41,7 @@ def __init__(self, files: Union[str, list, tuple],
paths (str, list, tuple): Path(s) to the gdx result file(s), assumed in same path if only one path given, defaults to working directory
scenario_names (str, list, tuple): Name of scenarios corresponding to each gdx file, defaults to ['SC1', 'SC2', ..., 'SCN'] if None given
system_directory (str, optional): GAMS system directory. Is not used if not specified.
result_type (str, optional): Specifies the type of result to extract. Use 'optiflow' for OptiFlow results. If not specified, it defaults to extracting Balmorel GDX results.
"""

## Loading scenarios
Expand Down Expand Up @@ -83,11 +85,12 @@ def __init__(self, files: Union[str, list, tuple],
if len(files) != len(scenario_names):
# Raise error if not given same amount of scenario_names and files
raise Exception("%d files, but %d scenario names given!\nProvide none or the same amount of scenario names as files"%(len(files), len(scenario_names)))

## Store MainResult databases
self.files = files
self.paths = paths
self.sc = scenario_names
self.type = result_type
self.db = {}

if system_directory != None:
Expand Down Expand Up @@ -116,7 +119,7 @@ def get_result(self, symbol: str, cols: str = 'None') -> pd.DataFrame:
for SC in self.sc:
# Get results from each scenario
try :
temp = symbol_to_df(self.db[SC], symbol, cols)
temp = symbol_to_df(self.db[SC], symbol, cols, result_type=self.type)
temp['Scenario'] = SC
# Put scenario in first column
temp = temp.loc[:, ['Scenario'] + list(temp.columns[:-1])]
Expand Down
172 changes: 111 additions & 61 deletions src/pybalmorel/formatting.py

Large diffs are not rendered by default.

13 changes: 11 additions & 2 deletions src/pybalmorel/interactive/interactive_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
import ipywidgets as widgets
from ipywidgets import interact, interactive
from ..plotting.plot_functions import plot_bar_chart
from ..formatting import mainresults_symbol_columns

from ..formatting import optiflow_mainresults_symbol_columns, balmorel_mainresults_symbol_columns

#%% ------------------------------- ###
### 1. Bar chart interactive ###
Expand All @@ -35,6 +34,16 @@ def interactive_bar_chart(MainResults_instance):
MainResults_instance (MainResults): Takes an instance of the MainResults class and opens a GUI for plotting
"""

"""Result type definition"""
result_type = MainResults_instance.type.lower()
print(f"Result type: {result_type}")

# Initial selection for plotting
if result_type=='optiflow':
mainresults_symbol_columns=optiflow_mainresults_symbol_columns
elif result_type=='balmorel':
mainresults_symbol_columns=balmorel_mainresults_symbol_columns

""" Buttons definition """

# Initial selection for plotting
Expand Down
11 changes: 9 additions & 2 deletions src/pybalmorel/plotting/plot_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,14 @@ def plot_bar_chart(df: pd.core.frame.DataFrame, filter: dict, series: Union[str,
"""

# Unit
unit = df['Unit'][0]
if 'Unit' in df.columns:
unit = df['Unit'][0] # Get the first unit value if the column exists
else:
unit = None # Set to an empty list

# Continue with unit_dict as normal
unit_dict = {'GW': 'Capacity', 'TWh': 'Energy', 'GWh': 'Energy'}

# Filtering the dataframe
query_parts = []
for key, value in filter.items():
Expand Down Expand Up @@ -226,6 +231,8 @@ def custom_sort_key(item):
else :
if unit in unit_dict:
ax.set_ylabel(f'{unit_dict[unit]} ({unit})', fontsize=yaxis[1])
elif unit==None:
ax.set_ylabel(f'Value', fontsize=yaxis[1])
else :
ax.set_ylabel(f'Value ({unit})', fontsize=yaxis[1])

Expand Down
29 changes: 22 additions & 7 deletions src/pybalmorel/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@

import gams
import pandas as pd
from .formatting import mainresult_symbol_columns
from .formatting import balmorel_symbol_columns, optiflow_symbol_columns

#%% ------------------------------- ###
### 1. GAMS Interface ###
### ------------------------------- ###

### 1.0 Converting a GDX file to a pandas dataframe
def symbol_to_df(db: gams.GamsDatabase, symbol: str,
cols: str = 'None', parameter_or_set: str = 'parameter'):
cols: str = 'None',
parameter_or_set: str = 'parameter',
result_type: str = 'balmorel'):
"""
Loads a symbol from a GDX database into a pandas dataframe
Expand All @@ -30,16 +32,29 @@ def symbol_to_df(db: gams.GamsDatabase, symbol: str,
else:
print('Choose either parameter or set!')

## Format by result type
result_type = result_type.lower()

if result_type=='balmorel':
mainresult_symbol_columns = balmorel_symbol_columns
elif result_type=='optiflow':
mainresult_symbol_columns = optiflow_symbol_columns

#Name columns
if cols == 'None':
try:
df.columns = mainresult_symbol_columns[symbol] + ['Unit', 'Value']
except KeyError:
print('Standard column format not found for this symbol')
elif type(cols) == list:
df.columns = cols
except ValueError:
try:
df.columns = mainresult_symbol_columns[symbol] + ['Value']
except KeyError:
print('Standard column format not found for this symbol')
else:
df.columns = cols


return df


def read_lines(name, file_path, make_space=True):

if make_space:
Expand Down

0 comments on commit fa1bf60

Please sign in to comment.