Skip to content

Commit

Permalink
Fix linting warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
k-knosala committed Oct 18, 2023
1 parent b8e4c08 commit 15a5881
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 45 deletions.
86 changes: 46 additions & 40 deletions hisim/system_setup_starter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,37 @@
The values from `system_setup_config` replace single values of the example's configuration object.
"""

import json
import importlib
import datetime
from pathlib import Path
from typing import Any, Union, Tuple, Optional
import json
from copy import deepcopy

from hisim import log
from hisim.simulator import SimulationParameters
from hisim.hisim_main import main
from hisim.postprocessingoptions import PostProcessingOptions
from hisim.utils import rgetattr, rsetattr, rhasattr
from pathlib import Path
import datetime
from hisim.utils import rsetattr, rhasattr
from hisim.simulator import SimulationParameters


def read_parameters_json(parameters_json_path: str) -> Union[dict, list]:
with open(parameters_json_path, "r") as c:
"""Read the parameter JSON string from file."""
with open(parameters_json_path, "r", encoding="utf8") as c:
parameters_json: Union[dict, list] = json.load(c)
return parameters_json


def set_values(setup_config, parameter_dict, nested=[]):
def set_values(setup_config, parameter_dict, nested=None):
"""Set values in config Dataclass from the parameter dictionnary."""
for key, value in parameter_dict.items():
if nested:
path_list = nested + [key]
else:
path_list = [key]
if isinstance(value, dict):
set_values(setup_config, value, nested + [key])
set_values(setup_config, value, path_list)
else:
attribute = ".".join(nested + [key])
attribute = ".".join(path_list)
if rhasattr(setup_config, attribute):
rsetattr(setup_config, attribute, value)
else:
Expand All @@ -46,8 +53,7 @@ def set_values(setup_config, parameter_dict, nested=[]):


def make_system_setup(
parameters_json: Union[dict, list],
result_path: str
parameters_json: Union[dict, list], result_directory: str
) -> Tuple[str, str, Optional[SimulationParameters], str]:
"""
Read setup parameters from JSON and build a system setup for a specific example.
Expand All @@ -58,21 +64,19 @@ def make_system_setup(
"System Setup Starter can only handle one setup at a time for now."
)

result_directory = result_path
Path(result_path).mkdir(parents=True, exist_ok=True)

path_to_module = parameters_json.pop("path_to_module")
_parameters_json = deepcopy(parameters_json)
Path(result_directory).mkdir(parents=True, exist_ok=True)
path_to_module = _parameters_json.pop("path_to_module")
setup_module_name = "examples." + path_to_module.split("/")[-1].replace(".py", "")
config_class_name = parameters_json.pop("config_class_name")
function_in_module = parameters_json.pop("function_in_module")
simulation_parameters_dict = parameters_json.pop("simulation_parameters")
config_class_name = _parameters_json.pop("config_class_name")
function_in_module = _parameters_json.pop("function_in_module")
simulation_parameters_dict = _parameters_json.pop("simulation_parameters")
module_config_path = str(Path(result_directory).joinpath("module_config.json"))
simulation_parameters_path = str(
Path(result_directory).joinpath("simulation_parameters.json")
)

setup_config_dict = parameters_json.pop("system_setup_config")
if parameters_json:
setup_config_dict = _parameters_json.pop("system_setup_config")
if _parameters_json:
raise AttributeError("There are unused attributes in parameters JSON.")

# Import modules for the specified system setup
Expand Down Expand Up @@ -117,37 +121,39 @@ def make_system_setup(
import sys

if len(sys.argv) == 1:
parameters_json_path = "input/request.json"
result_path = "results"
if not Path(parameters_json_path).is_file():
PARAMETERS_JSON_FILE = "input/request.json"
RESULT_DIRECTORY = "results"
if not Path(PARAMETERS_JSON_FILE).is_file():
log.information(
"Please specify an input JSON file or place it in `input/request.json`."
)
sys.exit(1)
elif len(sys.argv) == 2:
parameters_json_path = sys.argv[1]
result_path = "results"
PARAMETERS_JSON_FILE = sys.argv[1]
RESULT_DIRECTORY = "results"
elif len(sys.argv) == 3:
parameters_json_path = sys.argv[1]
result_path = sys.argv[2]
PARAMETERS_JSON_FILE = sys.argv[1]
RESULT_DIRECTORY = sys.argv[2]
else:
log.information("HiSim from JSON received too many arguments.")
sys.exit(1)

log.information(f"Reading parameters from {parameters_json_path}.")
log.information(f"Reading parameters from {PARAMETERS_JSON_FILE}.")

parameters_json = read_parameters_json(parameters_json_path)
my_parameters_json = read_parameters_json(PARAMETERS_JSON_FILE)

(
path_to_module,
function_in_module,
simulation_parameters,
module_config_path,
) = make_system_setup(parameters_json=parameters_json, result_path=result_path)
my_path_to_module,
my_function_in_module,
my_simulation_parameters,
my_module_config_path,
) = make_system_setup(
parameters_json=my_parameters_json, result_directory=RESULT_DIRECTORY
)

main(
path_to_module,
function_in_module,
simulation_parameters,
module_config_path,
my_path_to_module,
my_function_in_module,
my_simulation_parameters,
my_module_config_path,
)
28 changes: 23 additions & 5 deletions tests/test_system_setup_starter.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
"""Test system setup starter."""

import os
import time
import shutil
from hisim.system_setup_starter import make_system_setup
from hisim.hisim_main import main
from pathlib import Path
import json
import pytest
import time

from hisim.system_setup_starter import make_system_setup
from hisim.hisim_main import main

parameters_json = {
"path_to_module": "examples/household_1_advanced_hp_diesel_car.py",
Expand All @@ -13,7 +17,7 @@
"simulation_parameters": {
"start_date": "2021-01-01T00:00:00",
"end_date": "2021-01-02T00:00:00",
"seconds_per_timestep": 60,
"seconds_per_timestep": 900,
"post_processing_options": [13, 19, 20, 22],
},
"system_setup_config": {
Expand All @@ -28,6 +32,7 @@

@pytest.mark.base
def test_system_setup_starter():
"""Run a simulation from JSON."""
# Run simulation from config_json
result_directory = "results"
if Path(result_directory).is_dir():
Expand All @@ -40,7 +45,7 @@ def test_system_setup_starter():
module_config_path,
) = make_system_setup(
parameters_json=parameters_json,
result_path=result_directory,
result_directory=result_directory,
)
main(
path_to_module,
Expand All @@ -51,6 +56,19 @@ def test_system_setup_starter():
# Check results
assert os.path.isfile(result_directory + "/finished.flag")
assert os.path.isfile(result_directory + "/webtool_kpis.json")

with open(module_config_path, "r", encoding="utf8") as f:
created_module_config = json.load(f)
assert (
created_module_config["hp_config"]["set_thermal_output_power_in_watt"]
== parameters_json["system_setup_config"]["hp_config"][
"set_thermal_output_power_in_watt"
]
)
assert (
simulation_parameters.seconds_per_timestep
== parameters_json["simulation_parameters"]["seconds_per_timestep"]
)
# Remove result directory
time.sleep(1)
shutil.rmtree(result_directory)

0 comments on commit 15a5881

Please sign in to comment.