-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
bugfix(sb): handle missing objects in Scenario Builder configuration (#…
- Loading branch information
Showing
33 changed files
with
1,262 additions
and
632 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,87 +1,108 @@ | ||
from typing import Any, Dict, List | ||
import typing as t | ||
|
||
import typing_extensions as te | ||
|
||
from antarest.study.business.utils import execute_or_add_commands | ||
from antarest.study.model import Study | ||
from antarest.study.storage.storage_service import StudyStorageService | ||
from antarest.study.storage.variantstudy.model.command.update_scenario_builder import UpdateScenarioBuilder | ||
|
||
KEY_SEP = "," | ||
HL_COEF = 100 | ||
# Symbols used in scenario builder data | ||
_AREA_RELATED_SYMBOLS = "l", "h", "w", "s", "bc", "hgp" | ||
_LINK_RELATED_SYMBOLS = ("ntc",) | ||
_HYDRO_LEVEL_RELATED_SYMBOLS = "hl", "hfl" | ||
_CLUSTER_RELATED_SYMBOLS = "t", "r" | ||
|
||
_HYDRO_LEVEL_PERCENT = 100 | ||
|
||
_Section: te.TypeAlias = t.MutableMapping[str, t.Union[int, float]] | ||
_Sections: te.TypeAlias = t.MutableMapping[str, _Section] | ||
|
||
Ruleset: te.TypeAlias = t.MutableMapping[str, t.Any] | ||
Rulesets: te.TypeAlias = t.MutableMapping[str, Ruleset] | ||
|
||
|
||
class ScenarioBuilderManager: | ||
def __init__(self, storage_service: StudyStorageService) -> None: | ||
self.storage_service = storage_service | ||
|
||
def get_config(self, study: Study) -> Dict[str, Any]: | ||
temp = self.storage_service.get_storage(study).get(study, "/settings/scenariobuilder") | ||
|
||
def format_key(key: str) -> List[str]: | ||
parts = key.split(KEY_SEP) | ||
# "ntc,area1,area2,0" to ["ntc", "area1 / area2", "0"] | ||
if parts[0] == "ntc": | ||
return [parts[0], f"{parts[1]} / {parts[2]}", parts[3]] | ||
# "t,area1,0,thermal1" to ["t", "area1", "thermal1", "0"] | ||
elif parts[0] == "t": | ||
return [parts[0], parts[1], parts[3], parts[2]] | ||
# "[symbol],area1,0" to [[symbol], "area1", "0"] | ||
return parts | ||
|
||
def format_obj(obj: Dict[str, Any]) -> Dict[str, Any]: | ||
result = {} | ||
for k, v in obj.items(): | ||
if isinstance(v, dict): | ||
result[k] = format_obj(v) | ||
else: | ||
keys = format_key(k) | ||
nested_dict = result | ||
for key in keys[:-1]: | ||
nested_dict = nested_dict.setdefault(key, {}) | ||
nested_dict[keys[-1]] = v * HL_COEF if keys[0] == "hl" else v | ||
return result | ||
|
||
return format_obj(temp) | ||
|
||
def update_config(self, study: Study, data: Dict[str, Any]) -> None: | ||
def get_config(self, study: Study) -> Rulesets: | ||
sections = t.cast(_Sections, self.storage_service.get_storage(study).get(study, "/settings/scenariobuilder")) | ||
|
||
rulesets: Rulesets = {} | ||
for ruleset_name, data in sections.items(): | ||
ruleset = rulesets.setdefault(ruleset_name, {}) | ||
for key, value in data.items(): | ||
symbol, *parts = key.split(",") | ||
scenario = ruleset.setdefault(symbol, {}) | ||
if symbol in _AREA_RELATED_SYMBOLS: | ||
scenario_area = scenario.setdefault(parts[0], {}) | ||
scenario_area[parts[1]] = int(value) | ||
elif symbol in _HYDRO_LEVEL_RELATED_SYMBOLS: | ||
scenario_area = scenario.setdefault(parts[0], {}) | ||
scenario_area[parts[1]] = float(value) * _HYDRO_LEVEL_PERCENT | ||
elif symbol in _LINK_RELATED_SYMBOLS: | ||
scenario_link = scenario.setdefault(f"{parts[0]} / {parts[1]}", {}) | ||
scenario_link[parts[2]] = int(value) | ||
elif symbol in _CLUSTER_RELATED_SYMBOLS: | ||
scenario_area = scenario.setdefault(parts[0], {}) | ||
scenario_area_cluster = scenario_area.setdefault(parts[2], {}) | ||
scenario_area_cluster[parts[1]] = int(value) | ||
else: # pragma: no cover | ||
raise NotImplementedError(f"Unknown symbol {symbol}") | ||
|
||
return rulesets | ||
|
||
def update_config(self, study: Study, rulesets: Rulesets) -> None: | ||
file_study = self.storage_service.get_storage(study).get_raw(study) | ||
|
||
def to_valid_key(key: str) -> str: | ||
parts = key.split(KEY_SEP) | ||
# "ntc,area1 / area2,0" to "ntc,area1,area2,0" | ||
if parts[0] == "ntc": | ||
area1, area2 = parts[1].split(" / ") | ||
return KEY_SEP.join([parts[0], area1, area2, parts[2]]) | ||
# "t,area1,thermal1,0" to "t,area1,0,thermal1" | ||
elif parts[0] == "t": | ||
return KEY_SEP.join([parts[0], parts[1], parts[3], parts[2]]) | ||
# "[symbol],area1,0" | ||
return key | ||
|
||
def flatten_obj(obj: Dict[str, Any], parent_key: str = "") -> Dict[str, Dict[str, int]]: | ||
items = [] # type: ignore | ||
for k, v in obj.items(): | ||
new_key = parent_key + KEY_SEP + k if parent_key else k | ||
if isinstance(v, dict): | ||
items.extend(flatten_obj(v, new_key).items()) | ||
else: | ||
symbol = new_key.split(KEY_SEP)[0] | ||
items.append( | ||
( | ||
to_valid_key(new_key), | ||
v / HL_COEF if symbol == "hl" else v, | ||
) | ||
) | ||
return dict(items) | ||
sections: _Sections = {} | ||
for ruleset_name, ruleset in rulesets.items(): | ||
section = sections[ruleset_name] = {} | ||
for symbol, data in ruleset.items(): | ||
if symbol in _AREA_RELATED_SYMBOLS: | ||
_populate_common(section, symbol, data) | ||
elif symbol in _HYDRO_LEVEL_RELATED_SYMBOLS: | ||
_populate_hydro_levels(section, symbol, data) | ||
elif symbol in _LINK_RELATED_SYMBOLS: | ||
_populate_links(section, symbol, data) | ||
elif symbol in _CLUSTER_RELATED_SYMBOLS: | ||
_populate_clusters(section, symbol, data) | ||
else: # pragma: no cover | ||
raise NotImplementedError(f"Unknown symbol {symbol}") | ||
|
||
context = self.storage_service.variant_study_service.command_factory.command_context | ||
execute_or_add_commands( | ||
study, | ||
file_study, | ||
[ | ||
UpdateScenarioBuilder( | ||
# The value is a string when it is a ruleset cloning/deleting | ||
data={k: flatten_obj(v) if isinstance(v, dict) else v for k, v in data.items()}, | ||
command_context=self.storage_service.variant_study_service.command_factory.command_context, | ||
) | ||
], | ||
[UpdateScenarioBuilder(data=sections, command_context=context)], | ||
self.storage_service, | ||
) | ||
|
||
|
||
def _populate_common(section: _Section, symbol: str, data: t.Mapping[str, t.Mapping[str, t.Any]]) -> None: | ||
for area, scenario_area in data.items(): | ||
for year, value in scenario_area.items(): | ||
section[f"{symbol},{area},{year}"] = value | ||
|
||
|
||
def _populate_hydro_levels(section: _Section, symbol: str, data: t.Mapping[str, t.Mapping[str, t.Any]]) -> None: | ||
for area, scenario_area in data.items(): | ||
for year, value in scenario_area.items(): | ||
if isinstance(value, (int, float)) and value != float("nan"): | ||
value /= _HYDRO_LEVEL_PERCENT | ||
section[f"{symbol},{area},{year}"] = value | ||
|
||
|
||
def _populate_links(section: _Section, symbol: str, data: t.Mapping[str, t.Mapping[str, t.Any]]) -> None: | ||
for link, scenario_link in data.items(): | ||
for year, value in scenario_link.items(): | ||
area1, area2 = link.split(" / ") | ||
section[f"{symbol},{area1},{area2},{year}"] = value | ||
|
||
|
||
def _populate_clusters(section: _Section, symbol: str, data: t.Mapping[str, t.Mapping[str, t.Any]]) -> None: | ||
for area, scenario_area in data.items(): | ||
for cluster, scenario_area_cluster in scenario_area.items(): | ||
for year, value in scenario_area_cluster.items(): | ||
section[f"{symbol},{area},{year},{cluster}"] = value |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.